content
stringlengths 10
4.9M
|
---|
Teachers and principals have the right to search through students' personal diaries, cellphones or laptops under new guidelines issued by the Education Ministry.
The guidelines, released today by Education Minister Anne Tolley, say searches and confiscations affect student rights and their privacy and should only be carried out if a student has, or is believed to have, an item that poses an immediate or direct threat to safety.
However, school staff had to protect students and themselves and searches were an option if students did not surrender dangerous items like drugs or weapons when asked to.
''Students can be subject to a search while at school but only where there is good reason to do so, in terms of providing a safe physical and emotional environment for students, and where a search can be carried out in a safe and appropriate way,'' the guidelines say.
''A 'search' is not confined to physical intrusion and includes situations where a person is required to remove items of clothing or to empty out his or her pockets. It can also involve searching a student's correspondence including written and electronic material (e.g. in a diary, on a mobile phone or on a laptop).''
Schools should inform students, in an age appropriate way, of their policy on searches.
It was also recommended that school boards tell the wider school community of the policy.
''Staff need good grounds to believe a student has an item that poses an immediate or direct threat to safety. No search should be carried out based simply on suspicion or on a random or 'drag net' basis,'' the guidelines say.
''Reasonable cause to consider a search should be based on specific information regarding the student in question.''
Evidence to support a search may be circumstantial in some cases and may also be based on information provided by others.
Education Minister Anne Tolley said the ''vast majority'' of students were well-behaved but schools had asked for more support in dealing with ''challenging behaviour'' involving weapons and drugs.
''These new guidelines should give principals and teachers more confidence to pre-empt and deal with difficult situations, and ensure that this minority of students gets the message that drugs and weapons are not acceptable in our schools,'' Tolley said.
"This will allow teachers to manage any disruptions, and get on with the important job of lifting achievement.
The Ministry was also looking in to possible legislative changes to give schools more support in what was ''a complex legal area,'' she said.
|
#ifndef _MANIF_MANIF_SE_2_3TANGENT_H_
#define _MANIF_MANIF_SE_2_3TANGENT_H_
#include "manif/impl/se_2_3/SE_2_3Tangent_base.h"
namespace manif {
namespace internal {
//! Traits specialization
template <typename _Scalar>
struct traits<SE_2_3Tangent<_Scalar>>
{
using Scalar = _Scalar;
using LieGroup = SE_2_3<_Scalar>;
using Tangent = SE_2_3Tangent<_Scalar>;
using Base = SE_2_3TangentBase<Tangent>;
static constexpr int Dim = LieGroupProperties<Base>::Dim;
static constexpr int DoF = LieGroupProperties<Base>::DoF;
static constexpr int RepSize = DoF;
using DataType = Eigen::Matrix<Scalar, RepSize, 1>;
using Jacobian = Eigen::Matrix<Scalar, DoF, DoF>;
using LieAlg = Eigen::Matrix<Scalar, 5, 5>;
};
} /* namespace internal */
} /* namespace manif */
namespace manif {
//
// Tangent
//
/**
* @brief Represents an element of tangent space of SE_2_3.
*/
template <typename _Scalar>
struct SE_2_3Tangent : SE_2_3TangentBase<SE_2_3Tangent<_Scalar>>
{
private:
using Base = SE_2_3TangentBase<SE_2_3Tangent<_Scalar>>;
using Type = SE_2_3Tangent<_Scalar>;
protected:
using Base::derived;
public:
MANIF_MAKE_ALIGNED_OPERATOR_NEW_COND
MANIF_TANGENT_TYPEDEF
MANIF_INHERIT_TANGENT_API
MANIF_INHERIT_TANGENT_OPERATOR
SE_2_3Tangent() = default;
~SE_2_3Tangent() = default;
MANIF_COPY_CONSTRUCTOR(SE_2_3Tangent)
MANIF_MOVE_CONSTRUCTOR(SE_2_3Tangent)
template <typename _DerivedOther>
SE_2_3Tangent(const TangentBase<_DerivedOther>& o);
MANIF_TANGENT_ASSIGN_OP(SE_2_3Tangent)
// Tangent common API
DataType& coeffs();
const DataType& coeffs() const;
// SE_2_3Tangent specific API
protected:
DataType data_;
};
MANIF_EXTRA_TANGENT_TYPEDEF(SE_2_3Tangent);
template <typename _Scalar>
template <typename _DerivedOther>
SE_2_3Tangent<_Scalar>::SE_2_3Tangent(
const TangentBase<_DerivedOther>& o)
: data_(o.coeffs())
{
//
}
template <typename _Scalar>
typename SE_2_3Tangent<_Scalar>::DataType&
SE_2_3Tangent<_Scalar>::coeffs()
{
return data_;
}
template <typename _Scalar>
const typename SE_2_3Tangent<_Scalar>::DataType&
SE_2_3Tangent<_Scalar>::coeffs() const
{
return data_;
}
} /* namespace manif */
#endif /* _MANIF_MANIF_SE_2_3TANGENT_H_ */
|
# Problem: https://www.hackerrank.com/challenges/find-a-string/problem
def count_substring(string, sub_string):
str_len, sub_len, occurences, start = len(string), len(sub_string), 0, 0
for _ in range(str_len - sub_len +1):
if string[start:start+sub_len] == sub_string:
occurences += 1
start += 1
return occurences
string = input().strip()
sub_string = input().strip()
count = count_substring(string, sub_string)
print(count)
|
export class LineItemDialogPage {
readonly tag = 'ish-line-item-edit-dialog';
changeVariationSelection(values: { attr: string; value: string }[]) {
for (const x of values) {
// tslint:disable-next-line:ban
cy.get('ngb-modal-window')
.find(x.attr)
.select(x.value);
}
}
save() {
cy.get('[data-testing-id="confirm"]').click();
}
}
|
//Copyright (c) 2006-2009 Emil Dotchevski and Reverge Studios, Inc.
//Distributed under the Boost Software License, Version 1.0. (See accompanying
//file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef UUID_274DA366004E11DCB1DDFE2E56D89593
#define UUID_274DA366004E11DCB1DDFE2E56D89593
namespace
boost
{
namespace
exception_detail
{
template <class T>
class
refcount_ptr
{
public:
refcount_ptr():
px_(0)
{
}
~refcount_ptr()
{
release();
}
refcount_ptr( refcount_ptr const & x ):
px_(x.px_)
{
add_ref();
}
refcount_ptr &
operator=( refcount_ptr const & x )
{
adopt(x.px_);
return *this;
}
void
adopt( T * px )
{
release();
px_=px;
add_ref();
}
T *
get() const
{
return px_;
}
private:
T * px_;
void
add_ref()
{
if( px_ )
px_->add_ref();
}
void
release()
{
if( px_ )
px_->release();
}
};
}
////////////////////////////////////////////////////////////////////////
template <class Tag,class T>
class error_info;
typedef error_info<struct tag_throw_function,char const *> throw_function;
typedef error_info<struct tag_throw_file,char const *> throw_file;
typedef error_info<struct tag_throw_line,int> throw_line;
template <>
class
error_info<tag_throw_function,char const *>
{
public:
typedef char const * value_type;
value_type v_;
explicit
error_info( value_type v ):
v_(v)
{
}
};
template <>
class
error_info<tag_throw_file,char const *>
{
public:
typedef char const * value_type;
value_type v_;
explicit
error_info( value_type v ):
v_(v)
{
}
};
template <>
class
error_info<tag_throw_line,int>
{
public:
typedef int value_type;
value_type v_;
explicit
error_info( value_type v ):
v_(v)
{
}
};
template <class E,class Tag,class T>
E const & operator<<( E const &, error_info<Tag,T> const & );
class exception;
template <class>
class shared_ptr;
namespace
exception_detail
{
class error_info_base;
struct type_info_;
struct
error_info_container
{
virtual char const * diagnostic_information() const = 0;
virtual shared_ptr<error_info_base const> get( type_info_ const & ) const = 0;
virtual void set( shared_ptr<error_info_base const> const &, type_info_ const & ) = 0;
virtual void add_ref() const = 0;
virtual void release() const = 0;
protected:
virtual
~error_info_container() throw()
{
}
};
template <class>
struct get_info;
template <>
struct get_info<throw_function>;
template <>
struct get_info<throw_file>;
template <>
struct get_info<throw_line>;
char const * get_diagnostic_information( exception const & );
}
class
exception
{
protected:
exception():
throw_function_(0),
throw_file_(0),
throw_line_(-1)
{
}
#ifdef __HP_aCC
//On HP aCC, this protected copy constructor prevents throwing boost::exception.
//On all other platforms, the same effect is achieved by the pure virtual destructor.
exception( exception const & x ) throw():
data_(x.data_),
throw_function_(x.throw_function_),
throw_file_(x.throw_file_),
throw_line_(x.throw_line_)
{
}
#endif
virtual ~exception() throw()
#ifndef __HP_aCC
= 0 //Workaround for HP aCC, =0 incorrectly leads to link errors.
#endif
;
private:
template <class E>
friend
E const &
operator<<( E const & x, throw_function const & y )
{
x.throw_function_=y.v_;
return x;
}
template <class E>
friend
E const &
operator<<( E const & x, throw_file const & y )
{
x.throw_file_=y.v_;
return x;
}
template <class E>
friend
E const &
operator<<( E const & x, throw_line const & y )
{
x.throw_line_=y.v_;
return x;
}
friend char const * exception_detail::get_diagnostic_information( exception const & );
template <class E,class Tag,class T>
friend E const & operator<<( E const &, error_info<Tag,T> const & );
template <class>
friend struct exception_detail::get_info;
friend struct exception_detail::get_info<throw_function>;
friend struct exception_detail::get_info<throw_file>;
friend struct exception_detail::get_info<throw_line>;
mutable exception_detail::refcount_ptr<exception_detail::error_info_container> data_;
mutable char const * throw_function_;
mutable char const * throw_file_;
mutable int throw_line_;
};
inline
exception::
~exception() throw()
{
}
////////////////////////////////////////////////////////////////////////
namespace
exception_detail
{
template <class T>
struct
error_info_injector:
public T,
public exception
{
explicit
error_info_injector( T const & x ):
T(x)
{
}
~error_info_injector() throw()
{
}
};
struct large_size { char c[256]; };
large_size dispatch( exception * );
struct small_size { };
small_size dispatch( void * );
template <class,int>
struct enable_error_info_helper;
template <class T>
struct
enable_error_info_helper<T,sizeof(large_size)>
{
typedef T type;
};
template <class T>
struct
enable_error_info_helper<T,sizeof(small_size)>
{
typedef error_info_injector<T> type;
};
template <class T>
struct
enable_error_info_return_type
{
typedef typename enable_error_info_helper<T,sizeof(dispatch((T*)0))>::type type;
};
}
template <class T>
inline
typename
exception_detail::enable_error_info_return_type<T>::type
enable_error_info( T const & x )
{
typedef typename exception_detail::enable_error_info_return_type<T>::type rt;
return rt(x);
}
////////////////////////////////////////////////////////////////////////
namespace
exception_detail
{
class
clone_base
{
public:
virtual clone_base const * clone() const = 0;
virtual void rethrow() const = 0;
virtual
~clone_base() throw()
{
}
};
inline
void
copy_boost_exception( exception * a, exception const * b )
{
*a = *b;
}
inline
void
copy_boost_exception( void *, void const * )
{
}
template <class T>
class
clone_impl:
public T,
public clone_base
{
public:
explicit
clone_impl( T const & x ):
T(x)
{
copy_boost_exception(this,&x);
}
~clone_impl() throw()
{
}
private:
clone_base const *
clone() const
{
return new clone_impl(*this);
}
void
rethrow() const
{
throw*this;
}
};
}
template <class T>
inline
exception_detail::clone_impl<T>
enable_current_exception( T const & x )
{
return exception_detail::clone_impl<T>(x);
}
}
#endif
|
<filename>src/types.ts
import Context from "./context";
import http from "http";
export type LambdaHandler = (
event: object,
context: Context,
callback: Callback
) => Promise<object> | void;
export type LambdaResponseValue = object | string | number | undefined;
export type Callback = (err: null | Error, value?: LambdaResponseValue) => void;
export interface LambdaApiResponse {
readonly status: number;
readonly headers: http.IncomingHttpHeaders;
readonly body: Buffer;
}
export interface LambdaHeaders {
readonly "lambda-runtime-aws-request-id": string;
readonly "lambda-runtime-deadline-ms": string;
readonly "lambda-runtime-trace-id": string;
readonly "lambda-runtime-invoked-function-arn": string;
readonly "lambda-runtime-cognito-identity": string;
readonly "lambda-runtime-client-context": string;
}
export interface ContextBasedFunctionExecutor {
execute: (ctx: Context) => (fn: () => void) => void
}
export interface LambdaApi {
fetchNext: () => Promise<LambdaApiResponse>,
sendSuccessResponse: (id: string, obj: LambdaResponseValue) => Promise<LambdaApiResponse>,
sendErrorResponse: (id: string, err: Error) => Promise<LambdaApiResponse>,
sendErrorInit: (err: Error) => Promise<LambdaApiResponse>,
}
|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v2/resources/extension_feed_item.proto
package com.google.ads.googleads.v2.resources;
public interface ExtensionFeedItemOrBuilder extends
// @@protoc_insertion_point(interface_extends:google.ads.googleads.v2.resources.ExtensionFeedItem)
com.google.protobuf.MessageOrBuilder {
/**
* <pre>
* Immutable. The resource name of the extension feed item.
* Extension feed item resource names have the form:
* `customers/{customer_id}/extensionFeedItems/{feed_item_id}`
* </pre>
*
* <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @return The resourceName.
*/
java.lang.String getResourceName();
/**
* <pre>
* Immutable. The resource name of the extension feed item.
* Extension feed item resource names have the form:
* `customers/{customer_id}/extensionFeedItems/{feed_item_id}`
* </pre>
*
* <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @return The bytes for resourceName.
*/
com.google.protobuf.ByteString
getResourceNameBytes();
/**
* <pre>
* Output only. The ID of this feed item. Read-only.
* </pre>
*
* <code>.google.protobuf.Int64Value id = 24 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @return Whether the id field is set.
*/
boolean hasId();
/**
* <pre>
* Output only. The ID of this feed item. Read-only.
* </pre>
*
* <code>.google.protobuf.Int64Value id = 24 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @return The id.
*/
com.google.protobuf.Int64Value getId();
/**
* <pre>
* Output only. The ID of this feed item. Read-only.
* </pre>
*
* <code>.google.protobuf.Int64Value id = 24 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
com.google.protobuf.Int64ValueOrBuilder getIdOrBuilder();
/**
* <pre>
* Output only. The extension type of the extension feed item.
* This field is read-only.
* </pre>
*
* <code>.google.ads.googleads.v2.enums.ExtensionTypeEnum.ExtensionType extension_type = 13 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @return The enum numeric value on the wire for extensionType.
*/
int getExtensionTypeValue();
/**
* <pre>
* Output only. The extension type of the extension feed item.
* This field is read-only.
* </pre>
*
* <code>.google.ads.googleads.v2.enums.ExtensionTypeEnum.ExtensionType extension_type = 13 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @return The extensionType.
*/
com.google.ads.googleads.v2.enums.ExtensionTypeEnum.ExtensionType getExtensionType();
/**
* <pre>
* Start time in which this feed item is effective and can begin serving. The
* time is in the customer's time zone.
* The format is "YYYY-MM-DD HH:MM:SS".
* Examples: "2018-03-05 09:15:00" or "2018-02-01 14:34:30"
* </pre>
*
* <code>.google.protobuf.StringValue start_date_time = 5;</code>
* @return Whether the startDateTime field is set.
*/
boolean hasStartDateTime();
/**
* <pre>
* Start time in which this feed item is effective and can begin serving. The
* time is in the customer's time zone.
* The format is "YYYY-MM-DD HH:MM:SS".
* Examples: "2018-03-05 09:15:00" or "2018-02-01 14:34:30"
* </pre>
*
* <code>.google.protobuf.StringValue start_date_time = 5;</code>
* @return The startDateTime.
*/
com.google.protobuf.StringValue getStartDateTime();
/**
* <pre>
* Start time in which this feed item is effective and can begin serving. The
* time is in the customer's time zone.
* The format is "YYYY-MM-DD HH:MM:SS".
* Examples: "2018-03-05 09:15:00" or "2018-02-01 14:34:30"
* </pre>
*
* <code>.google.protobuf.StringValue start_date_time = 5;</code>
*/
com.google.protobuf.StringValueOrBuilder getStartDateTimeOrBuilder();
/**
* <pre>
* End time in which this feed item is no longer effective and will stop
* serving. The time is in the customer's time zone.
* The format is "YYYY-MM-DD HH:MM:SS".
* Examples: "2018-03-05 09:15:00" or "2018-02-01 14:34:30"
* </pre>
*
* <code>.google.protobuf.StringValue end_date_time = 6;</code>
* @return Whether the endDateTime field is set.
*/
boolean hasEndDateTime();
/**
* <pre>
* End time in which this feed item is no longer effective and will stop
* serving. The time is in the customer's time zone.
* The format is "YYYY-MM-DD HH:MM:SS".
* Examples: "2018-03-05 09:15:00" or "2018-02-01 14:34:30"
* </pre>
*
* <code>.google.protobuf.StringValue end_date_time = 6;</code>
* @return The endDateTime.
*/
com.google.protobuf.StringValue getEndDateTime();
/**
* <pre>
* End time in which this feed item is no longer effective and will stop
* serving. The time is in the customer's time zone.
* The format is "YYYY-MM-DD HH:MM:SS".
* Examples: "2018-03-05 09:15:00" or "2018-02-01 14:34:30"
* </pre>
*
* <code>.google.protobuf.StringValue end_date_time = 6;</code>
*/
com.google.protobuf.StringValueOrBuilder getEndDateTimeOrBuilder();
/**
* <pre>
* List of non-overlapping schedules specifying all time intervals
* for which the feed item may serve. There can be a maximum of 6 schedules
* per day.
* </pre>
*
* <code>repeated .google.ads.googleads.v2.common.AdScheduleInfo ad_schedules = 16;</code>
*/
java.util.List<com.google.ads.googleads.v2.common.AdScheduleInfo>
getAdSchedulesList();
/**
* <pre>
* List of non-overlapping schedules specifying all time intervals
* for which the feed item may serve. There can be a maximum of 6 schedules
* per day.
* </pre>
*
* <code>repeated .google.ads.googleads.v2.common.AdScheduleInfo ad_schedules = 16;</code>
*/
com.google.ads.googleads.v2.common.AdScheduleInfo getAdSchedules(int index);
/**
* <pre>
* List of non-overlapping schedules specifying all time intervals
* for which the feed item may serve. There can be a maximum of 6 schedules
* per day.
* </pre>
*
* <code>repeated .google.ads.googleads.v2.common.AdScheduleInfo ad_schedules = 16;</code>
*/
int getAdSchedulesCount();
/**
* <pre>
* List of non-overlapping schedules specifying all time intervals
* for which the feed item may serve. There can be a maximum of 6 schedules
* per day.
* </pre>
*
* <code>repeated .google.ads.googleads.v2.common.AdScheduleInfo ad_schedules = 16;</code>
*/
java.util.List<? extends com.google.ads.googleads.v2.common.AdScheduleInfoOrBuilder>
getAdSchedulesOrBuilderList();
/**
* <pre>
* List of non-overlapping schedules specifying all time intervals
* for which the feed item may serve. There can be a maximum of 6 schedules
* per day.
* </pre>
*
* <code>repeated .google.ads.googleads.v2.common.AdScheduleInfo ad_schedules = 16;</code>
*/
com.google.ads.googleads.v2.common.AdScheduleInfoOrBuilder getAdSchedulesOrBuilder(
int index);
/**
* <pre>
* The targeted device.
* </pre>
*
* <code>.google.ads.googleads.v2.enums.FeedItemTargetDeviceEnum.FeedItemTargetDevice device = 17;</code>
* @return The enum numeric value on the wire for device.
*/
int getDeviceValue();
/**
* <pre>
* The targeted device.
* </pre>
*
* <code>.google.ads.googleads.v2.enums.FeedItemTargetDeviceEnum.FeedItemTargetDevice device = 17;</code>
* @return The device.
*/
com.google.ads.googleads.v2.enums.FeedItemTargetDeviceEnum.FeedItemTargetDevice getDevice();
/**
* <pre>
* The targeted geo target constant.
* </pre>
*
* <code>.google.protobuf.StringValue targeted_geo_target_constant = 20 [(.google.api.resource_reference) = { ... }</code>
* @return Whether the targetedGeoTargetConstant field is set.
*/
boolean hasTargetedGeoTargetConstant();
/**
* <pre>
* The targeted geo target constant.
* </pre>
*
* <code>.google.protobuf.StringValue targeted_geo_target_constant = 20 [(.google.api.resource_reference) = { ... }</code>
* @return The targetedGeoTargetConstant.
*/
com.google.protobuf.StringValue getTargetedGeoTargetConstant();
/**
* <pre>
* The targeted geo target constant.
* </pre>
*
* <code>.google.protobuf.StringValue targeted_geo_target_constant = 20 [(.google.api.resource_reference) = { ... }</code>
*/
com.google.protobuf.StringValueOrBuilder getTargetedGeoTargetConstantOrBuilder();
/**
* <pre>
* The targeted keyword.
* </pre>
*
* <code>.google.ads.googleads.v2.common.KeywordInfo targeted_keyword = 22;</code>
* @return Whether the targetedKeyword field is set.
*/
boolean hasTargetedKeyword();
/**
* <pre>
* The targeted keyword.
* </pre>
*
* <code>.google.ads.googleads.v2.common.KeywordInfo targeted_keyword = 22;</code>
* @return The targetedKeyword.
*/
com.google.ads.googleads.v2.common.KeywordInfo getTargetedKeyword();
/**
* <pre>
* The targeted keyword.
* </pre>
*
* <code>.google.ads.googleads.v2.common.KeywordInfo targeted_keyword = 22;</code>
*/
com.google.ads.googleads.v2.common.KeywordInfoOrBuilder getTargetedKeywordOrBuilder();
/**
* <pre>
* Output only. Status of the feed item.
* This field is read-only.
* </pre>
*
* <code>.google.ads.googleads.v2.enums.FeedItemStatusEnum.FeedItemStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @return The enum numeric value on the wire for status.
*/
int getStatusValue();
/**
* <pre>
* Output only. Status of the feed item.
* This field is read-only.
* </pre>
*
* <code>.google.ads.googleads.v2.enums.FeedItemStatusEnum.FeedItemStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @return The status.
*/
com.google.ads.googleads.v2.enums.FeedItemStatusEnum.FeedItemStatus getStatus();
/**
* <pre>
* Sitelink extension.
* </pre>
*
* <code>.google.ads.googleads.v2.common.SitelinkFeedItem sitelink_feed_item = 2;</code>
* @return Whether the sitelinkFeedItem field is set.
*/
boolean hasSitelinkFeedItem();
/**
* <pre>
* Sitelink extension.
* </pre>
*
* <code>.google.ads.googleads.v2.common.SitelinkFeedItem sitelink_feed_item = 2;</code>
* @return The sitelinkFeedItem.
*/
com.google.ads.googleads.v2.common.SitelinkFeedItem getSitelinkFeedItem();
/**
* <pre>
* Sitelink extension.
* </pre>
*
* <code>.google.ads.googleads.v2.common.SitelinkFeedItem sitelink_feed_item = 2;</code>
*/
com.google.ads.googleads.v2.common.SitelinkFeedItemOrBuilder getSitelinkFeedItemOrBuilder();
/**
* <pre>
* Structured snippet extension.
* </pre>
*
* <code>.google.ads.googleads.v2.common.StructuredSnippetFeedItem structured_snippet_feed_item = 3;</code>
* @return Whether the structuredSnippetFeedItem field is set.
*/
boolean hasStructuredSnippetFeedItem();
/**
* <pre>
* Structured snippet extension.
* </pre>
*
* <code>.google.ads.googleads.v2.common.StructuredSnippetFeedItem structured_snippet_feed_item = 3;</code>
* @return The structuredSnippetFeedItem.
*/
com.google.ads.googleads.v2.common.StructuredSnippetFeedItem getStructuredSnippetFeedItem();
/**
* <pre>
* Structured snippet extension.
* </pre>
*
* <code>.google.ads.googleads.v2.common.StructuredSnippetFeedItem structured_snippet_feed_item = 3;</code>
*/
com.google.ads.googleads.v2.common.StructuredSnippetFeedItemOrBuilder getStructuredSnippetFeedItemOrBuilder();
/**
* <pre>
* App extension.
* </pre>
*
* <code>.google.ads.googleads.v2.common.AppFeedItem app_feed_item = 7;</code>
* @return Whether the appFeedItem field is set.
*/
boolean hasAppFeedItem();
/**
* <pre>
* App extension.
* </pre>
*
* <code>.google.ads.googleads.v2.common.AppFeedItem app_feed_item = 7;</code>
* @return The appFeedItem.
*/
com.google.ads.googleads.v2.common.AppFeedItem getAppFeedItem();
/**
* <pre>
* App extension.
* </pre>
*
* <code>.google.ads.googleads.v2.common.AppFeedItem app_feed_item = 7;</code>
*/
com.google.ads.googleads.v2.common.AppFeedItemOrBuilder getAppFeedItemOrBuilder();
/**
* <pre>
* Call extension.
* </pre>
*
* <code>.google.ads.googleads.v2.common.CallFeedItem call_feed_item = 8;</code>
* @return Whether the callFeedItem field is set.
*/
boolean hasCallFeedItem();
/**
* <pre>
* Call extension.
* </pre>
*
* <code>.google.ads.googleads.v2.common.CallFeedItem call_feed_item = 8;</code>
* @return The callFeedItem.
*/
com.google.ads.googleads.v2.common.CallFeedItem getCallFeedItem();
/**
* <pre>
* Call extension.
* </pre>
*
* <code>.google.ads.googleads.v2.common.CallFeedItem call_feed_item = 8;</code>
*/
com.google.ads.googleads.v2.common.CallFeedItemOrBuilder getCallFeedItemOrBuilder();
/**
* <pre>
* Callout extension.
* </pre>
*
* <code>.google.ads.googleads.v2.common.CalloutFeedItem callout_feed_item = 9;</code>
* @return Whether the calloutFeedItem field is set.
*/
boolean hasCalloutFeedItem();
/**
* <pre>
* Callout extension.
* </pre>
*
* <code>.google.ads.googleads.v2.common.CalloutFeedItem callout_feed_item = 9;</code>
* @return The calloutFeedItem.
*/
com.google.ads.googleads.v2.common.CalloutFeedItem getCalloutFeedItem();
/**
* <pre>
* Callout extension.
* </pre>
*
* <code>.google.ads.googleads.v2.common.CalloutFeedItem callout_feed_item = 9;</code>
*/
com.google.ads.googleads.v2.common.CalloutFeedItemOrBuilder getCalloutFeedItemOrBuilder();
/**
* <pre>
* Text message extension.
* </pre>
*
* <code>.google.ads.googleads.v2.common.TextMessageFeedItem text_message_feed_item = 10;</code>
* @return Whether the textMessageFeedItem field is set.
*/
boolean hasTextMessageFeedItem();
/**
* <pre>
* Text message extension.
* </pre>
*
* <code>.google.ads.googleads.v2.common.TextMessageFeedItem text_message_feed_item = 10;</code>
* @return The textMessageFeedItem.
*/
com.google.ads.googleads.v2.common.TextMessageFeedItem getTextMessageFeedItem();
/**
* <pre>
* Text message extension.
* </pre>
*
* <code>.google.ads.googleads.v2.common.TextMessageFeedItem text_message_feed_item = 10;</code>
*/
com.google.ads.googleads.v2.common.TextMessageFeedItemOrBuilder getTextMessageFeedItemOrBuilder();
/**
* <pre>
* Price extension.
* </pre>
*
* <code>.google.ads.googleads.v2.common.PriceFeedItem price_feed_item = 11;</code>
* @return Whether the priceFeedItem field is set.
*/
boolean hasPriceFeedItem();
/**
* <pre>
* Price extension.
* </pre>
*
* <code>.google.ads.googleads.v2.common.PriceFeedItem price_feed_item = 11;</code>
* @return The priceFeedItem.
*/
com.google.ads.googleads.v2.common.PriceFeedItem getPriceFeedItem();
/**
* <pre>
* Price extension.
* </pre>
*
* <code>.google.ads.googleads.v2.common.PriceFeedItem price_feed_item = 11;</code>
*/
com.google.ads.googleads.v2.common.PriceFeedItemOrBuilder getPriceFeedItemOrBuilder();
/**
* <pre>
* Promotion extension.
* </pre>
*
* <code>.google.ads.googleads.v2.common.PromotionFeedItem promotion_feed_item = 12;</code>
* @return Whether the promotionFeedItem field is set.
*/
boolean hasPromotionFeedItem();
/**
* <pre>
* Promotion extension.
* </pre>
*
* <code>.google.ads.googleads.v2.common.PromotionFeedItem promotion_feed_item = 12;</code>
* @return The promotionFeedItem.
*/
com.google.ads.googleads.v2.common.PromotionFeedItem getPromotionFeedItem();
/**
* <pre>
* Promotion extension.
* </pre>
*
* <code>.google.ads.googleads.v2.common.PromotionFeedItem promotion_feed_item = 12;</code>
*/
com.google.ads.googleads.v2.common.PromotionFeedItemOrBuilder getPromotionFeedItemOrBuilder();
/**
* <pre>
* Output only. Location extension. Locations are synced from a GMB account into a feed.
* This field is read-only.
* </pre>
*
* <code>.google.ads.googleads.v2.common.LocationFeedItem location_feed_item = 14 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @return Whether the locationFeedItem field is set.
*/
boolean hasLocationFeedItem();
/**
* <pre>
* Output only. Location extension. Locations are synced from a GMB account into a feed.
* This field is read-only.
* </pre>
*
* <code>.google.ads.googleads.v2.common.LocationFeedItem location_feed_item = 14 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @return The locationFeedItem.
*/
com.google.ads.googleads.v2.common.LocationFeedItem getLocationFeedItem();
/**
* <pre>
* Output only. Location extension. Locations are synced from a GMB account into a feed.
* This field is read-only.
* </pre>
*
* <code>.google.ads.googleads.v2.common.LocationFeedItem location_feed_item = 14 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
com.google.ads.googleads.v2.common.LocationFeedItemOrBuilder getLocationFeedItemOrBuilder();
/**
* <pre>
* Output only. Affiliate location extension. Feed locations are populated by Google Ads
* based on a chain ID.
* This field is read-only.
* </pre>
*
* <code>.google.ads.googleads.v2.common.AffiliateLocationFeedItem affiliate_location_feed_item = 15 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @return Whether the affiliateLocationFeedItem field is set.
*/
boolean hasAffiliateLocationFeedItem();
/**
* <pre>
* Output only. Affiliate location extension. Feed locations are populated by Google Ads
* based on a chain ID.
* This field is read-only.
* </pre>
*
* <code>.google.ads.googleads.v2.common.AffiliateLocationFeedItem affiliate_location_feed_item = 15 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @return The affiliateLocationFeedItem.
*/
com.google.ads.googleads.v2.common.AffiliateLocationFeedItem getAffiliateLocationFeedItem();
/**
* <pre>
* Output only. Affiliate location extension. Feed locations are populated by Google Ads
* based on a chain ID.
* This field is read-only.
* </pre>
*
* <code>.google.ads.googleads.v2.common.AffiliateLocationFeedItem affiliate_location_feed_item = 15 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
com.google.ads.googleads.v2.common.AffiliateLocationFeedItemOrBuilder getAffiliateLocationFeedItemOrBuilder();
/**
* <pre>
* Hotel Callout extension.
* </pre>
*
* <code>.google.ads.googleads.v2.common.HotelCalloutFeedItem hotel_callout_feed_item = 23;</code>
* @return Whether the hotelCalloutFeedItem field is set.
*/
boolean hasHotelCalloutFeedItem();
/**
* <pre>
* Hotel Callout extension.
* </pre>
*
* <code>.google.ads.googleads.v2.common.HotelCalloutFeedItem hotel_callout_feed_item = 23;</code>
* @return The hotelCalloutFeedItem.
*/
com.google.ads.googleads.v2.common.HotelCalloutFeedItem getHotelCalloutFeedItem();
/**
* <pre>
* Hotel Callout extension.
* </pre>
*
* <code>.google.ads.googleads.v2.common.HotelCalloutFeedItem hotel_callout_feed_item = 23;</code>
*/
com.google.ads.googleads.v2.common.HotelCalloutFeedItemOrBuilder getHotelCalloutFeedItemOrBuilder();
/**
* <pre>
* The targeted campaign.
* </pre>
*
* <code>.google.protobuf.StringValue targeted_campaign = 18 [(.google.api.resource_reference) = { ... }</code>
* @return Whether the targetedCampaign field is set.
*/
boolean hasTargetedCampaign();
/**
* <pre>
* The targeted campaign.
* </pre>
*
* <code>.google.protobuf.StringValue targeted_campaign = 18 [(.google.api.resource_reference) = { ... }</code>
* @return The targetedCampaign.
*/
com.google.protobuf.StringValue getTargetedCampaign();
/**
* <pre>
* The targeted campaign.
* </pre>
*
* <code>.google.protobuf.StringValue targeted_campaign = 18 [(.google.api.resource_reference) = { ... }</code>
*/
com.google.protobuf.StringValueOrBuilder getTargetedCampaignOrBuilder();
/**
* <pre>
* The targeted ad group.
* </pre>
*
* <code>.google.protobuf.StringValue targeted_ad_group = 19 [(.google.api.resource_reference) = { ... }</code>
* @return Whether the targetedAdGroup field is set.
*/
boolean hasTargetedAdGroup();
/**
* <pre>
* The targeted ad group.
* </pre>
*
* <code>.google.protobuf.StringValue targeted_ad_group = 19 [(.google.api.resource_reference) = { ... }</code>
* @return The targetedAdGroup.
*/
com.google.protobuf.StringValue getTargetedAdGroup();
/**
* <pre>
* The targeted ad group.
* </pre>
*
* <code>.google.protobuf.StringValue targeted_ad_group = 19 [(.google.api.resource_reference) = { ... }</code>
*/
com.google.protobuf.StringValueOrBuilder getTargetedAdGroupOrBuilder();
public com.google.ads.googleads.v2.resources.ExtensionFeedItem.ExtensionCase getExtensionCase();
public com.google.ads.googleads.v2.resources.ExtensionFeedItem.ServingResourceTargetingCase getServingResourceTargetingCase();
}
|
/**
* Created by genyus on 25/11/15.
*/
public class APIConst {
public final static String API_ROTTEN_TOMATOES_KEY = "4xdka4hpzszevvz2aba3xmtm";
public final static String API_PURCHASE_TOKEN = "rKfVOBGZrvJIOdGmXDHhFvOCVsyyzIZE";
public final static String API_PURCHASE_BASE_URL = "http://api-public.guidebox.com/v1.43/";
public final static String API_PURCHASE_ID = "/search/movie/id/themoviedb/";
public final static String API_PURCHASE_LINK = "/movie/";
public final static String API_TOKEN = "c1e4b32ab37e5086fe5c09521c0e67a7";
public final static String API_BASE_URL = "http://api.themoviedb.org/3/";
public final static String API_LIST_CATEGORIES = "genre/movie/list";
public final static String API_CONFIGURATION = "configuration";
public final static String API_LIST_MOVIES_CATEGORY = "discover/movie";
public final static String API_NOW_PLAYING = "movie/now_playing";
public final static String API_SEARCH = "search/movie";
public final static String API_INFO_MOVIE(int movie){
return "movie/"+movie;
}
public final static String API_CREW_MOVIE(int movie){
return "movie/"+movie+"/credits";
}
public final static String API_VIDEOS_MOVIE(int movie){
return "movie/"+movie+"/videos";
}
public final static String API_IMAGES_MOVIE(int movie){
return "movie/"+movie+"/images";
}
public final static String API_KEYWORDS_MOVIE(int movie) {
return "movie/"+movie+"/keywords";
}
public final static String API_PURCHASE_BASE_URL(Context context){
return API_PURCHASE_BASE_URL+context.getResources().getConfiguration().locale.getCountry()+"/"+API_PURCHASE_TOKEN;
//return API_PURCHASE_BASE_URL+"US/"+API_PURCHASE_TOKEN;
}
}
|
<gh_stars>0
/*
SCREENWaitBlanking.c
AUTHORS:
<EMAIL> mk
PLATFORMS:
All.
HISTORY:
01/23/06 mk Created.
05/31/11 mk Add 3rd method of waiting for vblank, based on vblank counter
queries on supported systems (OS/X and Linux) to work around
bugs in bufferswap wait method on OS/X "Snow Leopard".
Code will try beampos waits, fallback to vblank counter waits,
then fallback to swapbuffers waits.
DESCRIPTION:
Waits for beginning of vertical retrace. Blocks Matlabs or PTB's execution until then.
Screen('WaitBlanking') is here mostly for backwards-compatibility with old OS-9 and WinPTB.
It is not the recommended way of doing things for new code!
*/
#include "Screen.h"
// If you change the useString then also change the corresponding synopsis string in ScreenSynopsis.c
static char useString[] = "framesSinceLastWait = Screen('WaitBlanking', windowPtr [, waitFrames]);";
static char synopsisString[] =
"Wait for specified number of monitor refresh intervals, stopping PTB's "
"execution until then. Select waitFrames=1 (or omit it, since that's the default) "
"to wait for the beginning of the next frame. "
"\"windowPtr\" is the pointer to the onscreen window for which we should wait for. "
"framesSinceLastWait contains the number of video refresh intervals from the last "
"time Screen('WaitBlanking') or Screen('Flip') returned until return from "
"this call to WaitBlanking. Please note that this function is only provided to keep old code "
"from OS-9 PTB running. Use the Screen('Flip') command for all new code as this "
"allows for much higher accuracy and reliability of stimulus timing and enables "
"a huge number of new and very useful features! "
"COMPATIBILITY TO OS-9 PTB: If you absolutely need to run old code for the old MacOS-9 or Windows "
"Psychtoolbox, you can switch into a compatibility mode by adding the command "
"Screen('Preference', 'EmulateOldPTB', 1) at the very top of your script. This will restore "
"Offscreen windows and WaitBlanking functionality, but at the same time disable most of the new "
"features of the OpenGL Psychtoolbox. Please do not write new experiment code in the old style! "
"Emulation mode is pretty new and may contain significant bugs, so use with great caution!";
static char seeAlsoString[] = "OpenWindow Flip Screen('Preference', 'EmulateOldPTB', 1)";
PsychError SCREENWaitBlanking(void)
{
PsychWindowRecordType *windowRecord;
int waitFrames, framesWaited;
double tvbl, ifi;
long windowwidth, windowheight;
int vbl_startline, beampos, lastline;
psych_uint64 vblCount, vblRefCount;
CGDirectDisplayID cgDisplayID;
GLint read_buffer, draw_buffer;
// All subfunctions should have these two lines.
PsychPushHelp(useString, synopsisString, seeAlsoString);
if(PsychIsGiveHelp()){PsychGiveHelp();return(PsychError_none);};
PsychErrorExit(PsychCapNumInputArgs(2)); //The maximum number of inputs
PsychErrorExit(PsychRequireNumInputArgs(1)); //The required number of inputs
PsychErrorExit(PsychCapNumOutputArgs(1)); //The maximum number of outputs
// Get the window record from the window record argument and get info from the window record
PsychAllocInWindowRecordArg(kPsychUseDefaultArgPosition, TRUE, &windowRecord);
if(!PsychIsOnscreenWindow(windowRecord))
PsychErrorExitMsg(PsychError_user, "Tried to call 'WaitBlanking' on something else than an onscreen window!");
// Get the number of frames to wait:
waitFrames = 0;
PsychCopyInIntegerArg(2, FALSE, &waitFrames);
// We default to wait at least one interval if no argument supplied:
waitFrames = (waitFrames < 1) ? 1 : waitFrames;
// Enable this windowRecords framebuffer as current drawingtarget:
// This is needed to make sure that Offscreen windows work propely.
PsychSetDrawingTarget(windowRecord);
// Retrieve display handle for beamposition queries:
PsychGetCGDisplayIDFromScreenNumber(&cgDisplayID, windowRecord->screenNumber);
// Get window size and vblank startline:
windowwidth = (long) PsychGetWidthFromRect(windowRecord->rect);
windowheight = (long) PsychGetHeightFromRect(windowRecord->rect);
vbl_startline = windowRecord->VBL_Startline;
// Query duration of a monitor refresh interval: We try to use the measured interval,
// but fallback of the nominal value reported by the operating system if necessary:
if ((ifi = windowRecord->VideoRefreshInterval)<=0) {
if (PsychGetNominalFramerate(windowRecord->screenNumber) > 0) {
// Valid nominal framerate returned by OS: Calculate nominal IFI from it.
ifi = 1.0 / ((double) PsychGetNominalFramerate(windowRecord->screenNumber));
}
else {
// No reasonable value available! We fallback to an assumed 60 Hz refresh...
ifi = 1.0 / 60.0;
}
}
// Query vblcount to test if this method works correctly:
PsychOSGetVBLTimeAndCount(windowRecord, &vblRefCount);
// Check if beamposition queries are supported by this OS and working properly:
if (-1 != PsychGetDisplayBeamPosition(cgDisplayID, windowRecord->screenNumber) && windowRecord->VBL_Endline >= 0) {
// Beamposition queries supported and fine. We can wait for VBL without bufferswap-tricks:
// We query the rasterbeamposition and compare it
// to the known values for the VBL area. If we enter VBL, we take a timestamp and return -
// or wait for the next VBL if waitFrames>0
// Query current beamposition when entering WaitBlanking:
beampos = PsychGetDisplayBeamPosition(cgDisplayID, windowRecord->screenNumber);
// Are we in VBL when entering WaitBlanking? If so, we should wait for one additional frame,
// because by definition, WaitBlanking should always wait for at least one monitor refresh
// interval...
if ((beampos<=windowRecord->VBL_Endline) && (beampos>=vbl_startline)) waitFrames++;
while(waitFrames > 0) {
// Enough time for a sleep? If the beam is far away from VBL area, we try to sleep to
// yield some CPU time to other processes in the system -- we are nice citizens ;)
beampos = PsychGetDisplayBeamPosition(cgDisplayID, windowRecord->screenNumber);
while (( ((float)(vbl_startline - beampos)) / (float) windowRecord->VBL_Endline * ifi) > 0.003) {
// At least 3 milliseconds left until retrace. We sleep for 1 millisecond.
PsychWaitIntervalSeconds(0.001);
beampos = PsychGetDisplayBeamPosition(cgDisplayID, windowRecord->screenNumber);
}
// Less than 3 ms away from retrace. Busy-Wait for retrace...
lastline = PsychGetDisplayBeamPosition(cgDisplayID, windowRecord->screenNumber);
beampos = lastline;
while ((beampos < vbl_startline) && (beampos >= lastline)) {
lastline = beampos;
beampos = (long) PsychGetDisplayBeamPosition(cgDisplayID, windowRecord->screenNumber);
}
// Retrace! Take system timestamp of VBL onset:
PsychGetAdjustedPrecisionTimerSeconds(&tvbl);
// If this wasn't the last frame to wait, we need to wait for end of retrace before
// repeating the loop, because otherwise we would detect the same VBL and skip frames.
// If it is the last frame, we skip it and return as quickly as possible to save the
// Matlab script some extra Millisecond for drawing...
if (waitFrames>1) {
beampos = vbl_startline;
while ((beampos<=windowRecord->VBL_Endline) && (beampos>=vbl_startline)) { beampos = PsychGetDisplayBeamPosition(cgDisplayID, windowRecord->screenNumber); };
}
// Done with this refresh interval...
// Decrement remaining number of frames to wait:
waitFrames--;
}
}
else if (vblRefCount > 0) {
// Display beamposition queries unsupported, but vblank count queries seem to work. Try those.
// Should work on Linux:
while(waitFrames > 0) {
vblCount = vblRefCount;
// Wait for next vblank counter increment - aka start of next frame (its vblank):
while (vblCount == vblRefCount) {
// Requery:
tvbl = PsychOSGetVBLTimeAndCount(windowRecord, &vblCount);
// Yield at least 100 usecs. This is accurate as this code-path
// only executes on OS/X and Linux, never on Windows (as of 01/06/2011):
PsychYieldIntervalSeconds(0.000100);
}
vblRefCount = vblCount;
// Done with this refresh interval...
// Decrement remaining number of frames to wait:
waitFrames--;
}
}
else {
// Other methods unsupported. We use the doublebuffer swap method of waiting for retrace.
//
// Working principle: On each frame, we first copy the content of the (user visible) frontbuffer into the backbuffer.
// Then we ask the OS to perform a front-backbuffer swap on next vertical retrace and go to sleep via glFinish() et al.
// until the OS signals swap-completion. This way PTB's/Matlabs execution will stall until VBL, when swap happens and
// we get woken up. We repeat this procedure 'waitFrames' times, then we take a high precision timestamp and exit the
// Waitblanking loop. As backbuffer and frontbuffer are identical (due to the copy) at swap time, the visual display
// won't change at all for the subject.
// This method should work reliably, but it has one drawback: A random wakeup delay (scheduling jitter) is added after
// retrace has been entered, so Waitblanking returns only after the beam has left retrace state on older hardware.
// This means a bit less time (1 ms?) for stimulus drawing on Windows than on OS-X where Waitblanking returns faster.
// Child protection:
if (windowRecord->windowType != kPsychDoubleBufferOnscreen) {
PsychErrorExitMsg(PsychError_internal, "WaitBlanking tried to perform swap-waiting on a single buffered window!");
}
// Setup buffers for front->back copy op:
// Backup old read- writebuffer assignments:
glGetIntegerv(GL_READ_BUFFER, &read_buffer);
glGetIntegerv(GL_DRAW_BUFFER, &draw_buffer);
// Set read- and writebuffer properly:
glReadBuffer(GL_FRONT);
glDrawBuffer(GL_BACK);
// Reset viewport to full-window default:
glViewport(0, 0, windowwidth, windowheight);
glScissor(0, 0, windowwidth, windowheight);
// Reset color buffer writemask to "All enabled":
glColorMask(TRUE, TRUE, TRUE, TRUE);
glDisable(GL_BLEND);
glPixelZoom(1,1);
// Disable draw shader:
PsychSetShader(windowRecord, 0);
// Swap-Waiting loop for 'waitFrames' frames:
while(waitFrames > 0) {
// Copy current content of front buffer into backbuffer:
glRasterPos2i(0, windowheight);
glCopyPixels(0, 0, windowwidth, windowheight, GL_COLOR);
// Ok, front- and backbuffer are now identical, so a bufferswap
// will be a visual no-op.
// Enable beamsyncing of bufferswaps to VBL:
PsychOSSetVBLSyncLevel(windowRecord, 1);
// Trigger bufferswap in sync with retrace:
PsychOSFlipWindowBuffers(windowRecord);
// Protect against multi-threading trouble if needed:
PsychLockedTouchFramebufferIfNeeded(windowRecord);
// Wait for swap-completion, aka beginning of VBL:
PsychWaitPixelSyncToken(windowRecord, FALSE);
// VBL happened - Take system timestamp:
PsychGetAdjustedPrecisionTimerSeconds(&tvbl);
// This code-chunk is an alternate way of syncing, only used for debugging:
if (false) {
// Disable beamsyncing of bufferswaps to VBL:
PsychOSSetVBLSyncLevel(windowRecord, 0);
// Swap buffers immediately without vsync:
PsychOSFlipWindowBuffers(windowRecord);
// Protect against multi-threading trouble if needed:
PsychLockedTouchFramebufferIfNeeded(windowRecord);
}
// Decrement remaining number of frames to wait:
waitFrames--;
} // Do it again...
// Enable beamsyncing of bufferswaps to VBL:
PsychOSSetVBLSyncLevel(windowRecord, 1);
// Restore assignment of read- writebuffers and such:
glEnable(GL_BLEND);
glReadBuffer(read_buffer);
glDrawBuffer(draw_buffer);
// Done with Windows waitblanking...
}
// Compute number of frames waited: It is timestamp of return of this waitblanking minus
// timestamp of return of last waitblanking, divided by duration of a monitor refresh
// interval, mathematically rounded to an integral number:
framesWaited = (int) (((tvbl - windowRecord->time_at_last_vbl) / ifi) + 0.5f);
// Update timestamp for next invocation of Waitblanking:
windowRecord->time_at_last_vbl = tvbl;
// Return optional number of frames waited:
PsychCopyOutDoubleArg(1, FALSE, (double) framesWaited);
// Done.
return(PsychError_none);
}
|
// DiscordBotsGGRoundTripper is an http.RoundTripper to mock the response of
// the discord.bots.gg API.
func DiscordBotsGGRoundTripper(t *testing.T) http.RoundTripper {
return roundTripperFunc(
func(req *http.Request) (*http.Response, error) {
defer func() {
closeErr := req.Body.Close()
if closeErr != nil {
t.Errorf("Error closing request body: %s", closeErr)
}
}()
reqBody, err := ioutil.ReadAll(req.Body)
if err != nil {
t.Errorf("Error reading request body: %s", err)
}
reqStats := &api.StatsUpdate{}
err = json.Unmarshal(reqBody, reqStats)
if err != nil {
t.Errorf("Error unmarshaling request body: %s", err)
}
respStats := &api.StatsResponse{
Stats: reqStats.Stats,
}
respBody, err := json.Marshal(respStats)
if err != nil {
t.Errorf("Error marshaling response body: %s", err)
}
return &http.Response{
Status: http.StatusText(http.StatusOK),
StatusCode: http.StatusOK,
Header: make(http.Header),
Request: req,
ContentLength: int64(len(respBody)),
Body: ioutil.NopCloser(bytes.NewReader(respBody)),
}, nil
},
)
}
|
<filename>src/main/java/ui/list_item/TaskItem.java<gh_stars>0
package ui.list_item;
import javafx.geometry.Pos;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.Priority;
import model.Task;
import model.Team;
public class TaskItem {
private Task task;
private Team team;
private TaskItem.OnItemClickListener onItemClickListener;
public TaskItem(Team team, Task task) {
this.task = task;
this.team = team;
}
public void setOnItemClickListener(TaskItem.OnItemClickListener listener) {
this.onItemClickListener = listener;
}
public HBox draw() {
HBox hBox = new HBox();
Pane pane = new Pane();
hBox.setSpacing(10);
Label label;
Label label1;
Label label2;
Label label3;
label = new Label(task.getTitle());
label1 = new Label(task.getPriority());
label2 = new Label(String.format("Team: %s", team.getName()));
label3 = new Label(String.format("Deadline: %s", task.getTimeOfDeadlineFormatted()));
hBox.getStyleClass().add("list-item");
HBox.setHgrow(hBox, Priority.ALWAYS);
hBox.setAlignment(Pos.CENTER_LEFT);
HBox.setHgrow(hBox, Priority.ALWAYS);
HBox.setHgrow(pane, Priority.ALWAYS);
hBox.setOnMouseClicked((event -> onItemClickListener.onClick(this.team, this.task)));
hBox.getChildren().addAll(label, label1, pane, label2, label3);
return hBox;
}
public interface OnItemClickListener {
void onClick(Team team, Task task);
}
}
|
/**
* A thread which does all of the {@link FileSystem}-related operations for
* tasks. It picks the next task in the queue, promotes outputs of
* {@link TaskStatus.State#SUCCEEDED} tasks & discards outputs for
* {@link TaskStatus.State#FAILED} or {@link TaskStatus.State#KILLED} tasks.
*/
private class TaskCommitQueue extends Thread {
private LinkedBlockingQueue<JobInProgress.JobWithTaskContext> queue =
new LinkedBlockingQueue <JobInProgress.JobWithTaskContext>();
public TaskCommitQueue() {
setName("Task Commit Thread");
setDaemon(true);
}
public void addToQueue(JobInProgress.JobWithTaskContext j) {
while (true) { // loop until the element gets added
try {
queue.put(j);
return;
} catch (InterruptedException ie) {}
}
}
@Override
public void run() {
int batchCommitSize = conf.getInt("jobtracker.task.commit.batch.size",
5000);
while (!isInterrupted()) {
try {
ArrayList <JobInProgress.JobWithTaskContext> jobList =
new ArrayList<JobInProgress.JobWithTaskContext>(batchCommitSize);
// Block if the queue is empty
jobList.add(queue.take());
queue.drainTo(jobList, batchCommitSize);
JobInProgress[] jobs = new JobInProgress[jobList.size()];
TaskInProgress[] tips = new TaskInProgress[jobList.size()];
TaskAttemptID[] taskids = new TaskAttemptID[jobList.size()];
JobTrackerMetrics[] metrics = new JobTrackerMetrics[jobList.size()];
Iterator<JobInProgress.JobWithTaskContext> iter = jobList.iterator();
int count = 0;
while (iter.hasNext()) {
JobInProgress.JobWithTaskContext j = iter.next();
jobs[count] = j.getJob();
tips[count] = j.getTIP();
taskids[count]= j.getTaskID();
metrics[count] = j.getJobTrackerMetrics();
++count;
}
Task[] tasks = new Task[jobList.size()];
TaskStatus[] status = new TaskStatus[jobList.size()];
boolean[] isTipComplete = new boolean[jobList.size()];
TaskStatus.State[] states = new TaskStatus.State[jobList.size()];
synchronized (JobTracker.this) {
for(int i = 0; i < jobList.size(); ++i) {
synchronized (jobs[i]) {
synchronized (tips[i]) {
status[i] = tips[i].getTaskStatus(taskids[i]);
tasks[i] = tips[i].getTask(taskids[i]);
states[i] = status[i].getRunState();
isTipComplete[i] = tips[i].isComplete();
}
}
}
}
//For COMMIT_PENDING tasks, we save the task output in the dfs
//as well as manipulate the JT datastructures to reflect a
//successful task. This guarantees that we don't declare a task
//as having succeeded until we have successfully completed the
//dfs operations.
//For failed tasks, we just do the dfs operations here. The
//datastructures updates is done earlier as soon as the failure
//is detected so that the JT can immediately schedule another
//attempt for that task.
Set<TaskID> seenTIPs = new HashSet<TaskID>();
for(int index = 0; index < jobList.size(); ++index) {
try {
if (states[index] == TaskStatus.State.COMMIT_PENDING) {
if (!isTipComplete[index]) {
if (!seenTIPs.contains(tips[index].getTIPId())) {
tasks[index].saveTaskOutput();
seenTIPs.add(tips[index].getTIPId());
} else {
// since other task of this tip has saved its output
isTipComplete[index] = true;
}
}
}
} catch (IOException ioe) {
// Oops! Failed to copy the task's output to its final place;
// fail the task!
states[index] = TaskStatus.State.FAILED;
synchronized (JobTracker.this) {
String reason = "Failed to rename output with the exception: "
+ StringUtils.stringifyException(ioe);
TaskStatus.Phase phase = (tips[index].isMapTask()
? TaskStatus.Phase.MAP
: TaskStatus.Phase.REDUCE);
jobs[index].failedTask(tips[index], status[index].getTaskID(),
reason, phase, TaskStatus.State.FAILED,
status[index].getTaskTracker(), null);
}
LOG.info("Failed to rename the output of "
+ status[index].getTaskID() + " with "
+ StringUtils.stringifyException(ioe));
}
}
synchronized (JobTracker.this) {
//do a check for the case where after the task went to
//COMMIT_PENDING, it was lost. So although we would have
//saved the task output, we cannot declare it a SUCCESS.
for(int i = 0; i < jobList.size(); ++i) {
TaskStatus newStatus = null;
if(states[i] == TaskStatus.State.COMMIT_PENDING) {
synchronized (jobs[i]) {
synchronized (tips[i]) {
status[i] = tips[i].getTaskStatus(taskids[i]);
if (!isTipComplete[i]) {
if (status[i].getRunState()
!= TaskStatus.State.COMMIT_PENDING) {
states[i] = TaskStatus.State.KILLED;
} else {
states[i] = TaskStatus.State.SUCCEEDED;
}
} else {
tips[i].addDiagnosticInfo(tasks[i].getTaskID(),
"Already completed TIP");
states[i] = TaskStatus.State.KILLED;
}
//create new status if required. If the state changed
//from COMMIT_PENDING to KILLED in the JobTracker, while
//we were saving the output,the JT would have called
//updateTaskStatus and we don't need to call it again
newStatus = (TaskStatus)status[i].clone();
newStatus.setRunState(states[i]);
newStatus.setProgress(
(states[i] == TaskStatus.State.SUCCEEDED)
? 1.0f
: 0.0f);
}
if (newStatus != null) {
jobs[i].updateTaskStatus(tips[i], newStatus, metrics[i]);
}
}
}
}
}
} catch (InterruptedException ie) {
break;
}
catch (Throwable t) {
LOG.error(getName() + " got an exception: " +
StringUtils.stringifyException(t));
}
}
LOG.warn(getName() + " exiting...");
}
}
|
use fs::{off_t, FileDesc};
use prelude::*;
use process::{get_current, Process, ProcessRef};
use std::fmt;
// TODO: Rename VMSpace to VMUniverse
#[macro_use]
mod vm_range;
mod process_vm;
mod vm_area;
mod vm_domain;
mod vm_space;
pub use self::process_vm::ProcessVM;
pub use self::vm_range::{VMRange, VMRangeTrait};
// TODO: separate proc and flags
// TODO: accept fd and offset
pub fn do_mmap(addr: usize, size: usize, flags: VMAreaFlags) -> Result<usize, Error> {
let current_ref = get_current();
let mut current_process = current_ref.lock().unwrap();
let current_vm = current_process.get_vm_mut();
current_vm.mmap(addr, size, flags)
}
pub fn do_munmap(addr: usize, size: usize) -> Result<(), Error> {
let current_ref = get_current();
let mut current_process = current_ref.lock().unwrap();
let current_vm = current_process.get_vm_mut();
current_vm.munmap(addr, size)
}
// TODO: accept flags
pub fn do_mremap(
old_addr: usize,
old_size: usize,
options: &VMResizeOptions,
) -> Result<usize, Error> {
let current_ref = get_current();
let mut current_process = current_ref.lock().unwrap();
let current_vm = current_process.get_vm_mut();
current_vm.mremap(old_addr, old_size, options)
}
pub fn do_brk(addr: usize) -> Result<usize, Error> {
let current_ref = get_current();
let mut current_process = current_ref.lock().unwrap();
let current_vm = current_process.get_vm_mut();
current_vm.brk(addr)
}
pub const PAGE_SIZE: usize = 4096;
#[derive(Debug)]
pub struct VMSpace {
range: VMRange,
guard_type: VMGuardAreaType,
}
#[derive(Debug, Default)]
pub struct VMDomain {
range: VMRange,
}
#[derive(Debug, Default)]
pub struct VMArea {
range: VMRange,
flags: VMAreaFlags,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum VMGuardAreaType {
None,
Static { size: usize, align: usize },
Dynamic { size: usize },
}
#[derive(Copy, Clone, Debug, Default, PartialEq)]
pub struct VMAreaFlags(pub u32);
pub const VM_AREA_FLAG_R: u32 = 0x1;
pub const VM_AREA_FLAG_W: u32 = 0x2;
pub const VM_AREA_FLAG_X: u32 = 0x4;
impl VMAreaFlags {
pub fn can_execute(&self) -> bool {
self.0 & VM_AREA_FLAG_X == VM_AREA_FLAG_X
}
pub fn can_write(&self) -> bool {
self.0 & VM_AREA_FLAG_W == VM_AREA_FLAG_W
}
pub fn can_read(&self) -> bool {
self.0 & VM_AREA_FLAG_R == VM_AREA_FLAG_R
}
}
#[derive(Clone, Copy, PartialEq)]
pub struct VMAllocOptions {
size: usize,
addr: VMAddrOption,
growth: Option<VMGrowthType>,
}
impl VMAllocOptions {
pub fn new(size: usize) -> Result<VMAllocOptions, Error> {
if size % PAGE_SIZE != 0 {
return Err(Error::new(Errno::EINVAL, "Size is not page-aligned"));
}
Ok(VMAllocOptions {
size,
..Default::default()
})
}
pub fn addr(&mut self, addr: VMAddrOption) -> Result<&mut Self, Error> {
if addr.is_addr_given() && addr.get_addr() % PAGE_SIZE != 0 {
return Err(Error::new(Errno::EINVAL, "Invalid address"));
}
self.addr = addr;
Ok(self)
}
pub fn growth(&mut self, growth: VMGrowthType) -> Result<&mut Self, Error> {
self.growth = Some(growth);
Ok(self)
}
}
impl fmt::Debug for VMAllocOptions {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"VMAllocOptions {{ size: 0x{:X?}, addr: {:?}, growth: {:?} }}",
self.size, self.addr, self.growth
)
}
}
impl Default for VMAllocOptions {
fn default() -> VMAllocOptions {
VMAllocOptions {
size: 0,
addr: VMAddrOption::Any,
growth: None,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum VMAddrOption {
Any, // Free to choose any address
Hint(usize), // Near the given address
Fixed(usize), // Must be the given address
Beyond(usize), // Must be greater or equal to the given address
}
impl VMAddrOption {
pub fn is_addr_given(&self) -> bool {
match self {
VMAddrOption::Any => false,
_ => true,
}
}
pub fn get_addr(&self) -> usize {
match self {
VMAddrOption::Hint(addr) | VMAddrOption::Fixed(addr) | VMAddrOption::Beyond(addr) => {
*addr
}
VMAddrOption::Any => panic!("No address given"),
}
}
}
/// How VMRange may grow:
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum VMGrowthType {
Upward, // e.g., mmaped regions grow upward
Downward, // e.g., stacks grows downward
Fixed,
}
#[derive(Clone, Debug)]
pub struct VMResizeOptions {
new_size: usize,
new_addr: Option<VMAddrOption>,
}
impl VMResizeOptions {
pub fn new(new_size: usize) -> Result<VMResizeOptions, Error> {
if new_size % PAGE_SIZE != 0 {
return Err(Error::new(Errno::EINVAL, "Size is not page-aligned"));
}
Ok(VMResizeOptions {
new_size,
..Default::default()
})
}
pub fn addr(&mut self, new_addr: VMAddrOption) -> &mut Self {
self.new_addr = Some(new_addr);
self
}
}
impl Default for VMResizeOptions {
fn default() -> VMResizeOptions {
VMResizeOptions {
new_size: 0,
new_addr: None,
}
}
}
|
<filename>models/src/main/java/dev/zacsweers/jsonserialization/models/java_serialization/ResponseJ.java
package dev.zacsweers.jsonserialization.models.java_serialization;
import com.google.gson.annotations.SerializedName;
import com.squareup.moshi.Json;
import java.util.List;
import java.util.Objects;
public class ResponseJ {
public List<UserJ> users = null;
public String status = null;
@SerializedName("is_real_json") // Annotation needed for GSON
@Json(name = "is_real_json")
public boolean isRealJson = false;
@Override public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ResponseJ responseJ = (ResponseJ) o;
return isRealJson == responseJ.isRealJson
&& Objects.equals(users, responseJ.users)
&& Objects.equals(status, responseJ.status);
}
@Override public int hashCode() {
return Objects.hash(users, status, isRealJson);
}
}
|
<filename>app/src/main/java/arl/chronos/EscogerSonido.java
package arl.chronos;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.ContentUris;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;
import java.util.ArrayList;
import arl.chronos.adapters.RcvAdapterSonidos;
import arl.chronos.service.ServicioSonido;
import arl.chronos.classes.Sonido;
public class EscogerSonido extends AppCompatActivity {
private String nombreSonido;
private Button aceptar;
private Button cancelar;
private TextView sonidoElegido;
private RecyclerView recyclerView;
private RcvAdapterSonidos rcvAdapterSonidos;
private RecyclerView.LayoutManager layoutManager;
private ArrayList<Sonido> sonidoList;
private String selector;
public static final String EXTRA_NOMBRE_SONIDO = "arl.chronos.EXTRA_NOMBRE_SONIDO";
public static final String EXTRA_URI_SONIDO = "arl.chronos.EXTRA_URI_SONIDO";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.escoger_sonido);
selector = getIntent().getStringExtra("selector");
aceptar = findViewById(R.id.btn_aceptar_sonido);
cancelar = findViewById(R.id.btn_cancelar_sonido);
sonidoElegido = findViewById(R.id.tv_sonido_elegido);
sonidoList = getSonidoList();
recyclerView = findViewById(R.id.rcv_sonidos);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
rcvAdapterSonidos = new RcvAdapterSonidos();
recyclerView.setAdapter(rcvAdapterSonidos);
rcvAdapterSonidos.setSonidos(sonidoList);
rcvAdapterSonidos.setOnSonidoClickListener(new RcvAdapterSonidos.OnSonidoClickListener() {
@Override
public void onSonidoClick(String nombreSonido, String sonidoUri) {
sonidoElegido.setText(nombreSonido);
aceptar.setEnabled(true);
Log.d("EscogerSonido", "sonidoElegido = " + sonidoElegido);
Log.d("EscogerSonido", "sonidoUri = " + sonidoUri);
Intent intentServicio = new Intent(getApplicationContext(), ServicioSonido.class);
intentServicio.putExtra(EXTRA_NOMBRE_SONIDO, nombreSonido);
intentServicio.putExtra(EXTRA_URI_SONIDO, sonidoUri);
intentServicio.setAction(".classes.ServicioSonido");
startService(intentServicio);
}
});
cancelar.setOnClickListener(view -> {
Intent intentServicio = new Intent(getApplicationContext(), ServicioSonido.class);
intentServicio.setAction(".classes.ServicioSonido");
stopService(intentServicio);
Intent intent = new Intent(this, CrearEditarAlarma.class);
startActivity(intent);
});
if (sonidoElegido.getText().equals(getResources().getString(R.string.tv_ningun_sonido))) {
aceptar.setEnabled(false);
}
aceptar.setOnClickListener(view -> {
Intent intentServicio = new Intent(getApplicationContext(), ServicioSonido.class);
intentServicio.setAction(".classes.ServicioSonido");
stopService(intentServicio);
nombreSonido = sonidoElegido.getText().toString();
Intent intent = new Intent(this, CrearEditarAlarma.class);
intent.putExtra(EXTRA_NOMBRE_SONIDO, nombreSonido);
intent.putExtra(EXTRA_URI_SONIDO, localizarSonido(nombreSonido).toString()); // Se transforma la URI en String
setResult(RESULT_OK, intent);
finish();
});
}
public ArrayList<Sonido> getSonidoList() {
ArrayList<Sonido> sonidoList = new ArrayList<>();
Uri sonidos;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
sonidos = MediaStore.Audio.Media.getContentUri(MediaStore.VOLUME_INTERNAL);
} else {
if (selector.equals("system")) {
sonidos = MediaStore.Audio.Media.INTERNAL_CONTENT_URI;
} else {
sonidos = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
}
String[] columnas = new String[]{
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.TITLE
};
String ordenarSonido = MediaStore.Audio.Media.TITLE + " ASC";
try (Cursor cursor = getApplicationContext().getContentResolver().query(
sonidos, columnas, null, null, ordenarSonido
)) {
int idColumna = cursor.getColumnIndex(MediaStore.Audio.Media._ID);
int nombreColumna = cursor.getColumnIndex(MediaStore.Audio.Media.TITLE);
while (cursor.moveToNext()) {
// Obtiene los valores de las columnas del audio de turno
long id = cursor.getLong(idColumna);
String nombre = cursor.getString(nombreColumna);
Uri contentUri = null;
if (selector.equals("system")) {
contentUri = ContentUris.withAppendedId(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, id);
} else {
contentUri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, id);
}
// Guarda los valores de las columnas de contenUri en la lista.
sonidoList.add(new Sonido(contentUri, nombre));
}
}
return sonidoList;
}
// Busca y devuelve la Uri con el nombre de la canción/sonido elegido
private Uri localizarSonido(String nombreSonido) {
int s = 0;
for (int i = 0; i < sonidoList.size(); i++) {
if (sonidoList.get(i).getNombre().equals(nombreSonido)) {
s = i;
}
}
return sonidoList.get(s).getUri();
}
}
|
// Add a super, only a existing super can add a new and the super is not existed
func (k Keeper) AddSuper(ctx sdk.Context, super types.Super) {
store := ctx.KVStore(k.storeKey)
bz := k.cdc.MustMarshal(&super)
address, _ := sdk.AccAddressFromBech32(super.Address)
store.Set(types.GetSuperKey(address), bz)
}
|
<reponame>nagineni/chromium-crosswalk<gh_stars>0
// Copyright 2013 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.
#include <string>
#include "chrome/browser/extensions/activity_log/activity_log.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/extensions/extension_builder.h"
#include "net/dns/mock_host_resolver.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "net/test/embedded_test_server/http_request.h"
#include "net/test/embedded_test_server/http_response.h"
using net::test_server::BasicHttpResponse;
using net::test_server::HttpResponse;
using net::test_server::HttpRequest;
namespace extensions {
class ActivityLogApiTest : public ExtensionApiTest {
public:
ActivityLogApiTest() : saved_cmdline_(CommandLine::NO_PROGRAM) {}
virtual ~ActivityLogApiTest() {
ExtensionApiTest::SetUpCommandLine(&saved_cmdline_);
*CommandLine::ForCurrentProcess() = saved_cmdline_;
}
virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
ExtensionApiTest::SetUpCommandLine(command_line);
saved_cmdline_ = *CommandLine::ForCurrentProcess();
command_line->AppendSwitch(switches::kEnableExtensionActivityLogging);
}
scoped_ptr<HttpResponse> HandleRequest(const HttpRequest& request) {
scoped_ptr<BasicHttpResponse> response(new BasicHttpResponse);
response->set_code(net::HTTP_OK);
response->set_content("<html><head><title>ActivityLogTest</title>"
"</head><body>Hello World</body></html>");
return response.PassAs<HttpResponse>();
}
private:
CommandLine saved_cmdline_;
};
#if defined(OS_WIN) && !defined(NDEBUG)
// TODO(karenlees): fix flakiness on win debug - crbug.com/299393
#define MAYBE_TriggerEvent DISABLED_TriggerEvent
#else
// Disabled while waiting for Blink roll to avoid
// https://codereview.chromium.org/52203002
#define MAYBE_TriggerEvent DISABLED_TriggerEvent
#endif
// The test extension sends a message to its 'friend'. The test completes
// if it successfully sees the 'friend' receive the message.
IN_PROC_BROWSER_TEST_F(ActivityLogApiTest, MAYBE_TriggerEvent) {
ActivityLog::GetInstance(profile())->SetWatchdogAppActive(true);
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(StartEmbeddedTestServer());
embedded_test_server()->RegisterRequestHandler(
base::Bind(&ActivityLogApiTest::HandleRequest, base::Unretained(this)));
const Extension* friend_extension = LoadExtensionIncognito(
test_data_dir_.AppendASCII("activity_log_private/friend"));
ASSERT_TRUE(friend_extension);
ASSERT_TRUE(RunExtensionTest("activity_log_private/test"));
ActivityLog::GetInstance(profile())->SetWatchdogAppActive(false);
}
} // namespace extensions
|
def randWarp(win):
C = 0.1
ang = np.random.uniform(-1. * C, C)
s = np.sin(ang)
c = np.cos(ang)
warp_transform = \
np.array([[c + np.random.uniform(-1. * C, C), -s + np.random.uniform(-1. * C, C), 0.], \
[s + np.random.uniform(-1. * C, C), c + np.random.uniform(-1. * C, C), 0.]])
h, w = win.shape
center_warp = np.array([[w/2], [h/2]])
warp_transform[:,2:] = center_warp - warp_transform[:,:2].dot(center_warp)
return cv.warpAffine(win, M=warp_transform, dsize=(w, h), borderMode=cv.BORDER_REFLECT)
|
Max Biaggi and Aprilia have been enjoying an exclusive four-day World Superbike test at Losail ahead of the season fianle in Qatar next weekend.
Last week the two-time World Superbike champion announced via Twitter he would be back with the Aprilia Racing Team for the final round of the season having previously made his return from retirement at Misano and Sepang, grabbing a podium finish in race one in Malaysia.
The 44-year-old Italian is currently running a four-day test at the Losail International Circuit on the outskirts of Doha which concludes on Thursday (8th October) ahead of next week's final round.
Biaggi will naturally be aiming for a return to the podium once again but says riding at night provides its own challenge along with recovering from a shoulder injury which was sustained in a training accident before the Malaysian World Superbike round.
"Riding at night absolutely fascinates me," Biaggi told worldsbk.com. "The eyes need to get accustomed to these enormously bright floodlights, which are really powerful. It seems like it's daytime.
"So far we can say that the weather conditions we've found here are not the best. It is hot, with temperatures of 40 degrees Celsius during the day; even at night, around 10 or 11 o'clock, we've got 35 degrees and 80% humidity. These are extreme conditions and being the only one out on track means the surface is not very clean and it will be difficult to improve.
"I'm happy with how the shoulder is. It's not as strong as before but at least it is no longer hurting."
|
import os
import numpy as np
import pandas as pd
import random
import cv2
import csv
import glob
from sklearn import model_selection
from keras import backend as K
from keras import models, optimizers
from keras.models import Sequential
from keras.layers import Conv2D, Cropping2D, Dense, Dropout, Flatten, Lambda, Activation, MaxPooling2D, Reshape
from keras.optimizers import Adam
from keras.utils.np_utils import to_categorical
from keras.callbacks import ModelCheckpoint
ROOT_PATH = './'
BATCH_SIZE = 4
EPOCHS = 15
IMAGE_HEIGHT = 600
IMAGE_WIDTH = 800
IMAGE_CHANNEL = 3
TOP_CROP = 266
BOTTOM_CROP = 326
MODEL_FILE_NAME = './sim_tl_classifier.h5'
# check for GPU
from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())
# if not os.path.exists('./traffic_light.csv'):
# with open('traffic_light.csv', 'w', newline='') as csvfile:
# mywriter = csv.writer(csvfile)
# mywriter.writerow(['path', 'class', 'color'])
# for myclass, directory in enumerate(['nolight', 'red', 'yellow', 'green']):
# for filename in glob.glob('./data/real_training_data/{}/*.jpg'.format(directory)):
# filename = '/'.join(filename.split('\\'))
# mywriter.writerow([filename, myclass, directory])
# print('CSV file created successfully')
# else:
# print('CSV already present')
def random_brightness(image):
# Convert 2 HSV colorspace from RGB colorspace
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
# Generate new random brightness
rand = random.uniform(0.3, 1.0)
hsv[:, :, 2] = rand*hsv[:, :, 2]
# Convert back to RGB colorspace
new_img = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)
return new_img
def zoom(image):
zoom_pix = random.randint(0, 10)
zoom_factor = 1 + (2*zoom_pix)/IMAGE_HEIGHT
image = cv2.resize(image, None, fx=zoom_factor,
fy=zoom_factor, interpolation=cv2.INTER_LINEAR)
top_crop = (image.shape[0] - IMAGE_HEIGHT)//2
# bottom_crop = image.shape[0] - top_crop - IMAGE_HEIGHT
left_crop = (image.shape[1] - IMAGE_WIDTH)//2
# right_crop = image.shape[1] - left_crop - IMAGE_WIDTH
image = image[top_crop: top_crop+IMAGE_HEIGHT,
left_crop: left_crop+IMAGE_WIDTH]
return image
# fuction to read image from file
def get_image(index, data, should_augment):
# Read image and appropiately traffic light color
image = cv2.imread(os.path.join(
ROOT_PATH, data['path'].values[index].strip()))
color = data['class'].values[index]
lucky = random.randint(0, 1)
too_lucky = random.randint(0, 1)
unlucky = random.randint(0, 1)
if should_augment:
if lucky == 1:
image = random_brightness(image)
if too_lucky == 1:
image = cv2.flip(image, 1)
if not unlucky == 1:
image = zoom(image)
return [image, color]
# generator function to return images batchwise
def generator(data, should_augment=False):
while True:
# Randomize the indices to make an array
indices_arr = np.random.permutation(data.count()[0])
for batch in range(0, len(indices_arr), BATCH_SIZE):
# slice out the current batch according to batch-size
current_batch = indices_arr[batch:(batch + BATCH_SIZE)]
# initializing the arrays, x_train and y_train
x_train = np.empty(
[0, IMAGE_HEIGHT, IMAGE_WIDTH, IMAGE_CHANNEL], dtype=np.float32)
y_train = np.empty([0], dtype=np.int32)
for i in current_batch:
# get an image and its corresponding color for an traffic light
[image, color] = get_image(i, data, should_augment)
# Appending them to existing batch
x_train = np.append(x_train, [image], axis=0)
y_train = np.append(y_train, [color])
y_train = to_categorical(y_train, num_classes=4)
yield (x_train, y_train)
def get_model(time_len=1):
model = Sequential()
model.add(Cropping2D(cropping=((0, 0), (0, 0)),
input_shape=(IMAGE_HEIGHT, IMAGE_WIDTH, IMAGE_CHANNEL)))
model.add(Lambda(lambda x: x/127.5 - 1.))
model.add(Conv2D(32, 8, strides=(4, 4), padding="same", activation='relu'))
model.add(MaxPooling2D(2, 2))
model.add(Conv2D(32, 4, strides=(2, 2), padding="same", activation='relu'))
model.add(MaxPooling2D(2, 2))
# model.add(Conv2D(64, 5, strides=(2, 2), padding="same", activation='relu'))
model.add(Flatten())
model.add(Dropout(.35))
model.add(Dense(128, activation='relu'))
model.add(Dropout(.5))
model.add(Dense(4))
# model.add(Lambda(lambda x: (K.exp(x) + 1e-4) / (K.sum(K.exp(x)) + 1e-4)))
model.add(Lambda(lambda x: K.tf.nn.softmax(x)))
model.compile(optimizer=Adam(lr=1e-4),
loss='categorical_crossentropy', metrics=['accuracy'])
model.summary()
return model
if __name__ == "__main__":
data = pd.read_csv(os.path.join('./sim_traffic_light_train.csv'))
# Split data into random training and validation sets
d_train, d_valid = model_selection.train_test_split(data, test_size=.2)
train_gen = generator(d_train, False)
validation_gen = generator(d_valid, False)
model = get_model()
# checkpoint to save best weights after each epoch based on the improvement in val_loss
checkpoint = ModelCheckpoint(MODEL_FILE_NAME, monitor='val_loss', verbose=1,save_best_only=True, mode='min',save_weights_only=False)
callbacks_list = [checkpoint] #,callback_each_epoch]
print('Training started....')
history = model.fit_generator(
train_gen,
steps_per_epoch=len(d_train)//BATCH_SIZE,
epochs=EPOCHS,
validation_data=validation_gen,
validation_steps=len(d_valid)//BATCH_SIZE,
verbose=1,
callbacks=callbacks_list
)
# print("Saving model..")
# model.save("./tl_classifier_keras.h5")
# print("Model Saved successfully!!")
# Destroying the current TF graph to avoid clutter from old models / layers
K.clear_session()
|
<gh_stars>0
package com.show.tt.ui.widget.message;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import com.show.tt.DB.entity.MessageEntity;
import com.show.tt.DB.entity.UserEntity;
import com.show.tt.R;
import com.show.tt.imservice.entity.ImageMessage;
import com.show.tt.ui.widget.GifLoadTask;
import com.show.tt.ui.widget.GifView;
/**
* Created by zhujian on 15/3/26.
*/
public class GifImageRenderView extends BaseMsgRenderView {
private GifView messageContent;
public GifView getMessageContent()
{
return messageContent;
}
public static GifImageRenderView inflater(Context context,ViewGroup viewGroup,boolean isMine){
int resource = isMine? R.layout.tt_mine_gifimage_message_item :R.layout.tt_other_gifimage_message_item;
GifImageRenderView gifRenderView = (GifImageRenderView) LayoutInflater.from(context).inflate(resource, viewGroup, false);
gifRenderView.setMine(isMine);
return gifRenderView;
}
public GifImageRenderView(Context context, AttributeSet attrs) {
super(context, attrs);
}
protected void onFinishInflate() {
super.onFinishInflate();
messageContent = (GifView) findViewById(R.id.message_image);
}
/**
* 控件赋值
* @param messageEntity
* @param userEntity
*/
@Override
public void render(MessageEntity messageEntity, UserEntity userEntity,Context context) {
super.render(messageEntity, userEntity,context);
ImageMessage imageMessage = (ImageMessage) messageEntity;
String url = imageMessage.getUrl();
new GifLoadTask() {
@Override
protected void onPostExecute(byte[] bytes) {
messageContent.setBytes(bytes);
messageContent.startAnimation();
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
}.execute(url);
}
@Override
public void msgFailure(MessageEntity messageEntity) {
super.msgFailure(messageEntity);
}
/**----------------set/get---------------------------------*/
public void setMine(boolean isMine) {
this.isMine = isMine;
}
public void setParentView(ViewGroup parentView) {
this.parentView = parentView;
}
}
|
//
// GBAEmulationViewController.h
// GBA4iOS
//
// Created by <NAME> on 7/19/13.
// Copyright (c) 2013 <NAME>. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "GBAROM.h"
@interface GBAEmulationViewController : UIViewController
@property (strong, nonatomic) GBAROM *rom;
@property (assign, nonatomic) CGFloat blurAlpha;
@property (strong, nonatomic) UIImageView *blurredContentsImageView;
- (void)showSplashScreen;
- (void)blurWithInitialAlpha:(CGFloat)alpha;
- (void)removeBlur;
- (void)refreshLayout;
- (void)pauseEmulation;
- (void)resumeEmulation;
- (void)prepareAndPresentViewController:(UIViewController *)viewController;
- (void)prepareForDismissingPresentedViewController:(UIViewController *)dismissedViewController;
- (void)autoSaveIfPossible;
- (void)launchGameWithCompletion:(void (^)(void))completionBlock;
@end
|
from operator import itemgetter
import itertools
class Light:
def __init__(self, _switch_list: list, p: int):
self.switch_list = _switch_list
self.p = p
def is_on(self, all_switch_states: list) -> int:
implemented_switches = itemgetter(*self.switch_list)(all_switch_states)
if isinstance(implemented_switches, int):
return implemented_switches == self.p
else:
return sum(implemented_switches) % 2 == self.p
if __name__ == '__main__':
i = input()
switch_total_number = int(i.split()[0])
lights_total_number = int(i.split()[1])
lines = [input() for i in range(lights_total_number)]
p_list = [int(x) for x in input().split()]
lights = []
for index, line in enumerate(lines):
switch_list = [int(x)-1 for x in line.split()]
del switch_list[0]
lights.append(Light(switch_list, p_list[index]))
number_of_all_on = 0
switch_pattern_iter = itertools.product([1, 0], repeat=switch_total_number)
for switch_pattern in switch_pattern_iter:
for light in lights:
if not light.is_on(list(switch_pattern)):
break
else:
number_of_all_on += 1
print(number_of_all_on)
|
//package robotcollisions;
import java.util.*;
import java.io.*;
public class robotcollosions {
static int[] ans;
static boolean[] v;
static int m;
public static void solve(int[][] robots) {
//System.out.println("FUNCTION CALL");
TreeSet<int[]> left = new TreeSet<int[]>((a, b) -> a[0] - b[0]);
TreeSet<int[]> right = new TreeSet<int[]>((a, b) -> a[0] - b[0]);
for(int i = 0; i < robots.length; i++) {
if(robots[i][1] == 0) {
left.add(new int[] {robots[i][0], robots[i][2]});
}
else {
right.add(new int[] {robots[i][0], robots[i][2]});
}
}
//System.out.print("LEFT: ");
// for(int[] i : left) {
// //System.out.print("[" + i[0] + ", " + i[1] + "] ");
// }
//System.out.println();
//System.out.print("RIGHT: ");
// for(int[] i : right) {
// //System.out.print("[" + i[0] + ", " + i[1] + "] ");
// }
//System.out.println();
int[] pointer = new int[] {0, 0};
while(left.ceiling(pointer) != null) {
pointer = left.ceiling(pointer);
////System.out.println(pointer[0] + " " + pointer[1]);
if(right.floor(pointer) != null) {
int[] next = right.floor(pointer);
left.remove(pointer);
right.remove(next);
ans[pointer[1]] = (pointer[0] - next[0]) / 2;
ans[next[1]] = (pointer[0] - next[0]) / 2;
}
else {
pointer = new int[] {pointer[0] + 1, pointer[1]};
}
}
//System.out.println("REMAINING LEFT: " + left.size() + " REMAINING RIGHT: " + right.size());
while(left.size() > 1) {
int[] a = left.pollFirst();
int[] b = left.pollFirst();
ans[a[1]] = (a[0] + b[0]) / 2;
ans[b[1]] = (a[0] + b[0]) / 2;
//System.out.println("LEFTWARDS: " + a[0] + " " + b[0] + " " + v.length);
}
while(right.size() > 1) {
int[] a = right.pollLast();
int[] b = right.pollLast();
ans[a[1]] = ((m - a[0]) + (m - b[0])) / 2;
ans[b[1]] = ((m - a[0]) + (m - b[0])) / 2;
}
if(left.size() == 1 && right.size() == 1) {
int[] a = right.pollLast();
int[] b = left.pollFirst();
//System.out.println("FINAL CLAUSE: " + (m + (m - a[0])) + " " + b[0] + " " + a[0] + " " + b[0]);
ans[a[1]] = (m + (m - a[0]) + b[0]) / 2;
ans[b[1]] = (m + (m - a[0]) + b[0]) / 2;
}
//System.out.println();
}
public static void main(String[] args) throws IOException {
BufferedReader fin = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(fin.readLine());
StringBuilder fout = new StringBuilder();
while(t-- > 0) {
StringTokenizer st = new StringTokenizer(fin.readLine());
int n = Integer.parseInt(st.nextToken());
m = Integer.parseInt(st.nextToken());
int[] nums = new int[n];
char[] directions = new char[n];
st = new StringTokenizer(fin.readLine());
StringTokenizer st2 = new StringTokenizer(fin.readLine());
int numEven = 0;
for(int i = 0; i < n; i++) {
nums[i] = Integer.parseInt(st.nextToken());
directions[i] = st2.nextToken().charAt(0);
if(nums[i] % 2 == 0) {
numEven ++;
}
}
ans = new int[n];
v = new boolean[n];
Arrays.fill(ans, -1);
int[][] next = new int[numEven][3]; //initial position, direction, id
int pointer = 0;
//System.out.print("INPUT EVEN: ");
for(int i = 0; i < n; i++) {
if(nums[i] % 2 == 0) {
//System.out.print("{" + nums[i] + ", " + directions[i] + "} ");
next[pointer][0] = nums[i];
next[pointer][1] = directions[i] == 'R'? 1 : 0; //1 for right, 0 for left
next[pointer][2] = i;
pointer ++;
}
}
//System.out.println();
Arrays.sort(next, (a, b) -> a[0] - b[0]);
solve(next);
next = new int[n - numEven][3];
pointer = 0;
//System.out.print("INPUT ODD: ");
for(int i = 0; i < n; i++) {
if(nums[i] % 2 == 1) {
//System.out.print("{" + nums[i] + ", " + directions[i] + "} ");
next[pointer][0] = nums[i];
next[pointer][1] = directions[i] == 'R'? 1 : 0; //1 for right, 0 for left
next[pointer][2] = i;
pointer ++;
}
}
//System.out.println();
Arrays.sort(next, (a, b) -> a[0] - b[0]);
solve(next);
for(int i : ans) {
fout.append(i).append(" ");
}
fout.append("\n");
////System.out.print(fout);;
}
System.out.print(fout);
}
}
|
/**
* Find the intersection of the bounding box and the line formed by the two
* points. If known, the first point should be the point inside the bounding
* box while the second should be the point outside. And this should only be
* called when you know there is an intersection otherwise null will be
* returned.
*
* @param bbox The GeographicBoundingBox to check against.
* @param pointA The first point in the line (inside point).
* @param pointB The second point in the line (outside point).
* @return The position of the intersection (or null if intersection not
* found).
*/
private static GeographicPosition findIntersection(GeographicBoundingBox bbox, Vector2d pointA, Vector2d pointB)
{
GeographicPosition geoPos = null;
Line2d southLine = createLine(bbox.getLowerLeft(), bbox.getLowerRight());
Line2d westLine = createLine(bbox.getLowerLeft(), bbox.getUpperLeft());
Line2d northLine = createLine(bbox.getUpperLeft(), bbox.getUpperRight());
Line2d eastLine = createLine(bbox.getUpperRight(), bbox.getLowerRight());
if (Math.signum(pointA.getX()) != Math.signum(pointB.getX()) && Math.abs(pointA.getX()) > 170)
{
double boundary = 180 * Math.signum(pointA.getX());
geoPos = new GeographicPosition(
LatLonAlt.createFromDegreesMeters(pointA.getY(), boundary, ALTM, Altitude.ReferenceLevel.TERRAIN));
}
else
{
if (LineSegment2d.segmentsIntersect(bbox.getLowerLeft().getLatLonAlt().asVec2d(),
bbox.getLowerRight().getLatLonAlt().asVec2d(), pointA, pointB))
{
List<? extends Vector2d> intersection = southLine.getSegmentIntersection(pointA, pointB);
if (intersection.size() == 1)
{
return new GeographicPosition(LatLonAlt.createFromDegreesMeters(intersection.get(0).getY(),
intersection.get(0).getX(), ALTM, Altitude.ReferenceLevel.TERRAIN));
}
}
if (LineSegment2d.segmentsIntersect(bbox.getLowerLeft().getLatLonAlt().asVec2d(),
bbox.getUpperLeft().getLatLonAlt().asVec2d(), pointA, pointB))
{
List<? extends Vector2d> intersection = westLine.getSegmentIntersection(pointA, pointB);
if (intersection.size() == 1)
{
return new GeographicPosition(LatLonAlt.createFromDegreesMeters(intersection.get(0).getY(),
intersection.get(0).getX(), ALTM, Altitude.ReferenceLevel.TERRAIN));
}
}
if (LineSegment2d.segmentsIntersect(bbox.getUpperLeft().getLatLonAlt().asVec2d(),
bbox.getUpperRight().getLatLonAlt().asVec2d(), pointA, pointB))
{
List<? extends Vector2d> intersection = northLine.getSegmentIntersection(pointA, pointB);
if (intersection.size() == 1)
{
return new GeographicPosition(LatLonAlt.createFromDegreesMeters(intersection.get(0).getY(),
intersection.get(0).getX(), ALTM, Altitude.ReferenceLevel.TERRAIN));
}
}
if (LineSegment2d.segmentsIntersect(bbox.getUpperRight().getLatLonAlt().asVec2d(),
bbox.getLowerRight().getLatLonAlt().asVec2d(), pointA, pointB))
{
List<? extends Vector2d> intersection = eastLine.getSegmentIntersection(pointA, pointB);
if (intersection.size() == 1)
{
geoPos = new GeographicPosition(LatLonAlt.createFromDegreesMeters(intersection.get(0).getY(),
intersection.get(0).getX(), ALTM, Altitude.ReferenceLevel.TERRAIN));
}
}
}
return geoPos;
}
|
/* eslint-disable @typescript-eslint/no-non-null-assertion */
import {
$el,
bind,
getBooleanTypeAttr,
getNumTypeAttr,
getStrTypeAttr,
removeAttrs,
setHtml
} from '../../dom-utils';
import { warn } from '../../mixins';
import { type, validComps } from '../../utils';
import PREFIX from '../prefix';
interface Config {
config(
el: string
): {
value: number;
step: number;
disabled: boolean;
readOnly: boolean;
editable: boolean;
events({ onChange, onFocus, onBlur }: InputNumberEvents): void;
};
}
interface InputNumberEvents {
onChange?: (value: number) => void;
onFocus?: (event: InputEvent) => void;
onBlur?: () => void;
}
function addNum(num1: number, num2: number): number {
let sq1: number, sq2: number;
try {
sq1 = num1.toString().split('.')[1].length;
} catch (e) {
sq1 = 0;
}
try {
sq2 = num2.toString().split('.')[1].length;
} catch (e) {
sq2 = 0;
}
const m = Math.pow(10, Math.max(sq1, sq2));
return (Math.round(num1 * m) + Math.round(num2 * m)) / m;
}
class InputNumber implements Config {
readonly VERSION: string;
readonly COMPONENTS: NodeListOf<HTMLElement>;
constructor() {
this.VERSION = 'v1.0';
this.COMPONENTS = $el('r-input-number', { all: true });
this._create(this.COMPONENTS);
}
public config(
el: string
): {
value: number;
step: number;
disabled: boolean;
readOnly: boolean;
editable: boolean;
events({ onChange, onFocus, onBlur }: InputNumberEvents): void;
} {
const target = $el(el) as HTMLElement;
validComps(target, 'input-number');
const { _attrs, _setValue, _setDisabled } = InputNumber.prototype;
const { min, max, step, disabled, readOnly, editable, precision, formatter } = _attrs(
target
);
const Input = target.querySelector(`.${PREFIX.inputnb}-input`)! as HTMLInputElement;
const ArrowUp = target.querySelector(`.${PREFIX.inputnb}-handler-up`);
const ArrowDown = target.querySelector(`.${PREFIX.inputnb}-handler-down`);
const BtnUp = target.querySelector(`.${PREFIX.inputnb}-controls-outside-up`);
const BtnDown = target.querySelector(`.${PREFIX.inputnb}-controls-outside-down`);
return {
get value() {
return Number(Input.value);
},
set value(newVal: number) {
if (newVal && !type.isNum(newVal)) return;
_setValue(Input, newVal, formatter, precision, min, max);
},
get step() {
return step;
},
set step(newVal: number) {
if (newVal && !type.isNum(newVal)) return;
Input.step = step;
},
get disabled() {
return disabled;
},
set disabled(newVal: boolean) {
if (newVal && !type.isBol(newVal)) return;
_setDisabled(target, Input, newVal);
},
get readOnly() {
return readOnly;
},
set readOnly(newVal: boolean) {
if (newVal && !type.isBol(newVal)) return;
Input.readOnly = newVal;
const disableArrow = (elem1: Element | null, elem2: Element | null) => {
if (elem1) {
// @ts-ignore
elem1.style.pointerEvents = newVal ? 'none' : '';
// @ts-ignore
elem2.style.pointerEvents = newVal ? 'none' : '';
}
};
disableArrow(ArrowUp, ArrowDown);
disableArrow(BtnUp, BtnDown);
},
get editable() {
return editable;
},
set editable(newVal: boolean) {
if (newVal && !type.isBol(newVal)) return;
Input.style.pointerEvents = !newVal ? 'none' : '';
},
events({ onChange, onFocus, onBlur }) {
let value: number;
const changeEv = (e: Event) => {
e.stopPropagation();
value = Number(Input.value);
if (!isNaN(value)) {
onChange && type.isFn(onChange, value);
} else {
warn(`Invalid input value --> '${Input.value}' at '${el}'`);
return;
}
};
if (ArrowUp) {
bind(ArrowUp, 'click', changeEv);
bind(ArrowDown, 'click', changeEv);
}
if (BtnUp) {
bind(BtnUp, 'click', changeEv);
bind(BtnDown, 'click', changeEv);
}
bind(Input, 'keydown', (e: KeyboardEvent) => {
if (e.key === 'ArrowUp' || e.key === 'ArrowDown') changeEv(e);
});
bind(Input, 'input', (e: InputEvent) => changeEv(e));
bind(Input, 'focus', (e: InputEvent) => {
e.stopPropagation();
onFocus && type.isFn(onFocus, e);
});
bind(Input, 'blur', (e: InputEvent) => {
e.stopPropagation();
onBlur && type.isFn(onBlur);
});
}
};
}
private _create(COMPONENTS: NodeListOf<HTMLElement>) {
COMPONENTS.forEach((node) => {
const {
min,
max,
step,
value,
name,
inputId,
parser,
formatter,
precision,
disabled,
editable,
readOnly,
size,
placeholder,
controlsOutside
} = this._attrs(node);
this._setMainTemplate(node);
this._setOutSide(node, controlsOutside);
const Input = node.querySelector(`.${PREFIX.inputnb}-input`)! as HTMLInputElement;
const ArrowUp = node.querySelector(`.${PREFIX.inputnb}-handler-up`);
const ArrowDown = node.querySelector(`.${PREFIX.inputnb}-handler-down`);
const BtnUp = node.querySelector(`.${PREFIX.inputnb}-controls-outside-up`);
const BtnDown = node.querySelector(`.${PREFIX.inputnb}-controls-outside-down`);
this._setInput(Input, min, max, step, name, inputId, placeholder);
this._setValue(Input, value, formatter, precision, min, max);
this._setSize(node, size);
this._setDisabled(node, Input, disabled);
this._setReadonlyAndEditable(Input, readOnly, editable);
this._setHandler(ArrowUp, ArrowDown, BtnUp, BtnDown, value, min, max);
this._handleChange(
Input,
ArrowUp,
ArrowDown,
BtnUp,
BtnDown,
min,
max,
step,
precision,
readOnly,
parser,
formatter
);
removeAttrs(node, [
'min',
'max',
'step',
'value',
'precision',
'size',
'name',
'parser',
'formatter',
'input-id',
'placeholder',
'disabled',
'editable',
'readOnly',
'controls-outside'
]);
});
}
private _setMainTemplate(node: HTMLElement): void {
node.classList.add(`${PREFIX.inputnb}`);
const template = `
<div class="${PREFIX.inputnb}-handler-wrap">
<a class="${PREFIX.inputnb}-handler ${PREFIX.inputnb}-handler-up">
<span class="${PREFIX.inputnb}-handler-up-inner ${PREFIX.icon} ${PREFIX.icon}-ios-arrow-up"></span>
</a>
<a class="${PREFIX.inputnb}-handler ${PREFIX.inputnb}-handler-down">
<span class="${PREFIX.inputnb}-handler-down-inner ${PREFIX.icon} ${PREFIX.icon}-ios-arrow-down"></span>
</a>
</div>
<div class="${PREFIX.inputnb}-input-wrap">
<input autocomplete="off" spellcheck="false" class="${PREFIX.inputnb}-input">
</div>
`;
setHtml(node, template);
}
private _setOutSide(node: HTMLElement, controlsOutside: boolean): void {
if (!controlsOutside) return;
node.classList.add(`${PREFIX.inputnb}-controls-outside`);
const handlerWrap = node.querySelector(`.${PREFIX.inputnb}-handler-wrap`)!;
const template = `
<div class="${PREFIX.inputnb}-controls-outside-btn ${PREFIX.inputnb}-controls-outside-down">
<i class="${PREFIX.icon} ${PREFIX.icon}-ios-remove"></i>
</div>
<div class="${PREFIX.inputnb}-controls-outside-btn ${PREFIX.inputnb}-controls-outside-up">
<i class="${PREFIX.icon} ${PREFIX.icon}-ios-add"></i>
</div>
`;
handlerWrap.insertAdjacentHTML('afterend', template);
handlerWrap.remove();
}
private _setInput(
input: HTMLInputElement,
min: number,
max: number,
step: number,
name: string,
inputId: string,
placeholder: string
): void {
isNaN(min) || min === 0 ? (input.min = `${min}`) : '';
isNaN(max) || min === 0 ? (input.max = `${max}`) : '';
isNaN(step) && step !== 1 ? (input.step = `${step}`) : '';
name ? (input.name = name) : '';
inputId ? (input.id = inputId) : '';
placeholder ? (input.placeholder = placeholder) : '';
}
private _formatterVal(input: HTMLInputElement, formatter: string, val: number): void {
// `约定的 ${value}`替换为 `${val}`
const resVal = formatter.replace('value', 'val');
input.value = `${formatter ? eval(resVal) : val}`;
}
private _parserVal(parser: string, val: string): string {
if (parser) {
const _parser = eval(parser) as any[];
return val.replace(_parser[0], _parser[1]);
} else {
// 如果没有指定从 formatter 里转换回数字的方式,则使用默认正则方式
return val.replace(/[^\d.-]/g, '');
}
}
private _handleChange(
input: HTMLInputElement,
aUp: Element | null,
aDown: Element | null,
btnUp: Element | null,
btnDown: Element | null,
min: number,
max: number,
step: number,
precision: number,
readOnly: boolean,
parser: string,
formatter: string
): void {
if (readOnly) return;
const setValue = (val: number) => {
this._setValue(input, val, formatter, precision, min, max);
this._setHandler(aUp, aDown, btnUp, btnDown, val, min, max);
};
const changeStep = (type: 'up' | 'down'): false | undefined => {
// 如果指定了输入框展示值的格式,那么这里就要用 parser 的值转换为原来的值
const val = this._parserVal(parser, input.value);
const targetVal = Number(val);
if (type === 'up') {
if (addNum(targetVal, step) <= max) {
setValue(targetVal);
} else {
return false;
}
setValue(addNum(targetVal, step));
} else if (type === 'down') {
if (addNum(targetVal, step) >= min) {
setValue(targetVal);
} else {
return false;
}
setValue(addNum(targetVal, -step));
}
};
const handleKeyBoardChange = () => {
bind(input, 'keydown', (e: KeyboardEvent) => {
if (e.key !== 'ArrowUp' && e.key !== 'ArrowDown') return false;
if (e.key === 'ArrowUp') {
e.preventDefault();
changeStep('up');
}
if (e.key === 'ArrowDown') {
e.preventDefault();
changeStep('down');
}
});
};
const handleInputChange = () => {
bind(input, 'input', (e: InputEvent) => {
e.stopPropagation();
// 当输入框输入时只匹配数字、小数点和减号
const val = input.value.replace(/[^\d.-]/g, '');
setValue(Number(val));
});
};
const handleArrowChange = () => {
if (aUp && aDown) {
bind(aUp, 'click', () => changeStep('up'));
bind(aDown, 'click', () => changeStep('down'));
}
if (btnUp && btnDown) {
bind(btnUp, 'click', () => changeStep('up'));
bind(btnDown, 'click', () => changeStep('down'));
}
};
handleKeyBoardChange();
handleInputChange();
handleArrowChange();
}
private _setValue(
input: HTMLInputElement,
value: number,
formatter: string,
precision: number,
min: number,
max: number
): void {
let targetVal: any = !isNaN(precision) ? value.toFixed(precision) : value;
if ((targetVal && !isNaN(targetVal)) || targetVal === 0) {
if (targetVal > max && !isNaN(max)) {
targetVal = max;
} else if (targetVal < min && !isNaN(min)) {
targetVal = min;
}
// 如果指定了输入框展示值的格式则使用它,否则反之
this._formatterVal(input, formatter, targetVal);
}
}
private _setSize(node: Element, size: string): void {
if (!size) return;
node.classList.add(`${PREFIX.inputnb}-${size}`);
}
private _setReadonlyAndEditable(
input: HTMLInputElement,
readOnly: boolean,
editable: string
): void {
if (readOnly) input.readOnly = true;
if (readOnly || editable === 'false') input.style.pointerEvents = 'none';
}
private _setDisabled(node: HTMLElement, input: HTMLInputElement, disabled: boolean): void {
if (!disabled) {
node.classList.remove(`${PREFIX.inputnb}-disabled`);
input.disabled = false;
} else {
node.classList.add(`${PREFIX.inputnb}-disabled`);
input.disabled = true;
}
}
private _setHandler(
aUp: Element | null,
aDown: Element | null,
btnUp: Element | null,
btnDown: Element | null,
value: number,
min: number,
max: number
): void {
const isSetDisable = (elm1: Element, elm2: Element, outside: boolean) => {
const upDisabledCls = outside ? 'controls-outside-btn' : 'handler-up';
const downDisabledCls = outside ? 'controls-outside-btn' : 'handler-down';
if (Math.ceil(value) >= max) {
elm1.classList.add(`${PREFIX.inputnb}-${upDisabledCls}-disabled`);
} else {
elm1.classList.remove(`${PREFIX.inputnb}-${upDisabledCls}-disabled`);
}
if (Math.ceil(value) <= min) {
elm2.classList.add(`${PREFIX.inputnb}-${downDisabledCls}-disabled`);
} else {
elm2.classList.remove(`${PREFIX.inputnb}-${downDisabledCls}-disabled`);
}
};
if (aUp && aDown) isSetDisable(aUp, aDown, false);
if (btnUp && btnDown) isSetDisable(btnUp, btnDown, true);
}
private _attrs(node: HTMLElement) {
return {
min: getNumTypeAttr(node, 'min', -Infinity),
max: getNumTypeAttr(node, 'max', Infinity),
step: getNumTypeAttr(node, 'step', 1),
value: getNumTypeAttr(node, 'value', 0),
precision: getNumTypeAttr(node, 'precision'),
size: getStrTypeAttr(node, 'size', ''),
name: getStrTypeAttr(node, 'name', ''),
inputId: getStrTypeAttr(node, 'input-id', ''),
parser: getStrTypeAttr(node, 'parser', ''),
formatter: getStrTypeAttr(node, 'formatter', ''),
placeholder: getStrTypeAttr(node, 'placeholder', ''),
disabled: getBooleanTypeAttr(node, 'disabled'),
readOnly: getBooleanTypeAttr(node, 'readonly'),
editable: getStrTypeAttr(node, 'editable', 'true'),
controlsOutside: getBooleanTypeAttr(node, 'controls-outside')
};
}
}
export default InputNumber;
|
Pitfalls in CT diagnosis of appendicitis: Pictorial essay
Despite the high diagnostic accuracy of CT for appendicitis, numerous pitfalls exist that may result in a misdiagnosis. This pictorial review outlines the potential pitfalls in the CT diagnosis of appendicitis that includes atypical position of the appendix and coexisting pathologies. Various mimickers of appendicitis and clinical dilemmas will be highlighted. Upon completion, the reviewer should have an improved ability to recognise appendicitis mimickers and identify equivocal or atypical findings.
|
/**
* The watcher of the nodePath
*/
private class RootNodeWatcher implements Watcher {
@Override
public void process(WatchedEvent event) {
synchronized (mapLock) {
if (event.getType() == Event.EventType.NodeDeleted) {
LOGGER.warn("The node {} has been deleted,clear local map and try to watch the root node.", nodePath);
localMap.clear();
try {
getZkClient().exists(nodePath, new RootNodeWatcher());
} catch (KeeperException e) {
onKeeperException(e, "Watch the node " + nodePath + " fail");
} catch (InterruptedException e) {
onInterrupted(e);
}
} else if (event.getType() == Event.EventType.NodeCreated) {
LOGGER.warn("The node {} has beean created,refetch", nodePath);
try {
updateChildren();
} catch (KeeperException e) {
onKeeperException(e, "Prcoess event " + event + " fail.");
} catch (InterruptedException e) {
onInterrupted(e);
}
}
}
}
}
|
package net.raysforge.gltf;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
public class TestBSP2GLTF_textured {
private static final String outDir = "D:\\Action\\id\\Q3\\Quake3\\baseq3\\tex";
public static HashMap<String, String> fileNameMap = new HashMap<String, String>();
// Quake 3 BSP files do not store the extension of the used texture.
// So here we create a map that stores the name and the name with the extension.
public static void saveFilesInMap(File directory) {
File[] listFiles = directory.listFiles();
for (File file : listFiles) {
if( file.isDirectory() ) {
saveFilesInMap(file);
} else {
String fileNameSansExt = file.getPath().replaceFirst("[.][^.]+$", "");
String path=file.getPath();
fileNameSansExt=fileNameSansExt.substring(outDir.length()+1).replace('\\', '/');
path=path.substring(outDir.length()+1).replace('\\', '/');
fileNameMap.put(fileNameSansExt, path);
//System.out.println(fileNameSansExt + " -> " + path);
}
}
}
public static void main(String[] args) throws IOException {
saveFilesInMap(new File(outDir));
BSP2GLTF_textured bsp2glTF = new BSP2GLTF_textured(new File("q3dm17.bsp"), new File(outDir), fileNameMap);
bsp2glTF.writeGLTF();
}
}
|
/**
* Creates and returns a GenericRegisterTable of the appropriate type.
*
* @param account the account to create a new table for
* @return returns a GenericRegisterTable of the appropriate type
*/
public static RegisterTable generateTable(final Account account) {
AbstractRegisterTableModel m = getTableModel(account);
if (m instanceof SortableTableModel) {
return new SortedRegisterTable(m);
}
return new RegisterTable(m);
}
|
#include "RSA.h"
#include "DataStream.h"
#include <boost/multiprecision/cpp_int.hpp>
#include <boost/multiprecision/miller_rabin.hpp>
#include <utility>
using boost::multiprecision::cpp_int;
RSAClient::RSAClient(size_t _bit_size, int _e) {
bit_size = _bit_size;
e = _e;
cpp_int p = gen_prime(bit_size, _e);
cpp_int q = gen_prime(bit_size, _e);
n = p * q;
cpp_int toit = (p - 1) * (q - 1); // since (p,q) are prime
do {
d = inv_mod(e, toit);
if(!d) e++;
} while (d == 0);
}
RSA_key RSAClient::get_public_key() {
return std::make_pair(e, n);
}
DataStream RSAClient::decrypt(const DataStream &cipher) {
return DataStream(powm(cipher.getCppInt(), d, n), bit_size*2);
}
DataStream encrypt(const DataStream &ds, const RSA_key &key, size_t bit_size) {
return DataStream(powm(ds.getCppInt(), key.first, key.second), bit_size*2);
}
cpp_int inv_mod(const cpp_int &num, const cpp_int &mod) {
cpp_int r0 = mod, r1 = num;
cpp_int t0 = 0, t1 = 1;
while(r1 != 0) {
cpp_int q = r0 / r1;
cpp_int r2 = r0 - q * r1;
cpp_int t2 = t0 - q * t1;
r0 = r1;
r1 = r2;
t0 = t1;
t1 = t2;
}
if(r0 > 1) {
return 0;
}
return (t0 + mod) % mod;
}
cpp_int gen_prime(size_t bit_size, int no_div) {
cpp_int prime;
do {
if(no_div > 0) {
do {
prime = get_random_key(bit_size / 8).getCppInt();
} while ((prime - 1) % no_div == 0);
} else {
prime = get_random_key(bit_size / 8).getCppInt();
}
} while(!miller_rabin_test(prime, 100));
return prime;
}
|
/*
* This is an example of a more complex path to really test the tuning.
*/
@Disabled
@Autonomous(group = "drive")
public class AutoBlueTestWithObjectDetect extends LinearOpMode {
Hardware22 robot;
SampleMecanumDrive drive;
TrajectoryGenerator generator;
OpenCvCamera webcam;
//-1 for debug, but we can keep it like this because if it works, it should change to either 0 or 255
private static int valMid = -1;
private static int valLeft = -1;
// private static int valRight = -1;
private static float rectHeight = 1f/8f;
private static float rectWidth = 1f/8f;
private static float offsetX = 0f/8f;//changing this moves the three rects and the three circles left or right, range : (-2, 2) not inclusive
private static float offsetY = 0f/8f;//changing this moves the three rects and circles up or down, range: (-4, 4) not inclusive
private static float[] midPos = {7f/8f+offsetX, 4f/8f+offsetY};//0 = col, 1 = row
private static float[] leftPos = {2.75f/8f+offsetX, 4f/8f+offsetY};
// private static float[] rightPos = {7f/8f+offsetX, 4f/8f+offsetY};
//moves all rectangles right or left by amount. units are in ratio to monitor
@Override
public void runOpMode() throws InterruptedException {
robot = new Hardware22(hardwareMap);
drive = robot.drive;
generator = robot.generator;
int cameraMonitorViewId = hardwareMap.appContext.getResources().getIdentifier("cameraMonitorViewId", "id", hardwareMap.appContext.getPackageName());
webcam = OpenCvCameraFactory.getInstance().createWebcam(hardwareMap.get(WebcamName.class, "Webcam 1"), cameraMonitorViewId);
webcam.openCameraDevice();
webcam.setPipeline(new SamplePipeline());
//the maximum resolution you can stream at and still get up to 30FPS is 480p (640x480).
webcam.startStreaming(640, 480, OpenCvCameraRotation.UPRIGHT);
/*
//code needed for camera to display on FTC Dashboard
FtcDashboard dashboard = FtcDashboard.getInstance();
telemetry = dashboard.getTelemetry();
FtcDashboard.getInstance().startCameraStream(webcam, 10);
telemetry.update();
*/
telemetry.addData("Values", valLeft+" "+valMid);
telemetry.update();
Vector2d vector = new Vector2d(-32.25, 61.5);
Pose2d startPose = new Pose2d(vector, Math.toRadians(270));
drive.setPoseEstimate(startPose);
ArrayList<Double[]> trajectory1 = new ArrayList<>();
generator.generateTrajectoryListItem(-30, 47, 310, 0, PathType.SPLINE_TO_LINEAR, trajectory1);
generator.generateTrajectoryListItem(-22, 36.5, PathType.LINE_TO_CONSTANT, trajectory1);
// Approaching to duck wheel
generator.generateTrajectoryListItem(-60, 56.25, 0, PathType.LINE_TO_LINEAR, trajectory1);
// At duck wheel
generator.generateTrajectoryListItem(-60, 56.25 + 1.7, 0, PathType.LINE_TO_LINEAR, trajectory1);
ArrayList<Double[]> trajectory2 = new ArrayList<>();
generator.generateTrajectoryListItem(-50, 66.7, 0, PathType.LINE_TO_LINEAR, trajectory2);
generator.generateTrajectoryListItem(50, 67.2, 0, PathType.LINE_TO_LINEAR, trajectory2);
ArrayList<Trajectory> compiled1 = generator.compileTrajectoryList(startPose, trajectory1);
ArrayList<Trajectory> compiled2 = generator.compileTrajectoryList(compiled1.get(compiled1.size() - 1).end(), trajectory2);
waitForStart();
//duck detection
if (valLeft == 255) {
telemetry.addData("Position", "Left");
telemetry.update();
sleep(1000);
}
else if (valMid == 255) {
telemetry.addData("Position", "Middle");
telemetry.update();
sleep(1000);
}
else {
telemetry.addData("Position", "Right");
telemetry.update();
sleep(1000);
}
telemetry.update();
// if (isStopRequested()) return;
TrajectoryGenerator.executeTrajectoryList(drive, compiled1);
sleep(500);
robot.towerMotor.setPower(Constants.towerWheelSpeedEndgame);
sleep(2000);
robot.towerMotor.setPower(0);
sleep(500);
TrajectoryGenerator.executeTrajectoryList(drive, compiled2);
}
class SamplePipeline extends OpenCvPipeline {
Mat yCbCr = new Mat();
Mat yMat = new Mat();
Mat CbMat = new Mat();
Mat CrMat = new Mat();
Mat thresholdMat = new Mat();
Mat all = new Mat();
@Override
public Mat processFrame(Mat input)
{
Imgproc.cvtColor(input, yCbCr, Imgproc.COLOR_RGB2YCrCb);//converts rgb to ycrcb
Core.extractChannel(yCbCr, yMat, 0);//extracts cb channel as black and white RGB
Core.extractChannel(yCbCr, CrMat, 1);//extracts cb channel as black and white RGB
Core.extractChannel(yCbCr, CbMat, 2);//extracts cb channel as black and white RGB
Imgproc.threshold(CbMat, thresholdMat, 102, 255, Imgproc.THRESH_BINARY_INV);
//any pixel with a hue value less than 102 is being set to 0 (yellow)
//any pixel with a hue value greater than 102 is being set to 255(blue)
//Then swaps the blue and the yellows with the binary inv line
CbMat.copyTo(all);//copies mat object
//get values from frame
double[] pixMid = thresholdMat.get((int)(input.rows()* midPos[1]), (int)(input.cols()* midPos[0]));//gets value at circle
valMid = (int)pixMid[0];
double[] pixLeft = thresholdMat.get((int)(input.rows()* leftPos[1]), (int)(input.cols()* leftPos[0]));//gets value at circle
valLeft = (int)pixLeft[0];
// double[] pixRight = thresholdMat.get((int)(input.rows()* rightPos[1]), (int)(input.cols()* rightPos[0]));//gets value at circle
// valRight = (int)pixRight[0];
//create three points
Point pointMid = new Point((int)(input.cols()* midPos[0]), (int)(input.rows()* midPos[1]));
Point pointLeft = new Point((int)(input.cols()* leftPos[0]), (int)(input.rows()* leftPos[1]));
// Point pointRight = new Point((int)(input.cols()* rightPos[0]), (int)(input.rows()* rightPos[1]));
//draw circles on those points
Imgproc.circle(all, pointMid,5, new Scalar( 255, 0, 0 ),1 );//draws circle
Imgproc.circle(all, pointLeft,5, new Scalar( 255, 0, 0 ),1 );//draws circle
// Imgproc.circle(all, pointRight,5, new Scalar( 255, 0, 0 ),1 );//draws circle
//draw 3 rectangles
Imgproc.rectangle(//1-3
all,
new Point(
input.cols()*(leftPos[0]-rectWidth/2),
input.rows()*(leftPos[1]-rectHeight/2)),
new Point(
input.cols()*(leftPos[0]+rectWidth/2),
input.rows()*(leftPos[1]+rectHeight/2)),
new Scalar(0, 255, 0), 3);
Imgproc.rectangle(//3-5
all,
new Point(
input.cols()*(midPos[0]-rectWidth/2),
input.rows()*(midPos[1]-rectHeight/2)),
new Point(
input.cols()*(midPos[0]+rectWidth/2),
input.rows()*(midPos[1]+rectHeight/2)),
new Scalar(0, 255, 0), 3);
/* Imgproc.rectangle(//5-7
all,
new Point(
input.cols()*(rightPos[0]-rectWidth/2),
input.rows()*(rightPos[1]-rectHeight/2)),
new Point(
input.cols()*(rightPos[0]+rectWidth/2),
input.rows()*(rightPos[1]+rectHeight/2)),
new Scalar(0, 255, 0), 3); */
//return input; // this is the line that declares which image is returned to the viewport (DS)
//return CbMat;
return all;
}
}
}
|
import com.jayfella.mesh.marchingcubes.ArrayDensityVolume;
import com.jayfella.mesh.marchingcubes.DensityVolume;
import com.jayfella.mesh.MarchingCubesMeshGenerator;
import com.jme3.app.SimpleApplication;
import com.jme3.light.AmbientLight;
import com.jme3.light.DirectionalLight;
import com.jme3.material.Material;
import com.jme3.math.ColorRGBA;
import com.jme3.math.Vector3f;
import com.jme3.scene.Geometry;
import com.jme3.scene.Mesh;
import com.jme3.system.AppSettings;
import noise.GemsFractalDensityVolume;
public class TestMarchingCubes extends SimpleApplication {
public static void main(String... args) {
TestMarchingCubes testMarchingCubes = new TestMarchingCubes();
AppSettings appSettings = new AppSettings(true);
appSettings.setResolution(1280, 720);
appSettings.setAudioRenderer(null);
testMarchingCubes.setSettings(appSettings);
testMarchingCubes.setShowSettings(false);
testMarchingCubes.start();
}
@Override
public void simpleInitApp() {
flyCam.setDragToRotate(true);
flyCam.setMoveSpeed(50);
// a 3D noise generator.
// https://developer.nvidia.com/gpugems/gpugems3/part-i-geometry/chapter-1-generating-complex-procedural-terrains-using-gpu
GemsFractalDensityVolume densityVolume = new GemsFractalDensityVolume("my seed".hashCode());
// the coordinates of the density volume to begin extracting.
int[] coords = { 132, 0, 32 };
// the size of the mesh we want to generate.
int[] meshSize = { 32, 32, 32 };
MarchingCubesMeshGenerator meshGenerator = new MarchingCubesMeshGenerator(meshSize[0], meshSize[1], meshSize[2]);
int[] requiredVolumeSize = meshGenerator.getRequiredVolumeSize();
// Extract a section of the densityVolume that we want to visualize.
DensityVolume chunkVolume = ArrayDensityVolume.extractVolume(densityVolume,
coords[0], coords[1], coords[2],
requiredVolumeSize[0], (int)requiredVolumeSize[1], (int)requiredVolumeSize[2]);
// generate the mesh.
Mesh mesh = meshGenerator.buildMesh(chunkVolume);
// standard JME scene stuff.
Geometry geometry = new Geometry("Marching Cubes", mesh);
// hint: IsoSurface meshes generally require some sort of texture mapping algorithm such as TriPlanar Mapping.
geometry.setMaterial(new Material(assetManager, "Common/MatDefs/Light/Lighting.j3md"));
// add some light so we can see it better.
rootNode.addLight(new DirectionalLight(new Vector3f(-1, -1, -1).normalizeLocal(), ColorRGBA.White.clone()));
rootNode.addLight(new AmbientLight(new ColorRGBA(0.4f, 0.4f, 0.4f, 1.0f)));
rootNode.attachChild(geometry);
// look at it.
cam.setLocation(new Vector3f(0, meshSize[1] / 4f, 0));
cam.lookAt(new Vector3f(meshSize[0] / 2f, 0, meshSize[2] / 2f), Vector3f.UNIT_Y);
}
}
|
// instructionArgs collects all the arguments to an instruction.
func instructionArgs(node *node32) (argNodes []*node32) {
for node = skipWS(node); node != nil; node = skipWS(node.next) {
assertNodeType(node, ruleInstructionArg)
argNodes = append(argNodes, node.up)
}
return argNodes
}
|
/*
* Called from debugger/panic on cpus which have been stopped. We must still
* process the IPIQ while stopped.
*
* If we are dumping also try to process any pending interrupts. This may
* or may not work depending on the state of the cpu at the point it was
* stopped.
*/
void
lwkt_smp_stopped(void)
{
globaldata_t gd = mycpu;
if (dumping) {
lwkt_process_ipiq();
--gd->gd_intr_nesting_level;
splz();
++gd->gd_intr_nesting_level;
} else {
lwkt_process_ipiq();
}
cpu_smp_stopped();
}
|
/**
*
* @author P. Mark Anderson
*/
public class TaskDef extends IdDef implements Comparator {
public TaskDef() {
super();
setDefName("Task");
}
public TaskDef(Map m) {
super(m, "Task");
}
public int getOrdinal() {
return Integer.parseInt((String)getProperty("ordinal"));
}
public int compare(Object o1, Object o2) {
int ord1 = ((TaskDef)o1).getOrdinal();
int ord2 = ((TaskDef)o2).getOrdinal();
if (ord1 < ord2)
return -1;
if (ord1 == ord2)
return 0;
return 1;
}
/**
* Note: this comparator imposes orderings that are
* inconsistent with equals. Instead, it uses Object's
* equals() method.
*/
public boolean equals(Object obj) {
return this.equals(obj);
}
}
|
You are being watched. The government has a secret system —a machine— that spies on you every hour of every day. I know, because I built it. I designed the machine to detect acts of terror, but it sees everything.
So begins the opening monologue on the CBS television show Person of Interest, spoken by the designer of ‘The Machine’, technology genius and billionaire, Harold Finch. The Machine is a mass surveillance computer system, monitoring data input from just about every electronic source in the world (phones, cameras, computers etc), which it analyzes in order to predict violent acts. But given its omnipotence, there are far too many predictions to act on, and so instead it is programmed to only pass on ‘relevant’ threats – ie. major terrorist events – to the government.
The procedural element of the show is that Finch has a software backdoor that sends him the ‘irrelevant’ predictions so that he can try to stop that violent act occurring as well: each episode, he and his small team of law enforcement officers and former government agents are given the social security number of an individual connected to the threat, though the team do not know if the individual is the victim or the perpetrator.
The larger story arc, however, is all about the Machine – how Harold came to build it and the effect of doing so on both him and those around him; the power that such surveillance hands to whomever controls it, and the lengths some would go to in order to have that control; and what might happen if such a powerful ‘intelligence’ became sentient. And of course, the question that hangs over the entire storyline, is the debate between how surveillance can be used to keep people safe, versus how it can be used in corrupt ways.
The show is science fiction, but given the news stories listed below, we might say only barely – the Person of Interest future doesn’t seem that far off at all.
Surveillance via your own smartphone
We already know that smartphones can track everywhere you go via the built-in GPS, and the Person of Interest team certainly utilise that function to their advantage. But in the show, Finch’s team also often take advantage of a hack which “force pairs” their smartphone with the person of interest’s phone, allowing them to hear every conversation within hearing distance of the phone. It’s a rather helpful – if clumsily powerful – plot device, allowing them to eavesdrop from a distance with the simple touch of a button.
But in the real world, where phones aren’t always in microphone mode, and are a bit tougher to hack, the nearest thing might be this recent hack by security researchers from Stanford University, who discovered a way to turn the gyroscopes within modern smartphones into crude microphones:
Here’s how it works: the tiny gyros in your phone that measure orientation do so using vibrating pressure plates. As it turns out, they can also pick up air vibrations from sounds, and many Android devices can do it in the 80 to 250 hertz range — exactly the frequency of a human voice.
And if you think this sort of surveillance might be fairly unlikely in the real world, you should definitely watch this talk by Jacob Appelbaum on the militarisation of the internet and hijacking of technologies for surveillance (transcript here). As one pundit noted, “No matter how bad you think the NSA’s information surveillance and capture is, I can just about guarantee that this will show you that it’s an order of magnitude worse than you imagined”:
I’m betting by the time you get to the bit about the NSA’s ability to radiate people with up to 1KW of RF (under the heading of “Specialized Philip K. Dick inspired nightmares”) you’ll be getting a little freaked out about our brave new world…
The NSA is harvesting millions of facial images from the web for facial recognition
The Machine uses facial recognition to identify every face it picks up, across the entire world, through surveillance cameras. While that sort of observational power is likely to be beyond current technology (from the point of view of the public at least), it’s something that the spooks at the NSA would love to have at their disposal. One of the leaks from NSA whistleblower Edward Snowden detailed how the agency is harvesting millions of facial images from the Web for use in a facial recognition program called ‘Identity Intelligence’. And what’s more, the NSA is linking these facial images with other biometrics and identity data:
The NSA’s goal — in which it has been moderately successful — is to match images from disparate databases, including databases of intercepted videoconferences (in February 2014, another Snowden publication revealed that NSA partner GCHQ had intercepted millions of Yahoo video chat stills), images captured by airports of fliers, and hacked national identity card databases from other countries. According to the article, the NSA is trying to hack the national ID card databases of “Pakistan, Saudi Arabia and Iran.”
Note too that the FBI recently caught a fugitive who had been on the run for 14 years through facial recognition – their software identified the fugitive’s face on a visa application submitted under a fake identity, based on an image on file. The FBI’s system seems fairly basic, but its likely that alphabet soup agencies have much more power at their fingertips then they divulge to the public…
What can you do about the future chances of being tracked via facial recognition? Not a whole lot, although Daily Grail editor Cat Vincent does discuss some possibilities in this earlier post on the NSA’s facial recognition program.
All-seeing surveillance
When it comes to all-seeing surveillance, one of the tropes of the conspiracy genre is the ‘all-seeing eye in the sky’ – satellites with super-high resolution cameras, able to watch our every move. And there’s no doubt, the number of satellites, and their capabilities, is constantly expanding – and what’s more, it’s not just a government thing anymore. But with the development of drone technologies, space-based surveillance now seems a whole lot more redundant: why put a camera hundreds or thousands of kilometres away, when you can have a mobile camera based immediately above locations? Welcome to the new world of Wide Area Aerial Surveillance (WAAS) via drones:
Systems such as Gorgan Stare, ARGUS, Vigilant Stare and Constant Hawk are all developmental iterations of the Pentagon’s goal to be able to continuously survey a whole village, or even an entire city, via a single ‘sensor platform,’ or just a handful of systems that are networked together. Additionally, these systems are to allow multiple “customers,” or end users, to manipulate and leverage their collected video data in real time. Generally, the Wide Area Aerial Surveillance (WAAS) concept works by taking a high-endurance aerial sensor “platform,” such as a MQ-9 Reaper or IAI Eithan unmanned aircraft system, or a blimp or airship, and marrying it with a WAAS type sensor payload. This payload usually consists of canoe shaped pod that has high-resolution electro-optical sensors pointed in many directions in a fixed manner. Onboard computing and software can then stitch these staring cameras’ “pictures” together, creating a continuous high resolution overall image of a large swath of land or sea below. Users can then instruct the WAAS system to send them a high-resolution live video feed of a certain area of that massive ‘fused’ picture. The WAAS system then data-links down the video of the geographical area requested by the user. Thus the user will have real time streaming video imagery of a portion of the entire area WAAS is persistently viewing at any given time.
Keep increasing that video fidelity, throw in some advanced facial recognition tech, along with GPS tracking and an always-on microphone in your phone…and a Person of Interest scenario doesn’t seem that far off. All that is maybe lacking is the presence of ‘The Machine’. But are we even that far from that scenario?
The rise of Artificial Intelligence
News stories touching on advances in artificial intelligence (AI) seem to be coming thick and fast lately, from a machine learning algorithm finding things in fine art paintings that art historians had never noticed through to a robot that studies YouTube videos to learn all about humans and how they interact with the world. And, three years on from the debut of the ‘basic’ AI of Apple’s Siri, ‘her’ inventors are said to now be building a radical new AI that will do anything you ask.
Perhaps the most interesting of all though is Google’s interest in AI. A recent news report discussed how Google is using “an algorithm to automatically pull in information from all over the web, using machine learning to turn the raw data into usable pieces of knowledge”, which will become the Knowledge Vault, “a single base of facts about the world, and the people and objects in it”.
Knowledge Vault promises to supercharge our interactions with machines, but it also comes with an increased privacy risk. The Vault doesn’t care if you are a person or a mountain – it is voraciously gathering every piece of information it can find. “Behind the scenes, Google doesn’t only have public data,” says Suchanek. It can also pull in information from Gmail, Google+ and YouTube. “You and I are stored in the Knowledge Vault in the same way as Elvis Presley,”
And earlier this year, it was revealed that Google had bought AI start-up DeepMind for an estimated $400 million, bringing it under the umbrella of their Google X division, a facility dedicated to making major technological breakthroughs. The reasoning for their interest in AI sounds almost like a description of the Machine in Person of Interest:
Much of the fundamental infrastructure within Google is based on language, speech, translation, and visual processing. All of this depends upon the use of so called Machine Learning and AI. A common thread among all of these tasks and many others at Google is that it gathers unimaginably large volumes of direct or indirect data. This data provides what the company calls “evidence of relationships of interest” which they then apply to adaptive learning algorithms. In turn these smart algorithms create new potential opportunities in areas that the rest of us have yet to grasp. In short, they might very well be attempting to predict the future based on the search/web surfing habits of the millions who visit the company’s products and services every day. They know what we want, before we do.
A whole new level of control
Most of us are familiar with social networks nagging us to complete our profile, adding in those few bits of private information that we haven’t yet shared with a faceless corporation. In one particular episode of Person of Interest, Finch and his ex-CIA ‘muscle’ John Reece discuss the amount of information that people happily put up on social networks:
Reece: Never understood why people put all their information on those sites. Used to make our job a lot easier in the CIA. Finch: Of course, that’s why I created them. Reece: You’re telling me you invented online social networking Finch? Finch: The Machine needed more information. People’s social graph, their associations…the government have been trying to figure it out for years. Turns out, most people were happy to volunteer it. Business wound up being quite profitable too…
Surveillance, at its heart, is a method of control. But the growth of social networks – and in particular the move to ‘filtered feeds’, where you only see a fraction of the data stream directed at you, determined to be the most relevant to you by certain algorithms – now allows a less passive, and more fine-grained, pernicious type of control: direct influence over your mind. Once the social network takes control over what we see in our timeline or stream, direct manipulation becomes a real possibility. Exhibit A: a recent Facebook experiment in which user feeds were manipulated to see whether their emotions could be affected:
For one week in January 2012, data scientists skewed what almost 700,000 Facebook users saw when they logged into its service. Some people were shown content with a preponderance of happy and positive words; some were shown content analyzed as sadder than average. And when the week was over, these manipulated users were more likely to post either especially positive or negative words themselves. This tinkering was just revealed as part of a new study, published in the prestigious Proceedings of the National Academy of Sciences. Many previous studies have used Facebook data to examine “emotional contagion,” as this one did. This study is different because, while other studies have observed Facebook user data, this one set out to manipulate it.
The near-ubiquitousness of Facebook, and the ability to filter feeds, opens a whole Pandora’s box of control. What if Facebook expands into other business fields, then modifies feeds to only feature products from their subsidiaries and to not show competitor’s products? Or more dramatically, what if the control is of a political or ethical nature, censoring certain ‘news’ that particular people don’t want seen? The recent Ferguson demonstrations offer an excellent example of the difference in exposure to certain news stories between the algorithmic filtering of Facebook and the ‘raw feed’ of Twitter. And yet, there are now suggestions that Twitter’s timeline too will soon be filtered.
And if you think that it’s at least a small blessing that the government can’t control large corporations like Facebook, just remember that didn’t stop them from being forced to help the government spy on us all – Yahoo was even threatened with a $250K daily fine if it didn’t use PRISM.
In the end, it seems we might all be persons of interest to the government…
————————
If the above article hasn’t scared you off social media, you can keep up to date with more fascinating stories like this one by liking The Daily Grail’s Facebook page, following us on Twitter, and/or putting us in your Google+ circles.
You might also like:
|
<reponame>msamogh/rasa
import logging
from collections import namedtuple
from typing import Any, List, Text, Dict
from rasa.core.events import Event
from rasa.core.frames import FrameSet
from rasa.core.frames.utils import (
push_slots_into_current_frame,
pop_slots_from_current_frame,
frames_from_tracker_slots,
)
logger = logging.getLogger(__name__)
class FrameIntent(object):
"""Wrapper for frames-related properties of an intent (extracted from the domain)."""
def __init__(
self, can_contain_frame_ref, on_frame_match_failed, on_frame_ref_identified
):
"""Initialize a FrameIntent.
Args:
can_contain_frame_ref: Whether or not this intent can contain a
frame reference.
on_frame_match_failed: The strategy to be followed in case the entities
extracted from the user utterance does not fully match any existing
frame in the FrameSet.
on_frame_ref_identified: The course of action to be taken once the frame
ref has been identified.
"""
self.can_contain_frame_ref = can_contain_frame_ref
self.on_frame_match_failed = on_frame_match_failed
self.on_frame_ref_identified = on_frame_ref_identified
@classmethod
def from_intent(cls, domain: "Domain", intent: Text):
"""Create a FrameIntent instance from the intent name.
Args:
domain: Domain object that describes this intent.
intent: Name of the intent.
Returns:
The FrameIntent object.
"""
props = domain.intent_properties[intent]
can_contain_frame_ref = props["can_contain_frame_ref"]
on_frame_match_failed = props["on_frame_match_failed"]
on_frame_ref_identified = props["on_frame_ref_identified"]
return cls(
can_contain_frame_ref, on_frame_match_failed, on_frame_ref_identified
)
class FramePolicy(object):
def __init__(self, domain: "Domain") -> None:
self.domain = domain
def predict(
self, tracker: "DialogueStateTracker", user_utterance: "UserUttered"
) -> List[Event]:
# 1. Copy the slot values in the tracker over to the current frame. This step
# is needed since a custom action might have modified the tracker's slots
# since the last `UserUttered` event. Essentially, we want the frames inside
# `tracker.frames` to reflect the latest state of the tracker.
# 2. If the latest user-utterance calls for any changes to the FrameSet - either
# changing the active frame or creating a new frame, make those changes.
# 3. Copy the slots from the current frame (potentially changed after step 2)
# over to the tracker (essentially the reverse of step 1).
events = (
push_slots_into_current_frame(tracker)
+ self.get_frame_events(tracker, user_utterance)
+ pop_slots_from_current_frame()
)
return events
def get_frame_events(
self, tracker: "DialogueStateTracker", user_utterance: "UserUttered"
) -> List[Event]:
"""Update the FrameSet based on the user_utterance."""
intent = user_utterance.intent
frame_intent = FrameIntent.from_intent(self.domain, intent["name"])
dialogue_entities = FrameSet.get_framed_entities(
user_utterance.entities, self.domain
)
latest_frameset = frames_from_tracker_slots(tracker)
if frame_intent.can_contain_frame_ref:
ref_frame_idx = self.get_best_matching_frame_idx(
frames=latest_frameset.frames,
current_frame_idx=latest_frameset.current_frame_idx,
framed_entities=dialogue_entities,
frame_intent=frame_intent,
)
events = self.on_frame_ref_identified(
frames=latest_frameset.frames,
framed_entities=dialogue_entities,
current_frame_idx=latest_frameset.current_frame_idx,
ref_frame_idx=ref_frame_idx,
frame_intent=frame_intent,
)
return events
return []
def get_best_matching_frame_idx(
self,
frames: List["Frame"],
frame_intent: FrameIntent,
framed_entities: Dict[Text, Any],
) -> int:
"""Identify which frame the user is talking about.
There are 3 possibilities here:
1. the current frame
2. an existing frame that is not the current frame
3. a new frame.
Args:
frames: List of all the frames in the FrameSet
frame_intent: Frame-related properties of the intent
framed_entities: Relevant entities in the user_utterance
Returns:
int: index of the frame being referenced
"""
raise NotImplementedError
def on_frame_ref_identified(
self,
tracker: "DialogueStateTracker",
ref_frame_idx: int,
frame_intent: FrameIntent,
) -> List[Event]:
"""Course of action to take once the frame ref has been identified.
Args:
tracker: The DialogueStateTracker object.
ref_frame_idx:
"""
return NotImplementedError
|
package org.kakara.client;
import org.kakara.client.join.JoinDetails;
import org.kakara.client.join.LocalJoin;
import org.kakara.client.local.game.ClientResourceManager;
import org.kakara.client.local.game.IntegratedServer;
import org.kakara.client.local.game.commands.ClientCommandManager;
import org.kakara.core.common.EnvType;
import org.kakara.core.common.Serverable;
import org.kakara.core.common.calculator.CalculatorRegistry;
import org.kakara.core.common.command.CommandManager;
import org.kakara.core.common.events.EventManager;
import org.kakara.core.common.events.game.GameEventManager;
import org.kakara.core.common.exceptions.NoServerVersionAvailableException;
import org.kakara.core.common.game.GameSettings;
import org.kakara.core.common.game.Item;
import org.kakara.core.common.game.ItemRegistry;
import org.kakara.core.common.gui.container.ContainerUtils;
import org.kakara.core.common.mod.ModManager;
import org.kakara.core.common.mod.game.GameModManager;
import org.kakara.core.common.resources.ResourceManager;
import org.kakara.core.common.service.ServiceManager;
import org.kakara.core.common.settings.SettingRegistry;
import org.kakara.core.common.settings.simple.SimpleSettingManager;
import org.kakara.core.common.world.WorldGenerationRegistry;
import org.kakara.core.server.ServerGameInstance;
import org.kakara.core.server.game.ServerItemStack;
import org.kakara.core.server.world.WorldManager;
import org.kakara.game.GameServiceManager;
import org.kakara.game.ServerLoadException;
import org.kakara.game.calculator.GameCalculatorRegistry;
import org.kakara.game.item.GameItemRegistry;
import org.kakara.game.items.GameItemStack;
import org.kakara.game.mod.KakaraMod;
import org.kakara.game.server.gui.ServerContainerUtils;
import org.kakara.game.settings.JsonSettingController;
import org.kakara.game.world.GameWorldGenerationRegistry;
import java.io.File;
/**
* The complete Implementation of the ServerGameInstance.
*/
public class LocalClient extends Client implements ServerGameInstance {
private final GameSettings settings;
private final KakaraGame kakaraGame;
private final ItemRegistry itemManager;
private final ResourceManager resourceManager;
private final ModManager modManager;
private final File workingDirectory;
private final WorldGenerationRegistry worldGenerationManager;
private final EventManager eventManager;
private final CommandManager commandManager;
private WorldManager worldManager;
private final ServiceManager serviceManager;
private final SettingRegistry settingManager;
private final LocalJoin localJoin;
private final ContainerUtils containerUtils;
private final CalculatorRegistry calculatorRegistry;
/**
* Construct the Local Client.
*
* <p>This is constructed by default in {@link KakaraGame#join(JoinDetails)}.</p>
*
* @param joinDetails The information about how the user joined.
* @param kakaraGame The instance of KakaraGame.
* @param gameSettings The game settings.
*/
public LocalClient(LocalJoin joinDetails, KakaraGame kakaraGame, GameSettings gameSettings) {
this.settings = gameSettings;
this.kakaraGame = kakaraGame;
workingDirectory = joinDetails.getWorkingDirectory();
itemManager = new GameItemRegistry();
modManager = new GameModManager(new KakaraMod(this));
resourceManager = new ClientResourceManager();
eventManager = new GameEventManager();
commandManager = new ClientCommandManager();
worldGenerationManager = new GameWorldGenerationRegistry();
containerUtils = new ServerContainerUtils();
serviceManager = new GameServiceManager();
calculatorRegistry = new GameCalculatorRegistry();
registerDefaultServices();
File settings = new File(workingDirectory, "settings");
settings.mkdir();
settingManager = new SimpleSettingManager(settings);
this.localJoin = joinDetails;
}
/**
* Register the default services for the client.
*/
private void registerDefaultServices() {
serviceManager.registerService(new JsonSettingController());
}
/**
* Setup the LocalClient for use.
*
* <p>This must be called.</p>
*
* @throws ServerLoadException If an error occurs while loading.
*/
public void setup() throws ServerLoadException {
if (settings.isTestMode()) {
server = new IntegratedServer(localJoin.getSave(), localJoin.getSelf(), null);
((IntegratedServer) server).start();
} else {
//TODO implement world joining
}
}
/**
* {@inheritDoc}
*/
@Override
public GameSettings getGameSettings() {
return settings;
}
/**
* {@inheritDoc}
*/
@Override
public ServerItemStack createItemStack(Item item) {
return new GameItemStack(1, item);
}
/**
* {@inheritDoc}
*/
@Override
public ResourceManager getResourceManager() {
return resourceManager;
}
/**
* {@inheritDoc}
*/
@Override
public ItemRegistry getItemRegistry() {
return itemManager;
}
/**
* {@inheritDoc}
*/
@Override
public WorldManager getWorldManager() {
return worldManager;
}
/**
* Set the world manager.
*
* @param worldManager The world manager to set.
*/
public void setWorldManager(WorldManager worldManager) {
this.worldManager = worldManager;
}
/**
* {@inheritDoc}
*/
@Override
public ModManager getModManager() {
return modManager;
}
/**
* {@inheritDoc}
*/
@Override
public ContainerUtils getContainerUtils() {
return containerUtils;
}
/**
* {@inheritDoc}
*/
@Override
public ServiceManager getServiceManager() {
return serviceManager;
}
/**
* {@inheritDoc}
*/
@Override
public File getWorkingDirectory() {
return workingDirectory;
}
/**
* {@inheritDoc}
*/
@Override
public EventManager getEventManager() {
return eventManager;
}
/**
* {@inheritDoc}
*/
@Override
public WorldGenerationRegistry getWorldGenerationRegistry() {
return worldGenerationManager;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isIntegratedServer() {
return true;
}
/**
* {@inheritDoc}
*/
@Override
public CommandManager getCommandManager() {
return commandManager;
}
/**
* {@inheritDoc}
*/
@Override
public EnvType getType() {
return EnvType.SERVER;
}
/**
* {@inheritDoc}
*/
@Override
public CalculatorRegistry getCalculatorRegistry() {
return calculatorRegistry;
}
/**
* {@inheritDoc}
*/
@Override
public SettingRegistry getGameSettingRegistry() {
return settingManager;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isServerVersionAvailable() {
return false;
}
/**
* {@inheritDoc}
*/
@Override
public <T extends Serverable> T getServerVersion() {
return null;
}
/**
* {@inheritDoc}
*/
@Override
public void requiresServerVersion() throws NoServerVersionAvailableException {
}
}
|
/*Package resource provides tools for the Resource Description Framework (RDF),
see https://www.w3.org/RDF/.
*/
package resource
|
Pre-course
Complete the registration survey to provide information about yourself, your school or district, and your goals for participating in the Learning Differences MOOC-Ed.
Thinking Differently about Student Learning
Participants will further their thinking about Learning Differences and the "myth of average" among their students. Educators will begin to develop and apply learning differences teaching competencies which will support student learning. The essential questions for this unit are:
What are learning differences?
How does thinking about students' learning differences affect my teaching practice?
What are the benefits of focusing on students' strengths rather than weaknesses? What are the challenges of this approach?
Working Memory
This unit focuses on the impact of working memory on student learning and behavior in classrooms. Participants will learn and apply strategies to better support students' working memories. The essential questions are:
What is Working Memory and how does it affect student learning?
How can teachers support students who struggle with working memory or leverage students with strong working memory?
Which strategies or solutions related to working memory best meet your students' needs?
Executive Function
This unit establishes a basic understanding of executive functioning skills by explaining what they are and how they impact student learning. The essential questions are:
What are executive functioning skills and how do they affect student learning?
How can teachers develop students' executive functioning skills in classrooms?
Which strategies or solutions related to executive functions best meet your students' needs?
Student Motivation
This unit focuses on the impact of students' motivation on learning and behavior in classrooms. Participants will learn and apply strategies to better foster student motivation. The essential questions are:
What are intrinsic and extrinsic motivation and how do they affect student learning?
How can teachers build intrinsic and extrinsic motivation in classrooms?
Which strategies or solutions related to motivation best meet your students' needs?
Strategies for Supporting the Whole Student
The purpose of this unit is to get you thinking about the complexities and relatedness of learning differences. Then, we hope to begin honing your skills to approach a student and identify how to leverage that student's learning profile to best support him or her. We have referenced this as being a "learning scientist" throughout the course. The essential questions for this unit are:
How do the constructs of learning work together to build a complex, individual learner profile in each of my students?
How can I collect student data to select and implement strategies to support individual student needs?
Internalizing a Growth Mindset
In prior units, we built knowledge of and strategies for addressing various constructs of learning differences. In this unit, we bring these elements together to apply in your classroom and outline opportunities for future learning. The essential questions are:
What progress have you made in your classroom with regard to learning differences?
What strategies or next steps would you take to continue down this path?
Interested in the Learning Differences Coaching Component?
During the course, instructional coaches, media coordinators, and teacher leaders will have the opportunity to participate in three additional modules that are focused on strategies for coaching and supporting other teachers in their work with learning differences. The outline for the coaching portion of the course is in the next tab.
|
/*
* Copyright 2013 SURFnet bv, The Netherlands
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.surfnet.coin.shared.log.diagnostics;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.EnumSet;
import java.util.Scanner;
import javax.servlet.DispatcherType;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.client.apache4.ApacheHttpClient4;
import com.sun.jersey.client.apache4.config.ApacheHttpClient4Config;
import com.sun.jersey.client.apache4.config.DefaultApacheHttpClient4Config;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.session.SessionHandler;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class DiagnosticsLoggerFilterITest {
public static final String SUCCESS_URL = "http://localhost:57467/test/success";
public static final String ERROR_URL = "http://localhost:57467/test/error";
private static final String CREATE_SESSION_URL = "http://localhost:57467/test/createSession";
private Server server;
private ServletContextHandler context;
private File logfile;
@Before
public void before() throws Exception {
logfile = new File("target/dump.log");
System.setProperty("logback.configurationFile", "logback-DiagnosticsLoggerFilterITest.xml");
server = new Server(57467);
context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setSessionHandler(new SessionHandler());
context.setContextPath("/test");
server.setHandler(context);
context.addFilter(DiagnosticsLoggerFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
context.addServlet(new ServletHolder(new ContentServlet()), "/success");
context.addServlet(new ServletHolder(new InternalServerError()), "/error");
context.addServlet(new ServletHolder(new CreateSessionServlet()), "/createSession");
server.start();
}
@After
public void stopServer() throws Exception {
server.stop();
}
@Test
public void testHappy() throws Exception {
Client client = new Client();
String result = client.
resource(SUCCESS_URL)
.get(String.class);
assertEquals("hello world", result);
}
@Test
public void testInternalServerError() throws Exception {
Client client = new Client();
try {
client
.resource(ERROR_URL)
.get(String.class);
fail("Should throw an exception because server should return 500");
} catch (RuntimeException rte) {
assertTrue("Logfile should exist", logfile.exists());
assertTrue(new Scanner(logfile).useDelimiter("\\z").next().contains("Will throw an RTE"));
}
}
@Test
public void crossRequestWithoutSession() throws FileNotFoundException {
Client client = new Client();
try {
client
.resource(SUCCESS_URL)
.get(String.class);
Scanner scanner = new Scanner(logfile).useDelimiter("\\z");
// if file exists, test that debug statement is not written (there is no error condition yet)
if (scanner.hasNext()) {
String logContents = scanner.next();
assertFalse(logContents.contains("getContent from ContentServlet"));
}
client.resource(ERROR_URL).get(String.class);
fail("Should throw RTE");
} catch (RuntimeException rte) {
assertTrue("Logfile should exist", logfile.exists());
String logContents = new Scanner(logfile).useDelimiter("\\z").next();
assertFalse("No session is used, log file should not contain entry from first, successful request", logContents.contains("getContent from ContentServlet"));
assertTrue(logContents.contains("Will throw an RTE"));
}
}
@Test
public void crossRequestWithSession() throws FileNotFoundException {
// Apache httpclient has session support, while the default client from Jersey has not.
DefaultApacheHttpClient4Config config = new DefaultApacheHttpClient4Config();
config.getProperties().put(ApacheHttpClient4Config.PROPERTY_DISABLE_COOKIES, false);
ApacheHttpClient4 client = ApacheHttpClient4.create(config);
client.resource(CREATE_SESSION_URL).get(String.class);
try {
client
.resource(SUCCESS_URL)
.get(String.class);
Scanner scanner = new Scanner(logfile).useDelimiter("\\z");
// if file exists, test that debug statement is not written (there is no error condition yet)
if (scanner.hasNext()) {
String logContents = scanner.next();
assertFalse(logContents.contains("getContent from ContentServlet"));
}
client.resource(ERROR_URL).get(String.class);
fail("Should throw RTE");
} catch (RuntimeException rte) {
assertTrue("Logfile should exist", logfile.exists());
String logContents = new Scanner(logfile).useDelimiter("\\z").next();
System.out.println(logContents);
assertTrue("HttpSession is used, log file should contain entry from first, successful request", logContents.contains("getContent from ContentServlet"));
assertTrue(logContents.contains("Will throw an RTE"));
}
}
public static class ContentServlet extends HttpServlet {
private static final Logger LOG = LoggerFactory.getLogger(ContentServlet.class);
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
LOG.debug("This servlet logs something at DEBUG level");
LOG.info("This servlet logs something at INFO level");
response.setStatus(HttpServletResponse.SC_OK);
response.getWriter().print(getContent());
}
public String getContent() {
LOG.info("getContent from ContentServlet");
return "hello world";
}
}
public static class InternalServerError extends ContentServlet {
private static final Logger LOG = LoggerFactory.getLogger(InternalServerError.class);
public String getContent() {
LOG.error("Will throw an RTE");
throw new RuntimeException("Runtime exception on purpose");
}
}
public static class CreateSessionServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.getSession(true).setAttribute("foo", "bar");
}
}
}
|
// SPDX-License-Identifier: GPL-2.0-only
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/mod_devicetable.h>
#include <linux/spi/spi.h>
struct rtspi {
void __iomem *base;
};
/* SPI Flash Configuration Register */
#define RTL_SPI_SFCR 0x00
#define RTL_SPI_SFCR_RBO BIT(28)
#define RTL_SPI_SFCR_WBO BIT(27)
/* SPI Flash Control and Status Register */
#define RTL_SPI_SFCSR 0x08
#define RTL_SPI_SFCSR_CSB0 BIT(31)
#define RTL_SPI_SFCSR_CSB1 BIT(30)
#define RTL_SPI_SFCSR_RDY BIT(27)
#define RTL_SPI_SFCSR_CS BIT(24)
#define RTL_SPI_SFCSR_LEN_MASK ~(0x03 << 28)
#define RTL_SPI_SFCSR_LEN1 (0x00 << 28)
#define RTL_SPI_SFCSR_LEN4 (0x03 << 28)
/* SPI Flash Data Register */
#define RTL_SPI_SFDR 0x0c
#define REG(x) (rtspi->base + x)
static void rt_set_cs(struct spi_device *spi, bool active)
{
struct rtspi *rtspi = spi_controller_get_devdata(spi->controller);
u32 value;
/* CS0 bit is active low */
value = readl(REG(RTL_SPI_SFCSR));
if (active)
value |= RTL_SPI_SFCSR_CSB0;
else
value &= ~RTL_SPI_SFCSR_CSB0;
writel(value, REG(RTL_SPI_SFCSR));
}
static void set_size(struct rtspi *rtspi, int size)
{
u32 value;
value = readl(REG(RTL_SPI_SFCSR));
value &= RTL_SPI_SFCSR_LEN_MASK;
if (size == 4)
value |= RTL_SPI_SFCSR_LEN4;
else if (size == 1)
value |= RTL_SPI_SFCSR_LEN1;
writel(value, REG(RTL_SPI_SFCSR));
}
static inline void wait_ready(struct rtspi *rtspi)
{
while (!(readl(REG(RTL_SPI_SFCSR)) & RTL_SPI_SFCSR_RDY))
cpu_relax();
}
static void send4(struct rtspi *rtspi, const u32 *buf)
{
wait_ready(rtspi);
set_size(rtspi, 4);
writel(*buf, REG(RTL_SPI_SFDR));
}
static void send1(struct rtspi *rtspi, const u8 *buf)
{
wait_ready(rtspi);
set_size(rtspi, 1);
writel(buf[0] << 24, REG(RTL_SPI_SFDR));
}
static void rcv4(struct rtspi *rtspi, u32 *buf)
{
wait_ready(rtspi);
set_size(rtspi, 4);
*buf = readl(REG(RTL_SPI_SFDR));
}
static void rcv1(struct rtspi *rtspi, u8 *buf)
{
wait_ready(rtspi);
set_size(rtspi, 1);
*buf = readl(REG(RTL_SPI_SFDR)) >> 24;
}
static int transfer_one(struct spi_controller *ctrl, struct spi_device *spi,
struct spi_transfer *xfer)
{
struct rtspi *rtspi = spi_controller_get_devdata(ctrl);
void *rx_buf;
const void *tx_buf;
int cnt;
tx_buf = xfer->tx_buf;
rx_buf = xfer->rx_buf;
cnt = xfer->len;
if (tx_buf) {
while (cnt >= 4) {
send4(rtspi, tx_buf);
tx_buf += 4;
cnt -= 4;
}
while (cnt) {
send1(rtspi, tx_buf);
tx_buf++;
cnt--;
}
} else if (rx_buf) {
while (cnt >= 4) {
rcv4(rtspi, rx_buf);
rx_buf += 4;
cnt -= 4;
}
while (cnt) {
rcv1(rtspi, rx_buf);
rx_buf++;
cnt--;
}
}
spi_finalize_current_transfer(ctrl);
return 0;
}
static void init_hw(struct rtspi *rtspi)
{
u32 value;
/* Turn on big-endian byte ordering */
value = readl(REG(RTL_SPI_SFCR));
value |= RTL_SPI_SFCR_RBO | RTL_SPI_SFCR_WBO;
writel(value, REG(RTL_SPI_SFCR));
value = readl(REG(RTL_SPI_SFCSR));
/* Permanently disable CS1, since it's never used */
value |= RTL_SPI_SFCSR_CSB1;
/* Select CS0 for use */
value &= RTL_SPI_SFCSR_CS;
writel(value, REG(RTL_SPI_SFCSR));
}
static int realtek_rtl_spi_probe(struct platform_device *pdev)
{
struct spi_controller *ctrl;
struct rtspi *rtspi;
int err;
ctrl = devm_spi_alloc_master(&pdev->dev, sizeof(*rtspi));
if (!ctrl) {
dev_err(&pdev->dev, "Error allocating SPI controller\n");
return -ENOMEM;
}
platform_set_drvdata(pdev, ctrl);
rtspi = spi_controller_get_devdata(ctrl);
rtspi->base = devm_platform_get_and_ioremap_resource(pdev, 0, NULL);
if (IS_ERR(rtspi->base)) {
dev_err(&pdev->dev, "Could not map SPI register address");
return -ENOMEM;
}
init_hw(rtspi);
ctrl->dev.of_node = pdev->dev.of_node;
ctrl->flags = SPI_CONTROLLER_HALF_DUPLEX;
ctrl->set_cs = rt_set_cs;
ctrl->transfer_one = transfer_one;
err = devm_spi_register_controller(&pdev->dev, ctrl);
if (err) {
dev_err(&pdev->dev, "Could not register SPI controller\n");
return -ENODEV;
}
return 0;
}
static const struct of_device_id realtek_rtl_spi_of_ids[] = {
{ .compatible = "realtek,rtl8380-spi" },
{ .compatible = "realtek,rtl8382-spi" },
{ .compatible = "realtek,rtl8391-spi" },
{ .compatible = "realtek,rtl8392-spi" },
{ .compatible = "realtek,rtl8393-spi" },
{ /* sentinel */ }
};
MODULE_DEVICE_TABLE(of, realtek_rtl_spi_of_ids);
static struct platform_driver realtek_rtl_spi_driver = {
.probe = realtek_rtl_spi_probe,
.driver = {
.name = "realtek-rtl-spi",
.of_match_table = realtek_rtl_spi_of_ids,
},
};
module_platform_driver(realtek_rtl_spi_driver);
MODULE_LICENSE("GPL v2");
MODULE_AUTHOR("Bert Vermeulen <[email protected]>");
MODULE_DESCRIPTION("Realtek RTL SPI driver");
|
import torch
import numpy as np
from lib.evaluator.iou import iou
def nms(pred, iou_threshold, score_threshold):
'''Non maxima suppresion for predictions'''
#filter by score threshold
idx = pred[:,-1] > score_threshold
pred = pred[idx]
#order predictions by descending score
idx = np.argsort(pred[:,-1])
predScore = pred[idx, -1]
pred = pred[idx, :-1]
#contiguous array
pred = np.ascontiguousarray(pred[::-1])
predScore = np.ascontiguousarray(predScore[::-1])
#calculate iou for each box
for boxidx, box in enumerate(pred[:-1]):
boxcopies = np.tile(box.reshape(1,-1), (len(pred)-boxidx-1,1))
ious = iou(torch.FloatTensor(boxcopies), torch.FloatTensor(pred[boxidx+1:]))
mask = (ious<iou_threshold).float().view(-1,1).repeat(1,7).numpy()
pred[boxidx+1:] *= mask
#remove zeroed entries
idx = pred[:,3] > 0
pred = pred[idx]
predScore = predScore[idx]
#Add scores back
pred = np.hstack((pred, predScore.reshape(-1,1)))
return pred
|
<reponame>AeroPython/AeroPy
# coding: utf-8
"""Tests of the ISA functions.
All numerical results are validated against the `COESA`_ standard.
.. _`COESA`: http://hdl.handle.net/2060/19770009539
Based on scikit-aero (c) 2012 scikit-aero authors.
"""
import numpy as np
from numpy.testing import (assert_equal, assert_almost_equal,
assert_array_equal, assert_array_almost_equal)
import pytest
from aeropy.atmosphere.isa import atm
def test_sea_level():
h = 0.0 # m
expected_T = 288.15 # K
expected_p = 101325.0 # Pa
expected_rho = 1.2250 # kg / m3
T, p, rho = atm(h)
# Reads: "Assert if T equals expected_T"
assert_equal(T, expected_T)
assert_equal(p, expected_p)
assert_almost_equal(rho, expected_rho, decimal=4)
def test_scalar_input_returns_scalar_output():
h = 0.0 # m
T, p, rho = atm(h)
# Reads: "Assert if T is a float"
assert isinstance(T, float)
assert isinstance(p, float)
assert isinstance(rho, float)
def test_array_input_returns_array_output():
num = 5
h = np.zeros(5) # m
T, p, rho = atm(h)
# Reads: "Assert if the length of T equals num"
# Notice that T has to be a sequence in the first place or len(T)
# will raise TypeError
assert_equal(len(T), num)
assert_equal(len(p), num)
assert_equal(len(rho), num)
def test_emits_warning_for_altitude_outside_range(recwarn):
h = -1.0 # m
atm(h)
warning = recwarn.pop(RuntimeWarning)
assert issubclass(warning.category, RuntimeWarning)
def test_values_outside_range_are_nan():
h = np.array([-1.0, 0.0]) # m
T, p, rho = atm(h)
assert_equal(T[0], np.nan)
assert_equal(p[0], np.nan)
assert_equal(rho[0], np.nan)
def test_results_under_11km():
h = np.array([0.0,
50.0,
550.0,
6500.0,
10000.0,
11000.0
]) # m
expected_T = np.array([288.150,
287.825,
284.575,
245.900,
223.150,
216.650
]) # K
expected_p = np.array([101325.0,
100720.0,
94890.0,
44034.0,
26436.0,
22632.0
]) # Pa
expected_rho = np.array([1.2250,
1.2191,
1.1616,
0.62384,
0.41271,
0.36392
]) # kg / m3
T, p, rho = atm(h)
assert_array_almost_equal(T, expected_T, decimal=3)
assert_array_almost_equal(p, expected_p, decimal=-1)
assert_array_almost_equal(rho, expected_rho, decimal=4)
def test_results_under_20km():
h = np.array([12000,
14200,
17500,
20000
]) # m
expected_T = np.array([216.650,
216.650,
216.650,
216.650,
]) # K
expected_p = np.array([19330.0,
13663.0,
8120.5,
5474.8
]) # Pa
expected_rho = np.array([0.31083,
0.21971,
0.13058,
0.088035
]) # kg / m3
T, p, rho = atm(h)
assert_array_almost_equal(T, expected_T, decimal=3)
assert_array_almost_equal(p, expected_p, decimal=0)
assert_array_almost_equal(rho, expected_rho, decimal=5)
def test_results_under_32km():
h = np.array([22100,
24000,
28800,
32000
]) # m
expected_T = np.array([218.750,
220.650,
225.450,
228.650
]) # K
expected_p = np.array([3937.7,
2930.4,
1404.8,
868.01
]) # Pa
expected_rho = np.array([0.062711,
0.046267,
0.021708,
0.013225
]) # kg / m3
T, p, rho = atm(h)
assert_array_almost_equal(T, expected_T, decimal=3)
assert_array_almost_equal(p, expected_p, decimal=1)
assert_array_almost_equal(rho, expected_rho, decimal=5)
|
/*
* JBoss, Home of Professional Open Source
*
* Copyright 2015 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak.authorization.policy.provider.js;
import java.util.function.BiFunction;
import org.keycloak.authorization.AuthorizationProvider;
import org.keycloak.authorization.model.Policy;
import org.keycloak.authorization.policy.evaluation.Evaluation;
import org.keycloak.authorization.policy.provider.PolicyProvider;
import org.keycloak.scripting.EvaluatableScriptAdapter;
/**
* @author <a href="mailto:<EMAIL>"><NAME></a>
*/
class JSPolicyProvider implements PolicyProvider {
private final BiFunction<AuthorizationProvider, Policy, EvaluatableScriptAdapter> evaluatableScript;
JSPolicyProvider(final BiFunction<AuthorizationProvider, Policy, EvaluatableScriptAdapter> evaluatableScript) {
this.evaluatableScript = evaluatableScript;
}
@Override
public void evaluate(Evaluation evaluation) {
Policy policy = evaluation.getPolicy();
AuthorizationProvider authorization = evaluation.getAuthorizationProvider();
final EvaluatableScriptAdapter adapter = evaluatableScript.apply(authorization, policy);
try {
//how to deal with long running scripts -> timeout?
adapter.eval(bindings -> {
bindings.put("script", adapter.getScriptModel());
bindings.put("$evaluation", evaluation);
});
}
catch (Exception e) {
throw new RuntimeException("Error evaluating JS Policy [" + policy.getName() + "].", e);
}
}
@Override
public void close() {
}
}
|
<filename>crates/ruma-events/src/room/name.rs<gh_stars>1000+
//! Types for the `m.room.name` event.
use ruma_events_macros::EventContent;
use ruma_identifiers::RoomNameBox;
use serde::{Deserialize, Serialize};
/// The content of an `m.room.name` event.
///
/// The room name is a human-friendly string designed to be displayed to the end-user.
#[derive(Clone, Debug, Deserialize, Serialize, EventContent)]
#[ruma_event(type = "m.room.name", kind = State)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
pub struct RoomNameEventContent {
/// The name of the room.
#[serde(default, deserialize_with = "ruma_serde::empty_string_as_none")]
pub name: Option<RoomNameBox>,
}
impl RoomNameEventContent {
/// Create a new `RoomNameEventContent` with the given name.
pub fn new(name: Option<RoomNameBox>) -> Self {
Self { name }
}
}
#[cfg(test)]
mod tests {
use std::convert::TryFrom;
use js_int::{int, uint};
use matches::assert_matches;
use ruma_common::MilliSecondsSinceUnixEpoch;
use ruma_identifiers::{event_id, room_id, user_id, RoomNameBox};
use ruma_serde::Raw;
use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
use super::RoomNameEventContent;
use crate::{StateEvent, Unsigned};
#[test]
fn serialization_with_optional_fields_as_none() {
let name_event = StateEvent {
content: RoomNameEventContent { name: RoomNameBox::try_from("The room name").ok() },
event_id: event_id!("$h29iv0s8:example.com"),
origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(1)),
prev_content: None,
room_id: room_id!("!n8f893n9:example.com"),
sender: user_id!("@carl:example.com"),
state_key: "".into(),
unsigned: Unsigned::default(),
};
let actual = to_json_value(&name_event).unwrap();
let expected = json!({
"content": {
"name": "The room name"
},
"event_id": "$h29iv0s8:example.com",
"origin_server_ts": 1,
"room_id": "!n8f893n9:example.com",
"sender": "@carl:example.com",
"state_key": "",
"type": "m.room.name"
});
assert_eq!(actual, expected);
}
#[test]
fn serialization_with_all_fields() {
let name_event = StateEvent {
content: RoomNameEventContent { name: RoomNameBox::try_from("The room name").ok() },
event_id: event_id!("$h29iv0s8:example.com"),
origin_server_ts: MilliSecondsSinceUnixEpoch(uint!(1)),
prev_content: Some(RoomNameEventContent {
name: RoomNameBox::try_from("The old name").ok(),
}),
room_id: room_id!("!n8f893n9:example.com"),
sender: user_id!("@carl:example.com"),
state_key: "".into(),
unsigned: Unsigned { age: Some(int!(100)), ..Unsigned::default() },
};
let actual = to_json_value(&name_event).unwrap();
let expected = json!({
"content": {
"name": "The room name"
},
"event_id": "$h29iv0s8:example.com",
"origin_server_ts": 1,
"prev_content": { "name": "The old name" },
"room_id": "!n8f893n9:example.com",
"sender": "@carl:example.com",
"state_key": "",
"type": "m.room.name",
"unsigned": {
"age": 100
}
});
assert_eq!(actual, expected);
}
#[test]
fn absent_field_as_none() {
let json_data = json!({
"content": {},
"event_id": "$h29iv0s8:example.com",
"origin_server_ts": 1,
"room_id": "!n8f893n9:example.com",
"sender": "@carl:example.com",
"state_key": "",
"type": "m.room.name"
});
assert_eq!(
from_json_value::<StateEvent<RoomNameEventContent>>(json_data).unwrap().content.name,
None
);
}
#[test]
fn name_fails_validation_when_too_long() {
// "XXXX .." 256 times
let long_string: String = "X".repeat(256);
assert_eq!(long_string.len(), 256);
let long_content_json = json!({ "name": &long_string });
let from_raw: Raw<RoomNameEventContent> = from_json_value(long_content_json).unwrap();
let result = from_raw.deserialize();
assert!(result.is_err(), "Result should be invalid: {:?}", result);
}
#[test]
fn json_with_empty_name_creates_content_as_none() {
let long_content_json = json!({ "name": "" });
let from_raw: Raw<RoomNameEventContent> = from_json_value(long_content_json).unwrap();
assert_matches!(from_raw.deserialize().unwrap(), RoomNameEventContent { name: None });
}
#[test]
fn new_with_empty_name_creates_content_as_none() {
assert_matches!(
RoomNameEventContent::new(RoomNameBox::try_from(String::new()).ok()),
RoomNameEventContent { name: None }
);
}
#[test]
fn null_field_as_none() {
let json_data = json!({
"content": {
"name": null
},
"event_id": "$h29iv0s8:example.com",
"origin_server_ts": 1,
"room_id": "!n8f893n9:example.com",
"sender": "@carl:example.com",
"state_key": "",
"type": "m.room.name"
});
assert_eq!(
from_json_value::<StateEvent<RoomNameEventContent>>(json_data).unwrap().content.name,
None
);
}
#[test]
fn empty_string_as_none() {
let json_data = json!({
"content": {
"name": ""
},
"event_id": "$h29iv0s8:example.com",
"origin_server_ts": 1,
"room_id": "!n8f893n9:example.com",
"sender": "@carl:example.com",
"state_key": "",
"type": "m.room.name"
});
assert_eq!(
from_json_value::<StateEvent<RoomNameEventContent>>(json_data).unwrap().content.name,
None
);
}
#[test]
fn nonempty_field_as_some() {
let name = RoomNameBox::try_from("The room name").ok();
let json_data = json!({
"content": {
"name": "The room name"
},
"event_id": "$h29iv0s8:example.com",
"origin_server_ts": 1,
"room_id": "!n8f893n9:example.com",
"sender": "@carl:example.com",
"state_key": "",
"type": "m.room.name"
});
assert_eq!(
from_json_value::<StateEvent<RoomNameEventContent>>(json_data).unwrap().content.name,
name
);
}
}
|
Republican Gov. Sam Brownback signed into law Thursday restrictions on how much cash Kansas welfare recipients can withdraw from ATMs using their benefits cards, a move some critics slammed as a “tax on the poor."
The measure set the withdrawal limit at $25 per transaction. With an average withdrawal fee in U.S. of $4.35, according to bankrate.com, and with most ATMs not dispensing $5 bills, the fee amounts to about a 20 percent levy on the poor.
The law also bans poor families from using welfare money to attend concerts, get tattoos, see a psychic or buy lingerie. The list of don'ts runs to several dozen items and is part of a growing number of laws in more than 20 states that curtail people’s spending patterns.
The measure passed by the Republican-dominated Kansas legislature appears to include the most exhaustive list of welfare spending curbs in the nation, according to officials at the state’s Department for Children and Families.
State officials said that it is difficult to track how often welfare assistance is used for items on the state's new list, because recipients can use their benefits cards to withdraw cash. The new limits on ATM use are supposed to prevent the poor from spending tax dollars on luxuries, state officials argue.
But the limit will significantly harm welfare recipients’ spending patterns, according to Elizabeth Lower-Basch, director at Center for Law and Social Policy (CLASP), an advocacy group for low-income people.
“It’s really disconnected from the reality of people’s lives. The single biggest expense that people have is rent,” said Lower-Basch, adding that a $25 limit would likely result in multiple trips to an ATM until the total amount of rent money is withdrawn. “They’re just going to have to go every day to get their rent money.”
"Also," she added, “No ATM gives you a $25 bill, so the real limit is $20. “It’s a mess.”
Many banks charge additional fees for every cash withdrawal with the government-issued social assistance cards, accruing millions of dollars each year.
California welfare recipients, for example, spent $19 million on the fees last year, effectively shifting public funds from where they are most needed to banks, according to a report from the California Reinvestment Coalition, an advocacy organization for low-income families. The total fee of using an Electronic Benefit Card at an ATM can be up to $4 in most states, the report found.
“It’s a tax on the poor, basically, because they are charged every time they withdraw funds from the ATM. Welfare benefits are not very high in the first place, so this just takes money out of poor people’s pockets,” Lower-Basch said.
The Kansas list with restrictions is part of a broader welfare law taking effect in July that Brownback and his allies say is aimed at moving poor families from social services into jobs.
"We want to get people off of public assistance and into private-sector employment, and we've had a lot of success with that," Brownback said during an interview this week with The Associated Press.
A 2012 federal law requires states to prevent benefit-card use at liquor stores, gambling establishments or adult-entertainment businesses.
At least 23 states have additional restrictions on how cards can be used, mostly for alcohol, tobacco, gambling and adult-oriented businesses, according to the National Conference of State Legislatures (NCSL).
A few states — not Kansas — prohibit buying guns, according to the NCSL, and a few ban tattoos or body piercings. Massachusetts prohibits spending on jewelry, bail bonds or "vacation services." A 2014 Louisiana law bars card use on cruise ships, which is also on the Kansas list.
A 2014 federal report said a review of eight states' data showed transactions with benefit cards at liquor stores, casinos or strip clubs accounted for less than 1 percent of the total.
"The list has attracted attention because it feels mean-spirited," said Shannon Cotsoradis, president of the advocacy group Kansas Action for Children. "It really seems to make a statement about how we feel about the poor."
Phyllis Gilmore, secretary of the Kansas Department for Children and Families, said her state's list is a “composite” of others and has educational value, sending the message that cash assistance should be used for necessities.
The department said it reclaimed $199,000 in cash assistance from 81 fraud cases from July through February, but said most involved questions about eligibility. Kansas provided $14 million in cash assistance during the same period.
“Every dollar that is used fraudulently is a dollar that is not going to an American who is struggling,” said state Sen. Michael O'Donnell, a Wichita Republican who supported the bill.
The number of cash assistance recipients in Kansas has dropped 63 percent since Brownback took office, to about 14,700 in February. Brownback said the decline confirms the success of his policies, but critics note that U.S. Census Bureau figures show the state's child poverty rate remaining at about 19 percent through 2013.
Al Jazeera and The Associated Press
|
<filename>tests/kamereon/test_kamereon_vehicle_data.py<gh_stars>0
"""Tests for Kamereon models."""
from typing import cast
import pytest
from tests import fixtures
from renault_api.kamereon import enums
from renault_api.kamereon import models
from renault_api.kamereon import schemas
from renault_api.kamereon.helpers import DAYS_OF_WEEK
@pytest.mark.parametrize(
"filename",
fixtures.get_json_files(f"{fixtures.KAMEREON_FIXTURE_PATH}/vehicle_data"),
)
def test_vehicle_data_response(filename: str) -> None:
"""Test vehicle data response."""
response: models.KamereonVehicleDataResponse = fixtures.get_file_content_as_schema(
filename, schemas.KamereonVehicleDataResponseSchema
)
response.raise_for_error_code()
# Ensure the VIN is hidden
assert response.data is not None
assert response.data.id is not None
assert response.data.id.startswith(("VF1AAAA", "UU1AAAA"))
def test_battery_status_1() -> None:
"""Test vehicle data for battery-status.1.json."""
response: models.KamereonVehicleDataResponse = fixtures.get_file_content_as_schema(
f"{fixtures.KAMEREON_FIXTURE_PATH}/vehicle_data/battery-status.1.json",
schemas.KamereonVehicleDataResponseSchema,
)
response.raise_for_error_code()
assert response.data is not None
assert response.data.raw_data["attributes"] == {
"timestamp": "2020-11-17T09:06:48+01:00",
"batteryLevel": 50,
"batteryAutonomy": 128,
"batteryCapacity": 0,
"batteryAvailableEnergy": 0,
"plugStatus": 0,
"chargingStatus": -1.0,
}
vehicle_data = cast(
models.KamereonVehicleBatteryStatusData,
response.get_attributes(schemas.KamereonVehicleBatteryStatusDataSchema),
)
assert vehicle_data.timestamp == "2020-11-17T09:06:48+01:00"
assert vehicle_data.batteryLevel == 50
assert vehicle_data.batteryTemperature is None
assert vehicle_data.batteryAutonomy == 128
assert vehicle_data.batteryCapacity == 0
assert vehicle_data.batteryAvailableEnergy == 0
assert vehicle_data.plugStatus == 0
assert vehicle_data.chargingStatus == -1.0
assert vehicle_data.chargingRemainingTime is None
assert vehicle_data.chargingInstantaneousPower is None
assert vehicle_data.get_plug_status() == enums.PlugState.UNPLUGGED
assert vehicle_data.get_charging_status() == enums.ChargeState.CHARGE_ERROR
def test_battery_status_2() -> None:
"""Test vehicle data for battery-status.2.json."""
response: models.KamereonVehicleDataResponse = fixtures.get_file_content_as_schema(
f"{fixtures.KAMEREON_FIXTURE_PATH}/vehicle_data/battery-status.2.json",
schemas.KamereonVehicleDataResponseSchema,
)
response.raise_for_error_code()
assert response.data is not None
assert response.data.raw_data["attributes"] == {
"timestamp": "2020-01-12T21:40:16Z",
"batteryLevel": 60,
"batteryTemperature": 20,
"batteryAutonomy": 141,
"batteryCapacity": 0,
"batteryAvailableEnergy": 31,
"plugStatus": 1,
"chargingStatus": 1.0,
"chargingRemainingTime": 145,
"chargingInstantaneousPower": 27.0,
}
vehicle_data = cast(
models.KamereonVehicleBatteryStatusData,
response.get_attributes(schemas.KamereonVehicleBatteryStatusDataSchema),
)
assert vehicle_data.timestamp == "2020-01-12T21:40:16Z"
assert vehicle_data.batteryLevel == 60
assert vehicle_data.batteryTemperature == 20
assert vehicle_data.batteryAutonomy == 141
assert vehicle_data.batteryCapacity == 0
assert vehicle_data.batteryAvailableEnergy == 31
assert vehicle_data.plugStatus == 1
assert vehicle_data.chargingStatus == 1.0
assert vehicle_data.chargingRemainingTime == 145
assert vehicle_data.chargingInstantaneousPower == 27.0
assert vehicle_data.get_plug_status() == enums.PlugState.PLUGGED
assert vehicle_data.get_charging_status() == enums.ChargeState.CHARGE_IN_PROGRESS
def test_cockpit_zoe() -> None:
"""Test vehicle data for cockpit.zoe.json."""
response: models.KamereonVehicleDataResponse = fixtures.get_file_content_as_schema(
f"{fixtures.KAMEREON_FIXTURE_PATH}/vehicle_data/cockpit.zoe.json",
schemas.KamereonVehicleDataResponseSchema,
)
response.raise_for_error_code()
assert response.data is not None
assert response.data.raw_data["attributes"] == {"totalMileage": 49114.27}
vehicle_data = cast(
models.KamereonVehicleCockpitData,
response.get_attributes(schemas.KamereonVehicleCockpitDataSchema),
)
assert vehicle_data.totalMileage == 49114.27
assert vehicle_data.fuelAutonomy is None
assert vehicle_data.fuelQuantity is None
def test_cockpit_captur_ii() -> None:
"""Test vehicle data for cockpit.captur_ii.json."""
response: models.KamereonVehicleDataResponse = fixtures.get_file_content_as_schema(
f"{fixtures.KAMEREON_FIXTURE_PATH}/vehicle_data/cockpit.captur_ii.json",
schemas.KamereonVehicleDataResponseSchema,
)
response.raise_for_error_code()
assert response.data is not None
assert response.data.raw_data["attributes"] == {
"fuelAutonomy": 35.0,
"fuelQuantity": 3.0,
"totalMileage": 5566.78,
}
vehicle_data = cast(
models.KamereonVehicleCockpitData,
response.get_attributes(schemas.KamereonVehicleCockpitDataSchema),
)
assert vehicle_data.totalMileage == 5566.78
assert vehicle_data.fuelAutonomy == 35.0
assert vehicle_data.fuelQuantity == 3.0
def test_charging_settings_single() -> None:
"""Test vehicle data for charging-settings.json."""
response: models.KamereonVehicleDataResponse = fixtures.get_file_content_as_schema(
f"{fixtures.KAMEREON_FIXTURE_PATH}/vehicle_data/charging-settings.single.json",
schemas.KamereonVehicleDataResponseSchema,
)
response.raise_for_error_code()
assert response.data is not None
assert response.data.raw_data["attributes"] == {
"mode": "scheduled",
"schedules": [
{
"id": 1,
"activated": True,
"monday": {"startTime": "T12:00Z", "duration": 15},
"tuesday": {"startTime": "T04:30Z", "duration": 420},
"wednesday": {"startTime": "T22:30Z", "duration": 420},
"thursday": {"startTime": "T22:00Z", "duration": 420},
"friday": {"startTime": "T12:15Z", "duration": 15},
"saturday": {"startTime": "T12:30Z", "duration": 30},
"sunday": {"startTime": "T12:45Z", "duration": 45},
}
],
}
vehicle_data = cast(
models.KamereonVehicleChargingSettingsData,
response.get_attributes(schemas.KamereonVehicleChargingSettingsDataSchema),
)
assert vehicle_data.mode == "scheduled"
assert vehicle_data.schedules is not None
assert len(vehicle_data.schedules) == 1
schedule_data = vehicle_data.schedules[0]
assert schedule_data.id == 1
assert schedule_data.activated is True
assert schedule_data.monday is not None
assert schedule_data.monday.startTime == "T12:00Z"
assert schedule_data.monday.duration == 15
assert schedule_data.tuesday is not None
assert schedule_data.tuesday.startTime == "T04:30Z"
assert schedule_data.tuesday.duration == 420
assert schedule_data.wednesday is not None
assert schedule_data.wednesday.startTime == "T22:30Z"
assert schedule_data.wednesday.duration == 420
assert schedule_data.thursday is not None
assert schedule_data.thursday.startTime == "T22:00Z"
assert schedule_data.thursday.duration == 420
assert schedule_data.friday is not None
assert schedule_data.friday.startTime == "T12:15Z"
assert schedule_data.friday.duration == 15
assert schedule_data.saturday is not None
assert schedule_data.saturday.startTime == "T12:30Z"
assert schedule_data.saturday.duration == 30
assert schedule_data.sunday is not None
assert schedule_data.sunday.startTime == "T12:45Z"
assert schedule_data.sunday.duration == 45
def test_charging_settings_multi() -> None:
"""Test vehicle data for charging-settings.json."""
response: models.KamereonVehicleDataResponse = fixtures.get_file_content_as_schema(
f"{fixtures.KAMEREON_FIXTURE_PATH}/vehicle_data/charging-settings.multi.json",
schemas.KamereonVehicleDataResponseSchema,
)
response.raise_for_error_code()
assert response.data is not None
assert response.data.raw_data["attributes"] == {
"mode": "scheduled",
"schedules": [
{
"id": 1,
"activated": True,
"monday": {"startTime": "T00:00Z", "duration": 450},
"tuesday": {"startTime": "T00:00Z", "duration": 450},
"wednesday": {"startTime": "T00:00Z", "duration": 450},
"thursday": {"startTime": "T00:00Z", "duration": 450},
"friday": {"startTime": "T00:00Z", "duration": 450},
"saturday": {"startTime": "T00:00Z", "duration": 450},
"sunday": {"startTime": "T00:00Z", "duration": 450},
},
{
"id": 2,
"activated": True,
"monday": {"startTime": "T23:30Z", "duration": 15},
"tuesday": {"startTime": "T23:30Z", "duration": 15},
"wednesday": {"startTime": "T23:30Z", "duration": 15},
"thursday": {"startTime": "T23:30Z", "duration": 15},
"friday": {"startTime": "T23:30Z", "duration": 15},
"saturday": {"startTime": "T23:30Z", "duration": 15},
"sunday": {"startTime": "T23:30Z", "duration": 15},
},
{"id": 3, "activated": False},
{"id": 4, "activated": False},
{"id": 5, "activated": False},
],
}
vehicle_data = cast(
models.KamereonVehicleChargingSettingsData,
response.get_attributes(schemas.KamereonVehicleChargingSettingsDataSchema),
)
assert vehicle_data.mode == "scheduled"
assert vehicle_data.schedules is not None
assert len(vehicle_data.schedules) == 5
schedule_data = vehicle_data.schedules[0]
assert schedule_data.id == 1
assert schedule_data.activated is True
assert schedule_data.monday is not None
assert schedule_data.monday.startTime == "T00:00Z"
assert schedule_data.monday.duration == 450
assert schedule_data.tuesday is not None
assert schedule_data.tuesday.startTime == "T00:00Z"
assert schedule_data.tuesday.duration == 450
assert schedule_data.wednesday is not None
assert schedule_data.wednesday.startTime == "T00:00Z"
assert schedule_data.wednesday.duration == 450
assert schedule_data.thursday is not None
assert schedule_data.thursday.startTime == "T00:00Z"
assert schedule_data.thursday.duration == 450
assert schedule_data.friday is not None
assert schedule_data.friday.startTime == "T00:00Z"
assert schedule_data.friday.duration == 450
assert schedule_data.saturday is not None
assert schedule_data.saturday.startTime == "T00:00Z"
assert schedule_data.saturday.duration == 450
assert schedule_data.sunday is not None
assert schedule_data.sunday.startTime == "T00:00Z"
assert schedule_data.sunday.duration == 450
def test_location_v1() -> None:
"""Test vehicle data for location.1.json."""
response: models.KamereonVehicleDataResponse = fixtures.get_file_content_as_schema(
f"{fixtures.KAMEREON_FIXTURE_PATH}/vehicle_data/location.1.json",
schemas.KamereonVehicleDataResponseSchema,
)
response.raise_for_error_code()
assert response.data is not None
assert response.data.raw_data["attributes"] == {
"gpsLatitude": 48.1234567,
"gpsLongitude": 11.1234567,
"lastUpdateTime": "2020-02-18T16:58:38Z",
}
vehicle_data = cast(
models.KamereonVehicleLocationData,
response.get_attributes(schemas.KamereonVehicleLocationDataSchema),
)
assert vehicle_data.gpsLatitude == 48.1234567
assert vehicle_data.gpsLongitude == 11.1234567
assert vehicle_data.lastUpdateTime == "2020-02-18T16:58:38Z"
def test_location_v2() -> None:
"""Test vehicle data for location.2.json."""
response: models.KamereonVehicleDataResponse = fixtures.get_file_content_as_schema(
f"{fixtures.KAMEREON_FIXTURE_PATH}/vehicle_data/location.2.json",
schemas.KamereonVehicleDataResponseSchema,
)
response.raise_for_error_code()
assert response.data is not None
assert response.data.raw_data["attributes"] == {
"gpsDirection": None,
"gpsLatitude": 48.1234567,
"gpsLongitude": 11.1234567,
"lastUpdateTime": "2020-02-18T16:58:38Z",
}
vehicle_data = cast(
models.KamereonVehicleLocationData,
response.get_attributes(schemas.KamereonVehicleLocationDataSchema),
)
assert vehicle_data.gpsLatitude == 48.1234567
assert vehicle_data.gpsLongitude == 11.1234567
assert vehicle_data.lastUpdateTime == "2020-02-18T16:58:38Z"
def test_lock_status_locked() -> None:
"""Test lock-status for lock-status.1.json."""
response: models.KamereonVehicleDataResponse = fixtures.get_file_content_as_schema(
f"{fixtures.KAMEREON_FIXTURE_PATH}/vehicle_data/lock-status.1.json",
schemas.KamereonVehicleDataResponseSchema,
)
response.raise_for_error_code()
assert response.data is not None
assert response.data.raw_data["attributes"] == {
"lockStatus": "locked",
"doorStatusRearLeft": "closed",
"doorStatusRearRight": "closed",
"doorStatusDriver": "closed",
"doorStatusPassenger": "closed",
"hatchStatus": "closed",
"lastUpdateTime": "2022-02-02T13:51:13Z",
}
vehicle_data = cast(
models.KamereonVehicleLockStatusData,
response.get_attributes(schemas.KamereonVehicleLockStatusDataSchema),
)
assert vehicle_data.lockStatus == "locked"
assert vehicle_data.doorStatusRearLeft == "closed"
assert vehicle_data.doorStatusRearRight == "closed"
assert vehicle_data.doorStatusDriver == "closed"
assert vehicle_data.doorStatusPassenger == "closed"
assert vehicle_data.hatchStatus == "closed"
assert vehicle_data.lastUpdateTime == "2022-02-02T13:51:13Z"
def test_lock_status_unlocked() -> None:
"""Test lock-status for lock-status.2.json."""
response: models.KamereonVehicleDataResponse = fixtures.get_file_content_as_schema(
f"{fixtures.KAMEREON_FIXTURE_PATH}/vehicle_data/lock-status.2.json",
schemas.KamereonVehicleDataResponseSchema,
)
response.raise_for_error_code()
assert response.data is not None
assert response.data.raw_data["attributes"] == {
"lockStatus": "unlocked",
"doorStatusRearLeft": "closed",
"doorStatusRearRight": "closed",
"doorStatusDriver": "closed",
"doorStatusPassenger": "closed",
"hatchStatus": "closed",
"lastUpdateTime": "2022-02-02T13:51:13Z",
}
vehicle_data = cast(
models.KamereonVehicleLockStatusData,
response.get_attributes(schemas.KamereonVehicleLockStatusDataSchema),
)
assert vehicle_data.lockStatus == "unlocked"
assert vehicle_data.doorStatusRearLeft == "closed"
assert vehicle_data.doorStatusRearRight == "closed"
assert vehicle_data.doorStatusDriver == "closed"
assert vehicle_data.doorStatusPassenger == "closed"
assert vehicle_data.hatchStatus == "closed"
assert vehicle_data.lastUpdateTime == "2022-02-02T13:51:13Z"
def test_charge_mode() -> None:
"""Test vehicle data for charge-mode.json."""
response: models.KamereonVehicleDataResponse = fixtures.get_file_content_as_schema(
f"{fixtures.KAMEREON_FIXTURE_PATH}/vehicle_data/charge-mode.json",
schemas.KamereonVehicleDataResponseSchema,
)
response.raise_for_error_code()
assert response.data is not None
assert response.data.raw_data["attributes"] == {"chargeMode": "always"}
vehicle_data = cast(
models.KamereonVehicleChargeModeData,
response.get_attributes(schemas.KamereonVehicleChargeModeDataSchema),
)
assert vehicle_data.chargeMode == "always"
def test_hvac_settings_mode() -> None:
"""Test vehicle data with hvac settings for mode."""
response: models.KamereonVehicleDataResponse = fixtures.get_file_content_as_schema(
f"{fixtures.KAMEREON_FIXTURE_PATH}/vehicle_data/hvac-settings.json",
schemas.KamereonVehicleDataResponseSchema,
)
response.raise_for_error_code()
vehicle_data = cast(
models.KamereonVehicleHvacSettingsData,
response.get_attributes(schemas.KamereonVehicleHvacSettingsDataSchema),
)
assert vehicle_data.mode == "scheduled"
def test_hvac_settings_schedule() -> None:
"""Test vehicle data with hvac schedule entries."""
response: models.KamereonVehicleDataResponse = fixtures.get_file_content_as_schema(
f"{fixtures.KAMEREON_FIXTURE_PATH}/vehicle_data/hvac-settings.json",
schemas.KamereonVehicleDataResponseSchema,
)
response.raise_for_error_code()
vehicle_data = cast(
models.KamereonVehicleHvacSettingsData,
response.get_attributes(schemas.KamereonVehicleHvacSettingsDataSchema),
)
assert vehicle_data.mode == "scheduled"
assert vehicle_data.schedules is not None
assert vehicle_data.schedules[1].id == 2
assert vehicle_data.schedules[1].wednesday is not None
assert vehicle_data.schedules[1].wednesday.readyAtTime == "T15:15Z"
assert vehicle_data.schedules[1].friday is not None
assert vehicle_data.schedules[1].friday.readyAtTime == "T15:15Z"
assert vehicle_data.schedules[1].monday is None
for i in [0, 2, 3, 4]:
assert vehicle_data.schedules[i].id == i + 1
for day in DAYS_OF_WEEK:
assert vehicle_data.schedules[i].__dict__.get(day) is None
|
//! Returns the number of search grids
static int numGrids(const GridSet::DomainSetup& domainSetup)
{
static constexpr int sc_numGridsForTestParticleInsertion = 2;
if (domainSetup.doTestParticleInsertion)
{
return sc_numGridsForTestParticleInsertion;
}
else
{
int numGrids = 1;
for (auto haveDD : domainSetup.haveMultipleDomainsPerDim)
{
if (haveDD)
{
numGrids *= 2;
}
}
return numGrids;
}
}
|
<filename>src/main/java/lab/rest1/service/impl/UserServiceImpl.java
package lab.rest1.service.impl;
import lab.rest1.domain.Location;
import lab.rest1.domain.Owner;
import lab.rest1.domain.Pet;
import lab.rest1.domain.User;
import lab.rest1.repository.UserRepository;
import lab.rest1.service.UserService;
import org.apache.tomcat.util.digester.ArrayStack;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.File;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
private UserRepository userRespository;
@Autowired
public UserServiceImpl(UserRepository userRespository) {
this.userRespository = userRespository;
}
@Override
public void uploadPhoto(File photo) {
// TODO
}
@Override
public void markAsViewed(Pet pet) {
// TODO
}
@Override
public void askForReward(Owner owner) {
// TODO
}
@Override
public void save(User user) {
userRespository.save(user);
}
@Override
public void delete(User user) {
userRespository.delete(user);
}
@Override
public List<User> list() {
List<User> users = new ArrayStack<>();
userRespository.findAll().forEach(users::add);
return users;
}
@Override
public User find(User owner) {
return null;
}
@Override
public User findById(Long id) {
return userRespository.findById(id).get();
}
@Override
public void shareLocation(Location location) {
// TODO
}
}
|
// Ensure that a 3x1 trigger focuses on the tap coordinate.
TEST_F(MagnifierTest, TriggerFocus) {
MockMagnificationHandler handler;
magnifier()->RegisterHandler(handler.NewBinding());
static constexpr glm::vec2 tap_coordinate{.5f, -.25f};
SendPointerEvents(3 * TapEvents(1, tap_coordinate));
RunLoopFor(kTestTransitionPeriod);
EXPECT_EQ(handler.transform().Apply(tap_coordinate), tap_coordinate) << handler.transform();
}
|
/**
* A two dimensional vector point in space. Contains an x and a y floating point value.
* @author Peter Verzijl
* @version 1.0a
*/
public class Vector2 {
private float x;
private float y;
public static final Vector2 ZERO() { return new Vector2(0, 0); }
public static final Vector2 UNITY() { return new Vector2(1, 1); }
public static final Vector2 RIGHT() { return new Vector2(1, 0); }
public static final Vector2 UP() { return new Vector2(0, 1); }
/**
* The constructor for a floating point two dimensional vector.
* @param x The x coordinate.
* @param y The y coordinate.
*/
public Vector2(float x, float y) {
this.setX(x);
this.setY(y);
}
/**
* Creates a copy of the given vector.
* @param vector The vector to create a copy of.
*/
public Vector2(Vector2 vector) {
assert vector != null : "Error: You cannot create a Vector2 that is null!";
this.setX(vector.getX());
this.setY(vector.getY());
}
/**
* Creates a copy of the given vector.
* @param vector The vector to create a copy of.
*/
public Vector2(Vector3 vector) {
this.setX(vector.getX());
this.setY(vector.getY());
}
/**
* Sets the position of the vector.
* @param x The new value for the new x component of the vector.
* @param y The new value for the new y component of the vector.
*/
public void set(float x, float y) {
this.x = x;
this.y = y;
}
/**
* Sets the position of the old vector to the new one.
* @param newPosition The new position.
*/
public void set(Vector2 newPosition) {
this.x = newPosition.getX();
this.y = newPosition.getY();
}
/**
* Returns the magnitude or length of the vector.
* @return The magniude of the vector.
*/
public float magnitude() {
return (float) Math.sqrt(x * x + y * y);
}
/**
* Sets the vector to a given length.
* @param length The length of the vector
*/
public void setMagnitude(float length) {
normalize();
multiply(Math.abs(length));
}
/**
* Normalizes the vector.
*/
public void normalize() {
// Multiply by ratio
float magnitude = magnitude();
x = x / magnitude;
y = y / magnitude;
}
/**
* Returns a normalized copy of the vector.
* @return The normalized copy.
*/
public Vector2 normalized() {
Vector2 result = this.clone();
result.normalize();
return result;
}
/**
* Returns a copy of the current vector.
* @return A copy of the current vector.
*/
@Override
public Vector2 clone() {
return new Vector2(x, y);
}
/**
* Returns the x coordinate of the vector.
* @return The y coordinate
*/
public float getX() {
return x;
}
/**
* Sets the x coordinate of the vector.
* @param x The new value for the new x component of the vector.
*/
public void setX(float x) {
this.x = x;
}
/**
* Returns the y coordinate of the vector.
* @return The y coordinate
*/
public float getY() {
return y;
}
/**
* Sets the y coordinate of the vector.
* @param y The new value for the new x component of the vector.
*/
public void setY(float y) {
this.y = y;
}
/**
* Prints the vector in the following format (x, y).
*/
@Override
public String toString() {
return "(" + getX() + ", " + getY() + ")";
}
/**
* Adds one vector to the calling vector.
* @param vector The vector to add.
* @return this.
*/
public Vector2 add(Vector2 vector) {
x += vector.getX();
y += vector.getY();
return this;
}
/**
* Adds the two given components to the vector.
* @param x Amount of x to add.
* @param y Amount of y to add.
* @return this.
*/
public Vector2 add(float x, float y) {
this.x += x;
this.y += y;
return this;
}
/**
* Subtracts one vector to the calling vector.
* @param vector The vector to subtract.
* @return this.
*/
public Vector2 subtract(Vector2 vector) {
x -= vector.getX();
y -= vector.getY();
return this;
}
/**
* Subtracts the two given components to the vector.
* @param x Amount of x to subtract.
* @param y Amount of y to subtract.
* @return this.
*/
public Vector2 subtract(float x, float y) {
this.x -= x;
this.y -= y;
return this;
}
/**
* Multiplies the vector by a scalar.
* @param scalar The scalar to multiply the vector by.
* @return The resulting vector.
*/
public Vector2 multiply(float scalar) {
this.x *= scalar;
this.y *= scalar;
return this;
}
/**
* Returns the dot product of two vectors.
* Following the formula: a � b = ax � bx + ay � by
* @param v1 The first Vector3
* @param v2 The second Vector3
* @return The resulting lenth of the dot product.
*/
public static float dot(Vector2 v1, Vector2 v2) {
return v1.x * v2.x + v1.y * v2.y;
}
/**
* Interpolates linearly between two points.
* Uses a precise method which guarantees v = v1 at t = 1.
* @param v1 Vector a
* @param v2 Vector b
* @param t The fraction between the two vectors.
* @return The linearly interpolated vector between v1 and v2 at fraction t.
*/
public static Vector2 lerp(Vector2 v1, Vector2 v2, float t) {
float x = (1-t)*v1.getX() + t*v2.getX();
float y = (1-t)*v1.getY() + t*v2.getY();
return new Vector2(x, y);
}
/**
* Returns a spherically interpolated vector at point t.
* @param v1 The starting vector.
* @param v2 The ending vector.
* @param t The fraction between 1 and 0.
* @return The resulting spherically interpolated vector.
*/
public static Vector2 slerp(Vector2 v1, Vector2 v2, float t) {
return Vector3.slerp(v1.toVector3(), v2.toVector3(), t).toVector2();
}
/**
* Checks if two vectors are equal to another.
* @param vector The vector to check if equal.
* @return Weighter the two vectors are equal.
*/
public boolean equals(Vector2 vector) {
boolean result = false;
if (x == vector.getX() &&
y == vector.getY()) {
result = true;
}
return result;
}
/**
* Converts the Vector3 to a Vector2
* @return The new Vector2.
*/
public Vector3 toVector3() {
return new Vector3(x, y, 0);
}
}
|
package com.jdt.fedlearn.client.netty;
import com.jdt.fedlearn.client.util.ConfigUtil;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SocketClient {
Logger logger = LoggerFactory.getLogger(SocketClient.class);
public void connect() {
String url = ConfigUtil.getClientConfig().getNettyIp();
Integer port = ConfigUtil.getClientConfig().getNettyPort();
// 创建线程组
NioEventLoopGroup nioEventLoopGroup = new NioEventLoopGroup();
// netty启动辅助类
Bootstrap bootstrap = new Bootstrap();
//
bootstrap.group(nioEventLoopGroup)
.channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
.handler(new SocketClientInitializer(this));
try {
ChannelFuture connect = bootstrap
.connect(url, port)
.addListener(new ConnectionListener(this))// netty 启动时如果连接失败,会断线重连
.sync();//直到连接建立成功才执行后面的逻辑。
// 关闭客户端
connect.channel()
.closeFuture()
.sync();//连接建立成功后,直到连接断开才执行后面的逻辑。
logger.info("连接已断开。");
} catch (InterruptedException e) {
logger.error("netty 启动失败:{}",e.getMessage());
}
}
}
|
/**
* Checks that the writing transaction can proceed and updates the database
* to reflect the presence of changes.
* As this {@link Writer} is meant to be wrapped in {@link ThreadSafeWriter}, it has
* to be thread-safe unless one key is accessed for modification concurrently. This implies
* that lazy writing transaction initialization must be intrinsically thread-safe.
* Note that the unsetting of the flag in multithreaded scenarios still requires
* appropriate external synchronization delivered by {@link ThreadSafeWriter}.
*/
private void lazyPrepareTransaction() throws SQLException, StorageException {
if (!dbFlagSet) {
synchronized (dbFlagSettingLock) {
doLazyPrepareTransaction();
}
}
}
|
Governments must start holding companies criminally accountable for serious human rights abuses, including those committed overseas, Amnesty International said in launching a new set of principles for dealing with corporate crime.
A group of legal experts, with the support of Amnesty International and the International Corporate Accountability Roundtable (ICAR), have developed a set of Corporate Crime Principles to advance the investigation and prosecution of human rights cases.
“The inability and unwillingness of governments to meet their obligations under international law and stand up to rights-abusing companies sends the message that they are too powerful to prosecute,” said Seema Joshi, head of Amnesty’s of Business and Human Rights section. “No company, however powerful, should be above the law, yet in the last 15 years no country has put a company on trial after an NGO brought evidence of human rights related crimes abroad. The inability and unwillingness of governments to meet their obligations under international law and stand up to rights-abusing companies sends the message that they are too powerful to prosecute.”
The Corporate Crime Principles aim to address business involvement in a broad range of crimes linked to human rights abuses including forced labour, human trafficking, war crimes, economic crimes and environmental harm.
While they are aimed at governments and law enforcement officials in all countries, they highlight, in particular, cross-border crime where a business headquartered in one country is involved in criminal activity in another.
“Many of the documented cases implicate western corporations in serious human rights abuses in fragile or war-torn areas, and the ‘out of sight, out of mind’ mentality of these companies’ governments exposes a deadly double standard,” Joshi said. “Though prosecution is far from perfect even in countries that are headquarters to global corporations, there is no way that authorities would be passive spectators if these alleged abuses were happening in New York, Vancouver, London, Paris or Beijing.”
Some national justice systems do not have jurisdiction over crimes committed by their companies in other countries.
And even where those laws do exist, the power and financial clout of corporations makes authorities reluctant to act.
This often means that there is total impunity for companies when they are involved in criminal activity overseas, Joshi said.
“It is shocking that in some of these cases victims still have not received redress for horrific crimes,” said ICAR’s Ammol Mehra. “For example, no government has done an adequate investigation into the alleged involvement of Australian-Canadian multinational Anvil Mining in the Kilwa massacre in the Democratic Republic of the Congo in 2004, in which government forces killed and tortured civilians.”
Last year, UK authorities admitted to Amnesty International that they do not have the tools, resources or expertise to investigate whether the London office of multinational commodities giant Trafigura conspired to dump toxic waste in Côte d’Ivoire in 2006 – one of the worst corporate-created disasters of the 21st century.
Amnesty International and ICAR have documented 20 other examples where authorities have not prosecuted multinationals despite being provided with evidence of illegal conduct linked to serious human rights abuses in other countries.
“We need a sea-change in the approach of governments and law enforcement to these cases – corporate actors need to know that they will be held to account for corporate crimes and victims need to know that they will have justice for the harm caused,” Mehra said.
The principles highlight how political will and the commitment of law enforcement to tackling serious crimes can galvanize action in future cases.
Amnesty points to the successful prosecution in the Netherlands of Dutch businessman Frans van Anraat for war crimes for supplying Saddam Hussein’s regime with chemicals used in chemical weapons attacks against the Kurds in 1987 and 1988.
The Dutch International Crimes Unit that brought the case is now widely recognized as one of the most effective and active units specializing in international crime.
“We need a sea-change in the approach of governments and law enforcement to these cases – corporate actors need to know that they will be held to account for corporate crimes and victims need to know that they will have justice for the harm caused,” Mehra said.
|
package com.telecominfraproject.wlan.client.models.events.utils;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.telecominfraproject.wlan.core.model.extensibleenum.EnumWithId;
import com.telecominfraproject.wlan.core.model.json.BaseJsonModel;
public class WlanStatusCode implements EnumWithId {
private static final Logger LOG = LoggerFactory.getLogger(WlanStatusCode.class);
private static Object lock = new Object();
private static final Map<Integer, WlanStatusCode> ELEMENTS = new ConcurrentHashMap<>();
private static final Map<String, WlanStatusCode> ELEMENTS_BY_NAME = new ConcurrentHashMap<>();
public static final WlanStatusCode
WLAN_STATUS_SUCCESS = new WlanStatusCode(0,"WLAN_STATUS_SUCCESS"),
WLAN_STATUS_UNSPECIFIED_FAILURE = new WlanStatusCode(1,"WLAN_STATUS_UNSPECIFIED_FAILURE"),
WLAN_STATUS_TDLS_WAKEUP_ALTERNATE = new WlanStatusCode(2,"WLAN_STATUS_TDLS_WAKEUP_ALTERNATE"),
WLAN_STATUS_TDLS_WAKEUP_REJECT = new WlanStatusCode(3,"WLAN_STATUS_TDLS_WAKEUP_REJECT"),
WLAN_STATUS_SECURITY_DISABLED = new WlanStatusCode(5,"WLAN_STATUS_SECURITY_DISABLED"),
WLAN_STATUS_UNACCEPTABLE_LIFETIME = new WlanStatusCode(6,"WLAN_STATUS_UNACCEPTABLE_LIFETIME"),
WLAN_STATUS_NOT_IN_SAME_BSS = new WlanStatusCode(7,"WLAN_STATUS_NOT_IN_SAME_BSS"),
WLAN_STATUS_CAPS_UNSUPPORTED = new WlanStatusCode(10,"WLAN_STATUS_CAPS_UNSUPPORTED"),
WLAN_STATUS_REASSOC_NO_ASSOC = new WlanStatusCode(11,"WLAN_STATUS_REASSOC_NO_ASSOC"),
WLAN_STATUS_ASSOC_DENIED_UNSPEC = new WlanStatusCode(12,"WLAN_STATUS_ASSOC_DENIED_UNSPEC"),
WLAN_STATUS_NOT_SUPPORTED_AUTH_ALG = new WlanStatusCode(13,"WLAN_STATUS_NOT_SUPPORTED_AUTH_ALG"),
WLAN_STATUS_UNKNOWN_AUTH_TRANSACTION = new WlanStatusCode(14,"WLAN_STATUS_UNKNOWN_AUTH_TRANSACTION"),
WLAN_STATUS_CHALLENGE_FAIL = new WlanStatusCode(15,"WLAN_STATUS_CHALLENGE_FAIL"),
WLAN_STATUS_AUTH_TIMEOUT = new WlanStatusCode(16,"WLAN_STATUS_AUTH_TIMEOUT"),
WLAN_STATUS_AP_UNABLE_TO_HANDLE_NEW_STA = new WlanStatusCode(17,"WLAN_STATUS_AP_UNABLE_TO_HANDLE_NEW_STA"),
WLAN_STATUS_ASSOC_DENIED_RATES = new WlanStatusCode(18,"WLAN_STATUS_ASSOC_DENIED_RATES"),
WLAN_STATUS_ASSOC_DENIED_NOSHORT = new WlanStatusCode(19,"WLAN_STATUS_ASSOC_DENIED_NOSHORT"),
WLAN_STATUS_SPEC_MGMT_REQUIRED = new WlanStatusCode(22,"WLAN_STATUS_SPEC_MGMT_REQUIRED"),
WLAN_STATUS_PWR_CAPABILITY_NOT_VALID = new WlanStatusCode(23,"WLAN_STATUS_PWR_CAPABILITY_NOT_VALID"),
WLAN_STATUS_SUPPORTED_CHANNEL_NOT_VALID = new WlanStatusCode(24,"WLAN_STATUS_SUPPORTED_CHANNEL_NOT_VALID"),
WLAN_STATUS_ASSOC_DENIED_NO_SHORT_SLOT_TIME = new WlanStatusCode(25,"WLAN_STATUS_ASSOC_DENIED_NO_SHORT_SLOT_TIME"),
WLAN_STATUS_ASSOC_DENIED_NO_HT = new WlanStatusCode(27,"WLAN_STATUS_ASSOC_DENIED_NO_HT"),
WLAN_STATUS_R0KH_UNREACHABLE = new WlanStatusCode(28,"WLAN_STATUS_R0KH_UNREACHABLE"),
WLAN_STATUS_ASSOC_DENIED_NO_PCO = new WlanStatusCode(29,"WLAN_STATUS_ASSOC_DENIED_NO_PCO"),
WLAN_STATUS_ASSOC_REJECTED_TEMPORARILY = new WlanStatusCode(30,"WLAN_STATUS_ASSOC_REJECTED_TEMPORARILY"),
WLAN_STATUS_ROBUST_MGMT_FRAME_POLICY_VIOLATION = new WlanStatusCode(31,"WLAN_STATUS_ROBUST_MGMT_FRAME_POLICY_VIOLATION"),
WLAN_STATUS_UNSPECIFIED_QOS_FAILURE = new WlanStatusCode(32,"WLAN_STATUS_UNSPECIFIED_QOS_FAILURE"),
WLAN_STATUS_DENIED_INSUFFICIENT_BANDWIDTH = new WlanStatusCode(33,"WLAN_STATUS_DENIED_INSUFFICIENT_BANDWIDTH"),
WLAN_STATUS_DENIED_POOR_CHANNEL_CONDITIONS = new WlanStatusCode(34,"WLAN_STATUS_DENIED_POOR_CHANNEL_CONDITIONS"),
WLAN_STATUS_DENIED_QOS_NOT_SUPPORTED = new WlanStatusCode(35,"WLAN_STATUS_DENIED_QOS_NOT_SUPPORTED"),
WLAN_STATUS_REQUEST_DECLINED = new WlanStatusCode(37,"WLAN_STATUS_REQUEST_DECLINED"),
WLAN_STATUS_INVALID_PARAMETERS = new WlanStatusCode(38,"WLAN_STATUS_INVALID_PARAMETERS"),
WLAN_STATUS_REJECTED_WITH_SUGGESTED_CHANGES = new WlanStatusCode(39,"WLAN_STATUS_REJECTED_WITH_SUGGESTED_CHANGES"),
WLAN_STATUS_INVALID_IE = new WlanStatusCode(40,"WLAN_STATUS_INVALID_IE"),
WLAN_STATUS_GROUP_CIPHER_NOT_VALID = new WlanStatusCode(41,"WLAN_STATUS_GROUP_CIPHER_NOT_VALID"),
WLAN_STATUS_PAIRWISE_CIPHER_NOT_VALID = new WlanStatusCode(42,"WLAN_STATUS_PAIRWISE_CIPHER_NOT_VALID"),
WLAN_STATUS_AKMP_NOT_VALID = new WlanStatusCode(43,"WLAN_STATUS_AKMP_NOT_VALID"),
WLAN_STATUS_UNSUPPORTED_RSN_IE_VERSION = new WlanStatusCode(44,"WLAN_STATUS_UNSUPPORTED_RSN_IE_VERSION"),
WLAN_STATUS_INVALID_RSN_IE_CAPAB = new WlanStatusCode(45,"WLAN_STATUS_INVALID_RSN_IE_CAPAB"),
WLAN_STATUS_CIPHER_REJECTED_PER_POLICY = new WlanStatusCode(46,"WLAN_STATUS_CIPHER_REJECTED_PER_POLICY"),
WLAN_STATUS_TS_NOT_CREATED = new WlanStatusCode(47,"WLAN_STATUS_TS_NOT_CREATED"),
WLAN_STATUS_DIRECT_LINK_NOT_ALLOWED = new WlanStatusCode(48,"WLAN_STATUS_DIRECT_LINK_NOT_ALLOWED"),
WLAN_STATUS_DEST_STA_NOT_PRESENT = new WlanStatusCode(49,"WLAN_STATUS_DEST_STA_NOT_PRESENT"),
WLAN_STATUS_DEST_STA_NOT_QOS_STA = new WlanStatusCode(50,"WLAN_STATUS_DEST_STA_NOT_QOS_STA"),
WLAN_STATUS_ASSOC_DENIED_LISTEN_INT_TOO_LARGE = new WlanStatusCode(51,"WLAN_STATUS_ASSOC_DENIED_LISTEN_INT_TOO_LARGE"),
WLAN_STATUS_INVALID_FT_ACTION_FRAME_COUNT = new WlanStatusCode(52,"WLAN_STATUS_INVALID_FT_ACTION_FRAME_COUNT"),
WLAN_STATUS_INVALID_PMKID = new WlanStatusCode(53,"WLAN_STATUS_INVALID_PMKID"),
WLAN_STATUS_INVALID_MDIE = new WlanStatusCode(54,"WLAN_STATUS_INVALID_MDIE"),
WLAN_STATUS_INVALID_FTIE = new WlanStatusCode(55,"WLAN_STATUS_INVALID_FTIE"),
WLAN_STATUS_REQUESTED_TCLAS_NOT_SUPPORTED = new WlanStatusCode(56,"WLAN_STATUS_REQUESTED_TCLAS_NOT_SUPPORTED"),
WLAN_STATUS_INSUFFICIENT_TCLAS_PROCESSING_RESOURCES = new WlanStatusCode(57,"WLAN_STATUS_INSUFFICIENT_TCLAS_PROCESSING_RESOURCES"),
WLAN_STATUS_TRY_ANOTHER_BSS = new WlanStatusCode(58,"WLAN_STATUS_TRY_ANOTHER_BSS"),
WLAN_STATUS_GAS_ADV_PROTO_NOT_SUPPORTED = new WlanStatusCode(59,"WLAN_STATUS_GAS_ADV_PROTO_NOT_SUPPORTED"),
WLAN_STATUS_NO_OUTSTANDING_GAS_REQ = new WlanStatusCode(60,"WLAN_STATUS_NO_OUTSTANDING_GAS_REQ"),
WLAN_STATUS_GAS_RESP_NOT_RECEIVED = new WlanStatusCode(61,"WLAN_STATUS_GAS_RESP_NOT_RECEIVED"),
WLAN_STATUS_STA_TIMED_OUT_WAITING_FOR_GAS_RESP = new WlanStatusCode(62,"WLAN_STATUS_STA_TIMED_OUT_WAITING_FOR_GAS_RESP"),
WLAN_STATUS_GAS_RESP_LARGER_THAN_LIMIT = new WlanStatusCode(63,"WLAN_STATUS_GAS_RESP_LARGER_THAN_LIMIT"),
WLAN_STATUS_REQ_REFUSED_HOME = new WlanStatusCode(64,"WLAN_STATUS_REQ_REFUSED_HOME"),
WLAN_STATUS_ADV_SRV_UNREACHABLE = new WlanStatusCode(65,"WLAN_STATUS_ADV_SRV_UNREACHABLE"),
WLAN_STATUS_REQ_REFUSED_SSPN = new WlanStatusCode(67,"WLAN_STATUS_REQ_REFUSED_SSPN"),
WLAN_STATUS_REQ_REFUSED_UNAUTH_ACCESS = new WlanStatusCode(68,"WLAN_STATUS_REQ_REFUSED_UNAUTH_ACCESS"),
WLAN_STATUS_INVALID_RSNIE = new WlanStatusCode(72,"WLAN_STATUS_INVALID_RSNIE"),
WLAN_STATUS_U_APSD_COEX_NOT_SUPPORTED = new WlanStatusCode(73,"WLAN_STATUS_U_APSD_COEX_NOT_SUPPORTED"),
WLAN_STATUS_U_APSD_COEX_MODE_NOT_SUPPORTED = new WlanStatusCode(74,"WLAN_STATUS_U_APSD_COEX_MODE_NOT_SUPPORTED"),
WLAN_STATUS_BAD_INTERVAL_WITH_U_APSD_COEX = new WlanStatusCode(75,"WLAN_STATUS_BAD_INTERVAL_WITH_U_APSD_COEX"),
WLAN_STATUS_ANTI_CLOGGING_TOKEN_REQ = new WlanStatusCode(76,"WLAN_STATUS_ANTI_CLOGGING_TOKEN_REQ"),
WLAN_STATUS_FINITE_CYCLIC_GROUP_NOT_SUPPORTED = new WlanStatusCode(77,"WLAN_STATUS_FINITE_CYCLIC_GROUP_NOT_SUPPORTED"),
WLAN_STATUS_CANNOT_FIND_ALT_TBTT = new WlanStatusCode(78,"WLAN_STATUS_CANNOT_FIND_ALT_TBTT"),
WLAN_STATUS_TRANSMISSION_FAILURE = new WlanStatusCode(79,"WLAN_STATUS_TRANSMISSION_FAILURE"),
WLAN_STATUS_REQ_TCLAS_NOT_SUPPORTED = new WlanStatusCode(80,"WLAN_STATUS_REQ_TCLAS_NOT_SUPPORTED"),
WLAN_STATUS_TCLAS_RESOURCES_EXCHAUSTED = new WlanStatusCode(81,"WLAN_STATUS_TCLAS_RESOURCES_EXCHAUSTED"),
WLAN_STATUS_REJECTED_WITH_SUGGESTED_BSS_TRANSITION = new WlanStatusCode(82,"WLAN_STATUS_REJECTED_WITH_SUGGESTED_BSS_TRANSITION"),
WLAN_STATUS_REJECT_WITH_SCHEDULE = new WlanStatusCode(83,"WLAN_STATUS_REJECT_WITH_SCHEDULE"),
WLAN_STATUS_REJECT_NO_WAKEUP_SPECIFIED = new WlanStatusCode(84,"WLAN_STATUS_REJECT_NO_WAKEUP_SPECIFIED"),
WLAN_STATUS_SUCCESS_POWER_SAVE_MODE = new WlanStatusCode(85,"WLAN_STATUS_SUCCESS_POWER_SAVE_MODE"),
WLAN_STATUS_PENDING_ADMITTING_FST_SESSION = new WlanStatusCode(86,"WLAN_STATUS_PENDING_ADMITTING_FST_SESSION"),
WLAN_STATUS_PERFORMING_FST_NOW = new WlanStatusCode(87,"WLAN_STATUS_PERFORMING_FST_NOW"),
WLAN_STATUS_PENDING_GAP_IN_BA_WINDOW = new WlanStatusCode(88,"WLAN_STATUS_PENDING_GAP_IN_BA_WINDOW"),
WLAN_STATUS_REJECT_U_PID_SETTING = new WlanStatusCode(89,"WLAN_STATUS_REJECT_U_PID_SETTING"),
WLAN_STATUS_REFUSED_EXTERNAL_REASON = new WlanStatusCode(92,"WLAN_STATUS_REFUSED_EXTERNAL_REASON"),
WLAN_STATUS_REFUSED_AP_OUT_OF_MEMORY = new WlanStatusCode(93,"WLAN_STATUS_REFUSED_AP_OUT_OF_MEMORY"),
WLAN_STATUS_REJECTED_EMERGENCY_SERVICE_NOT_SUPPORTED = new WlanStatusCode(94,"WLAN_STATUS_REJECTED_EMERGENCY_SERVICE_NOT_SUPPORTED"),
WLAN_STATUS_QUERY_RESP_OUTSTANDING = new WlanStatusCode(95,"WLAN_STATUS_QUERY_RESP_OUTSTANDING"),
WLAN_STATUS_REJECT_DSE_BAND = new WlanStatusCode(96,"WLAN_STATUS_REJECT_DSE_BAND"),
WLAN_STATUS_TCLAS_PROCESSING_TERMINATED = new WlanStatusCode(97,"WLAN_STATUS_TCLAS_PROCESSING_TERMINATED"),
WLAN_STATUS_TS_SCHEDULE_CONFLICT = new WlanStatusCode(98,"WLAN_STATUS_TS_SCHEDULE_CONFLICT"),
WLAN_STATUS_DENIED_WITH_SUGGESTED_BAND_AND_CHANNEL = new WlanStatusCode(99,"WLAN_STATUS_DENIED_WITH_SUGGESTED_BAND_AND_CHANNEL"),
WLAN_STATUS_MCCAOP_RESERVATION_CONFLICT = new WlanStatusCode(100,"WLAN_STATUS_MCCAOP_RESERVATION_CONFLICT"),
WLAN_STATUS_MAF_LIMIT_EXCEEDED = new WlanStatusCode(101,"WLAN_STATUS_MAF_LIMIT_EXCEEDED"),
WLAN_STATUS_MCCA_TRACK_LIMIT_EXCEEDED = new WlanStatusCode(102,"WLAN_STATUS_MCCA_TRACK_LIMIT_EXCEEDED"),
WLAN_STATUS_DENIED_DUE_TO_SPECTRUM_MANAGEMENT = new WlanStatusCode(103,"WLAN_STATUS_DENIED_DUE_TO_SPECTRUM_MANAGEMENT"),
WLAN_STATUS_ASSOC_DENIED_NO_VHT = new WlanStatusCode(104,"WLAN_STATUS_ASSOC_DENIED_NO_VHT"),
WLAN_STATUS_ENABLEMENT_DENIED = new WlanStatusCode(105,"WLAN_STATUS_ENABLEMENT_DENIED"),
WLAN_STATUS_RESTRICTION_FROM_AUTHORIZED_GDB = new WlanStatusCode(106,"WLAN_STATUS_RESTRICTION_FROM_AUTHORIZED_GDB"),
WLAN_STATUS_AUTHORIZATION_DEENABLED = new WlanStatusCode(107,"WLAN_STATUS_AUTHORIZATION_DEENABLED"),
WLAN_STATUS_FILS_AUTHENTICATION_FAILURE = new WlanStatusCode(112,"WLAN_STATUS_FILS_AUTHENTICATION_FAILURE"),
WLAN_STATUS_UNKNOWN_AUTHENTICATION_SERVER = new WlanStatusCode(113,"WLAN_STATUS_UNKNOWN_AUTHENTICATION_SERVER"),
WLAN_STATUS_UNKNOWN_PASSWORD_IDENTIFIER = new WlanStatusCode(123,"WLAN_STATUS_UNKNOWN_PASSWORD_IDENTIFIER"),
WLAN_STATUS_SAE_HASH_TO_ELEMENT = new WlanStatusCode(126,"WLAN_STATUS_SAE_HASH_TO_ELEMENT"),
WLAN_STATUS_SAE_PK = new WlanStatusCode(127,"WLAN_STATUS_SAE_PK"),
UNSUPPORTED = new WlanStatusCode(-1, "UNSUPPORTED") ;
static {
//try to load all the subclasses explicitly - to avoid timing issues when items coming from subclasses may be registered some time later, after the parent class is loaded
Set<Class<? extends WlanStatusCode>> subclasses = BaseJsonModel.getReflections().getSubTypesOf(WlanStatusCode.class);
for(Class<?> cls: subclasses) {
try {
Class.forName(cls.getName());
} catch (ClassNotFoundException e) {
LOG.warn("Cannot load class {} : {}", cls.getName(), e);
}
}
}
private final int id;
private final String name;
protected WlanStatusCode(int id, String name) {
synchronized(lock) {
LOG.debug("Registering WlanStatusCode by {} : {}", this.getClass().getSimpleName(), name);
this.id = id;
this.name = name;
ELEMENTS_BY_NAME.values().forEach(s -> {
if(s.getName().equals(name)) {
throw new IllegalStateException("WlanStatusCode item for "+ name + " is already defined, cannot have more than one of them");
}
});
if(ELEMENTS.containsKey(id)) {
throw new IllegalStateException("WlanStatusCode item "+ name + "("+id+") is already defined, cannot have more than one of them");
}
ELEMENTS.put(id, this);
ELEMENTS_BY_NAME.put(name, this);
}
}
@Override
public int getId() {
return id;
}
@Override
public String getName() {
return name;
}
public static WlanStatusCode getById(int enumId){
return ELEMENTS.get(enumId);
}
@JsonCreator
public static WlanStatusCode getByName(String value) {
WlanStatusCode ret = ELEMENTS_BY_NAME.get(value);
if (ret == null) {
ret = UNSUPPORTED;
}
return ret;
}
public static List<WlanStatusCode> getValues() {
return new ArrayList<>(ELEMENTS.values());
}
public static boolean isUnsupported(WlanStatusCode value) {
return (UNSUPPORTED.equals(value));
}
@Override
public int hashCode() {
return id;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof WlanStatusCode)) {
return false;
}
WlanStatusCode other = (WlanStatusCode) obj;
return id == other.id;
}
@Override
public String toString() {
return name;
}
}
|
{-
Dinner with Ambiants: ICFP Programming Contest 2004
Programming Assignment for Advanced Functional Programming
Universiteit Utrecht, Software Technology Master
-}
module Simulator.Base where
import Control.Monad.State
import Data.Array.IO
import Data.Bits
import Data.Int
import Data.List
import Data.Maybe
import qualified Data.Set as S
import Ant.Base
------------------------------------------------------------------
data GameState = GameState
{ world :: World
, redInstructions :: AntInstructions
, blackInstructions :: AntInstructions
, antPositions :: AntPositions
, randoms :: [Int]
, roundNumber :: Int
, foodAdmin :: FoodAdmin
}
type Sim = StateT GameState IO
runSimulator :: Sim () -> GameState -> IO GameState
runSimulator = execStateT
------------------------------------------------------------------
-- 2.1 Geometry
data Pos = Pos { posX :: !Int, posY :: !Int }
instance Show Pos where
show p = "(" ++ show (posX p) ++ ", " ++ show (posY p) ++ ")"
instance Eq Pos where
p1 == p2 = posX p1 == posX p2 && posY p1 == posY p2
-- x and y are swapped
instance Ord Pos where
compare p1 p2 = compare (posY p1, posX p1) (posY p2, posX p2)
-- x and y are swapped
instance Ix Pos where
range (p1, p2) =
[ Pos x y | y <- [posY p1..posY p2], x <- [posX p1..posX p2] ]
index (p1, p2) p =
(posY p - posY p1) * (1 + posX p2 - posX p1) + posX p - posX p1
inRange (p1, p2) p =
let between :: Ord a => a -> a -> a -> Bool
between x y z = x <= y && y <= z
in between (posX p1) (posX p) (posX p2) &&
between (posY p1) (posY p) (posY p2)
rangeSize (p1, p2) =
(1 + posX p2 - posX p1) * (1 + posY p2 - posY p1)
type Dir = Int -- 0..5
adjacentCell :: Pos -> Dir -> Pos
adjacentCell p = posPlus p . f
where
f 0 = Pos 1 0
f 1 | even (posY p) = Pos 0 1
| otherwise = Pos 1 1
f 2 | even (posY p) = Pos (-1) 1
| otherwise = Pos 0 1
f 3 = Pos (-1) 0
f 4 | even (posY p) = Pos (-1) (-1)
| otherwise = Pos 0 (-1)
f 5 | even (posY p) = Pos 0 (-1)
| otherwise = Pos 1 (-1)
f d = error ("adjacentCell: " ++ show d)
posPlus :: Pos -> Pos -> Pos
posPlus p1 p2 = Pos { posX = posX p1 + posX p2, posY = posY p1 + posY p2 }
turn :: LeftOrRight -> Dir -> Dir
turn IsLeft d = (d+5) `mod` 6
turn IsRight d = (d+1) `mod` 6
sensedCell :: Pos -> Dir -> SenseDir -> Pos
sensedCell p _ Here = p
sensedCell p d Ahead = adjacentCell p d
sensedCell p d LeftAhead = adjacentCell p (turn IsLeft d)
sensedCell p d RightAhead = adjacentCell p (turn IsRight d)
------------------------------------------------------------------
-- 2.2 Biology
data AntColor = Red | Black deriving Eq
instance Show AntColor where
show Red = "red"
show Black = "black"
otherColor :: AntColor -> AntColor
otherColor Red = Black
otherColor Black = Red
data Ant = Ant
{ antId :: Int
, antColor :: AntColor
, antState :: Int
, antResting :: Int
, antDirection :: Dir
, antHasFood :: Bool
} deriving (Eq)
instance Show Ant where
show a = concat $ intersperse ", "
[ show (antColor a) ++ " ant of id " ++ show (antId a)
, "dir " ++ show (antDirection a)
, "food " ++ if antHasFood a then "1" else "0"
, "state " ++ show (antState a)
, "resting " ++ show (antResting a)
]
setState :: Int -> Ant -> Ant
setState x ant = ant {antState = x}
setResting :: Int -> Ant -> Ant
setResting x ant = ant {antResting = x}
setDirection :: Dir -> Ant -> Ant
setDirection x ant = ant {antDirection = x}
setHasFood :: Bool -> Ant -> Ant
setHasFood x ant = ant {antHasFood = x}
------------------------------------------------------------------
-- 2.3 Geography
rocky :: Cell -> Bool
rocky c = cellType c == Rocky
maybeAntAt :: Pos -> Sim (Maybe Ant)
maybeAntAt p =
do w <- gets world
cell <- liftIO $ readArray w p
return (antInCell cell)
setAntAt :: Ant -> Pos -> Sim ()
setAntAt a p =
do setAntPosition p a
changeCellAt (\cell -> cell { antInCell = Just a }) p
clearAntAt :: Ant -> Pos -> Sim ()
clearAntAt a p =
do setAntNoPosition a
changeCellAt (\cell -> cell { antInCell = Nothing }) p
------------------------------------------------------------------
-- 2.4 Cartography
-- (see ReadWorld.hs)
type World = IOArray Pos Cell
data Cell = Cell
{ antInCell :: Maybe Ant
, cellType :: CellType
, food :: Int
, anthill :: Maybe AntColor
, markersRed :: Markers
, markersBlack :: Markers
} deriving Eq
data CellType = Rocky | Clear deriving (Eq, Show)
showCell :: (Pos, Cell) -> String
showCell (p, cell)
| rocky cell = "cell " ++ show p ++ ": rock"
| otherwise =
let begin = "cell " ++ show p ++ ": "
hill = maybe "" (\c -> show c ++ " hill; ") (anthill cell)
g c bs = if anyMarker bs then show c ++ " marks: " ++ showMarkers bs ++ "; " else ""
redmarks = g Red (markersRed cell)
blackmarks = g Black (markersBlack cell)
foodtext = if food cell > 0 then show (food cell) ++ " food; " else ""
anttext = maybe "" show (antInCell cell)
in begin ++ foodtext ++ hill ++ redmarks ++ blackmarks ++ anttext
------------------------------------------------------------------
-- 2.5 Chemistry
type MarkerNumber = Int -- 0..5
type Markers = Int8
noMarkers :: Markers
noMarkers = 0
anyMarker :: Markers -> Bool
anyMarker = (/= 0)
showMarkers :: Markers -> String
showMarkers m =
concat [ show i | i <- [0..5], testBit m i]
setMarkerAt :: AntColor -> MarkerNumber -> Cell -> Cell
setMarkerAt c m cell =
case c of
Red -> cell {markersRed = setBit (markersRed cell) m}
Black -> cell {markersBlack = setBit (markersBlack cell) m}
clearMarkerAt :: AntColor -> MarkerNumber -> Cell -> Cell
clearMarkerAt c m cell =
case c of
Red -> cell {markersRed = clearBit (markersRed cell) m}
Black -> cell {markersBlack = clearBit (markersBlack cell) m}
------------------------------------------------------------------
-- 2.6 Phenomenology
cellMatches :: Cell -> Condition -> AntColor -> Bool
cellMatches cell cond c =
case (cond, antInCell cell) of
(Rock , _ ) -> rocky cell
(Food , _ ) -> food cell > 0
(Home , _ ) -> anthill cell == Just c
(FoeHome , _ ) -> anthill cell == Just (otherColor c)
(Marker i , _ ) -> testBit (case c of Red -> markersRed cell ; Black -> markersBlack cell) (fromEnum i)
(FoeMarker , _ ) -> anyMarker (case c of Red -> markersBlack cell; Black -> markersRed cell )
(_ , Nothing ) -> False
(Friend , Just ant) -> antColor ant == c
(Foe , Just ant) -> antColor ant /= c
(FriendWithFood, Just ant) -> antColor ant == c && antHasFood ant
(FoeWithFood , Just ant) -> antColor ant /= c && antHasFood ant
------------------------------------------------------------------
-- 2.7 Neurology
type AntState = Int
type Instruction = Command AntState
getInstruction :: AntColor -> AntState -> Sim Instruction
getInstruction c st =
do instrs <- case c of Red -> gets redInstructions ; Black -> gets blackInstructions
liftIO $ readArray instrs st
------------------------------------------------------------------
-- 2.8 Neuro-Cartography
-- (see ReadInstructions.hs)
type AntInstructions = IOArray Int Instruction
------------------------------------------------------------------
-- 2.9 Martial Arts
adjacentAnts :: Pos -> AntColor -> Sim Bool
adjacentAnts p c =
do free <- foldM op 0 [0..5]
return (free <= 1)
where
op :: Int -> Dir -> Sim Int
op free d
| free >= 2 = return free
| otherwise =
do mAnt <- maybeAntAt (adjacentCell p d)
return (free + maybe 1 (\ant -> if antColor ant == c then 0 else 1) mAnt)
checkForSurroundedAntAt :: Pos -> Sim ()
checkForSurroundedAntAt p =
do mAnt <- maybeAntAt p
case mAnt of
Nothing -> return ()
Just ant ->
do kill <- adjacentAnts p (otherColor (antColor ant))
when kill $
do clearAntAt ant p
changeCellAt (addFood $ 3 + if antHasFood ant then 1 else 0) p
cell <- cellAt p
scoreKill ant cell
setFoodAtPos (food cell) p
checkForSurroundedAnts :: Pos -> Sim ()
checkForSurroundedAnts p =
do checkForSurroundedAntAt p
mapM_ (checkForSurroundedAntAt . adjacentCell p) [0..5]
------------------------------------------------------------------
-- 2.10 Number Theory
randomStream :: Int -> [Int]
randomStream =
let f :: Int -> Int
f x = x * 22695477 + 1
g :: Int -> Int
g x = (x `div` 65536) `mod` 16384
in map g . drop 4 . iterate f
randomInt :: Int -> Sim Int
randomInt n =
do i:is <- gets randoms
modify (\s -> s { randoms = is })
return (i `mod` n)
------------------------------------------------------------------
-- 2.11 Kinetics
step :: (Int, Maybe Pos) -> Sim ()
step (_, Nothing) = return ()
step (i, Just pos) =
do cell <- cellAt pos
case (antInCell cell) of
Nothing -> return ()
Just ant
| antResting ant > 0 || antId ant /= i ->
changeCellAt (changeAnt $ changeResting (\x -> x-1)) pos
| otherwise ->
do instruction <- getInstruction (antColor ant) (antState ant)
f <- doInstruction pos cell ant instruction
changeCellAt f pos
doInstruction :: Pos -> Cell -> Ant -> Instruction -> Sim (Cell -> Cell)
doInstruction pos cell ant instruction =
case instruction of
Sense sensedir st1 st2 cond ->
do let newpos = sensedCell pos (antDirection ant) sensedir
newCell <- cellAt newpos
let b = cellMatches newCell cond (antColor ant)
return $
changeAnt (setState (if b then st1 else st2))
Mark i st ->
return $
setMarkerAt (antColor ant) (fromEnum i) .
changeAnt (setState st)
Unmark i st ->
return $
clearMarkerAt (antColor ant) (fromEnum i) .
changeAnt (setState st)
PickUp st1 st2
| antHasFood ant || food cell == 0 ->
return $
changeAnt (setState st2)
| otherwise ->
do scorePickup ant cell
setFoodAtPos (food cell - 1) pos
return $
addFood (-1) .
changeAnt (setState st1 . setHasFood True)
Drop st
| antHasFood ant ->
do scoreDrop ant cell
setFoodAtPos (food cell) pos
return $
addFood 1 .
changeAnt (setState st . setHasFood False)
| otherwise ->
return $
changeAnt (setState st)
Turn lr st ->
return $
changeAnt (setState st . setDirection (turn lr (antDirection ant)))
Move st1 st2 ->
do let newpos = adjacentCell pos (antDirection ant)
newCell <- cellAt newpos
if rocky newCell || isJust (antInCell newCell)
then
return (changeAnt (setState st2))
else
do clearAntAt ant pos
setAntAt (setResting 14 . setState st1 $ ant) newpos
checkForSurroundedAnts newpos
return id
Flip n st1 st2 ->
do i <- randomInt n
return $
changeAnt (setState $ if i == 0 then st1 else st2)
changeAnt :: (Ant -> Ant) -> Cell -> Cell
changeAnt f c =
c { antInCell = fmap f (antInCell c) }
addFood :: Int -> Cell -> Cell
addFood extra c =
c { food = extra + food c }
changeResting :: (Int -> Int) -> Ant -> Ant
changeResting f a =
a { antResting = f (antResting a) }
------------------------------------------------------------------
-- 2.12 Game Play and Scoring
-- (see GamePlay.hs)
------------------------------------------------------------------
-- Food Administration
data FoodAdmin = FoodAdmin
{ blackScore :: Int
, redScore :: Int
, blackCarried :: Int
, redCarried :: Int
, remaining :: Int
, locations :: S.Set Pos
} deriving (Eq,Show)
changeFoodAdmin :: (FoodAdmin -> FoodAdmin) -> Sim ()
changeFoodAdmin f =
modify (\s -> s { foodAdmin = f (foodAdmin s) })
noFood :: FoodAdmin
noFood = FoodAdmin 0 0 0 0 0 S.empty
changeScore :: Maybe AntColor -> (Int -> Int) -> FoodAdmin -> FoodAdmin
changeScore Nothing f score = score { remaining = f (remaining score)}
changeScore (Just Red) f score = score { redScore = f (redScore score) }
changeScore (Just Black) f score = score { blackScore = f (blackScore score) }
changeCarried :: AntColor -> (Int -> Int) -> FoodAdmin-> FoodAdmin
changeCarried Red f score = score { redCarried = f (redCarried score) }
changeCarried Black f score = score { blackCarried = f (blackCarried score) }
scoreDrop :: Ant -> Cell -> Sim ()
scoreDrop ant cell =
changeFoodAdmin ( changeCarried (antColor ant) (\x -> x-1)
. changeScore (anthill cell) (+1)
)
scorePickup :: Ant -> Cell -> Sim ()
scorePickup ant cell =
changeFoodAdmin ( changeCarried (antColor ant) (+1)
. changeScore (anthill cell) (\x -> x-1)
)
scoreKill :: Ant -> Cell -> Sim ()
scoreKill ant cell =
changeFoodAdmin ( changeCarried (antColor ant) (if antHasFood ant then (\x -> x-1) else id)
. changeScore (anthill cell) (if antHasFood ant then (+4) else (+3))
)
setFoodAtPos :: Int -> Pos -> Sim ()
setFoodAtPos i pos =
changeFoodAdmin (\s -> s { locations = if i==0 then S.delete pos (locations s)
else S.insert pos (locations s)})
------------------------------------------------------------------
-- Ant Positions
type AntPositions = IOArray Int (Maybe Pos)
setAntMaybePosition :: Maybe Pos -> Ant -> Sim ()
setAntMaybePosition mpos ant =
do pm <- gets antPositions
liftIO $ writeArray pm (antId ant) mpos
setAntPosition :: Pos -> Ant -> Sim ()
setAntPosition = setAntMaybePosition . Just
setAntNoPosition :: Ant -> Sim ()
setAntNoPosition = setAntMaybePosition Nothing
cellAt :: Pos -> Sim Cell
cellAt pos =
do arr <- gets world
liftIO $ readArray arr pos
changeCellAt :: (Cell -> Cell) -> Pos -> Sim ()
changeCellAt f p =
do arr <- gets world
cell <- liftIO $ readArray arr p
liftIO (writeArray arr p (f cell))
|
// StringToShare will split a share string into a Point.
func StringToShare(s string) (Point, error) {
a := strings.Split(s, "-")
if len(a) != 2 {
return Point{0, nil}, ErrInvalidSyntax
}
x, err := strconv.Atoi(a[0])
if err != nil {
return Point{0, nil}, err
}
y := gmp.NewInt(0)
y.SetString(a[1], 16)
return Point{uint32(x), y}, nil
}
|
use core::convert::TryFrom;
use core::hash::Hash;
use core::ops::*;
// TODO(teaiwthsand): add things like wrapping add/sub/mul/div and others to these types
// TODO(teawithsand): add outpu=self for all ops
/// Type of single digit used in bignum operations.
/// Implemented by all primitive types.
/// Endianness should be handled internally.
pub trait UnsignedNumDigit:
Sized
+ core::fmt::Debug
+ Copy
+ Clone
+ Add<Output = Self>
+ AddAssign
+ Sub<Output = Self>
+ SubAssign
+ Mul<Output = Self>
+ MulAssign
+ Div<Output = Self>
+ DivAssign
+ Rem<Output = Self>
+ RemAssign
+ BitAnd<Output = Self>
+ BitAndAssign
+ BitOr<Output = Self>
+ BitOrAssign
+ BitXor<Output = Self>
+ BitXorAssign
+ Shl<Output = Self>
+ Shl<u32, Output = Self>
+ ShlAssign
+ Shr<Output = Self>
+ Shr<u32, Output = Self>
+ ShrAssign
+ Not<Output = Self>
+ PartialEq
+ Eq
+ Hash
+ PartialOrd
+ Ord
+ TryFrom<u8>
+ TryFrom<u16>
+ TryFrom<u32>
+ TryFrom<u64>
+ TryFrom<u128>
+ TryFrom<usize>
+ TryFrom<i8>
+ TryFrom<i16>
+ TryFrom<i32>
+ TryFrom<i64>
+ TryFrom<i128>
+ TryFrom<isize>
+ Default
{
/// Signed version of self.
type Signed: SignedNumDigit;
/// Type of exponent used for pow.
type Exponent: UnsignedNumDigit;
/// Number that is twice as big as current one.
// type Double: UnsignedNumDigit;
const ZERO: Self;
const ONE: Self;
const MAX: Self;
const MIN: Self;
const NUM_BITS: u32;
fn pow(self, other: Self::Exponent) -> Self;
fn wrapping_add(self, other: Self) -> Self;
fn wrapping_sub(self, other: Self) -> Self;
fn wrapping_div(self, other: Self) -> Self;
fn wrapping_mul(self, other: Self) -> Self;
fn wrapping_pow(self, other: Self::Exponent) -> Self;
fn wrapping_rem(self, other: Self) -> Self;
fn wrapping_shl(self, other: Self::Exponent) -> Self;
fn wrapping_shr(self, other: Self::Exponent) -> Self;
fn wrapping_div_euclid(self, other: Self) -> Self;
fn wrapping_rem_euclid(self, other: Self) -> Self;
fn checked_add(self, other: Self) -> Option<Self>;
fn checked_sub(self, other: Self) -> Option<Self>;
fn checked_div(self, other: Self) -> Option<Self>;
fn checked_mul(self, other: Self) -> Option<Self>;
fn checked_pow(self, other: Self::Exponent) -> Option<Self>;
fn checked_rem(self, other: Self) -> Option<Self>;
fn checked_shl(self, other: Self::Exponent) -> Option<Self>;
fn checked_shr(self, other: Self::Exponent) -> Option<Self>;
/*
fn unchecked_add(self, other: Self) -> Option<Self>;
fn unchecked_mul(self, other: Self) -> Option<Self>;
fn unchecked_sub(self, other: Self) -> Option<Self>;
*/
fn checked_div_euclid(self, other: Self) -> Option<Self>;
fn checked_rem_euclid(self, other: Self) -> Option<Self>;
fn overflowing_add(self, other: Self) -> (Self, bool);
fn overflowing_sub(self, other: Self) -> (Self, bool);
fn overflowing_div(self, other: Self) -> (Self, bool);
fn overflowing_mul(self, other: Self) -> (Self, bool);
fn overflowing_pow(self, other: Self::Exponent) -> (Self, bool);
fn overflowing_rem(self, other: Self) -> (Self, bool);
fn overflowing_shl(self, other: Self::Exponent) -> (Self, bool);
fn overflowing_shr(self, other: Self::Exponent) -> (Self, bool);
fn overflowing_div_euclid(self, other: Self) -> (Self, bool);
fn overflowing_rem_euclid(self, other: Self) -> (Self, bool);
//// Multiples two numbes, so that higher NUM_BITS are in 1st self and
//// lower NUM_BITS are in 2nd self
fn mul_to_parts(self, other: Self) -> (Self, Self);
}
/// Type of single digit used in bignum operations.
/// Implemented by all primitive types.
/// Endianness should be handled internally.
pub trait SignedNumDigit:
Sized
+ Copy
+ Clone
+ Add
+ AddAssign
+ Sub
+ SubAssign
+ Mul
+ MulAssign
+ Div
+ DivAssign
+ Rem
+ RemAssign
+ Neg
+ BitAnd
+ BitAndAssign
+ BitOr
+ BitOrAssign
+ BitXor
+ BitXorAssign
+ Shl
+ ShlAssign
+ Shr
+ ShrAssign
+ Not
+ PartialEq
+ Eq
+ Hash
+ PartialOrd
+ Ord
+ TryFrom<u8>
+ TryFrom<u16>
+ TryFrom<u32>
+ TryFrom<u64>
+ TryFrom<u128>
+ TryFrom<i8>
+ TryFrom<i16>
+ TryFrom<i32>
+ TryFrom<i64>
+ TryFrom<i128>
+ Default
{
/// Signed version of self.
type Unsigned: UnsignedNumDigit;
/// Type of exponent used for pow.
type Exponent: UnsignedNumDigit;
/// Number that is twice as big as current one.
// type Double: SignedNumDigit;
const ZERO: Self;
const ONE: Self;
const MAX: Self;
const MIN: Self;
const NUM_BITS: u32;
fn abs(self) -> Self;
fn pow(self, other: Self::Exponent) -> Self;
fn wrapping_abs(self) -> Self;
fn wrapping_add(self, other: Self) -> Self;
fn wrapping_sub(self, other: Self) -> Self;
fn wrapping_div(self, other: Self) -> Self;
fn wrapping_mul(self, other: Self) -> Self;
fn wrapping_neg(self) -> Self;
fn wrapping_pow(self, other: Self::Exponent) -> Self;
fn wrapping_rem(self, other: Self) -> Self;
fn wrapping_shl(self, other: Self::Exponent) -> Self;
fn wrapping_shr(self, other: Self::Exponent) -> Self;
fn wrapping_div_euclid(self, other: Self) -> Self;
fn wrapping_rem_euclid(self, other: Self) -> Self;
fn checked_abs(self) -> Option<Self>;
fn checked_add(self, other: Self) -> Option<Self>;
fn checked_sub(self, other: Self) -> Option<Self>;
fn checked_div(self, other: Self) -> Option<Self>;
fn checked_mul(self, other: Self) -> Option<Self>;
fn checked_neg(self) -> Option<Self>;
fn checked_pow(self, other: Self::Exponent) -> Option<Self>;
fn checked_rem(self, other: Self) -> Option<Self>;
fn checked_shl(self, other: Self::Exponent) -> Option<Self>;
fn checked_shr(self, other: Self::Exponent) -> Option<Self>;
/*
fn unchecked_add(self, other: Self) -> Option<Self>;
fn unchecked_mul(self, other: Self) -> Option<Self>;
fn unchecked_sub(self, other: Self) -> Option<Self>;
*/
fn checked_div_euclid(self, other: Self) -> Option<Self>;
fn checked_rem_euclid(self, other: Self) -> Option<Self>;
fn overflowing_abs(self) -> (Self, bool);
fn overflowing_add(self, other: Self) -> (Self, bool);
fn overflowing_sub(self, other: Self) -> (Self, bool);
fn overflowing_div(self, other: Self) -> (Self, bool);
fn overflowing_mul(self, other: Self) -> (Self, bool);
fn overflowing_neg(self) -> (Self, bool);
fn overflowing_pow(self, other: Self::Exponent) -> (Self, bool);
fn overflowing_rem(self, other: Self) -> (Self, bool);
fn overflowing_shl(self, other: Self::Exponent) -> (Self, bool);
fn overflowing_shr(self, other: Self::Exponent) -> (Self, bool);
fn overflowing_div_euclid(self, other: Self) -> (Self, bool);
fn overflowing_rem_euclid(self, other: Self) -> (Self, bool);
}
macro_rules! generate_mapping {
{
$(
$vis:vis fn $name:ident($($arg_name:ident: $arg_ty:ty),*) -> $ret:ty;
)*
} => {
$(
#[inline]
fn $name(self, $($arg_name: $arg_ty),*) -> $ret {
self.$name($($arg_name),*)
}
)*
};
}
macro_rules! derive_signed_num_digit {
($type:ident, $unsigned:ident, $double:ty) => {
impl SignedNumDigit for $type {
type Unsigned = $unsigned;
type Exponent = u32;
// type Double = $double;
const ZERO: Self = 0 as Self;
const ONE: Self = 1 as Self;
const MAX: Self = (!(0 as Self::Unsigned) >> 1) as Self;
const MIN: Self = -(Self::MAX) - 1;
const NUM_BITS: u32 = (core::mem::size_of::<$type>() as u32) * 8;
generate_mapping! {
fn abs() -> Self;
fn pow(exp: Self::Exponent) -> Self;
fn wrapping_abs() -> Self;
fn wrapping_add(other: Self) -> Self;
fn wrapping_sub(other: Self) -> Self;
fn wrapping_div(other: Self) -> Self;
fn wrapping_mul(other: Self) -> Self;
fn wrapping_neg() -> Self;
fn wrapping_pow(other: Self::Exponent) -> Self;
fn wrapping_rem(other: Self) -> Self;
fn wrapping_shl(other: u32) -> Self;
fn wrapping_shr(other: u32) -> Self;
fn wrapping_div_euclid(other: Self) -> Self;
fn wrapping_rem_euclid(other: Self) -> Self;
fn checked_abs() -> Option<Self>;
fn checked_add(other: Self) -> Option<Self>;
fn checked_sub(other: Self) -> Option<Self>;
fn checked_div(other: Self) -> Option<Self>;
fn checked_mul(other: Self) -> Option<Self>;
fn checked_neg() -> Option<Self>;
fn checked_pow(other: Self::Exponent) -> Option<Self>;
fn checked_rem(other: Self) -> Option<Self>;
fn checked_shl(other: Self::Exponent) -> Option<Self>;
fn checked_shr(other: Self::Exponent) -> Option<Self>;
/*
fn unchecked_add(other: Self) -> Option<Self>;
fn unchecked_mul(other: Self) -> Option<Self>;
fn unchecked_sub(other: Self) -> Option<Self>;
*/
fn checked_div_euclid(other: Self) -> Option<Self>;
fn checked_rem_euclid(other: Self) -> Option<Self>;
fn overflowing_abs() -> (Self, bool);
fn overflowing_add(other: Self) -> (Self, bool);
fn overflowing_sub(other: Self) -> (Self, bool);
fn overflowing_div(other: Self) -> (Self, bool);
fn overflowing_mul(other: Self) -> (Self, bool);
fn overflowing_neg() -> (Self, bool);
fn overflowing_pow(other: Self::Exponent) -> (Self, bool);
fn overflowing_rem(other: Self) -> (Self, bool);
fn overflowing_shl(other: Self::Exponent) -> (Self, bool);
fn overflowing_shr(other: Self::Exponent) -> (Self, bool);
fn overflowing_div_euclid(other: Self) -> (Self, bool);
fn overflowing_rem_euclid(other: Self) -> (Self, bool);
}
}
};
}
macro_rules! derive_unsigned_num_digit {
($type:ident, $signed:ident, $double:ty) => {
impl UnsignedNumDigit for $type {
type Signed = $signed;
type Exponent = u32;
// type Double = $double;
const ZERO: Self = 0 as Self;
const ONE: Self = 1 as Self;
const MAX: Self = !(0 as Self);
const MIN: Self = 0 as Self;
const NUM_BITS: u32 = (core::mem::size_of::<$type>() as u32) * 8;
generate_mapping! {
fn pow(exp: Self::Exponent) -> Self;
fn wrapping_add(other: Self) -> Self;
fn wrapping_sub(other: Self) -> Self;
fn wrapping_div(other: Self) -> Self;
fn wrapping_mul(other: Self) -> Self;
fn wrapping_pow(other: Self::Exponent) -> Self;
fn wrapping_rem(other: Self) -> Self;
fn wrapping_shl(other: u32) -> Self;
fn wrapping_shr(other: u32) -> Self;
fn wrapping_div_euclid(other: Self) -> Self;
fn wrapping_rem_euclid(other: Self) -> Self;
fn checked_add(other: Self) -> Option<Self>;
fn checked_sub(other: Self) -> Option<Self>;
fn checked_div(other: Self) -> Option<Self>;
fn checked_mul(other: Self) -> Option<Self>;
fn checked_pow(other: Self::Exponent) -> Option<Self>;
fn checked_rem(other: Self) -> Option<Self>;
fn checked_shl(other: Self::Exponent) -> Option<Self>;
fn checked_shr(other: Self::Exponent) -> Option<Self>;
/*
fn unchecked_add(other: Self) -> Option<Self>;
fn unchecked_mul(other: Self) -> Option<Self>;
fn unchecked_sub(other: Self) -> Option<Self>;
*/
fn checked_div_euclid(other: Self) -> Option<Self>;
fn checked_rem_euclid(other: Self) -> Option<Self>;
fn overflowing_add(other: Self) -> (Self, bool);
fn overflowing_sub(other: Self) -> (Self, bool);
fn overflowing_div(other: Self) -> (Self, bool);
fn overflowing_mul(other: Self) -> (Self, bool);
fn overflowing_pow(other: Self::Exponent) -> (Self, bool);
fn overflowing_rem(other: Self) -> (Self, bool);
fn overflowing_shl(other: Self::Exponent) -> (Self, bool);
fn overflowing_shr(other: Self::Exponent) -> (Self, bool);
fn overflowing_div_euclid(other: Self) -> (Self, bool);
fn overflowing_rem_euclid(other: Self) -> (Self, bool);
}
#[inline]
fn mul_to_parts(self, other: Self) -> (Self, Self) {
let res = (self as $double) * (other as $double);
let ones = ((!(0 as $type)) as $double);
let lower_bits = (res & ones) as $type;
let higher_bits = ((res >> Self::NUM_BITS) & ones) as $type;
(higher_bits, lower_bits)
}
}
};
}
derive_unsigned_num_digit!(u8, i8, u16);
derive_unsigned_num_digit!(u16, i16, u32);
derive_unsigned_num_digit!(u32, i32, u64);
derive_unsigned_num_digit!(u64, i64, u128);
// derive_unsigned_num_digit!(u128, i128, u128);
// derive_unsigned_num_digit!(usize, isize, );
derive_signed_num_digit!(i8, u8, i16);
derive_signed_num_digit!(i16, u16, i32);
derive_signed_num_digit!(i32, u32, i64);
derive_signed_num_digit!(i64, u64, i128);
// derive_signed_num_digit!(i128, u128, i128);
// derive_signed_num_digit!(isize, usize);
|
<gh_stars>0
/*
* Copyright 2006-2008 NMaven Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sonatype.nmaven;
/**
* Enumeration of all the valid target types (module, library, winexe, exe, nar) for the .NET platform.
*/
public enum ArtifactType
{
EXE( "dotnet:exe", "exe", "exe" ),
GAC( "dotnet:gac", "library", "dll" ),
GAC_32( "dotnet:gac_32", "library", "dll" ),
GAC_GENERIC( "dotnet:gac_generic", "library", "dll" ),
GAC_MSIL( "dotnet:gac_msil", "library", "dll" ),
LIBRARY( "dotnet:library", "library", "dll" ),
LIBRARY_LEGACY( "library", "library", "dll" ),
MODULE( "dotnet:module", "module", "netmodule" ),
WINEXE( "dotnet:winexe", "winexe", "exe" ),
NULL( "null", "null", "null" );
/**
* The extension used for the artifact(netmodule, dll, exe)
*/
private String extension;
/**
* The packaging type (as given in the package tag within the pom.xml) of the artifact.
*/
private String packagingType;
/**
* The target types (module, library, winexe, exe) for the .NET platform.
*/
private String targetCompileType;
/**
* Constructor
*/
ArtifactType( String packagingType, String targetCompileType, String extension )
{
this.packagingType = packagingType;
this.targetCompileType = targetCompileType;
this.extension = extension;
}
/**
* Returns extension used for the artifact(netmodule, dll, exe).
*
* @return Extension used for the artifact(netmodule, dll, exe).
*/
public String getExtension()
{
return extension;
}
/**
* Returns the packaging type (as given in the package tag within the pom.xml) of the artifact.
*
* @return the packaging type (as given in the package tag within the pom.xml) of the artifact.
*/
public String getPackagingType()
{
return packagingType;
}
/**
* Returns target types (module, library, winexe, exe) for the .NET platform.
*
* @return target types (module, library, winexe, exe) for the .NET platform.
*/
public String getTargetCompileType()
{
return targetCompileType;
}
public boolean isMatchByString( String packaging )
{
if ( packaging == null )
{
throw new IllegalArgumentException( "packaging" );
}
return packaging.equals( packagingType );
}
/**
* Returns artifact type for the specified packaging name
*
* @param packagingName the package name (as given in the package tag within the pom.xml) of the artifact.
* @return the artifact type for the specified packaging name
*/
public static synchronized ArtifactType getArtifactTypeForPackagingName( String packagingName )
{
if(packagingName == null)
{
throw new IllegalArgumentException("packagingName");
}
String[] packagingNameTokens = packagingName.split( "[:]");
if(packagingNameTokens.length != 2 || !packagingNameTokens[0].equals( "nmaven"))
{
throw new IllegalArgumentException("packagingName");
}
return ArtifactType.valueOf( packagingNameTokens[1].toUpperCase());
}
}
|
/**
* Created by cameronearle on 9/23/16.
*/
public class ServerPinger implements Runnable {
private String address;
private ServerConnectDialog dialog;
private boolean finalResult;
public ServerPinger(String address, ServerConnectDialog dialog) {
this.address = address;
this.dialog = dialog;
}
@Override
public void run() {
dialog.setProgress(0);
dialog.setUnknownProgress(true);
dialog.setStatus("Polling");
boolean result = PollSock.poll(address);
dialog.setProgress(50);
dialog.setUnknownProgress(false);
dialog.setStatus("Checking");
if (result) {
dialog.setProgress(100);
dialog.setStatus("Connected to server");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {}
dialog.dispose();
} else {
dialog.setProgress(0);
dialog.setStatus("Failed to connect to server, try again");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {}
dialog.dispose();
}
finalResult = result;
}
public boolean getResult() {
return finalResult;
}
}
|
Abstract 3142: BRMS1 alters the tumor inflammatory signature and immune infiltration in lung adenocarcinoma
Background: Lung adenocarcinoma (LUAD) is the leading cause of cancer-related deaths. Metastatic cancer is highly fatal which contributes to at least 90% of cancer-associated morbidities and mortalities. During metastasis, tumor cells alter their signaling cascade and interact with the immune cells in the tumor microenvironment Therefore, it is necessary to characterize and understand how these cancer cells influence tumor-infiltrating immune cells to facilitate and even enhance their ability to metastasize. BRMS1 is a metastasis suppressor gene which is frequently downregulated in LUAD. We, and others, have shown that loss of BRMS1 results in distant metastatic disease. Given the strong correlation between immune suppression, metastasis, and therapy resistance we sought to elucidate if BRMS1 contributes to these processes. Specifically, we hypothesized that LUAD cells downregulate BRMS1 which influences the immune cell composition in the tumor. This creates an immune-suppressive tumor microenvironment aiding in metastasis.
Methods: To test our hypothesis, we generated KrasG12D P53fl/fl Brms1-/- mice which spontaneously develop tumors with Ad-Cre intratracheal inoculation. To elucidate the role of BRMS1 in the context of cancer, we performed RNA sequencing on tumors from Brms1 wild type and knockout background. We used MCP counter, an in silico cellular deconvolution algorithm on our bulk RNA seq data to identify various subsets of tumor-infiltrating immune cells. Furthermore, our observations were validated by immunofluorescence and flow cytometry.
Results: Differential gene expression analysis using RNA seq data revealed a reduction in CXCL9, CCL5, CLEC1B, CCL9, CCL7 and other proinflammatory molecules in the Brms1-/- tumors. Gene ontology and gene set enrichment analysis highlighted a diminished immune response signature in Brms1-/- tumors. Hallmarks like interferon and IL6 signaling, complement and inflammation are highly enriched in Brms1+/+ tumors. MCP counter also suggested a significant increase in NK cells and reduction in CD8+ T cell population in the Brms1-/- tumors. To validate our observation, we performed immunofluorescence and flow cytometry to assess the number of infiltrating immune cells in the tumor microenvironment. Immunofluorescence data showed reduced cytotoxic T cells (CD8+ T cells) in Brms1-/- mice. The flow cytometric analysis also revealed a reduction in the proliferative potential of these CD8+ T cells along with the increased presence of myeloid-derived suppressor cells in the Brms1-/- mice.
Conclusion: Our data suggest for the first time that reduced BRMS1 expression which is generally observed in multiple tumors not only influences metastasis but also alters tumor-infiltrating immune cell composition. Thus, BRMS1 downregulation presents as one of the potential immune evasion mechanisms that could be targeted for an improved therapy outcome in LAUD.
Citation Format: Manendra B. Lankadasari, Yuan Liu, Di He, Samhita Bapat, Brooke Mastrogiacomo, Harry B. Lengel, David R. Jones. BRMS1 alters the tumor inflammatory signature and immune infiltration in lung adenocarcinoma . In: Proceedings of the American Association for Cancer Research Annual Meeting 2022; 2022 Apr 8-13. Philadelphia (PA): AACR; Cancer Res 2022;82(12_Suppl):Abstract nr 3142.
|
def percentile(self, percent):
if percent < 0 or percent > 1:
raise Exception('percent must be between 0 and 1')
index = int(round(percent * len(self.cdfx)))
index = min(len(self.cdfy) - 1, index)
return self.cdfx[index]
|
/**
* Base class for implementations that access the test database
*
* @author Filip Neven
* @author Tim Ducheyne
*/
abstract public class BaseDatabaseAccessor
implements DatabaseAccessing {
/**
* The unitils configuration
*/
protected Properties configuration;
/**
* Provides connections to the unit test database
*/
protected SQLHandler sqlHandler;
/**
* DbSupport for the default schema
*/
protected DbSupport defaultDbSupport;
/**
* DbSupport for all schemas
*/
protected List<DbSupport> dbSupports;
protected String dialect;
/**
* Initializes the database operation class with the given {@link Properties}, {@link DataSource}.
*
* @param configuration
* The configuration, not null
* @param sqlHandler
* The sql handler, not null
*/
@Override
public void init(Properties configuration, SQLHandler sqlHandler, String dialect, List<String> schemaNames) {
this.configuration = configuration;
this.sqlHandler = sqlHandler;
this.dbSupports = getDbSupports(configuration, sqlHandler, dialect, schemaNames);
this.defaultDbSupport = getDefaultDbSupport(configuration, sqlHandler, dialect, (CollectionUtils.isEmpty(schemaNames) ? "" : schemaNames.get(0)));
this.dialect = dialect;
doInit(configuration);
}
/**
* Allows subclasses to perform some extra configuration using the given configuration.
*
* @param configuration
* The configuration, not null
*/
protected void doInit(Properties configuration) {
// do nothing
}
/**
* Gets the db support for the given schema.
*
* @param schemaName
* The schema, not null
* @return The db support, not null
*/
public DbSupport getDbSupport(String schemaName) {
return DbSupportFactory.getDbSupport(configuration, sqlHandler, schemaName, dialect);
}
}
|
<filename>homeassistant/components/yamaha_musiccast/__init__.py
"""The MusicCast integration."""
from __future__ import annotations
from datetime import timedelta
import logging
from aiomusiccast import MusicCastConnectionException
from aiomusiccast.capabilities import Capability
from aiomusiccast.musiccast_device import MusicCastData, MusicCastDevice
from homeassistant.components import ssdp
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_HOST, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.device_registry import CONNECTION_NETWORK_MAC, format_mac
from homeassistant.helpers.entity import DeviceInfo
from homeassistant.helpers.update_coordinator import (
CoordinatorEntity,
DataUpdateCoordinator,
UpdateFailed,
)
from .const import (
BRAND,
CONF_SERIAL,
CONF_UPNP_DESC,
DEFAULT_ZONE,
DOMAIN,
ENTITY_CATEGORY_MAPPING,
)
PLATFORMS = [Platform.MEDIA_PLAYER, Platform.NUMBER, Platform.SELECT]
_LOGGER = logging.getLogger(__name__)
SCAN_INTERVAL = timedelta(seconds=60)
async def get_upnp_desc(hass: HomeAssistant, host: str):
"""Get the upnp description URL for a given host, using the SSPD scanner."""
ssdp_entries = await ssdp.async_get_discovery_info_by_st(hass, "upnp:rootdevice")
matches = [w for w in ssdp_entries if w.ssdp_headers.get("_host", "") == host]
upnp_desc = None
for match in matches:
if upnp_desc := match.ssdp_location:
break
if not upnp_desc:
_LOGGER.warning(
"The upnp_description was not found automatically, setting a default one"
)
upnp_desc = f"http://{host}:49154/MediaRenderer/desc.xml"
return upnp_desc
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up MusicCast from a config entry."""
if entry.data.get(CONF_UPNP_DESC) is None:
hass.config_entries.async_update_entry(
entry,
data={
CONF_HOST: entry.data[CONF_HOST],
CONF_SERIAL: entry.data["serial"],
CONF_UPNP_DESC: await get_upnp_desc(hass, entry.data[CONF_HOST]),
},
)
client = MusicCastDevice(
entry.data[CONF_HOST],
async_get_clientsession(hass),
entry.data[CONF_UPNP_DESC],
)
coordinator = MusicCastDataUpdateCoordinator(hass, client=client)
await coordinator.async_config_entry_first_refresh()
coordinator.musiccast.build_capabilities()
hass.data.setdefault(DOMAIN, {})
hass.data[DOMAIN][entry.entry_id] = coordinator
await coordinator.musiccast.device.enable_polling()
hass.config_entries.async_setup_platforms(entry, PLATFORMS)
entry.async_on_unload(entry.add_update_listener(async_reload_entry))
return True
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry."""
unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
if unload_ok:
hass.data[DOMAIN][entry.entry_id].musiccast.device.disable_polling()
hass.data[DOMAIN].pop(entry.entry_id)
return unload_ok
async def async_reload_entry(hass: HomeAssistant, entry: ConfigEntry) -> None:
"""Reload config entry."""
await hass.config_entries.async_reload(entry.entry_id)
class MusicCastDataUpdateCoordinator(DataUpdateCoordinator[MusicCastData]):
"""Class to manage fetching data from the API."""
def __init__(self, hass: HomeAssistant, client: MusicCastDevice) -> None:
"""Initialize."""
self.musiccast = client
super().__init__(hass, _LOGGER, name=DOMAIN, update_interval=SCAN_INTERVAL)
self.entities: list[MusicCastDeviceEntity] = []
async def _async_update_data(self) -> MusicCastData:
"""Update data via library."""
try:
await self.musiccast.fetch()
except MusicCastConnectionException as exception:
raise UpdateFailed() from exception
return self.musiccast.data
class MusicCastEntity(CoordinatorEntity):
"""Defines a base MusicCast entity."""
coordinator: MusicCastDataUpdateCoordinator
def __init__(
self,
*,
name: str,
icon: str,
coordinator: MusicCastDataUpdateCoordinator,
enabled_default: bool = True,
) -> None:
"""Initialize the MusicCast entity."""
super().__init__(coordinator)
self._enabled_default = enabled_default
self._icon = icon
self._name = name
@property
def name(self) -> str:
"""Return the name of the entity."""
return self._name
@property
def icon(self) -> str:
"""Return the mdi icon of the entity."""
return self._icon
@property
def entity_registry_enabled_default(self) -> bool:
"""Return if the entity should be enabled when first added to the entity registry."""
return self._enabled_default
class MusicCastDeviceEntity(MusicCastEntity):
"""Defines a MusicCast device entity."""
_zone_id: str = DEFAULT_ZONE
@property
def device_id(self):
"""Return the ID of the current device."""
if self._zone_id == DEFAULT_ZONE:
return self.coordinator.data.device_id
return f"{self.coordinator.data.device_id}_{self._zone_id}"
@property
def device_name(self):
"""Return the name of the current device."""
return self.coordinator.data.zones[self._zone_id].name
@property
def device_info(self) -> DeviceInfo:
"""Return device information about this MusicCast device."""
device_info = DeviceInfo(
name=self.device_name,
identifiers={
(
DOMAIN,
self.device_id,
)
},
manufacturer=BRAND,
model=self.coordinator.data.model_name,
sw_version=self.coordinator.data.system_version,
)
if self._zone_id == DEFAULT_ZONE:
device_info["connections"] = {
(CONNECTION_NETWORK_MAC, format_mac(mac))
for mac in self.coordinator.data.mac_addresses.values()
}
else:
device_info["via_device"] = (DOMAIN, self.coordinator.data.device_id)
return device_info
class MusicCastCapabilityEntity(MusicCastDeviceEntity):
"""Base Entity type for all capabilities."""
def __init__(
self,
coordinator: MusicCastDataUpdateCoordinator,
capability: Capability,
zone_id: str = None,
) -> None:
"""Initialize a capability based entity."""
if zone_id is not None:
self._zone_id = zone_id
self.capability = capability
super().__init__(name=capability.name, icon="", coordinator=coordinator)
self._attr_entity_category = ENTITY_CATEGORY_MAPPING.get(capability.entity_type)
async def async_added_to_hass(self):
"""Run when this Entity has been added to HA."""
await super().async_added_to_hass()
# All capability based entities should register callbacks to update HA when their state changes
self.coordinator.musiccast.register_callback(self.async_write_ha_state)
async def async_will_remove_from_hass(self):
"""Entity being removed from hass."""
await super().async_added_to_hass()
self.coordinator.musiccast.remove_callback(self.async_write_ha_state)
@property
def unique_id(self) -> str:
"""Return the unique ID for this entity."""
return f"{self.device_id}_{self.capability.id}"
|
/*****************************************************************************
* draw sign/icon/symbol in the output picture
*****************************************************************************/
void puzzle_draw_sign(picture_t *p_pic_out, int32_t i_x, int32_t i_y, int32_t i_width, int32_t i_lines, const char **ppsz_sign, bool b_reverse)
{
plane_t *p_out = &p_pic_out->p[Y_PLANE];
int32_t i_pixel_pitch = p_pic_out->p[Y_PLANE].i_pixel_pitch;
uint8_t i_Y;
i_Y = ( p_out->p_pixels[ i_y * p_out->i_pitch + i_x ] >= 0x7F ) ? 0x00 : 0xFF;
for( int32_t y = 0; y < i_lines ; y++ )
for( int32_t x = 0; x < i_width; x++ ) {
int32_t i_dst_x = ( x + i_x ) * i_pixel_pitch;
int32_t i_dst_y = y + i_y;
if ( ppsz_sign[y][b_reverse?i_width-1-x:x] == 'o' ) {
if ((i_dst_x < p_out->i_visible_pitch) && (i_dst_y < p_out->i_visible_lines) && (i_dst_x >= 0 ) && (i_dst_y >= 0))
memset( &p_out->p_pixels[ i_dst_y * p_out->i_pitch + i_dst_x ], i_Y, p_out->i_pixel_pitch );
}
else if ( ppsz_sign[y][b_reverse?i_width-1-x:x] == '.' ) {
if ((i_dst_x < p_out->i_visible_pitch) && (i_dst_y < p_out->i_visible_lines) && (i_dst_x >= 0 ) && (i_dst_y >= 0))
p_out->p_pixels[ i_dst_y * p_out->i_pitch + i_dst_x ] = p_out->p_pixels[ i_dst_y * p_out->i_pitch + i_dst_x ] / 2 + i_Y / 2;
}
}
}
|
/**
* Sample rows. Filter rows based on line number
*
* @author Samatar
* @since 2-jun-2003
*/
public class SampleRows extends BaseStep implements StepInterface {
private static Class<?> PKG = SampleRowsMeta.class; // for i18n purposes, needed by Translator2!!
private SampleRowsMeta meta;
private SampleRowsData data;
public SampleRows( StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta,
Trans trans ) {
super( stepMeta, stepDataInterface, copyNr, transMeta, trans );
}
public boolean processRow( StepMetaInterface smi, StepDataInterface sdi ) throws KettleException {
meta = (SampleRowsMeta) smi;
data = (SampleRowsData) sdi;
Object[] r = getRow(); // get row, set busy!
if ( r == null ) { // no more input to be expected...
setOutputDone();
return false;
}
if ( first ) {
first = false;
String realRange = environmentSubstitute( meta.getLinesRange() );
data.addlineField = ( !Const.isEmpty( environmentSubstitute( meta.getLineNumberField() ) ) );
// get the RowMeta
data.previousRowMeta = getInputRowMeta().clone();
data.NrPrevFields = data.previousRowMeta.size();
data.outputRowMeta = data.previousRowMeta;
if ( data.addlineField ) {
meta.getFields( data.outputRowMeta, getStepname(), null, null, this, repository, metaStore );
}
String[] rangePart = realRange.split( "," );
ImmutableRangeSet.Builder<Integer> setBuilder = ImmutableRangeSet.builder();
for ( String part : rangePart ) {
if ( part.matches( "\\d+" ) ) {
if ( log.isDebug() ) {
logDebug( BaseMessages.getString( PKG, "SampleRows.Log.RangeValue", part ) );
}
int vpart = Integer.valueOf( part );
setBuilder.add( Range.singleton( vpart ) );
} else if ( part.matches( "\\d+\\.\\.\\d+" ) ) {
String[] rangeMultiPart = part.split( "\\.\\." );
Integer start = Integer.valueOf( rangeMultiPart[0] );
Integer end = Integer.valueOf( rangeMultiPart[1] );
Range<Integer> range = Range.closed( start, end );
if ( log.isDebug() ) {
logDebug( BaseMessages.getString( PKG, "SampleRows.Log.RangeValue", range ) );
}
setBuilder.add( range );
}
}
data.rangeSet = setBuilder.build();
} // end if first
if ( data.addlineField ) {
data.outputRow = RowDataUtil.allocateRowData( data.outputRowMeta.size() );
for ( int i = 0; i < data.NrPrevFields; i++ ) {
data.outputRow[i] = r[i];
}
} else {
data.outputRow = r;
}
int linesRead = (int) getLinesRead();
if ( data.rangeSet.contains( linesRead ) ) {
if ( data.addlineField ) {
data.outputRow[data.NrPrevFields] = getLinesRead();
}
// copy row to possible alternate rowset(s).
//
putRow( data.outputRowMeta, data.outputRow );
if ( log.isRowLevel() ) {
logRowlevel( BaseMessages.getString( PKG, "SampleRows.Log.LineNumber", linesRead
+ " : " + getInputRowMeta().getString( r ) ) );
}
}
// Check if maximum value has been exceeded
if ( data.rangeSet.isEmpty() || linesRead >= data.rangeSet.span().upperEndpoint() ) {
setOutputDone();
}
// Allowed to continue to read in data
return true;
}
public boolean init( StepMetaInterface smi, StepDataInterface sdi ) {
meta = (SampleRowsMeta) smi;
data = (SampleRowsData) sdi;
if ( super.init( smi, sdi ) ) {
// Add init code here.
return true;
}
return false;
}
}
|
<filename>20211SVAC/G14/InterpreteXPath/AST/Etiqueta.ts<gh_stars>1-10
import { Nodo } from "./Nodo";
import NodoAST from "./NodoAST";
export class Etiqueta extends Nodo{
identificador:string;
fila: number;
columna: number;
etiqueta: any;
valor:any;
constructor(id:string, fila:number, columna:number, etiqueta:Etiqueta, valor:any){
super( fila, columna)
this.identificador = id;
this.fila = fila;
this.columna = columna;
this.etiqueta = etiqueta;
this.valor = valor;
}
obtenerNodos(): Array<NodoAST> {
var nodo;
if( this.identificador == "atributo"){
nodo = new NodoAST("LISTA_ATRIBUTOS");
}else{
nodo = new NodoAST("LISTA_OBJETOS")
}
if(this.etiqueta!=null){
var eti = this.etiqueta.obtenerNodos()[0]
nodo.addHijo(eti);
}
if(this.valor != null){
nodo.addHijo(this.valor.obtenerNodos()[0])
}
return [nodo, nodo];
}
}
|
<reponame>kitsonk/dom-selector
import domSelector = require('./interfaces');
type DomTypes = Node|HTMLElement;
type ISelectorObject = domSelector.ISelectorObject;
/* Document */
var _doc: Document = typeof document !== 'undefined' ? document : undefined;
export function getDoc(): Document {
return _doc;
}
export function setDoc(value: Document): void {
_doc = value;
}
export function resetDoc(): void {
_doc = typeof document !== 'undefined' ? document : undefined;
}
/* Other Module Interfaces */
export var defaultTag: string = 'div';
export function selectorToObject(selector: string): ISelectorObject {
var selectorRE: RegExp = /\s*([-+~,<>\*])?\s*([-\w%$|]+)?((?:[.#][-\w%$|]+)+)?((?:\[[^\]]+\])+)?((?::{1,2}[-\w]+(?:\([^\)]+\))?)+)?/,
classIdRE: RegExp = /([.#])([-\w%$|]+)/g,
psuedoClassRE: RegExp = /(?::{1,2}([-\w]+)(?:\(([^\)]+)\))?)?/g,
attributeRE: RegExp = /\[([^\]+]*['"]?)\]/g,
attributeKeyValueRE: RegExp = /([^\]=]+)=?['"]?([^\]'"]*)['"]?/;
var parsedSelector: RegExpExecArray = selectorRE.exec(selector),
selectorObject: ISelectorObject = {},
attributes: string[],
attributeKeyValue: string[];
function parseClassId(t: string, marker: string, text: string): string {
if (marker === '.') {
if (!('classNames' in selectorObject)) {
selectorObject.classNames = [];
}
selectorObject.classNames.push(text);
} else if (marker === '#') {
selectorObject.id = text;
}
return '';
}
function parsePsuedoClasses(t: string, className: string, attributes: string): string {
if (className) {
if (!('psuedoClasses' in selectorObject)) {
selectorObject.psuedoClasses = {};
}
selectorObject.psuedoClasses[className] = attributes || null;
}
return '';
}
if (parsedSelector[1]) {
selectorObject.combinator = parsedSelector[1];
}
if (parsedSelector[2]) {
selectorObject.typeName = parsedSelector[2];
}
if (parsedSelector[3]) {
if (parsedSelector[3].replace(classIdRE, parseClassId)) {
throw new Error('Invalid class or ID');
}
}
if (parsedSelector[4]) {
attributes = parsedSelector[4].split(attributeRE);
selectorObject.attributes = {};
for (var i = 0; i < attributes.length; i++) {
if (attributes[i].length) {
attributeKeyValue = attributes[i].split(attributeKeyValueRE);
if (attributeKeyValue[1]) {
selectorObject.attributes[attributeKeyValue[1]] = attributeKeyValue[2];
}
}
}
}
if (parsedSelector[5]) {
if (parsedSelector[5].replace(psuedoClassRE, parsePsuedoClasses)) {
throw new Error('Invalid psuedo class');
}
}
return selectorObject;
}
export function selectorObjectToString(selectorObject: ISelectorObject): string {
var selector: string = '';
if (selectorObject.combinator) {
selector += selectorObject.combinator + ' ';
}
if (selectorObject.typeName) {
selector += selectorObject.typeName;
}
if (selectorObject.id) {
selector += '#' + selectorObject.id;
}
if (selectorObject.classNames && selectorObject.classNames.length) {
selector += '.' + selectorObject.classNames.join('.');
}
if (selectorObject.attributes) {
for (var key in selectorObject.attributes) {
selector += selectorObject.attributes[key] ? '[' + key + '="' + selectorObject.attributes[key] + '"]' : '[' + key + ']';
}
}
if (selectorObject.attributes) {
for (var key in selectorObject.psuedoClasses) {
selector += selectorObject.psuedoClasses[key] !== null ? ':' + key + '(' + selectorObject.psuedoClasses[key] + ')' : ':' + key;
}
}
return selector;
}
/* Use Root */
var unionSplit: RegExp = /([^\s,](?:"(?:\\.|[^"])+"|'(?:\\.|[^'])+'|[^,])*)/g,
uid:string = '__ur' + Math.floor(Math.random() * 100000000) + '__';
export function useRoot(context: HTMLElement, query: string, method: Function): NodeList {
var oldContext: HTMLElement = context,
oldId: string = context.getAttribute('id'),
newId: string = oldId || uid,
hasParent: boolean = Boolean(context.parentNode),
relativeHierarchySelector: boolean = /^\s*[+~]/.test(query);
if (relativeHierarchySelector && !hasParent) {
return new NodeList();
}
if (!oldId) {
context.setAttribute('id', newId);
}
else {
newId = newId.replace(/'/g, '\\$&');
}
if (relativeHierarchySelector) {
context = <HTMLElement>context.parentNode;
}
var selectors = query.match(unionSplit);
for (var i = 0; i < selectors.length; i++) {
selectors[i] = '[id="' + newId + '"] ' + selectors[i];
}
query = selectors.join(',');
try {
return method.call(context, query);
}
finally {
if (!oldId) {
oldContext.removeAttribute('id');
}
}
}
/* NodeArray */
var toStr:Function = Object.prototype.toString,
maxSafeInteger:number = Math.pow(2, 53) - 1,
hasOwnProperty = Object.prototype.hasOwnProperty;
function isCallable(fn:any):boolean {
return typeof fn === 'function' || toStr.call(fn) === '[object Function]';
}
function toInteger(value:any):number {
var num = Number(value);
if (isNaN(num)) { return 0; }
if (num === 0 || !isFinite(num)) { return num; }
return (num > 0 ? 1 : -1) * Math.floor(Math.abs(num));
}
function toLength(value:any):number {
var len = toInteger(value);
return Math.min(Math.max(len, 0), maxSafeInteger);
}
function getMaxIndexProperty(object:Object):number {
var maxIndex:number = -1,
isValidProperty:boolean;
for (var prop in object) {
isValidProperty = (String(toInteger(prop)) === prop && toInteger(prop) !== maxSafeInteger &&
hasOwnProperty.call(object, prop));
if (isValidProperty && prop > maxIndex) {
maxIndex = prop;
}
}
return maxIndex;
}
class ExtensionArray<T> {
constructor() {
Array.apply(this, arguments);
return new Array();
}
pop():any { }
push(val:T):number { return 0; }
splice(start:number, deleteCount:number, ...items:any[]):any { }
concat<U extends T[]>(...items: U[]): T[] { return []; }
forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void { }
length: number;
}
ExtensionArray['prototype'] = new Array();
export class NodeArray extends ExtensionArray<DomTypes> implements domSelector.INodeArray {
[index:number]: DomTypes;
private _length:number = 0;
private _isMutating:boolean = false;
get length():number {
var maxIndexProperty:number = +getMaxIndexProperty(this);
return Math.max(this._length, maxIndexProperty + 1);
}
set length(value: number) {
var constrainedValue:number = toLength(value),
currentLength:number = this.length;
if (constrainedValue !== +value) {
throw new RangeError();
}
if (!this._isMutating && constrainedValue < currentLength) {
this._isMutating = true;
this.splice(constrainedValue, currentLength - constrainedValue);
this._isMutating = false;
}
this._length = constrainedValue;
}
static from(arrayLike:any, mapFn?:Function, thisArg?:Object):NodeArray {
var C:Function = this,
items = Object(arrayLike);
if (arrayLike === null) {
throw new TypeError('NodeArray.from requires an array-like object - not null or undefined');
}
var T:Object;
if (typeof mapFn !== 'undefined') {
if (!isCallable(mapFn)) {
throw new TypeError('NodeArray.from: when provided, the second argument must be a function');
}
if (arguments.length > 2) {
T = arguments[2];
}
}
var len = toLength(items.length),
NA:NodeArray = new NodeArray(len),
k:number = 0,
kValue:any;
while (k < len) {
kValue = items[k];
if (mapFn) {
NA[k] = typeof T === 'undefined' ? mapFn(kValue, k) : mapFn.call(T, kValue, k);
}
else {
NA[k] = kValue;
}
k += 1;
}
NA.length = len;
return NA;
}
constructor();
constructor(length:number);
constructor(...items:any[]) {
super();
var length:number = 0;
if (items.length === 1 && typeof items[0] === 'number') {
length = items[0];
}
else if (items.length > 1) {
for (var i = 0; i < items.length; i++) {
this[i] = items[i];
}
length = items.length;
}
}
select(...selectors:(string|ISelectorObject)[]):NodeArray {
var results:any[] = [];
this.forEach(function (value: DomTypes) {
var args:any[] = [ value ];
args = args.concat(selectors);
select.apply(this, args).forEach(function (value:any) {
results.push(value);
});
});
return NodeArray.from(results);
}
put(target:DomTypes|string|ISelectorObject):NodeArray {
/* STUB */
return NodeArray.from([]);
}
create(...selectors:(string|ISelectorObject)[]):NodeArray {
/* STUB */
return NodeArray.from([]);
}
modify(...selectors:(string|ISelectorObject)[]):NodeArray {
/* STUB */
return NodeArray.from([]);
}
}
/* get */
export function get(id:string):HTMLElement {
return getDoc().getElementById(id);
}
/* select */
var slice = Array.prototype.slice,
fastPathRE:RegExp = /^([\w]*)#([\w\-]+$)|^(\.)([\w\-\*]+$)|^(\w+$)/;
export function select(target:DomTypes|Document, ...selectors:(string|ISelectorObject)[]):NodeArray;
export function select(...selectors:(string|ISelectorObject)[]):NodeArray;
export function select(...selectors:any[]):NodeArray {
var doc:Document = getDoc(),
node:HTMLElement = <HTMLElement><Node>doc,
selector:DomTypes|Document|string,
fastPath:RegExpExecArray,
fastPathResults:HTMLElement[],
results:HTMLElement[] = [];
function fastPathQuery(target:HTMLElement|Document, selectorMatch:string[]):HTMLElement[] {
var parent:Node,
found:HTMLElement;
if (selectorMatch[2]) {
/* Looks like we are selecting an ID */
found = get(selectorMatch[2]);
if (!found || (selectorMatch[1] && selectorMatch[1] !== found.tagName.toLowerCase())) {
/* Either the ID wasn't found or was a tag qualified that didn't match */
return [];
}
if (target !== doc) {
/* There is a root element, let's make sure it is in the ancestry tree */
parent = found;
while (parent !== node) {
parent = parent.parentNode;
if (!parent) {
/* Ooops, silly person tried selecting an ID that isn't a descendent of the root */
return [];
}
}
}
/* If there is part of the query we haven't resolved, then we need to send it back to select */
return selectorMatch[3] ? slice.call(select(found, selectorMatch[3])) : [ found ];
}
if (selectorMatch[3] && 'getElementsByClassName' in target) {
/* a .class selector */
return slice.call(target.getElementsByClassName(selectorMatch[4]));
}
if (selectorMatch[5]) {
/* a tag selector */
return slice.call(target.getElementsByTagName(selectorMatch[5]));
}
return [];
}
for (var i = 0; i < selectors.length; i++) {
selector = selectors[i];
if ((typeof selector === 'object' && selector && 'nodeType' in selector) || !selector) {
/* There is an argument that is the subject of subsequent queries */
node = <HTMLElement>selector;
continue;
}
if (!node) {
/* There is no subject at the moment, so we keep consuming arguments */
continue;
}
if (typeof selector === 'string') {
fastPath = fastPathRE.exec(selector);
if (fastPath) {
/* It is quicker to not use qSA */
fastPathResults = fastPathQuery(node, fastPath);
if (fastPathResults.length) {
/* We have results */
results = results.concat(fastPathResults);
}
}
else {
/* qSA Should be Faster */
if (node === <HTMLElement><Node>doc) {
/* This is a non-rooted query, so qSA by itself will work */
results = results.concat(slice.call(node.querySelectorAll(selector)));
}
else {
/* This is a rooted query, so we have to get qSA to behave logically */
results = results.concat(slice.call(useRoot(node, selector, node.querySelectorAll)));
}
}
}
else if(selector) {
throw new TypeError('Invalid argument type of: "' + typeof selector + '"');
}
}
return NodeArray.from(results);
}
/* put */
var fragmentFasterHeuristicRE:RegExp = /[-+,> ]/,
namespaces:boolean = false,
namespaceIndex:number;
function insertTextNode(doc:Document, node:HTMLElement, text:string) {
node.appendChild(doc.createTextNode(text));
}
export function put(target:DomTypes|Document|string, ...selectors:(DomTypes|string)[]):NodeArray {
var selector:DomTypes|string,
doc:Document = getDoc(),
currentNode:DomTypes,
referenceNode:DomTypes,
nextSibling:DomTypes,
fragment:DocumentFragment;
function insertLastNode():void {
if (currentNode && referenceNode && currentNode !== referenceNode) {
(referenceNode === target &&
(fragment ||
(fragment = fragmentFasterHeuristicRE.test(<string>selector) && doc.createDocumentFragment()))
|| referenceNode).insertBefore(currentNode, nextSibling || null);
}
}
function parseSelector(match: string, combinator:string, typeSelector:string, marker:string, classText:string, attributeText: string, psuedoClass: string, psuedoClassArgs: string):string {
// test
return '';
}
for (var i = 0; i < selectors.length; i++) {
selector = selectors[i];
if (typeof selector === 'object' && 'nodeType' in selector) {
//
}
if (typeof selector === 'string') {
//
}
else {
throw new TypeError('Invalid selector arguments. Must be of type string or DOM Node.');
}
}
return NodeArray.from([]);
}
/* Create */
export function create(...selectors:string[]):NodeArray {
return NodeArray.from([]);
}
/* Modify */
export function modify(target:DomTypes|string, ...selectors:string[]):NodeArray {
return NodeArray.from([]);
}
/* remove */
export function remove(nodes:NodeArray):NodeArray;
export function remove(...nodes:(DomTypes|string)[]):NodeArray;
export function remove(...nodes:any[]):NodeArray {
var results:any[] = [],
node:DomTypes|string;
if (nodes.length === 1 && nodes[0] instanceof NodeArray) {
nodes = nodes[0];
}
for (var i = 0; i < nodes.length; i++) {
node = nodes[i];
if (typeof node === 'string') {
node = get(<string>node);
}
}
return NodeArray.from(results);
}
|
//
// Created by <NAME> on 12.04.17.
//
#include "InputDevice.h"
#include <EventQueue/EventType.h>
#include <EventQueue/Event.h>
void InputDevice::check() {
for (auto &i:pins) {
// because it's pull-up...
int value = is_low(i.header, i.pin);
if (value != i.value) {
i.value = value;
this->onChange(i);
}
}
}
/**
* Initialize pins
* @param pins
*/
void InputDevice::addInput(int header, int pin) {
Pin p;
p.header = header;
p.pin = pin;
this->pins.push_back(p);
iolib_setdir(p.header, p.pin, BBBIO_DIR_IN);
}
InputDevice::InputDevice(std::string name,
std::function<void(InputDeviceType type, std::string name, int value)> callback) {
this->name = name;
this->callback = callback;
}
void InputDevice::emit(int value) {
std::cout << this->name << " -> " << value << std::endl;
if (callback) {
callback(this->getInputDeviceType(), this->name, value);
}
}
|
/**
* The application class for the OAuth2 REST exposure.
*
* @author Jens Borch Christiansen
*/
@ApplicationPath(OAuth2Application.API_ROOT)
public class OAuth2Application extends Application {
public static final String API_ROOT = "/";
private final Set<Class<?>> classes = new HashSet<>();
public OAuth2Application() {
classes.add(TokenExposure.class);
classes.add(JacksonFeature.class);
classes.add(NotAuthorizedExceptionMapper.class);
classes.add(ContainerExceptionMapper.class);
classes.add(ConstraintViolationExceptionMapper.class);
//Filters
classes.add(CORSFilter.class);
classes.add(DiagnosticFilter.class);
}
@Override
public Set<Class<?>> getClasses() {
return classes;
}
}
|
//! CO compiler backend interface definition.
//!
//! Backend is a part of the compiler that receives the compiled and type-checked program IR and
//! does something useful with it, for example, translating it into a target language, or executing
//! it directly.
use crate::program::Program;
/// Common interface for CO compiler backends.
pub trait Backend {
/// Process the compiled CO program.
///
/// Backends should report any user-caused errors to the user, and panic only if an internal
/// error occurs. The returned `Result` indicates whether any user-caused errors occurred and
/// were reported.
fn run(&self, file_name: &str, source: &str, program: Program) -> Result<(), ()>;
}
|
def removeComments(text):
pattern = r"""
## --------- COMMENT ---------
//.*?$ ## Start of // .... comment
| ##
/\* ## Start of /* ... */ comment
[^*]*\*+ ## Non-* followed by 1-or-more *'s
( ##
[^/*][^*]*\*+ ##
)* ## 0-or-more things which don't start with /
## but do end with '*'
/ ## End of /* ... */ comment
| ## -OR- various things which aren't comments:
( ##
## ------ " ... " STRING ------
" ## Start of " ... " string
( ##
\\. ## Escaped char
| ## -OR-
[^"\\] ## Non "\ characters
)* ##
" ## End of " ... " string
| ## -OR-
##
## ------ ' ... ' STRING ------
' ## Start of ' ... ' string
( ##
\\. ## Escaped char
| ## -OR-
[^'\\] ## Non '\ characters
)* ##
' ## End of ' ... ' string
| ## -OR-
##
## ------ ANYTHING ELSE -------
. ## Anything other char
[^/"'\\]* ## Chars which doesn't start a comment, string
) ## or escape
"""
regex = re.compile(pattern, re.VERBOSE|re.MULTILINE|re.DOTALL)
noncomments = [m.group(2) for m in regex.finditer(text) if m.group(2)]
return "".join(noncomments)
|
<gh_stars>0
#include "Man.h"
#include "../AI/AiRole.h"
#include <Engine/Modules/Collide.h>
Man::Man(World *world, Vector2D location, Vector2D scale, Rotator rotation) : Body(world, location)
{
this->setType(ActorType::Living);
this->speed = 50.0f;
this->updateActorId("Man");
this->setFraction(Fraction::BadGuys);
if (this->role != nullptr)
delete this->role;
this->role = new AiRole(world, this);
}
Man::~Man(void)
{
}
void Man::update(float deltatime)
{
if (this->tempLocation == this->getLocation())
{
this->findNextPathPoint();
}
float stepSize = this->speed * deltatime;
if (stepSize < (this->tempLocation - this->getLocation()).size())
{
Vector2D step = (this->tempLocation - this->getLocation()).ort() * stepSize;
// if actor's path is free
if (!Collide::isWillCollide(this, this->getOwnerWorld(), step))
{
// accept new position of the man
this->setLocation(this->getLocation() + step);
}
else
{
findNextPathPoint();
}
}
else
{
this->setLocation(this->tempLocation);
}
// use superclass method
Body::update(deltatime);
}
void Man::hit(IActor *instigator, float damageValue, Vector2D impulse)
{
Body::hit(instigator, damageValue, impulse);
}
|
// This is a cmakeify.yml that has "abi" instead of abis.
@NotNull
public static TestManifest singleABI() throws MalformedURLException {
return getResolvedManifest("coordinate:\n" +
" groupId: com.github.jomof\n" +
" artifactId: sqlite\n" +
" version: 0.0.0\n" +
"android:\n" +
" archives:\n" +
" - lib: libsqlite.a\n" +
" file: sqlite-android-cxx-platform-12-armeabi.zip\n" +
" sha256: 485db444abe7535b3cb745c159bbeddba8db9530caf7af8f62750b8cee8d6086\n" +
" size: 980275\n" +
" runtime: c++\n" +
" platform: 12\n" +
" ndk: r13b\n" +
" abi: armeabi\n" +
" - lib: libsqlite.a\n" +
" file: sqlite-android-cxx-platform-12-armeabi-v7a.zip\n" +
" sha256: 3efa3b51f23cdac7c55422423b845569b1522ba15fa46f1ba28f89dfeaba323e\n" +
" size: 944438\n" +
" runtime: c++\n" +
" platform: 12\n" +
" ndk: r13b\n" +
" abi: armeabi-v7a\n" +
" - lib: libsqlite.a\n" +
" file: sqlite-android-cxx-platform-12-x86.zip\n" +
" sha256: 50d9593ef6658f72f107c2bdf3f1dc03e292575081da645748f4f0286bde6d59\n" +
" size: 1010262\n" +
" runtime: c++\n" +
" platform: 12\n" +
" ndk: r13b\n" +
" abi: x86\n" +
" - lib: libsqlite.a\n" +
" file: sqlite-android-gnustl-platform-12-armeabi.zip\n" +
" sha256: 226e0074826878285f734a4fa0db2c1addf2a1b6558e2f6b1000601d9e0d52c0\n" +
" size: 980301\n" +
" runtime: gnustl\n" +
" platform: 12\n" +
" ndk: r13b\n" +
" abi: armeabi\n" +
" - lib: libsqlite.a\n" +
" file: sqlite-android-gnustl-platform-12-armeabi-v7a.zip\n" +
" sha256: db6cfc4c0428ad0cf103a2f35a45fcde1e7ed834ca984daabd8d1a1a2514e3cc\n" +
" size: 944460\n" +
" runtime: gnustl\n" +
" platform: 12\n" +
" ndk: r13b\n" +
" abi: armeabi-v7a\n" +
" - lib: libsqlite.a\n" +
" file: sqlite-android-gnustl-platform-12-x86.zip\n" +
" sha256: 52d85c384ed64081f5eac9af3615b32904e5dc25851d3606376e890a43c3bf69\n" +
" size: 1010292\n" +
" runtime: gnustl\n" +
" platform: 12\n" +
" ndk: r13b\n" +
" abi: x86\n" +
" - lib: libsqlite.a\n" +
" file: sqlite-android-stlport-platform-12-armeabi.zip\n" +
" sha256: 1c367b880ce3ed498db0d2844ebd71aa989c549af33410a42a65c901d33caf50\n" +
" size: 980298\n" +
" runtime: stlport\n" +
" platform: 12\n" +
" ndk: r13b\n" +
" abi: armeabi\n" +
" - lib: libsqlite.a\n" +
" file: sqlite-android-stlport-platform-12-armeabi-v7a.zip\n" +
" sha256: afca8597b8ec21729bad255f5978117dfe1d348bd947bdeba4a91fb0e8d120d3\n" +
" size: 944462\n" +
" runtime: stlport\n" +
" platform: 12\n" +
" ndk: r13b\n" +
" abi: armeabi-v7a\n" +
" - lib: libsqlite.a\n" +
" file: sqlite-android-stlport-platform-12-x86.zip\n" +
" sha256: c2f5f7fb2f4426c8ce2d2e827dd82626f33f50d751221a2003e3b39b45c11c78\n" +
" size: 1010270\n" +
" runtime: stlport\n" +
" platform: 12\n" +
" ndk: r13b\n" +
" abi: x86\n" +
" - lib: libsqlite.a\n" +
" file: sqlite-android-cxx-platform-21-armeabi.zip\n" +
" sha256: 3fcf7cf1921dff8bee24f33f2e1ea84e54610089fd612493c225da4c64a5ac21\n" +
" size: 980485\n" +
" runtime: c++\n" +
" platform: 21\n" +
" ndk: r13b\n" +
" abi: armeabi\n" +
" - lib: libsqlite.a\n" +
" file: sqlite-android-cxx-platform-21-armeabi-v7a.zip\n" +
" sha256: 669806ae1516cc3f11f4b7d72d6f97a033bda6da8a60e020b0d0c0aadef5db1c\n" +
" size: 944612\n" +
" runtime: c++\n" +
" platform: 21\n" +
" ndk: r13b\n" +
" abi: armeabi-v7a\n" +
" - lib: libsqlite.a\n" +
" file: sqlite-android-cxx-platform-21-arm64-v8a.zip\n" +
" sha256: 5f4dc6a1a81f1c694dcb51944080b33c7b9dec8021759c8891016d4b85d6f22f\n" +
" size: 954374\n" +
" runtime: c++\n" +
" platform: 21\n" +
" ndk: r13b\n" +
" abi: arm64-v8a\n" +
" - lib: libsqlite.a\n" +
" file: sqlite-android-cxx-platform-21-x86.zip\n" +
" sha256: 436db93e9a7124707b641c25247021d6f2af28ad8cb9c028a62217cb532764b4\n" +
" size: 1010367\n" +
" runtime: c++\n" +
" platform: 21\n" +
" ndk: r13b\n" +
" abi: x86\n" +
" - lib: libsqlite.a\n" +
" file: sqlite-android-cxx-platform-21-x86_64.zip\n" +
" sha256: 7a45cf3592d63a5f3ce673bbd1a87ea47c45d28e0441b51751d26f2f18dde46c\n" +
" size: 974454\n" +
" runtime: c++\n" +
" platform: 21\n" +
" ndk: r13b\n" +
" abi: x86_64\n" +
" - lib: libsqlite.a\n" +
" file: sqlite-android-gnustl-platform-21-armeabi.zip\n" +
" sha256: 06bd163a2a8dfae9a007446dd54e9d91361c762c95775b255a926301fbc265a9\n" +
" size: 980473\n" +
" runtime: gnustl\n" +
" platform: 21\n" +
" ndk: r13b\n" +
" abi: armeabi\n" +
" - lib: libsqlite.a\n" +
" file: sqlite-android-gnustl-platform-21-armeabi-v7a.zip\n" +
" sha256: 95caac16315a34464c3690d11ca08676182cf1519321a8ae912f64d2badd1119\n" +
" size: 944611\n" +
" runtime: gnustl\n" +
" platform: 21\n" +
" ndk: r13b\n" +
" abi: armeabi-v7a\n" +
" - lib: libsqlite.a\n" +
" file: sqlite-android-gnustl-platform-21-arm64-v8a.zip\n" +
" sha256: 1a50b8a3512438009cde20afc4d0db67377ea8521ec95204ac20648989541567\n" +
" size: 954354\n" +
" runtime: gnustl\n" +
" platform: 21\n" +
" ndk: r13b\n" +
" abi: arm64-v8a\n" +
" - lib: libsqlite.a\n" +
" file: sqlite-android-gnustl-platform-21-x86.zip\n" +
" sha256: 6632c8ecbbeb7de9e25ff7a5e6b79153198cc1eeaa0c874729513375a9ebec41\n" +
" size: 1010340\n" +
" runtime: gnustl\n" +
" platform: 21\n" +
" ndk: r13b\n" +
" abi: x86\n" +
" - lib: libsqlite.a\n" +
" file: sqlite-android-gnustl-platform-21-x86_64.zip\n" +
" sha256: 5c38449bb84b112f5361858edc1dcca5596b79e7df9a4707355324cc8b5314f1\n" +
" size: 974455\n" +
" runtime: gnustl\n" +
" platform: 21\n" +
" ndk: r13b\n" +
" abi: x86_64\n" +
" - lib: libsqlite.a\n" +
" file: sqlite-android-stlport-platform-21-armeabi.zip\n" +
" sha256: 652fdd5f95d3d3ddf11caf2e49193f93de9551d5e9b29fa4b25616622e8a20d2\n" +
" size: 980480\n" +
" runtime: stlport\n" +
" platform: 21\n" +
" ndk: r13b\n" +
" abi: armeabi\n" +
" - lib: libsqlite.a\n" +
" file: sqlite-android-stlport-platform-21-armeabi-v7a.zip\n" +
" sha256: 00c675c9788b7999695b9f2e9f5c40d9942c3051daeda812d17346bce3ba0035\n" +
" size: 944624\n" +
" runtime: stlport\n" +
" platform: 21\n" +
" ndk: r13b\n" +
" abi: armeabi-v7a\n" +
" - lib: libsqlite.a\n" +
" file: sqlite-android-stlport-platform-21-arm64-v8a.zip\n" +
" sha256: a73b37fbae458b7c1b80e6cec773f4551dfd1dc631a569c2ed4eeb7160602616\n" +
" size: 954358\n" +
" runtime: stlport\n" +
" platform: 21\n" +
" ndk: r13b\n" +
" abi: arm64-v8a\n" +
" - lib: libsqlite.a\n" +
" file: sqlite-android-stlport-platform-21-x86.zip\n" +
" sha256: 1d7ee2ed92e198bd5583091abe2c8fac734b46abc6867d6ef7630be18162ff75\n" +
" size: 1010370\n" +
" runtime: stlport\n" +
" platform: 21\n" +
" ndk: r13b\n" +
" abi: x86\n" +
" - lib: libsqlite.a\n" +
" file: sqlite-android-stlport-platform-21-x86_64.zip\n" +
" sha256: 4332466fe8ac9cf22d2a552fb996bde3da98df0647a3897d25cbdaa5360a7042\n" +
" size: 974553\n" +
" runtime: stlport\n" +
" platform: 21\n" +
" ndk: r13b\n" +
" abi: x86_64\n" +
"example: |\n" +
" #include <sqlite3.h>\n" +
" void test() {\n" +
" sqlite3_initialize();\n" +
" }");
}
|
/**
* If sibling is black, double black node is left child of its parent, siblings right child is black
* and sibling's left child is red then do a right rotation at siblings left child and swap colors.
* This converts it to delete case6. It will also have a mirror case.
*/
private void deleteCase5(Node doubleBlackNode, AtomicReference<Node> rootReference) {
Node siblingNode = findSiblingNode(doubleBlackNode).get();
if(siblingNode.color == Color.BLACK) {
if (isLeftChild(doubleBlackNode) && siblingNode.right.color == Color.BLACK && siblingNode.left.color == Color.RED) {
rightRotate(siblingNode.left, true);
} else if (!isLeftChild(doubleBlackNode) && siblingNode.left.color == Color.BLACK && siblingNode.right.color == Color.RED) {
leftRotate(siblingNode.right, true);
}
}
deleteCase6(doubleBlackNode, rootReference);
}
|
import fs from 'fs';
import path from 'path';
import matter from 'gray-matter';
import { mdPostTypes } from './interfaces';
export const getMdPosts = async () => {
// get files from the 'md-posts' directory
const files = fs.readdirSync(path.join('md-posts'));
let posts = [];
const headers = {
Authorization: `${process.env.GH_USERNAME}:${process.env.GH_TOKEN}`,
};
for (let idx = 0; idx < files.length; idx++) {
let file = files[idx];
const slug: String = file.replace('.md', '');
const mdWithMeta = fs.readFileSync(path.join('md-posts', file));
const { data: frontmatter } = matter(mdWithMeta);
const username: string = frontmatter.username;
let response = await fetch(`https://api.github.com/users/${username}`, {
method: 'GET',
headers: headers,
}).then((res) => res.json());
const resData = await {
slug: slug,
userData: response,
frontmatter: frontmatter,
};
posts.push(resData);
}
return { posts };
};
export const getSingleMdPosts = async (slugx: string) => {
// get files from the 'md-posts' directory
const files = fs.readdirSync(path.join('md-posts'));
let posts = [];
const headers = {
Authorization: `${process.env.GH_USERNAME}:${process.env.GH_TOKEN}`,
};
for (let idx = 0; idx < files.length; idx++) {
let file = files[idx];
const slug: String = file.replace('.md', '');
const mdWithMeta = fs.readFileSync(path.join('md-posts', file));
const { data: frontmatter, content } = matter(mdWithMeta);
const username: string = frontmatter.username;
let response = await fetch(`https://api.github.com/users/${username}`, {
method: 'GET',
headers: headers,
}).then((res) => res.json());
const resData = await {
slug: slug,
userData: response,
frontmatter: frontmatter,
content: content,
};
if (slugx == slug) {
return resData;
}
}
return { hello: 'hello' };
};
|
def _create_target_filter(self, target, target_filter='', ancillaries=None):
target = target.lower()
defaults = ['primary', 'color-enhanced', 'secondary', 'ancillary', 'stellar library', 'flux standards']
assert target in defaults, 'target list can only contain one of {0}'.format(defaults)
if 'primary' == target:
name = 'manga_target1'
value = self.datamodel.bitmasks['MANGA_TARGET1'].labels_to_value(['PRIMARY_v1_2_0', 'COLOR_ENHANCED_v1_2_0'])
elif 'color-enhanced' == target:
name = 'manga_target1'
value = self.datamodel.bitmasks['MANGA_TARGET1'].labels_to_value(['COLOR_ENHANCED_v1_2_0'])
elif 'secondary' == target:
name = 'manga_target1'
value = self.datamodel.bitmasks['MANGA_TARGET1'].labels_to_value(['SECONDARY_v1_2_0'])
elif 'ancillary' == target:
name = 'manga_target3'
value = self.datamodel.bitmasks['MANGA_TARGET3'].labels_to_value(ancillaries) if ancillaries else 0
elif 'stellar library' == target:
name = 'manga_target2'
value = sum([1<<i for i in (self.datamodel.bitmasks['MANGA_TARGET2'].schema.bit[2:17])])
elif 'flux standards' == target:
name = 'manga_target2'
bits = [20, 22, 23, 25, 26, 27]
value = sum([1<<i for i in bits])
self._add_columns('cube.{0}'.format(name))
base = ' or ' if target_filter else ''
op = '>' if value == 0 else '&'
target_filter += '{0}cube.{1} {2} {3}'.format(base, name, op, value)
return target_filter
|
California Coaster Kings was at the Opening Night of Universal Studios Hollywood’s Halloween Horror Nights 2015, and with Front of the Line passes visited every maze, every scare zone, and of course… the Terror Tram and the brand new JABBAWOCKEEZ show. In this particular review article, we’re looking at the 6 mazes the event had this year. Each is rated in 4 categories: Length, Scare, Set, and Experience. Each will also have a quick review!
The four ratings exist of a Length Rating, which relates to the length of a maze, the longer the better. This doesn’t necessarily mean physical length of walking through the maze, but may also indicate there are plenty of different scenes and the maze felt long. The Scare Rating is exactly what you think it is, how ‘scary’ does a maze get, is it gruesome, does it create a bunch of jump scares, etc. The Set Rating looks specifically at the job done regarding the theming of the maze, how immersive were the sets, how many different scenes, etc. And then last, but definitely not least… the Experience Rating. Which is mainly based off of the overall feel of the maze, was it a extreme, did it leave you breathless, etc. The overall experience, combined with the other three factors creates a Final Score for the maze.
The Walking Dead: Wolves Not Far – Length Rating: 9 Scare Rating: 8 Set Rating: 8 Experience Rating: 8 FINAL SCORE: 8.25
The Walking Dead: Wolves Not Far seemed to be the most popular maze of all, BY FAR. Lines were incredibly long, around 2 hours, and it was only opening night of Halloween Horror Nights. There was a good reason for it to be this popular, because this was one of the best mazes at this year’s event. It was long, incredibly detailed, and featured plenty of gruesome horrors, as well as jump-scares. Be aware that this maze, though clearly related to the popular TV series, is very understandable and enjoyable even if you’re not familiar with the TV series. There were plenty of actors, a lot of scenes… and doors… we all know what doors mean… 😀 Overall, it’s definitely a maze not to be missed, but if you don’t have Front of the Line passes, you better haul over to it as soon as Halloween Horror Nights open, or you’ll be waiting all night. (This maze is located on the Lower Lot, to the left of Transformers!).
Insidious: Return To The Further – Length Rating: 8 Scare Rating: 8 Set Rating: 8 Experience Rating: 8 FINAL SCORE: 8
I was pleasantly surprised with Insidious: Return To The Further, as you may indicate from the straight-8 ratings above, it was a solid maze. One thing I very much liked about it was the large amount of scenes in tight spaces, little hallways, etc. They do establish the theme of the maze (for those not familiar with the Insidious Saga) in the first few scenes, and then it becomes clear what’s going on all around the maze. There were some good jump scares, I personally felt that this was one of the least ‘gruesome’ mazes. In this maze, more than any other, due to the narrow scenes, actors get very close to you, just be aware of that. I personally think that’s great. The sets were very detailed and diverse. Overall it was a good maze, it wasn’t the best, and for me personally it didn’t stand out too much, but it’s a great maze to visit when you’ve done the best ones. (Located next to Jurassic Park the Ride, line starts with the stairs above the Jurassic Park gift store next to the Splashdown Lagoon – FOTL line is located near the restrooms on the opposite side if the Jurassic Park entrance).
Halloween: Michael Myers Comes Home – Length Rating: 9 Scare Rating: 8 Set Rating: 9 Experience Rating: 10 FINAL SCORE: 9
It was highly anticipated, and the talk of Horror Nights for quite some weeks… and let me tell you: it definitely lived up to the expectation. As the only maze located on the Upper Lot, the lines for it can differ immensely throughout the night. But make sure to watch the park’s wait-time directories because you’re not going to want to miss out on Halloween: Michael Myers Comes Home. The maze seemed endless to me, I walked at a very steady pace, and the different scenes just kept coming. There were plenty of movie references that scared me in multiple ways. In addition, there was an incredible amount of detail. The maze was filled with actors and creative ways of disorienting guests as well as having scare actors jump out at unexpected moments. The theme is well established, though there are a lot of movie references, the fact that a large part is going through a house primarily, means that audiences of all sorts can still enjoy the maze without understanding what’s supposedly going on. Overall, and this was the last maze I visited, I was overwhelmingly surprised with the maze and totally loved it. I would make the statement that this is the best maze at Halloween Horror Nights (Hollywood) 2015! (Located in the Universal Plaza on the Upper Lot).
This Is The End – 3D – Length Rating: 7 Scare Rating: 5 Set Rating: 7 Experience Rating: 7 FINAL SCORE: 6.5
This Is The End – 3D was a bit of a let-down for me. The maze is in 3D, 3D glasses will be provided. The maze is ‘trippy’ with the 3D effects, very similar to last year’s Clowns 3D maze. When you arrive you’ll see Michael Cera hanging off the light post, like in the movie, and with the audio it’s very comedic. I was thus expecting this maze to be very funny, once inside… not so much. The maze was very repetitive, though it was of descent length, there are some scenes, in the same sequence, that literally reappear later on in the maze. The 3D effects didn’t stand out to me much, and since the main point of this maze was to be a comical one, it wasn’t scary. I had maybe one jump-scare. Sadly, it wasn’t very funny either. It’s a fun maze, pretty simplistic, but not too exciting. It does offer a completely different experience than the other mazes, and is a good break (breather) in between some other more intense mazes, but do not make this maze your priority. I enjoyed this maze the least. (Located on the Lower lot behind the Revenge of the Mummy, entrance is next to Transformers on the right-hand side).
Crimson Peak: Maze of Madness – Length Rating: 8 Scare Rating: 7 Set Rating: 9 Experience Rating: 9 FINAL SCORE: 8.25
The movie has yet to debut, but the maze already looks exactly like the trailer of the movie. And that dear readers, is quite impressive. The amount of detail in Crimson Peak: Maze of Madness is to literally go mad about, every window is a screen, every mirror is a scare actor, and boy every single room is a detailed masterpiece. Of all mazes, the sets in Crimson Peak blew me away most. The Gothic style of the maze alone is quite creepy, but overall the scenes all seemed to fit together perfectly, the transitions were great, and the detail was never ending. Sometimes you have mazes where the next room will be totally different, but everything flowed very well. Though I didn’t really get scared at any moment in this maze, the maze is just a visual masterpiece. Make sure to check this maze out, it’s one of the prettiest mazes I’ve ever seen. (Located on the Backlot, take the shuttle to the maze, which departs next to the This Is The End maze entrance!).
AVP: Alien vs. Predator – Length Rating: 7.5 Scare Rating: 8 Set Rating: 8.5 Experience Rating: 9 FINAL SCORE: 8.25
There’s always that one maze that I end up LOVING, while noone else really mentions it. AVP is one of those mazes. I thought it was a truly brilliant one. Doing sci-fi right, not everyone is able to. This maze though, was almost perfect to me. Though it seemed a tad short to me, it had a great story-line, as you enter the forest, see a crashed space-ship-thing, and then the story goes from there. There are plenty of sci-fi space-ship sort of scenes that are wonderfully turned into something you want to be afraid of. In addition, the aliens used in the maze, blew me away, they were everywhere, they were large, and they jumped out at guests plenty of times. There were plenty of narrow spaces where they were on both sides of the hallway or room, and it was almost overwhelming. The finale of the maze is by far the best finale of any maze there. A lot of mazes just suddenly ended, I felt. AVP scared the living crap out of me in the grand finale. Overall, though the maze seemed a bit short, and the sets seemed a tad simplistic, I truly fell in love with this maze. I highly recommend everyone to check it out. (Located on the Backlot, take the shuttle to the maze, which departs next to the This Is The End maze entrance!).
As a quick final note: Halloween: Michael Myers Comes Homes was my favorite maze, and since it’s the only maze on the Upper Lot, watch the wait-times, as there may just be sudden short waits. AVP was the maze I love most, it’s not as ‘good’ as Halloween, or perhaps the Walking Dead for some, but I believe it’s a true must-experience. This Is The End – 3D is, very clearly, the worst maze this year. It’s a different, softer, experience, so definitely check it out if you have time, but it shouldn’t be a priority.
Thank you for checking out the Maze Ratings and Reviews of Halloween Horror Nights 2015, we will have the JABBAWOCKEEZ, Terror Tram, and Scare Zones Ratings and Reviews LIVE soon, so check back! In addition, share your thoughts of the mazes with us below! What’s your favorite?
Make sure to follow us on our social media for exclusive coverage! Facebook–Twitter–Instagram
Our Halloween 2015 Page is also LIVE. This page gathers all California Theme-park Halloween coverage on ONE simple page, and is an ultimate guide to use! Click on the banner to be redirected and prepare your Halloween trip!
|
/**
* @author Mark Vollmary
*
*/
public class Type<T> {
private final java.lang.reflect.Type type;
protected Type() {
super();
type = getTypeParameter(getClass());
}
protected Type(final java.lang.reflect.Type type) {
super();
this.type = type;
}
private static java.lang.reflect.Type getTypeParameter(final Class<?> clazz) {
final java.lang.reflect.Type superclass = clazz.getGenericSuperclass();
if (superclass instanceof Class) {
throw new RuntimeException("Missing type parameter.");
}
return ParameterizedType.class.cast(superclass).getActualTypeArguments()[0];
}
public java.lang.reflect.Type getType() {
return type;
}
}
|
// Cors is a middleware to handle Cross Origin Request
func (m Middleware) Cors(h http.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
baseOrigin := r.Header.Get("Origin")
if r.Method == "OPTIONS" {
log.Print("preflight detected: ", r.Header)
w.Header().Add("Connection", "keep-alive")
w.Header().Add("Access-Control-Allow-Origin", getAccessControlOriginVal(baseOrigin))
w.Header().Add("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE")
w.Header().Add("Access-Control-Allow-Headers", "authorization, content-type, accept, accept-language")
w.Header().Add("Access-Control-Max-Age", "86400")
} else {
w.Header().Set("Access-Control-Allow-Origin", getAccessControlOriginVal(baseOrigin))
h.ServeHTTP(w, r)
}
}
}
|
def finish(self):
self.mean = mean(self.list)
self.median = median(self.list)
self.standard_deviation = standard_deviation(self.list)
self._finish_stats()
|
.......... .......... .......... .......... .......... .......... .......... .......... .......... .......... .......... .......... .......... .......... .......... .......... .......... ..........
WASHINGTON – Why does our political system make it impossible even to consider solutions to gun violence? After the massacre in Las Vegas that has so far taken 58 lives and left more than 500 injured, the first reaction of the many politicians who carry water for the gun lobby was to declare it “premature” to discuss measures to keep guns out of the wrong hands.
The “premature” word echoed from President Trump’s White House on down, and those who used it were really saying that Congress would never enact even modest efforts to prevent mass shootings. This is damning evidence of the stranglehold that far-right lobbies have on today’s Republicans, who extol law-and-order except when maintaining it requires confronting the National Rifle Association.
But something else is at work here. As we argue in our book “One Nation After Trump” (by E.J. Dionne Jr., Norman J. Ornstein and Thomas E. Mann), the United States is now a non-majoritarian democracy. If that sounds like a contradiction in terms, that’s because it is. Claims that our republic is democratic are undermined by a system that vastly overrepresents the interests of rural areas and small states. This leaves the large share of Americans in metropolitan areas with limited influence over national policy. Nowhere is the imbalance more dramatic or destructive than on the issue of gun control.
ADVERTISEMENTSkip
Our fellow citizens overwhelmingly reject the idea that we should do nothing and let the killings continue. Majorities in both parties favor universal background checks, a ban on assault-style weapons, and measures to prevent the mentally ill and those on no-fly watch lists from buying guns.
Yet nothing happens.
The non-majoritarian nature of our institutions was brought home in 2013. After the Sandy Hook slaughter, the Senate voted 54-to-46 in favor of a background-checks amendment crafted by Sens. Joe Manchin, D-W.Va., and Pat Toomey, R-Pa. Those 54 votes were not enough to overcome a filibuster, which the GOP regularly abused during the Obama years. Worse, since most large-state senators voted for Manchin-Toomey, the 54 “yes” votes came from lawmakers representing 63 percent of the population. Their will was foiled by those who speak for just 37 percent of us.
Ending the filibuster would not solve the problem; in some cases, it might aggravate it. As The Washington Post’s Philip Bump has noted, if all 50 senators from the 25 smallest states voted for a bill and Vice President Pence cast his lot with them, senators representing just 16 percent of Americans could overrule those representing 84 percent.
This problem will get worse. David Birdsell, a Baruch College political scientist, has calculated that by 2040, 70 percent of Americans will live in 15 states – and be represented by only 30 of the 100 senators.
In the House, mischievously drawn district lines vastly distort the preferences of those who cast ballots. After the 2010 Census, the GOP controlled the redrawing of congressional boundaries in most key states. The result? The Brennan Center for Justice concluded that Republicans derived a net benefit of at least 16 seats from biased boundaries, about two-thirds of their current House margin.
The Electoral College, meanwhile, is increasingly out of line with the popular vote. In raw terms, Trump had the largest popular vote deficit of any Electoral College winner. It was the second time in just five elections that the two were at odds. Here again, the failure of our institutions to account for the movement to metropolitan areas is the culprit. In 1960, 63 percent of Americans lived in metros; by 2010, 84 percent did.
Voter-suppression efforts and the disenfranchisement of former felons in many states further skew electoral outcomes, as does the power of money in politics.
Constitutionally, representation in the Senate is difficult to change. But this month the Supreme Court heard a case on which it could – and should – rule to make gerrymandering much harder. A renewed Voting Rights Act and universal voter registration could restore access to the ballot box to those who have lost it. The National Popular Vote Interstate Compact is trying to move us toward the popular election of the president. And our campaign finance system badly needs repair.
Our paralysis on guns reflects a looming legitimacy crisis in our system. In the short run, advocates of sane gun laws should keep up the pressure, particularly in election showdowns involving candidates who resist any steps to make our country safer. In the long run, we need reforms to make majority rule a reality.
E.J. Dionne Jr., Norman J. Ornstein and Thomas E. Mann are the authors of “One Nation After Trump: A Guide for the Perplexed, the Disillusioned, the Desperate, and the Not-Yet-Deported” (St. Martin’s Press) from which parts of this article are drawn. Dionne’s columns, including those not published in the Journal, can be read at abqjournal.com/opinion – look for the syndicated columnist link. Copyright, Washington Post Writers Group; e-mail: [email protected]. Twitter: @EJDionne.
|
<gh_stars>0
package node
import (
"fmt"
"testing"
"time"
"k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/informers"
"k8s.io/client-go/kubernetes/fake"
operatorv1alpha1 "github.com/openshift/api/operator/v1alpha1"
"github.com/openshift/library-go/pkg/operator/staticpod/controller/common"
)
func fakeMasterNode(name string) *v1.Node {
n := &v1.Node{}
n.Name = name
n.Labels = map[string]string{
"node-role.kubernetes.io/master": "",
}
return n
}
func TestNewNodeController(t *testing.T) {
tests := []struct {
name string
startNodes []runtime.Object
startNodeStatus []operatorv1alpha1.NodeStatus
evaluateNodeStatus func([]operatorv1alpha1.NodeStatus) error
}{
{
name: "single-node",
startNodes: []runtime.Object{fakeMasterNode("test-node-1")},
evaluateNodeStatus: func(s []operatorv1alpha1.NodeStatus) error {
if len(s) != 1 {
return fmt.Errorf("expected 1 node status, got %d", len(s))
}
if s[0].NodeName != "test-node-1" {
return fmt.Errorf("expected 'test-node-1' as node name, got %q", s[0].NodeName)
}
return nil
},
},
{
name: "multi-node",
startNodes: []runtime.Object{fakeMasterNode("test-node-1"), fakeMasterNode("test-node-2"), fakeMasterNode("test-node-3")},
startNodeStatus: []operatorv1alpha1.NodeStatus{
{
NodeName: "test-node-1",
},
},
evaluateNodeStatus: func(s []operatorv1alpha1.NodeStatus) error {
if len(s) != 3 {
return fmt.Errorf("expected 3 node status, got %d", len(s))
}
if s[0].NodeName != "test-node-1" {
return fmt.Errorf("expected first node to be test-node-1, got %q", s[0].NodeName)
}
if s[1].NodeName != "test-node-2" {
return fmt.Errorf("expected second node to be test-node-2, got %q", s[1].NodeName)
}
return nil
},
},
{
name: "single-node-removed",
startNodes: []runtime.Object{},
startNodeStatus: []operatorv1alpha1.NodeStatus{
{
NodeName: "lost-node",
},
},
evaluateNodeStatus: func(s []operatorv1alpha1.NodeStatus) error {
if len(s) != 0 {
return fmt.Errorf("expected no node status, got %d", len(s))
}
return nil
},
},
{
name: "no-op",
startNodes: []runtime.Object{fakeMasterNode("test-node-1")},
startNodeStatus: []operatorv1alpha1.NodeStatus{
{
NodeName: "test-node-1",
},
},
evaluateNodeStatus: func(s []operatorv1alpha1.NodeStatus) error {
if len(s) != 1 {
return fmt.Errorf("expected one node status, got %d", len(s))
}
return nil
},
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
kubeClient := fake.NewSimpleClientset(test.startNodes...)
fakeLister := common.NewFakeNodeLister(kubeClient)
kubeInformers := informers.NewSharedInformerFactory(kubeClient, 1*time.Minute)
fakeStaticPodOperatorClient := common.NewFakeStaticPodOperatorClient(
&operatorv1alpha1.OperatorSpec{
ManagementState: operatorv1alpha1.Managed,
Version: "3.11.1",
},
&operatorv1alpha1.OperatorStatus{},
&operatorv1alpha1.StaticPodOperatorStatus{
LatestAvailableDeploymentGeneration: 1,
NodeStatuses: test.startNodeStatus,
},
nil,
)
c := NewNodeController(fakeStaticPodOperatorClient, kubeInformers)
// override the lister so we don't have to run the informer to list nodes
c.nodeLister = fakeLister
if err := c.sync(); err != nil {
t.Fatal(err)
}
_, status, _, _ := fakeStaticPodOperatorClient.Get()
if err := test.evaluateNodeStatus(status.NodeStatuses); err != nil {
t.Errorf("%s: failed to evaluate node status: %v", test.name, err)
}
})
}
}
|
def write_audio(path, audio, sample_rate):
soundfile.write(file=path, data=audio, samplerate=sample_rate)
|
/// Destroys a surface.
///
/// The supplied context must be the context the surface is associated with, or this returns
/// an `IncompatibleSurface` error.
///
/// You must explicitly call this method to dispose of a surface. Otherwise, a panic occurs in
/// the `drop` method.
pub fn destroy_surface(
&self,
context: &mut Context<Def, Alt>,
surface: &mut Surface<Def, Alt>,
) -> Result<(), Error> {
match (self, &mut *context) {
(&Device::Default(ref device), &mut Context::Default(ref mut context)) => {
match *surface {
Surface::Default(ref mut surface) => device.destroy_surface(context, surface),
_ => Err(Error::IncompatibleSurface),
}
}
(&Device::Alternate(ref device), &mut Context::Alternate(ref mut context)) => {
match *surface {
Surface::Alternate(ref mut surface) => device.destroy_surface(context, surface),
_ => Err(Error::IncompatibleSurface),
}
}
_ => Err(Error::IncompatibleContext),
}
}
|
About This Game
Two hundred persistent Captains that are able to do everything the player can, including forming dynamic factions, building structures, controlling territory, and going to War.
A true living galaxy that is not player centric. It will develop differently each game through the interactions of the agents.
Build your own faction from nothing.
Randomly generated modular parts. Build the mothership that suits your play style, on the fly, in seconds. Every part has its own unique stats that contribute to the mothership. Every part has its own hull integrity and damage states. Every part is a real, working, ship component.
Strategic ship building. The mass, location and shape of parts all matter. If a part blocks a turret, it will not fire. If a ship is too long, it will turn slowly. Too many engines will mean too little power for weapons. Every design choice counts.
A fully physics based 3d environment where everything is destructible, takes damage from impacts, can be grabbed and even thrown at enemies with the tractor beam.
Natural movement and controls. Movement is on a 2d plane and screen relative, much like an FPS. The combat feels like huge pirate ships battling on an ocean. Focus on tactical positioning and manage system power to unleash hell at the right moment.
Epic ship to ship battles. Tear the enemy apart piece by piece over minutes, instead of seconds.
In SPAZ 2 you must survive in an evolving post apocalyptic Galaxy. The zombie threat is defeated, infrastructure has collapsed, fuel is scarce, and scavenging means survival.Initially the Galaxy contains hundreds of fleets, each trying to survive. AI captains do everything the player can. The player is not special and is not the center of the Galaxy.As resource scarcity becomes critical, ships come into conflict just to survive. Factions may form for protection or split due to starvation. Old friends must become fodder.Stronger factions establish and defend territories, set up resource hubs, and establish star bases. Weaker factions may resort to banditry. Each captain is unique, persistent, and shapes the Galaxy.When factions meet, combat is usually the result. While the strategic side of SPAZ 2 is about exploration, territorial control, and faction building, the action side of SPAZ 2 is about ship construction, tactics, and salvage.Combat creates damaged ships and dead crew, but it also provides new salvaged parts. All the parts in SPAZ 2 are modular and randomly generated. If you see something you like, break it off an enemy, grab it with your tractor beam, and connect it to your ship. Ship construction can be done live during battles, though sometimes beating an enemy to death with their broken wing is also fun.Back on the star map, battles will attract other captains looking for salvage. Take your new parts and run. Upgrade, repair, and prepare to fight another day, for darker threats are about to emerge.
|
def make_scope_str(cls, extra):
if extra is None:
return cls.DEFAULT_SCOPE
elif isinstance(extra, basestring):
return cls.DEFAULT_SCOPE + ',' + extra
else:
return cls.DEFAULT_SCOPE + ','.join(extra)
|
/**
* Returns the list of formats that are supported out of the box.
*/
static QStringList supportedFormats()
{
QStringList formats;
QStringList filter = QStringList() << "*.mustache";
QFileInfoList entries = QDir(":/templates").entryInfoList(filter);
for (const QFileInfo &entry : entries) {
formats.append(entry.baseName());
}
return formats;
}
|
/**
* The Class Movie.
*/
public class Movie {
/** The title. */
private String title;
/** The running time. */
private int runningTime;
/** The dor. */
private LocalDate dor;
/** The genre. */
private String genre;
/** The description. */
private String description;
/** The poster URL. */
private String posterURL;
/**
* Instantiates a new movie.
*
* @param title
* the title
* @param runningTime
* the running time
* @param genre
* the genre
* @param description
* the description
* @param posterURL
* the poster URL
* @param yearNum
* the year num
* @param monthNum
* the month num
* @param dayNum
* the day num
*/
public Movie(String title, int runningTime, String genre, String description, String posterURL, int yearNum,
int monthNum, int dayNum) {
setTitle(title);
setRunningTime(runningTime);
setGenre(genre);
setDescription(description);
setPosterURL(posterURL);
setDor(yearNum, monthNum, dayNum);
}
/**
* View movie.
*/
public void viewMovie() {
System.out.print("Showing movies");
}
/**
* Sets the poster URL.
*
* @param posterURL
* the new poster URL
*/
// SETTERS//
public void setPosterURL(String posterURL) {
this.posterURL = posterURL;
}
/**
* Sets the description.
*
* @param description
* the new description
*/
public void setDescription(String description) {
this.description = description;
}
/**
* Sets the genre.
*
* @param genre
* the new genre
*/
public void setGenre(String genre) {
this.genre = genre;
}
/**
* Sets the running time.
*
* @param runningTime
* the new running time
*/
public void setRunningTime(int runningTime) {
this.runningTime = runningTime;
}
/**
* Sets the title.
*
* @param title
* the new title
*/
public void setTitle(String title) {
this.title = title;
}
/**
* Sets the dor.
*
* @param yearNum
* the year num
* @param monthNum
* the month num
* @param dayNum
* the day num
*/
public void setDor(int yearNum, int monthNum, int dayNum) {
this.dor = LocalDate.of(yearNum, monthNum, dayNum);
}
/**
* Gets the poster URL.
*
* @return the poster URL
*/
// GETTERS//
public String getPosterURL() {
return posterURL;
}
/**
* Gets the description.
*
* @return the description
*/
public String getDescription() {
return description;
}
/**
* Gets the genre.
*
* @return the genre
*/
public String getGenre() {
return genre;
}
/**
* Gets the running time.
*
* @return the running time
*/
public int getRunningTime() {
return runningTime;
}
/**
* Gets the title.
*
* @return the title
*/
public String getTitle() {
return title;
}
/**
* Gets the dor.
*
* @return the dor
*/
public LocalDate getDor() {
return dor;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return title;
}
}
|
/**
* Handles a connection to a server.
*/
private void handleConnection(Address address, Connection connection, Throwable error, CompletableFuture<Connection> future) {
if (open) {
if (error == null) {
setupConnection(address, connection, future);
} else {
connect(future);
}
}
}
|
// SetUserAgent sets the user agent value.
func (service *BaseService) SetUserAgent(userAgentString string) {
if userAgentString == "" {
userAgentString = service.buildUserAgent()
}
service.UserAgent = userAgentString
}
|
<filename>engines/experiment/plugin/rpc/runner/rpc.go
package runner
import (
"encoding/json"
"net/http"
"github.com/gojek/turing/engines/experiment/plugin/rpc/shared"
"github.com/gojek/turing/engines/experiment/runner"
)
// rpcClient implements ConfigurableExperimentRunner interface
type rpcClient struct {
shared.RPCClient
}
func (c *rpcClient) Configure(cfg json.RawMessage) error {
return c.Call("Plugin.Configure", cfg, new(interface{}))
}
func (c *rpcClient) GetTreatmentForRequest(
header http.Header,
payload []byte,
options runner.GetTreatmentOptions,
) (*runner.Treatment, error) {
req := GetTreatmentRequest{
Header: header,
Payload: payload,
Options: options,
}
var resp runner.Treatment
err := c.Call("Plugin.GetTreatmentForRequest", &req, &resp)
if err != nil {
return nil, err
}
return &resp, nil
}
// rpcServer serves the implementation of a ConfigurableExperimentRunner
type rpcServer struct {
Impl ConfigurableExperimentRunner
}
func (s *rpcServer) Configure(cfg json.RawMessage, _ *interface{}) (err error) {
return s.Impl.Configure(cfg)
}
func (s *rpcServer) GetTreatmentForRequest(req *GetTreatmentRequest, resp *runner.Treatment) error {
treatment, err := s.Impl.GetTreatmentForRequest(req.Header, req.Payload, req.Options)
if err != nil {
return err
}
*resp = *treatment
return nil
}
|
<filename>types/es-aggregate-error/implementation.d.ts
/// <reference types="node" />
declare class AggregateError extends Error implements NodeJS.ErrnoException {
readonly errors: ReadonlyArray<any>;
readonly name: 'AggregateError';
readonly message: string;
// Using `any` here, to match Node's own typings:
constructor(errors: ReadonlyArray<any>, message?: string);
}
export = AggregateError;
|
class Sampler:
"""Base class for log emission posterior probability samplers to be used in the hybrid ADVI scheme."""
def __init__(self, hybrid_inference_params: 'HybridInferenceParameters'):
self.hybrid_inference_params = hybrid_inference_params
@abstractmethod
def update_approximation(self, approx: pm.approximations.MeanField) -> None:
"""Take a new mean-field approximation and update the sampler routine accordingly.
Args:
approx: an instance of PyMC3 mean-field posterior approximation
Returns:
None
"""
raise NotImplementedError
@abstractmethod
def draw(self) -> np.ndarray:
"""Draw one sample (or average of several samples) from log emission posterior probability."""
raise NotImplementedError
@abstractmethod
def reset(self):
"""Reset the internal state of the sampler (e.g. previously accumulated samples)."""
raise NotImplementedError
@abstractmethod
def increment(self, update: np.ndarray):
"""Add an incremental update to the current estimate of the log emission posterior mean."""
raise NotImplementedError
@abstractmethod
def get_latest_log_emission_posterior_mean_estimator(self) -> np.ndarray:
"""Returns the latest estimate of the log emission posterior mean."""
raise NotImplementedError
|
def show_param_info(self, full_args_list, plugin):
logging.info("\nInformation for %s", self.show_plugin(plugin))
logging.info("\nDescription: %s", str(full_args_list["Description"]))
self.list_args(full_args_list["mandatory"], True)
if len(full_args_list["Optional"]) > 0:
self.list_args(full_args_list["Optional"], False)
logging.info("\nUsage: %s\n", self.get_args_example(full_args_list))
abort_framework("User is only viewing options, exiting")
|
/**
* Deletes all tables present in the mapping object.
* @throws IOException
*/
@Override
public void deleteSchema() {
if (mapping.getTables().isEmpty()) throw new IllegalStateException("There are not tables defined.");
if (preferredSchema == null){
LOG.debug("Delete schemas");
if (mapping.getTables().isEmpty()) throw new IllegalStateException("There are not tables defined.");
for(String tableName : mapping.getTables().keySet())
executeDeleteTableRequest(tableName);
LOG.debug("All schemas deleted successfully.");
}
else{
LOG.debug("create schema " + preferredSchema);
executeDeleteTableRequest(preferredSchema);
}
}
|
// UpdateDatadogAlertChannel updates a single datadog alert channel integration
func (svc *IntegrationsService) UpdateDatadogAlertChannel(data DatadogAlertChannel) (
response DatadogAlertChannelResponse,
err error,
) {
err = svc.update(data.IntgGuid, data, &response)
return
}
|
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/sched/clock.h>
#include <linux/mm.h>
#include <asm/cpufeature.h>
#include <asm/msr.h>
#include "cpu.h"
static void early_init_transmeta(struct cpuinfo_x86 *c)
{
u32 xlvl;
/* Transmeta-defined flags: level 0x80860001 */
xlvl = cpuid_eax(0x80860000);
if ((xlvl & 0xffff0000) == 0x80860000) {
if (xlvl >= 0x80860001)
c->x86_capability[CPUID_8086_0001_EDX] = cpuid_edx(0x80860001);
}
}
static void init_transmeta(struct cpuinfo_x86 *c)
{
unsigned int cap_mask, uk, max, dummy;
unsigned int cms_rev1, cms_rev2;
unsigned int cpu_rev, cpu_freq = 0, cpu_flags, new_cpu_rev;
char cpu_info[65];
early_init_transmeta(c);
cpu_detect_cache_sizes(c);
/* Print CMS and CPU revision */
max = cpuid_eax(0x80860000);
cpu_rev = 0;
if (max >= 0x80860001) {
cpuid(0x80860001, &dummy, &cpu_rev, &cpu_freq, &cpu_flags);
if (cpu_rev != 0x02000000) {
pr_info("CPU: Processor revision %u.%u.%u.%u, %u MHz\n",
(cpu_rev >> 24) & 0xff,
(cpu_rev >> 16) & 0xff,
(cpu_rev >> 8) & 0xff,
cpu_rev & 0xff,
cpu_freq);
}
}
if (max >= 0x80860002) {
cpuid(0x80860002, &new_cpu_rev, &cms_rev1, &cms_rev2, &dummy);
if (cpu_rev == 0x02000000) {
pr_info("CPU: Processor revision %08X, %u MHz\n",
new_cpu_rev, cpu_freq);
}
pr_info("CPU: Code Morphing Software revision %u.%u.%u-%u-%u\n",
(cms_rev1 >> 24) & 0xff,
(cms_rev1 >> 16) & 0xff,
(cms_rev1 >> 8) & 0xff,
cms_rev1 & 0xff,
cms_rev2);
}
if (max >= 0x80860006) {
cpuid(0x80860003,
(void *)&cpu_info[0],
(void *)&cpu_info[4],
(void *)&cpu_info[8],
(void *)&cpu_info[12]);
cpuid(0x80860004,
(void *)&cpu_info[16],
(void *)&cpu_info[20],
(void *)&cpu_info[24],
(void *)&cpu_info[28]);
cpuid(0x80860005,
(void *)&cpu_info[32],
(void *)&cpu_info[36],
(void *)&cpu_info[40],
(void *)&cpu_info[44]);
cpuid(0x80860006,
(void *)&cpu_info[48],
(void *)&cpu_info[52],
(void *)&cpu_info[56],
(void *)&cpu_info[60]);
cpu_info[64] = '\0';
pr_info("CPU: %s\n", cpu_info);
}
/* Unhide possibly hidden capability flags */
rdmsr(0x80860004, cap_mask, uk);
wrmsr(0x80860004, ~0, uk);
c->x86_capability[CPUID_1_EDX] = cpuid_edx(0x00000001);
wrmsr(0x80860004, cap_mask, uk);
/* All Transmeta CPUs have a constant TSC */
set_cpu_cap(c, X86_FEATURE_CONSTANT_TSC);
#ifdef CONFIG_SYSCTL
/*
* randomize_va_space slows us down enormously;
* it probably triggers retranslation of x86->native bytecode
*/
randomize_va_space = 0;
#endif
}
static const struct cpu_dev transmeta_cpu_dev = {
.c_vendor = "Transmeta",
.c_ident = { "GenuineTMx86", "TransmetaCPU" },
.c_early_init = early_init_transmeta,
.c_init = init_transmeta,
.c_x86_vendor = X86_VENDOR_TRANSMETA,
};
cpu_dev_register(transmeta_cpu_dev);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.