text
stringlengths 2
100k
| meta
dict |
---|---|
package fitnesse.reporting;
import fitnesse.testsystems.*;
public class ExitCodeListener implements TestSystemListener {
private int failCount;
public int getFailCount() {
return failCount;
}
@Override
public void testSystemStarted(TestSystem testSystem) {
}
@Override
public void testOutputChunk(String output) {
}
@Override
public void testStarted(TestPage testPage) {
}
@Override
public void testComplete(TestPage testPage, TestSummary testSummary) {
if (testSummary.getWrong() > 0 || testSummary.getExceptions() > 0) {
failCount++;
}
}
@Override
public void testSystemStopped(TestSystem testSystem, Throwable cause) {
if (cause != null) {
failCount++;
}
}
@Override
public void testAssertionVerified(Assertion assertion, TestResult testResult) {
}
@Override
public void testExceptionOccurred(Assertion assertion, ExceptionResult exceptionResult) {
}
}
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<link rel="stylesheet" href='file:///android_asset/jd/post_detail_style.css' type="text/css"/>
<script type="text/javascript" src="read.js"></script>
</head>
<body>
<div id="trick_space"></div>
<div id="main_content">
</div>
</body>
</html> | {
"pile_set_name": "Github"
} |
# CPU offloader
# Episode 10 : "Fact"
Welcome to this tenth episode of "CPU offloader", where we implement
the factoring of the outputs from the Continued Fraction algorothm.
The factoring is done in a number of steps.
## fact
The first step is to consider the product of many small primes. For instance
the product of all primes from 2 to 59 gives the value 0x683ba8ff3e8b8a015e,
which conveniently fits into 72 bits. Call this product P. So to determine
whether a given number Y factors completely over these small primes, just
calculate the gcd(Y, P). If this value is non-zero, then divide Y by this
number and repeat. If Y reaches the value 1, then the original value Y can be
completely factored over these small primes. Otherwise, if the gcd becomes 1
before Y reaches 1, then the original value Y can not be completely factored.
This may conveniently be described by the following pseudo-code:
```
do
P = gcd(Y, P)
Y = Y/P
while (P != 1)
```
So to perform the above algorithm, we need to calculate the gcd and to perform
a division.
### gcd
The original gcd algorithm described by Euclid involves division, and therefore
we could use the existing divmod module. However, I've chosen a different
algorithm with the expectation that it is faster and smaller. Basically the
algorithm works in the following steps:
1. Find the greatest common power of 2, by repeatedly dividing both numbers by
two, as long as they are both even.
2. Whenever one number is even it is divided by two.
3. If both numbers are odd, the smallest is subtracted from the largest.
4. Repeat steps 2 and 3 until the two numbers are equal. This will be the gcd.
### divexact
To calculate Y=Y/P we can make use of the fact that we know the remainder will
always by zero. In other words, the divison is always exact, and we can use
this knowledge to implement a faster division algorithm, where the result is
calculated from LSB to MSB, instead of the usual MSB to LSB.
## fact\_all
The fact module can factor a number over all primes from 2 to 59. However, by
repeatedly calling fact with larger primes, we can factor the number over a
larger range of primes. So the fact\_all module contains a list of
primes in lines 28-35.
## factors
The time required to reach a conclusion about the factorisation of the number Y
is quite long, much longer than it takes to generate the numbers Y. Therefore,
I've decided to instantiate a number of fact\_all modules in parallel, and
dispatch each computed Y to the next avaiable fact\_all module. This is all
done in the factors module.
The dispaching is basically a round-robin scheme, where a simple counter
indicates the next instance to receive a command. If the fact\_all module
is available it gets the command and the instance counter is incremented with
wrap-around. Otherwise, the Y value is discarded. This all takes place in the
process in lines 62-97.
Once the fact\_all modules have calculated their result, they are gathered and
sent as a response. If two (or more) fact\_all modules deliver a result
simultaneously, one of the values are discarded. This is handled in the process
in lines 122-154.
## alg
The alg module simply instatiates the CF and Factors modules and connects them
together.
## Statistics
I've chosen to collect some statistics from the Factors module. Specifically,
I'm now counting the following:
* Number of (X, Y) pairs generated by the CF module.
* Number of (X, Y) pairs discarded, because all Factoring modules are busy.
* Number of (X, Y) pairs discarded, because two Factoring modules respond simultaneously.
* Number of completely factored (X, Y) pairs.
* Average number of clock cycles to factor a single Y value.
Furthermore, I've made it possible to control the number of primes to factor
over, as well as the number of factoring modules to use.
## Testing in simulation
We have added many small modules in this episode, and I've chosen to write a small
test bench for each of these small modules.
## Testing in hardware
| {
"pile_set_name": "Github"
} |
//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)
#include <boost/exception/exception.hpp>
| {
"pile_set_name": "Github"
} |
*----------------------------------------------------------------------*
* CLASS lcl_Test DEFINITION
*----------------------------------------------------------------------*
*
*----------------------------------------------------------------------*
CLASS ltcl_test DEFINITION FOR TESTING
DURATION SHORT
RISK LEVEL HARMLESS
FINAL.
PRIVATE SECTION.
* ================
DATA: mt_code TYPE string_table,
ms_result TYPE scirest_ad,
mo_check TYPE REF TO zcl_aoc_check_30.
METHODS:
setup,
export_import FOR TESTING,
test001_01 FOR TESTING,
test001_02 FOR TESTING,
test001_03 FOR TESTING,
test001_04 FOR TESTING,
test001_05 FOR TESTING,
test001_06 FOR TESTING,
test001_07 FOR TESTING,
test001_08 FOR TESTING,
test001_09 FOR TESTING,
test001_10 FOR TESTING.
ENDCLASS. "lcl_Test
*----------------------------------------------------------------------*
* CLASS lcl_Test IMPLEMENTATION
*----------------------------------------------------------------------*
*
*----------------------------------------------------------------------*
CLASS ltcl_test IMPLEMENTATION.
* ==============================
DEFINE _code.
APPEND &1 TO mt_code.
END-OF-DEFINITION.
METHOD setup.
CREATE OBJECT mo_check.
zcl_aoc_unit_test=>set_check( mo_check ).
ENDMETHOD. "setup
METHOD export_import.
zcl_aoc_unit_test=>export_import( mo_check ).
ENDMETHOD.
METHOD test001_01.
* ===========
_code 'lx_error->to_fpm_error('.
_code 'EXPORTING iv_ref_name = lv_field_name'.
_code 'iv_ref_index = lv_row ).'.
ms_result = zcl_aoc_unit_test=>check( mt_code ).
cl_abap_unit_assert=>assert_equals( exp = '001'
act = ms_result-code ).
ENDMETHOD. "test1
METHOD test001_02.
* ===========
_code 'lx_error->to_fpm_error('.
_code 'iv_ref_name = lv_field_name'.
_code 'iv_ref_index = lv_row ).'.
ms_result = zcl_aoc_unit_test=>check( mt_code ).
cl_abap_unit_assert=>assert_initial( ms_result ).
ENDMETHOD. "test2
METHOD test001_03.
* ===========
_code 'li_bcs->send_mail('.
_code 'EXPORTING'.
_code 'iv_subject_text = iv_subject_text'.
_code 'iv_distr_list = iv_distr_list'.
_code 'iv_recipient = iv_recipient'.
_code 'it_body = lt_body_text ).'.
ms_result = zcl_aoc_unit_test=>check( mt_code ).
cl_abap_unit_assert=>assert_equals( exp = '001'
act = ms_result-code ).
ENDMETHOD.
METHOD test001_04.
* ===========
_code 'foo( EXPORTING iv_bar = bar( CHANGING cv_maz = lv_baz ) ).'.
ms_result = zcl_aoc_unit_test=>check( mt_code ).
cl_abap_unit_assert=>assert_equals( exp = '001'
act = ms_result-code ).
ENDMETHOD.
METHOD test001_05.
* ===========
_code 'foo( EXPORTING iv_bar = ''CHANGING'' ).'.
ms_result = zcl_aoc_unit_test=>check( mt_code ).
cl_abap_unit_assert=>assert_equals( exp = '001'
act = ms_result-code ).
ENDMETHOD.
METHOD test001_06.
* ===========
_code 'foo( EXPORTING iv_bar = '')'' CHANGING cv_moo = lv_boo ).'.
ms_result = zcl_aoc_unit_test=>check( mt_code ).
cl_abap_unit_assert=>assert_initial( ms_result ).
ENDMETHOD.
METHOD test001_07.
* ===========
_code 'foo( iv_bar = bar( EXPORTING ci_moo = lv_boo ) ).'.
ms_result = zcl_aoc_unit_test=>check( mt_code ).
cl_abap_unit_assert=>assert_equals( exp = '001'
act = ms_result-code ).
ENDMETHOD.
METHOD test001_08.
* ===========
_code ' cl_ci_inspection=>get_ref('.
_code ' EXPORTING'.
_code ' p_user = '''''.
_code ' p_name = lv_name'.
_code ' RECEIVING'.
_code ' p_ref = lo_ci'.
_code ' EXCEPTIONS'.
_code ' insp_not_exists = 1'.
_code ' OTHERS = 2 ).'.
ms_result = zcl_aoc_unit_test=>check( mt_code ).
cl_abap_unit_assert=>assert_initial( ms_result ).
ENDMETHOD.
METHOD test001_09.
* ===========
_code ' cl_ci_inspection=>get_ref('.
_code ' EXPORTING'.
_code ' p_user = '''''.
_code ' p_name = lv_name'.
_code ' EXCEPTIONS'.
_code ' insp_not_exists = 1'.
_code ' OTHERS = 2 ).'.
ms_result = zcl_aoc_unit_test=>check( mt_code ).
cl_abap_unit_assert=>assert_initial( ms_result ).
ENDMETHOD.
METHOD test001_10.
* ===========
_code 'lv_foo = bar( EXPORTING ci_moo = lv_boo ).'.
ms_result = zcl_aoc_unit_test=>check( mt_code ).
cl_abap_unit_assert=>assert_equals( exp = '001'
act = ms_result-code ).
ENDMETHOD.
ENDCLASS. "lcl_Test
| {
"pile_set_name": "Github"
} |
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Oct 25 2017 03:49:04).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//
#import "TPreviewOptionsGroup.h"
@interface TPreviewOptionsDateGroup : TPreviewOptionsGroup
{
}
+ (id)defaultGroup;
- (struct TString)displayNameForKey:(const struct TString *)arg1;
- (_Bool)hasSpotlightAttributes;
- (id)initWithTitle:(const struct TString *)arg1;
@end
| {
"pile_set_name": "Github"
} |
# This file is responsible for configuring your application
# and its dependencies with the aid of the Mix.Config module.
use Mix.Config
# This configuration is loaded before any dependency and is restricted
# to this project. If another project depends on this project, this
# file won't be loaded nor affect the parent project. For this reason,
# if you want to provide default values for your application for
# 3rd-party users, it should be done in your "mix.exs" file.
# You can configure for your application as:
#
# config :absinthe_relay, key: :value
#
# And access this configuration in your application as:
#
# Application.get_env(:absinthe_relay, :key)
#
# Or configure a 3rd-party app:
#
# config :logger, level: :info
#
# It is also possible to import configuration files, relative to this
# directory. For example, you can emulate configuration per environment
# by uncommenting the line below and defining dev.exs, test.exs and such.
# Configuration from the imported file will override the ones defined
# here (which is why it is important to import them last).
#
# import_config "#{Mix.env}.exs"
| {
"pile_set_name": "Github"
} |
// Tests classes passed by value, pointer and reference
// Note: C# module has a large runtime test
#pragma SWIG nowarn=SWIGWARN_TYPEMAP_THREAD_UNSAFE,SWIGWARN_TYPEMAP_DIRECTOROUT_PTR
%module(directors="1") director_classes
%feature("director") Base;
%feature("director") Derived;
%include "std_string.i"
%{
#if defined(__SUNPRO_CC)
#pragma error_messages (off, hidevf)
#endif
%}
%inline %{
#include <cstdio>
#include <iostream>
// Use for debugging
bool PrintDebug = false;
struct DoubleHolder
{
DoubleHolder(double v = 0.0) : val(v) {}
double val;
};
class Base {
protected:
double m_dd;
public:
Base(double dd) : m_dd(dd) {}
virtual ~Base() {}
virtual DoubleHolder Val(DoubleHolder x) { if (PrintDebug) std::cout << "Base - Val(" << x.val << ")" << std::endl; return x; }
virtual DoubleHolder& Ref(DoubleHolder& x) { if (PrintDebug) std::cout << "Base - Ref(" << x.val << ")" << std::endl; return x; }
virtual DoubleHolder* Ptr(DoubleHolder* x) { if (PrintDebug) std::cout << "Base - Ptr(" << x->val << ")" << std::endl; return x; }
virtual std::string FullyOverloaded(int x) { if (PrintDebug) std::cout << "Base - FullyOverloaded(int " << x << ")" << std::endl; return "Base::FullyOverloaded(int)"; }
virtual std::string FullyOverloaded(bool x) { if (PrintDebug) std::cout << "Base - FullyOverloaded(bool " << x << ")" << std::endl; return "Base::FullyOverloaded(bool)"; }
virtual std::string SemiOverloaded(int x) { if (PrintDebug) std::cout << "Base - SemiOverloaded(int " << x << ")" << std::endl; return "Base::SemiOverloaded(int)"; }
virtual std::string SemiOverloaded(bool x) { if (PrintDebug) std::cout << "Base - SemiOverloaded(bool " << x << ")" << std::endl; return "Base::SemiOverloaded(bool)"; }
virtual std::string DefaultParms(int x, double y = 1.1) {
if (PrintDebug) std::cout << "Base - DefaultParms(" << x << ", " << y << ")" << std::endl;
std::string ret("Base::DefaultParms(int");
if (y!=1.1)
ret = ret + std::string(", double");
ret = ret + std::string(")");
return ret;
}
};
class Derived : public Base {
public:
Derived(double dd) : Base(dd) {}
virtual ~Derived() {}
virtual DoubleHolder Val(DoubleHolder x) { if (PrintDebug) std::cout << "Derived - Val(" << x.val << ")" << std::endl; return x; }
virtual DoubleHolder& Ref(DoubleHolder& x) { if (PrintDebug) std::cout << "Derived - Ref(" << x.val << ")" << std::endl; return x; }
virtual DoubleHolder* Ptr(DoubleHolder* x) { if (PrintDebug) std::cout << "Derived - Ptr(" << x->val << ")" << std::endl; return x; }
virtual std::string FullyOverloaded(int x) { if (PrintDebug) std::cout << "Derived - FullyOverloaded(int " << x << ")" << std::endl; return "Derived::FullyOverloaded(int)"; }
virtual std::string FullyOverloaded(bool x) { if (PrintDebug) std::cout << "Derived - FullyOverloaded(bool " << x << ")" << std::endl; return "Derived::FullyOverloaded(bool)"; }
virtual std::string SemiOverloaded(int x) { if (PrintDebug) std::cout << "Derived - SemiOverloaded(int " << x << ")" << std::endl; return "Derived::SemiOverloaded(int)"; }
// No SemiOverloaded(bool x)
virtual std::string DefaultParms(int x, double y = 1.1) {
if (PrintDebug) std::cout << "Derived - DefaultParms(" << x << ", " << y << ")" << std::endl;
std::string ret("Derived::DefaultParms(int");
if (y!=1.1)
ret = ret + std::string(", double");
ret = ret + std::string(")");
return ret;
}
};
class Caller {
private:
Base *m_base;
void delBase() { delete m_base; m_base = 0; }
public:
Caller(): m_base(0) {}
~Caller() { delBase(); }
void set(Base *b) { delBase(); m_base = b; }
void reset() { m_base = 0; }
DoubleHolder ValCall(DoubleHolder x) { return m_base->Val(x); }
DoubleHolder& RefCall(DoubleHolder& x) { return m_base->Ref(x); }
DoubleHolder* PtrCall(DoubleHolder* x) { return m_base->Ptr(x); }
std::string FullyOverloadedCall(int x) { return m_base->FullyOverloaded(x); }
std::string FullyOverloadedCall(bool x) { return m_base->FullyOverloaded(x); }
std::string SemiOverloadedCall(int x) { return m_base->SemiOverloaded(x); }
std::string SemiOverloadedCall(bool x) { return m_base->SemiOverloaded(x); }
std::string DefaultParmsCall(int x) { return m_base->DefaultParms(x); }
std::string DefaultParmsCall(int x, double y) { return m_base->DefaultParms(x, y); }
};
%}
| {
"pile_set_name": "Github"
} |
package com.discovery.grpc;
import static io.grpc.stub.ClientCalls.asyncUnaryCall;
import static io.grpc.stub.ClientCalls.asyncServerStreamingCall;
import static io.grpc.stub.ClientCalls.asyncClientStreamingCall;
import static io.grpc.stub.ClientCalls.asyncBidiStreamingCall;
import static io.grpc.stub.ClientCalls.blockingUnaryCall;
import static io.grpc.stub.ClientCalls.blockingServerStreamingCall;
import static io.grpc.stub.ClientCalls.futureUnaryCall;
import static io.grpc.MethodDescriptor.generateFullMethodName;
import static io.grpc.stub.ServerCalls.asyncUnaryCall;
import static io.grpc.stub.ServerCalls.asyncServerStreamingCall;
import static io.grpc.stub.ServerCalls.asyncClientStreamingCall;
import static io.grpc.stub.ServerCalls.asyncBidiStreamingCall;
import static io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall;
import static io.grpc.stub.ServerCalls.asyncUnimplementedStreamingCall;
/**
*/
@javax.annotation.Generated(
value = "by gRPC proto compiler (version 1.5.0)",
comments = "Source: Discovery.proto")
public final class DiscoveryServiceGrpc {
private DiscoveryServiceGrpc() {}
public static final String SERVICE_NAME = "com.discovery.grpc.DiscoveryService";
// Static method descriptors that strictly reflect the proto.
@io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/1901")
public static final io.grpc.MethodDescriptor<com.discovery.grpc.DiscoveryRequest,
com.discovery.grpc.DiscoveryResponse> METHOD_LIST_DISCOVERY =
io.grpc.MethodDescriptor.<com.discovery.grpc.DiscoveryRequest, com.discovery.grpc.DiscoveryResponse>newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName(
"com.discovery.grpc.DiscoveryService", "listDiscovery"))
.setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller(
com.discovery.grpc.DiscoveryRequest.getDefaultInstance()))
.setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller(
com.discovery.grpc.DiscoveryResponse.getDefaultInstance()))
.build();
@io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/1901")
public static final io.grpc.MethodDescriptor<com.discovery.grpc.DiscoveryRequest,
com.discovery.grpc.DiscoveryResponse> METHOD_ADD_DISCOVERY =
io.grpc.MethodDescriptor.<com.discovery.grpc.DiscoveryRequest, com.discovery.grpc.DiscoveryResponse>newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName(
"com.discovery.grpc.DiscoveryService", "addDiscovery"))
.setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller(
com.discovery.grpc.DiscoveryRequest.getDefaultInstance()))
.setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller(
com.discovery.grpc.DiscoveryResponse.getDefaultInstance()))
.build();
@io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/1901")
public static final io.grpc.MethodDescriptor<com.discovery.grpc.DiscoveryRequest,
com.discovery.grpc.DiscoveryResponse> METHOD_REMOVE_DISCOVERY =
io.grpc.MethodDescriptor.<com.discovery.grpc.DiscoveryRequest, com.discovery.grpc.DiscoveryResponse>newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName(
"com.discovery.grpc.DiscoveryService", "removeDiscovery"))
.setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller(
com.discovery.grpc.DiscoveryRequest.getDefaultInstance()))
.setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller(
com.discovery.grpc.DiscoveryResponse.getDefaultInstance()))
.build();
@io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/1901")
public static final io.grpc.MethodDescriptor<com.discovery.grpc.DiscoveryRequest,
com.discovery.grpc.DiscoveryResponse> METHOD_MODIFY_DISCOVERY =
io.grpc.MethodDescriptor.<com.discovery.grpc.DiscoveryRequest, com.discovery.grpc.DiscoveryResponse>newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName(
"com.discovery.grpc.DiscoveryService", "modifyDiscovery"))
.setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller(
com.discovery.grpc.DiscoveryRequest.getDefaultInstance()))
.setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller(
com.discovery.grpc.DiscoveryResponse.getDefaultInstance()))
.build();
/**
* Creates a new async stub that supports all call types for the service
*/
public static DiscoveryServiceStub newStub(io.grpc.Channel channel) {
return new DiscoveryServiceStub(channel);
}
/**
* Creates a new blocking-style stub that supports unary and streaming output calls on the service
*/
public static DiscoveryServiceBlockingStub newBlockingStub(
io.grpc.Channel channel) {
return new DiscoveryServiceBlockingStub(channel);
}
/**
* Creates a new ListenableFuture-style stub that supports unary calls on the service
*/
public static DiscoveryServiceFutureStub newFutureStub(
io.grpc.Channel channel) {
return new DiscoveryServiceFutureStub(channel);
}
/**
*/
public static abstract class DiscoveryServiceImplBase implements io.grpc.BindableService {
/**
*/
public void listDiscovery(com.discovery.grpc.DiscoveryRequest request,
io.grpc.stub.StreamObserver<com.discovery.grpc.DiscoveryResponse> responseObserver) {
asyncUnimplementedUnaryCall(METHOD_LIST_DISCOVERY, responseObserver);
}
/**
*/
public void addDiscovery(com.discovery.grpc.DiscoveryRequest request,
io.grpc.stub.StreamObserver<com.discovery.grpc.DiscoveryResponse> responseObserver) {
asyncUnimplementedUnaryCall(METHOD_ADD_DISCOVERY, responseObserver);
}
/**
*/
public void removeDiscovery(com.discovery.grpc.DiscoveryRequest request,
io.grpc.stub.StreamObserver<com.discovery.grpc.DiscoveryResponse> responseObserver) {
asyncUnimplementedUnaryCall(METHOD_REMOVE_DISCOVERY, responseObserver);
}
/**
*/
public void modifyDiscovery(com.discovery.grpc.DiscoveryRequest request,
io.grpc.stub.StreamObserver<com.discovery.grpc.DiscoveryResponse> responseObserver) {
asyncUnimplementedUnaryCall(METHOD_MODIFY_DISCOVERY, responseObserver);
}
@java.lang.Override public final io.grpc.ServerServiceDefinition bindService() {
return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor())
.addMethod(
METHOD_LIST_DISCOVERY,
asyncUnaryCall(
new MethodHandlers<
com.discovery.grpc.DiscoveryRequest,
com.discovery.grpc.DiscoveryResponse>(
this, METHODID_LIST_DISCOVERY)))
.addMethod(
METHOD_ADD_DISCOVERY,
asyncUnaryCall(
new MethodHandlers<
com.discovery.grpc.DiscoveryRequest,
com.discovery.grpc.DiscoveryResponse>(
this, METHODID_ADD_DISCOVERY)))
.addMethod(
METHOD_REMOVE_DISCOVERY,
asyncUnaryCall(
new MethodHandlers<
com.discovery.grpc.DiscoveryRequest,
com.discovery.grpc.DiscoveryResponse>(
this, METHODID_REMOVE_DISCOVERY)))
.addMethod(
METHOD_MODIFY_DISCOVERY,
asyncUnaryCall(
new MethodHandlers<
com.discovery.grpc.DiscoveryRequest,
com.discovery.grpc.DiscoveryResponse>(
this, METHODID_MODIFY_DISCOVERY)))
.build();
}
}
/**
*/
public static final class DiscoveryServiceStub extends io.grpc.stub.AbstractStub<DiscoveryServiceStub> {
private DiscoveryServiceStub(io.grpc.Channel channel) {
super(channel);
}
private DiscoveryServiceStub(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected DiscoveryServiceStub build(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
return new DiscoveryServiceStub(channel, callOptions);
}
/**
*/
public void listDiscovery(com.discovery.grpc.DiscoveryRequest request,
io.grpc.stub.StreamObserver<com.discovery.grpc.DiscoveryResponse> responseObserver) {
asyncUnaryCall(
getChannel().newCall(METHOD_LIST_DISCOVERY, getCallOptions()), request, responseObserver);
}
/**
*/
public void addDiscovery(com.discovery.grpc.DiscoveryRequest request,
io.grpc.stub.StreamObserver<com.discovery.grpc.DiscoveryResponse> responseObserver) {
asyncUnaryCall(
getChannel().newCall(METHOD_ADD_DISCOVERY, getCallOptions()), request, responseObserver);
}
/**
*/
public void removeDiscovery(com.discovery.grpc.DiscoveryRequest request,
io.grpc.stub.StreamObserver<com.discovery.grpc.DiscoveryResponse> responseObserver) {
asyncUnaryCall(
getChannel().newCall(METHOD_REMOVE_DISCOVERY, getCallOptions()), request, responseObserver);
}
/**
*/
public void modifyDiscovery(com.discovery.grpc.DiscoveryRequest request,
io.grpc.stub.StreamObserver<com.discovery.grpc.DiscoveryResponse> responseObserver) {
asyncUnaryCall(
getChannel().newCall(METHOD_MODIFY_DISCOVERY, getCallOptions()), request, responseObserver);
}
}
/**
*/
public static final class DiscoveryServiceBlockingStub extends io.grpc.stub.AbstractStub<DiscoveryServiceBlockingStub> {
private DiscoveryServiceBlockingStub(io.grpc.Channel channel) {
super(channel);
}
private DiscoveryServiceBlockingStub(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected DiscoveryServiceBlockingStub build(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
return new DiscoveryServiceBlockingStub(channel, callOptions);
}
/**
*/
public com.discovery.grpc.DiscoveryResponse listDiscovery(com.discovery.grpc.DiscoveryRequest request) {
return blockingUnaryCall(
getChannel(), METHOD_LIST_DISCOVERY, getCallOptions(), request);
}
/**
*/
public com.discovery.grpc.DiscoveryResponse addDiscovery(com.discovery.grpc.DiscoveryRequest request) {
return blockingUnaryCall(
getChannel(), METHOD_ADD_DISCOVERY, getCallOptions(), request);
}
/**
*/
public com.discovery.grpc.DiscoveryResponse removeDiscovery(com.discovery.grpc.DiscoveryRequest request) {
return blockingUnaryCall(
getChannel(), METHOD_REMOVE_DISCOVERY, getCallOptions(), request);
}
/**
*/
public com.discovery.grpc.DiscoveryResponse modifyDiscovery(com.discovery.grpc.DiscoveryRequest request) {
return blockingUnaryCall(
getChannel(), METHOD_MODIFY_DISCOVERY, getCallOptions(), request);
}
}
/**
*/
public static final class DiscoveryServiceFutureStub extends io.grpc.stub.AbstractStub<DiscoveryServiceFutureStub> {
private DiscoveryServiceFutureStub(io.grpc.Channel channel) {
super(channel);
}
private DiscoveryServiceFutureStub(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected DiscoveryServiceFutureStub build(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
return new DiscoveryServiceFutureStub(channel, callOptions);
}
/**
*/
public com.google.common.util.concurrent.ListenableFuture<com.discovery.grpc.DiscoveryResponse> listDiscovery(
com.discovery.grpc.DiscoveryRequest request) {
return futureUnaryCall(
getChannel().newCall(METHOD_LIST_DISCOVERY, getCallOptions()), request);
}
/**
*/
public com.google.common.util.concurrent.ListenableFuture<com.discovery.grpc.DiscoveryResponse> addDiscovery(
com.discovery.grpc.DiscoveryRequest request) {
return futureUnaryCall(
getChannel().newCall(METHOD_ADD_DISCOVERY, getCallOptions()), request);
}
/**
*/
public com.google.common.util.concurrent.ListenableFuture<com.discovery.grpc.DiscoveryResponse> removeDiscovery(
com.discovery.grpc.DiscoveryRequest request) {
return futureUnaryCall(
getChannel().newCall(METHOD_REMOVE_DISCOVERY, getCallOptions()), request);
}
/**
*/
public com.google.common.util.concurrent.ListenableFuture<com.discovery.grpc.DiscoveryResponse> modifyDiscovery(
com.discovery.grpc.DiscoveryRequest request) {
return futureUnaryCall(
getChannel().newCall(METHOD_MODIFY_DISCOVERY, getCallOptions()), request);
}
}
private static final int METHODID_LIST_DISCOVERY = 0;
private static final int METHODID_ADD_DISCOVERY = 1;
private static final int METHODID_REMOVE_DISCOVERY = 2;
private static final int METHODID_MODIFY_DISCOVERY = 3;
private static final class MethodHandlers<Req, Resp> implements
io.grpc.stub.ServerCalls.UnaryMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ServerStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ClientStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.BidiStreamingMethod<Req, Resp> {
private final DiscoveryServiceImplBase serviceImpl;
private final int methodId;
MethodHandlers(DiscoveryServiceImplBase serviceImpl, int methodId) {
this.serviceImpl = serviceImpl;
this.methodId = methodId;
}
@java.lang.Override
@java.lang.SuppressWarnings("unchecked")
public void invoke(Req request, io.grpc.stub.StreamObserver<Resp> responseObserver) {
switch (methodId) {
case METHODID_LIST_DISCOVERY:
serviceImpl.listDiscovery((com.discovery.grpc.DiscoveryRequest) request,
(io.grpc.stub.StreamObserver<com.discovery.grpc.DiscoveryResponse>) responseObserver);
break;
case METHODID_ADD_DISCOVERY:
serviceImpl.addDiscovery((com.discovery.grpc.DiscoveryRequest) request,
(io.grpc.stub.StreamObserver<com.discovery.grpc.DiscoveryResponse>) responseObserver);
break;
case METHODID_REMOVE_DISCOVERY:
serviceImpl.removeDiscovery((com.discovery.grpc.DiscoveryRequest) request,
(io.grpc.stub.StreamObserver<com.discovery.grpc.DiscoveryResponse>) responseObserver);
break;
case METHODID_MODIFY_DISCOVERY:
serviceImpl.modifyDiscovery((com.discovery.grpc.DiscoveryRequest) request,
(io.grpc.stub.StreamObserver<com.discovery.grpc.DiscoveryResponse>) responseObserver);
break;
default:
throw new AssertionError();
}
}
@java.lang.Override
@java.lang.SuppressWarnings("unchecked")
public io.grpc.stub.StreamObserver<Req> invoke(
io.grpc.stub.StreamObserver<Resp> responseObserver) {
switch (methodId) {
default:
throw new AssertionError();
}
}
}
private static final class DiscoveryServiceDescriptorSupplier implements io.grpc.protobuf.ProtoFileDescriptorSupplier {
@java.lang.Override
public com.google.protobuf.Descriptors.FileDescriptor getFileDescriptor() {
return com.discovery.grpc.DiscoveryOuterClass.getDescriptor();
}
}
private static volatile io.grpc.ServiceDescriptor serviceDescriptor;
public static io.grpc.ServiceDescriptor getServiceDescriptor() {
io.grpc.ServiceDescriptor result = serviceDescriptor;
if (result == null) {
synchronized (DiscoveryServiceGrpc.class) {
result = serviceDescriptor;
if (result == null) {
serviceDescriptor = result = io.grpc.ServiceDescriptor.newBuilder(SERVICE_NAME)
.setSchemaDescriptor(new DiscoveryServiceDescriptorSupplier())
.addMethod(METHOD_LIST_DISCOVERY)
.addMethod(METHOD_ADD_DISCOVERY)
.addMethod(METHOD_REMOVE_DISCOVERY)
.addMethod(METHOD_MODIFY_DISCOVERY)
.build();
}
}
}
return result;
}
}
| {
"pile_set_name": "Github"
} |
/*****************************************************************************
Copyright (c) 2014, Intel Corp.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Intel Corporation nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************
* Contents: Native high-level C interface to LAPACK function zhetri2x
* Author: Intel Corporation
* Generated June 2016
*****************************************************************************/
#include "lapacke_utils.h"
lapack_int LAPACKE_zhetri2x( int matrix_layout, char uplo, lapack_int n,
lapack_complex_double* a, lapack_int lda,
const lapack_int* ipiv, lapack_int nb )
{
lapack_int info = 0;
lapack_complex_double* work = NULL;
if( matrix_layout != LAPACK_COL_MAJOR && matrix_layout != LAPACK_ROW_MAJOR ) {
LAPACKE_xerbla( "LAPACKE_zhetri2x", -1 );
return -1;
}
#ifndef LAPACK_DISABLE_NAN_CHECK
if( LAPACKE_get_nancheck() ) {
/* Optionally check input matrices for NaNs */
if( LAPACKE_zge_nancheck( matrix_layout, n, n, a, lda ) ) {
return -4;
}
}
#endif
/* Allocate memory for working array(s) */
work = (lapack_complex_double*)
LAPACKE_malloc( sizeof(lapack_complex_double) * MAX(1,n+nb+1)*(+1) );
if( work == NULL ) {
info = LAPACK_WORK_MEMORY_ERROR;
goto exit_level_0;
}
/* Call middle-level interface */
info = LAPACKE_zhetri2x_work( matrix_layout, uplo, n, a, lda, ipiv, work,
nb );
/* Release memory and exit */
LAPACKE_free( work );
exit_level_0:
if( info == LAPACK_WORK_MEMORY_ERROR ) {
LAPACKE_xerbla( "LAPACKE_zhetri2x", info );
}
return info;
}
| {
"pile_set_name": "Github"
} |
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
window.CodeMirror = {};
(function() {
"use strict";
function splitLines(string){ return string.split(/\r?\n|\r/); };
function StringStream(string) {
this.pos = this.start = 0;
this.string = string;
this.lineStart = 0;
}
StringStream.prototype = {
eol: function() {return this.pos >= this.string.length;},
sol: function() {return this.pos == 0;},
peek: function() {return this.string.charAt(this.pos) || null;},
next: function() {
if (this.pos < this.string.length)
return this.string.charAt(this.pos++);
},
eat: function(match) {
var ch = this.string.charAt(this.pos);
if (typeof match == "string") var ok = ch == match;
else var ok = ch && (match.test ? match.test(ch) : match(ch));
if (ok) {++this.pos; return ch;}
},
eatWhile: function(match) {
var start = this.pos;
while (this.eat(match)){}
return this.pos > start;
},
eatSpace: function() {
var start = this.pos;
while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;
return this.pos > start;
},
skipToEnd: function() {this.pos = this.string.length;},
skipTo: function(ch) {
var found = this.string.indexOf(ch, this.pos);
if (found > -1) {this.pos = found; return true;}
},
backUp: function(n) {this.pos -= n;},
column: function() {return this.start - this.lineStart;},
indentation: function() {return 0;},
match: function(pattern, consume, caseInsensitive) {
if (typeof pattern == "string") {
var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;};
var substr = this.string.substr(this.pos, pattern.length);
if (cased(substr) == cased(pattern)) {
if (consume !== false) this.pos += pattern.length;
return true;
}
} else {
var match = this.string.slice(this.pos).match(pattern);
if (match && match.index > 0) return null;
if (match && consume !== false) this.pos += match[0].length;
return match;
}
},
current: function(){return this.string.slice(this.start, this.pos);},
hideFirstChars: function(n, inner) {
this.lineStart += n;
try { return inner(); }
finally { this.lineStart -= n; }
}
};
CodeMirror.StringStream = StringStream;
CodeMirror.startState = function (mode, a1, a2) {
return mode.startState ? mode.startState(a1, a2) : true;
};
var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {};
CodeMirror.defineMode = function (name, mode) {
if (arguments.length > 2)
mode.dependencies = Array.prototype.slice.call(arguments, 2);
modes[name] = mode;
};
CodeMirror.defineMIME = function (mime, spec) { mimeModes[mime] = spec; };
CodeMirror.resolveMode = function(spec) {
if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
spec = mimeModes[spec];
} else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
spec = mimeModes[spec.name];
}
if (typeof spec == "string") return {name: spec};
else return spec || {name: "null"};
};
CodeMirror.getMode = function (options, spec) {
spec = CodeMirror.resolveMode(spec);
var mfactory = modes[spec.name];
if (!mfactory) throw new Error("Unknown mode: " + spec);
return mfactory(options, spec);
};
CodeMirror.registerHelper = CodeMirror.registerGlobalHelper = Math.min;
CodeMirror.defineMode("null", function() {
return {token: function(stream) {stream.skipToEnd();}};
});
CodeMirror.defineMIME("text/plain", "null");
CodeMirror.runMode = function (string, modespec, callback, options) {
var mode = CodeMirror.getMode({ indentUnit: 2 }, modespec);
if (callback.nodeType == 1) {
var tabSize = (options && options.tabSize) || 4;
var node = callback, col = 0;
node.innerHTML = "";
callback = function (text, style) {
if (text == "\n") {
node.appendChild(document.createElement("br"));
col = 0;
return;
}
var content = "";
// replace tabs
for (var pos = 0; ;) {
var idx = text.indexOf("\t", pos);
if (idx == -1) {
content += text.slice(pos);
col += text.length - pos;
break;
} else {
col += idx - pos;
content += text.slice(pos, idx);
var size = tabSize - col % tabSize;
col += size;
for (var i = 0; i < size; ++i) content += " ";
pos = idx + 1;
}
}
if (style) {
var sp = node.appendChild(document.createElement("span"));
sp.className = "cm-" + style.replace(/ +/g, " cm-");
sp.appendChild(document.createTextNode(content));
} else {
node.appendChild(document.createTextNode(content));
}
};
}
var lines = splitLines(string), state = (options && options.state) || CodeMirror.startState(mode);
for (var i = 0, e = lines.length; i < e; ++i) {
if (i) callback("\n");
var stream = new CodeMirror.StringStream(lines[i]);
if (!stream.string && mode.blankLine) mode.blankLine(state);
while (!stream.eol()) {
var style = mode.token(stream, state);
callback(stream.current(), style, i, stream.start, state);
stream.start = stream.pos;
}
}
};
})();
| {
"pile_set_name": "Github"
} |
//
// std_type_info.cpp
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Definitions of the std::type_info implementation functions, used for
// Run-Time Type Information (RTTI).
//
#include <vcruntime_internal.h>
#include <vcruntime_string.h>
#include <vcruntime_typeinfo.h>
//#include <undname.h>
#include <msvcrt_IAT.h>
#if 0 //直接由msvcrt.dll提供
extern "C" int __cdecl __std_type_info_compare(
__std_type_info_data const* const lhs,
__std_type_info_data const* const rhs
)
{
if (lhs == rhs)
{
return 0;
}
return strcmp(lhs->_DecoratedName + 1, rhs->_DecoratedName + 1);
}
#endif
extern "C" size_t __cdecl __std_type_info_hash(
__std_type_info_data const* const data
)
{
// FNV-1a hash function for the undecorated name
#ifdef _WIN64
static_assert(sizeof(size_t) == 8, "This code is for 64-bit size_t.");
size_t const fnv_offset_basis = 14695981039346656037ULL;
size_t const fnv_prime = 1099511628211ULL;
#else
static_assert(sizeof(size_t) == 4, "This code is for 32-bit size_t.");
size_t const fnv_offset_basis = 2166136261U;
size_t const fnv_prime = 16777619U;
#endif
size_t value = fnv_offset_basis;
for (char const* it = data->_DecoratedName + 1; *it != '\0'; ++it)
{
value ^= static_cast<size_t>(static_cast<unsigned char>(*it));
value *= fnv_prime;
}
#ifdef _WIN64
static_assert(sizeof(size_t) == 8, "This code is for 64-bit size_t.");
value ^= value >> 32;
#else
static_assert(sizeof(size_t) == 4, "This code is for 32-bit size_t.");
#endif
return value;
}
#if 0 //直接由msvcrt.dll提供
extern "C" char const* __cdecl __std_type_info_name(
__std_type_info_data* const data,
__type_info_node* const root_node
)
{
// First check to see if we've already cached the undecorated name; if we
// have, we can just return it:
{
char const* const cached_undecorated_name = __crt_interlocked_read_pointer(&data->_UndecoratedName);
if (cached_undecorated_name)
{
return cached_undecorated_name;
}
}
__crt_unique_heap_ptr<char> undecorated_name(__unDName(
nullptr,
data->_DecoratedName + 1,
0,
[](size_t const n) { return _malloc_crt(n); },
[](void* const p) { return _free_crt(p); },
UNDNAME_32_BIT_DECODE | UNDNAME_TYPE_ONLY));
if (!undecorated_name)
{
return nullptr; // CRT_REFACTOR TODO This is nonconforming
}
size_t undecorated_name_length = strlen(undecorated_name.get());
while (undecorated_name_length != 0 && undecorated_name.get()[undecorated_name_length - 1] == ' ')
{
undecorated_name.get()[undecorated_name_length - 1] = '\0';
--undecorated_name_length;
}
size_t const undecorated_name_count = undecorated_name_length + 1;
size_t const node_size = sizeof(SLIST_ENTRY) + undecorated_name_count;
__crt_unique_heap_ptr<void> node_block(_malloc_crt(node_size));
if (!node_block)
{
return nullptr; // CRT_REFACTOR TODO This is nonconforming
}
PSLIST_ENTRY const node_header = static_cast<PSLIST_ENTRY>(node_block.get());
char* const node_string = reinterpret_cast<char*>(node_header + 1);
*node_header = SLIST_ENTRY{};
strcpy_s(node_string, undecorated_name_count, undecorated_name.get());
char const* const cached_undecorated_name = __crt_interlocked_compare_exchange_pointer(
&data->_UndecoratedName,
node_string,
nullptr);
// If the cache already contained an undecorated name pointer, another
// thread must have cached it while we were computing the undecorated
// name. Discard the string we created and return the cached string:
if (cached_undecorated_name)
{
return cached_undecorated_name;
}
// Otherwise, we've successfully cached our string; link it into the list
// and return it:
node_block.detach();
InterlockedPushEntrySList(&root_node->_Header, node_header);
return node_string;
}
#endif
// This function is called during module unload to clean up all of the undecorated
// name strings that were allocated by calls to name().
extern "C" void __cdecl __std_type_info_destroy_list(
__type_info_node* const root_node
)
{
PSLIST_ENTRY current_node = InterlockedFlushSList(&root_node->_Header);
while (current_node)
{
PSLIST_ENTRY const next_node = current_node->Next;
_free_crt(current_node);
current_node = next_node;
}
}
| {
"pile_set_name": "Github"
} |
// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
#ifndef OPENCV_COLOR_MOMENT_HASH_HPP
#define OPENCV_COLOR_MOMENT_HASH_HPP
#include "img_hash_base.hpp"
namespace cv {
namespace img_hash {
//! @addtogroup img_hash
//! @{
/** @brief Image hash based on color moments.
See @cite tang2012perceptual for details.
*/
class CV_EXPORTS_W ColorMomentHash : public ImgHashBase
{
public:
CV_WRAP static Ptr<ColorMomentHash> create();
protected:
ColorMomentHash() {}
};
/** @brief Computes color moment hash of the input, the algorithm
is come from the paper "Perceptual Hashing for Color Images
Using Invariant Moments"
@param inputArr input image want to compute hash value,
type should be CV_8UC4, CV_8UC3 or CV_8UC1.
@param outputArr 42 hash values with type CV_64F(double)
*/
CV_EXPORTS_W void colorMomentHash(cv::InputArray inputArr, cv::OutputArray outputArr);
//! @}
}} // cv::img_hash::
#endif // OPENCV_COLOR_MOMENT_HASH_HPP
| {
"pile_set_name": "Github"
} |
# db1104
# candidate master for s8
mariadb::shard: 's8'
mariadb::binlog_format: 'STATEMENT'
| {
"pile_set_name": "Github"
} |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.mapred;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.StringTokenizer;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Counters;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.v2.jobhistory.JHAdminConfig;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* Basic testing for the MiniMRClientCluster. This test shows an example class
* that can be used in MR1 or MR2, without any change to the test. The test will
* use MiniMRYarnCluster in MR2, and MiniMRCluster in MR1.
*/
public class TestMiniMRClientCluster {
private static Path inDir = null;
private static Path outDir = null;
private static Path testdir = null;
private static Path[] inFiles = new Path[5];
private static MiniMRClientCluster mrCluster;
private class InternalClass {
}
@BeforeClass
public static void setup() throws IOException {
final Configuration conf = new Configuration();
final Path TEST_ROOT_DIR = new Path(System.getProperty("test.build.data",
"/tmp"));
testdir = new Path(TEST_ROOT_DIR, "TestMiniMRClientCluster");
inDir = new Path(testdir, "in");
outDir = new Path(testdir, "out");
FileSystem fs = FileSystem.getLocal(conf);
if (fs.exists(testdir) && !fs.delete(testdir, true)) {
throw new IOException("Could not delete " + testdir);
}
if (!fs.mkdirs(inDir)) {
throw new IOException("Mkdirs failed to create " + inDir);
}
for (int i = 0; i < inFiles.length; i++) {
inFiles[i] = new Path(inDir, "part_" + i);
createFile(inFiles[i], conf);
}
// create the mini cluster to be used for the tests
mrCluster = MiniMRClientClusterFactory.create(
InternalClass.class, 1, new Configuration());
}
@AfterClass
public static void cleanup() throws IOException {
// clean up the input and output files
final Configuration conf = new Configuration();
final FileSystem fs = testdir.getFileSystem(conf);
if (fs.exists(testdir)) {
fs.delete(testdir, true);
}
// stopping the mini cluster
mrCluster.stop();
}
@Test
public void testRestart() throws Exception {
String rmAddress1 = mrCluster.getConfig().get(YarnConfiguration.RM_ADDRESS);
String rmAdminAddress1 = mrCluster.getConfig().get(
YarnConfiguration.RM_ADMIN_ADDRESS);
String rmSchedAddress1 = mrCluster.getConfig().get(
YarnConfiguration.RM_SCHEDULER_ADDRESS);
String rmRstrackerAddress1 = mrCluster.getConfig().get(
YarnConfiguration.RM_RESOURCE_TRACKER_ADDRESS);
String rmWebAppAddress1 = mrCluster.getConfig().get(
YarnConfiguration.RM_WEBAPP_ADDRESS);
String mrHistAddress1 = mrCluster.getConfig().get(
JHAdminConfig.MR_HISTORY_ADDRESS);
String mrHistWebAppAddress1 = mrCluster.getConfig().get(
JHAdminConfig.MR_HISTORY_WEBAPP_ADDRESS);
mrCluster.restart();
String rmAddress2 = mrCluster.getConfig().get(YarnConfiguration.RM_ADDRESS);
String rmAdminAddress2 = mrCluster.getConfig().get(
YarnConfiguration.RM_ADMIN_ADDRESS);
String rmSchedAddress2 = mrCluster.getConfig().get(
YarnConfiguration.RM_SCHEDULER_ADDRESS);
String rmRstrackerAddress2 = mrCluster.getConfig().get(
YarnConfiguration.RM_RESOURCE_TRACKER_ADDRESS);
String rmWebAppAddress2 = mrCluster.getConfig().get(
YarnConfiguration.RM_WEBAPP_ADDRESS);
String mrHistAddress2 = mrCluster.getConfig().get(
JHAdminConfig.MR_HISTORY_ADDRESS);
String mrHistWebAppAddress2 = mrCluster.getConfig().get(
JHAdminConfig.MR_HISTORY_WEBAPP_ADDRESS);
assertEquals("Address before restart: " + rmAddress1
+ " is different from new address: " + rmAddress2, rmAddress1,
rmAddress2);
assertEquals("Address before restart: " + rmAdminAddress1
+ " is different from new address: " + rmAdminAddress2,
rmAdminAddress1, rmAdminAddress2);
assertEquals("Address before restart: " + rmSchedAddress1
+ " is different from new address: " + rmSchedAddress2,
rmSchedAddress1, rmSchedAddress2);
assertEquals("Address before restart: " + rmRstrackerAddress1
+ " is different from new address: " + rmRstrackerAddress2,
rmRstrackerAddress1, rmRstrackerAddress2);
assertEquals("Address before restart: " + rmWebAppAddress1
+ " is different from new address: " + rmWebAppAddress2,
rmWebAppAddress1, rmWebAppAddress2);
assertEquals("Address before restart: " + mrHistAddress1
+ " is different from new address: " + mrHistAddress2, mrHistAddress1,
mrHistAddress2);
assertEquals("Address before restart: " + mrHistWebAppAddress1
+ " is different from new address: " + mrHistWebAppAddress2,
mrHistWebAppAddress1, mrHistWebAppAddress2);
}
@Test
public void testJob() throws Exception {
final Job job = createJob();
org.apache.hadoop.mapreduce.lib.input.FileInputFormat.setInputPaths(job,
inDir);
org.apache.hadoop.mapreduce.lib.output.FileOutputFormat.setOutputPath(job,
new Path(outDir, "testJob"));
assertTrue(job.waitForCompletion(true));
validateCounters(job.getCounters(), 5, 25, 5, 5);
}
private void validateCounters(Counters counters, long mapInputRecords,
long mapOutputRecords, long reduceInputGroups, long reduceOutputRecords) {
assertEquals("MapInputRecords", mapInputRecords, counters.findCounter(
"MyCounterGroup", "MAP_INPUT_RECORDS").getValue());
assertEquals("MapOutputRecords", mapOutputRecords, counters.findCounter(
"MyCounterGroup", "MAP_OUTPUT_RECORDS").getValue());
assertEquals("ReduceInputGroups", reduceInputGroups, counters.findCounter(
"MyCounterGroup", "REDUCE_INPUT_GROUPS").getValue());
assertEquals("ReduceOutputRecords", reduceOutputRecords, counters
.findCounter("MyCounterGroup", "REDUCE_OUTPUT_RECORDS").getValue());
}
private static void createFile(Path inFile, Configuration conf)
throws IOException {
final FileSystem fs = inFile.getFileSystem(conf);
if (fs.exists(inFile)) {
return;
}
FSDataOutputStream out = fs.create(inFile);
out.writeBytes("This is a test file");
out.close();
}
public static Job createJob() throws IOException {
final Job baseJob = Job.getInstance(mrCluster.getConfig());
baseJob.setOutputKeyClass(Text.class);
baseJob.setOutputValueClass(IntWritable.class);
baseJob.setMapperClass(MyMapper.class);
baseJob.setReducerClass(MyReducer.class);
baseJob.setNumReduceTasks(1);
return baseJob;
}
public static class MyMapper extends
org.apache.hadoop.mapreduce.Mapper<Object, Text, Text, IntWritable> {
private final static IntWritable one = new IntWritable(1);
private Text word = new Text();
public void map(Object key, Text value, Context context)
throws IOException, InterruptedException {
context.getCounter("MyCounterGroup", "MAP_INPUT_RECORDS").increment(1);
StringTokenizer iter = new StringTokenizer(value.toString());
while (iter.hasMoreTokens()) {
word.set(iter.nextToken());
context.write(word, one);
context.getCounter("MyCounterGroup", "MAP_OUTPUT_RECORDS").increment(1);
}
}
}
public static class MyReducer extends
org.apache.hadoop.mapreduce.Reducer<Text, IntWritable, Text, IntWritable> {
private IntWritable result = new IntWritable();
public void reduce(Text key, Iterable<IntWritable> values, Context context)
throws IOException, InterruptedException {
context.getCounter("MyCounterGroup", "REDUCE_INPUT_GROUPS").increment(1);
int sum = 0;
for (IntWritable val : values) {
sum += val.get();
}
result.set(sum);
context.write(key, result);
context.getCounter("MyCounterGroup", "REDUCE_OUTPUT_RECORDS")
.increment(1);
}
}
}
| {
"pile_set_name": "Github"
} |
// moment.js locale configuration
// locale : dutch (nl)
// author : Joris Röling : https://github.com/jjupiter
(function (factory) {
if (typeof define === 'function' && define.amd) {
define(['moment'], factory); // AMD
} else if (typeof exports === 'object') {
module.exports = factory(require('../moment')); // Node
} else {
factory(window.moment); // Browser global
}
}(function (moment) {
var monthsShortWithDots = "jan._feb._mrt._apr._mei_jun._jul._aug._sep._okt._nov._dec.".split("_"),
monthsShortWithoutDots = "jan_feb_mrt_apr_mei_jun_jul_aug_sep_okt_nov_dec".split("_");
return moment.defineLocale('nl', {
months : "januari_februari_maart_april_mei_juni_juli_augustus_september_oktober_november_december".split("_"),
monthsShort : function (m, format) {
if (/-MMM-/.test(format)) {
return monthsShortWithoutDots[m.month()];
} else {
return monthsShortWithDots[m.month()];
}
},
weekdays : "zondag_maandag_dinsdag_woensdag_donderdag_vrijdag_zaterdag".split("_"),
weekdaysShort : "zo._ma._di._wo._do._vr._za.".split("_"),
weekdaysMin : "Zo_Ma_Di_Wo_Do_Vr_Za".split("_"),
longDateFormat : {
LT : "HH:mm",
L : "DD-MM-YYYY",
LL : "D MMMM YYYY",
LLL : "D MMMM YYYY LT",
LLLL : "dddd D MMMM YYYY LT"
},
calendar : {
sameDay: '[vandaag om] LT',
nextDay: '[morgen om] LT',
nextWeek: 'dddd [om] LT',
lastDay: '[gisteren om] LT',
lastWeek: '[afgelopen] dddd [om] LT',
sameElse: 'L'
},
relativeTime : {
future : "over %s",
past : "%s geleden",
s : "een paar seconden",
m : "één minuut",
mm : "%d minuten",
h : "één uur",
hh : "%d uur",
d : "één dag",
dd : "%d dagen",
M : "één maand",
MM : "%d maanden",
y : "één jaar",
yy : "%d jaar"
},
ordinal : function (number) {
return number + ((number === 1 || number === 8 || number >= 20) ? 'ste' : 'de');
},
week : {
dow : 1, // Monday is the first day of the week.
doy : 4 // The week that contains Jan 4th is the first week of the year.
}
});
}));
| {
"pile_set_name": "Github"
} |
<HTML
><HEAD
><TITLE
>SDL_GetModState</TITLE
><META
NAME="GENERATOR"
CONTENT="Modular DocBook HTML Stylesheet Version 1.76b+
"><LINK
REL="HOME"
TITLE="SDL Library Documentation"
HREF="index.html"><LINK
REL="UP"
TITLE="Event Functions."
HREF="eventfunctions.html"><LINK
REL="PREVIOUS"
TITLE="SDL_GetKeyState"
HREF="sdlgetkeystate.html"><LINK
REL="NEXT"
TITLE="SDL_SetModState"
HREF="sdlsetmodstate.html"></HEAD
><BODY
CLASS="REFENTRY"
BGCOLOR="#FFF8DC"
TEXT="#000000"
LINK="#0000ee"
VLINK="#551a8b"
ALINK="#ff0000"
><DIV
CLASS="NAVHEADER"
><TABLE
SUMMARY="Header navigation table"
WIDTH="100%"
BORDER="0"
CELLPADDING="0"
CELLSPACING="0"
><TR
><TH
COLSPAN="3"
ALIGN="center"
>SDL Library Documentation</TH
></TR
><TR
><TD
WIDTH="10%"
ALIGN="left"
VALIGN="bottom"
><A
HREF="sdlgetkeystate.html"
ACCESSKEY="P"
>Prev</A
></TD
><TD
WIDTH="80%"
ALIGN="center"
VALIGN="bottom"
></TD
><TD
WIDTH="10%"
ALIGN="right"
VALIGN="bottom"
><A
HREF="sdlsetmodstate.html"
ACCESSKEY="N"
>Next</A
></TD
></TR
></TABLE
><HR
ALIGN="LEFT"
WIDTH="100%"></DIV
><H1
><A
NAME="SDLGETMODSTATE"
></A
>SDL_GetModState</H1
><DIV
CLASS="REFNAMEDIV"
><A
NAME="AEN5721"
></A
><H2
>Name</H2
>SDL_GetModState -- Get the state of modifier keys.</DIV
><DIV
CLASS="REFSYNOPSISDIV"
><A
NAME="AEN5724"
></A
><H2
>Synopsis</H2
><DIV
CLASS="FUNCSYNOPSIS"
><A
NAME="AEN5725"
></A
><P
></P
><PRE
CLASS="FUNCSYNOPSISINFO"
>#include "SDL.h"</PRE
><P
><CODE
><CODE
CLASS="FUNCDEF"
>SDLMod <B
CLASS="FSFUNC"
>SDL_GetModState</B
></CODE
>(void);</CODE
></P
><P
></P
></DIV
></DIV
><DIV
CLASS="REFSECT1"
><A
NAME="AEN5731"
></A
><H2
>Description</H2
><P
>Returns the current state of the modifier keys (CTRL, ALT, etc.).</P
></DIV
><DIV
CLASS="REFSECT1"
><A
NAME="AEN5734"
></A
><H2
>Return Value</H2
><P
>The return value can be an OR'd combination of the SDLMod enum.</P
><P
><A
NAME="AEN5738"
></A
><BLOCKQUOTE
CLASS="BLOCKQUOTE"
><P
><B
>SDLMod</B
></P
><PRE
CLASS="PROGRAMLISTING"
>typedef enum {
KMOD_NONE = 0x0000,
KMOD_LSHIFT= 0x0001,
KMOD_RSHIFT= 0x0002,
KMOD_LCTRL = 0x0040,
KMOD_RCTRL = 0x0080,
KMOD_LALT = 0x0100,
KMOD_RALT = 0x0200,
KMOD_LMETA = 0x0400,
KMOD_RMETA = 0x0800,
KMOD_NUM = 0x1000,
KMOD_CAPS = 0x2000,
KMOD_MODE = 0x4000,
} SDLMod;</PRE
></BLOCKQUOTE
>
SDL also defines the following symbols for convenience:
<A
NAME="AEN5741"
></A
><BLOCKQUOTE
CLASS="BLOCKQUOTE"
><PRE
CLASS="PROGRAMLISTING"
>#define KMOD_CTRL (KMOD_LCTRL|KMOD_RCTRL)
#define KMOD_SHIFT (KMOD_LSHIFT|KMOD_RSHIFT)
#define KMOD_ALT (KMOD_LALT|KMOD_RALT)
#define KMOD_META (KMOD_LMETA|KMOD_RMETA)</PRE
></BLOCKQUOTE
></P
></DIV
><DIV
CLASS="REFSECT1"
><A
NAME="AEN5743"
></A
><H2
>See Also</H2
><P
><A
HREF="sdlgetkeystate.html"
><TT
CLASS="FUNCTION"
>SDL_GetKeyState</TT
></A
></P
></DIV
><DIV
CLASS="NAVFOOTER"
><HR
ALIGN="LEFT"
WIDTH="100%"><TABLE
SUMMARY="Footer navigation table"
WIDTH="100%"
BORDER="0"
CELLPADDING="0"
CELLSPACING="0"
><TR
><TD
WIDTH="33%"
ALIGN="left"
VALIGN="top"
><A
HREF="sdlgetkeystate.html"
ACCESSKEY="P"
>Prev</A
></TD
><TD
WIDTH="34%"
ALIGN="center"
VALIGN="top"
><A
HREF="index.html"
ACCESSKEY="H"
>Home</A
></TD
><TD
WIDTH="33%"
ALIGN="right"
VALIGN="top"
><A
HREF="sdlsetmodstate.html"
ACCESSKEY="N"
>Next</A
></TD
></TR
><TR
><TD
WIDTH="33%"
ALIGN="left"
VALIGN="top"
>SDL_GetKeyState</TD
><TD
WIDTH="34%"
ALIGN="center"
VALIGN="top"
><A
HREF="eventfunctions.html"
ACCESSKEY="U"
>Up</A
></TD
><TD
WIDTH="33%"
ALIGN="right"
VALIGN="top"
>SDL_SetModState</TD
></TR
></TABLE
></DIV
></BODY
></HTML
> | {
"pile_set_name": "Github"
} |
#include <iostream>
#include "dynet/dynet.h"
#include "dynet/training.h"
#include "dynet/expr.h"
#include "dynet/io.h"
#include "dynet/model.h"
#include "dynet/devices.h"
using namespace std;
using namespace dynet;
int main(int argc, char** argv) {
dynet::initialize(argc, argv);
const unsigned ITERATIONS = 30;
// ParameterCollection (all the model parameters).
ParameterCollection m;
SimpleSGDTrainer trainer(m);
// Get two devices, the CPU device and GPU device
Device* cpu_device = get_device_manager()->get_global_device("CPU");
Device* gpu_device = get_device_manager()->get_global_device("GPU:0");
const unsigned HIDDEN_SIZE = 8;
Parameter p_W = m.add_parameters({HIDDEN_SIZE, 2}, gpu_device);
Parameter p_b = m.add_parameters({HIDDEN_SIZE}, gpu_device);
Parameter p_V = m.add_parameters({1, HIDDEN_SIZE}, cpu_device);
Parameter p_a = m.add_parameters({1}, cpu_device);
if (argc == 2) {
// Load the model and parameters from file if given.
TextFileLoader loader(argv[1]);
loader.populate(m);
}
// Static declaration of the computation graph.
ComputationGraph cg;
Expression W = parameter(cg, p_W);
Expression b = parameter(cg, p_b);
Expression V = parameter(cg, p_V);
Expression a = parameter(cg, p_a);
// Set x_values to change the inputs to the network.
vector<dynet::real> x_values(2);
Expression x = input(cg, {2}, &x_values, gpu_device);
dynet::real y_value; // Set y_value to change the target output.
Expression y = input(cg, &y_value, cpu_device);
Expression h = tanh(W * x + b);
Expression h_cpu = to_device(h, cpu_device);
Expression y_pred = V*h_cpu + a;
Expression loss_expr = squared_distance(y_pred, y);
// Show the computation graph, just for fun.
cg.print_graphviz();
// Train the parameters.
for (unsigned iter = 0; iter < ITERATIONS; ++iter) {
double loss = 0;
for (unsigned mi = 0; mi < 4; ++mi) {
bool x1 = mi % 2;
bool x2 = (mi / 2) % 2;
x_values[0] = x1 ? 1 : -1;
x_values[1] = x2 ? 1 : -1;
y_value = (x1 != x2) ? 1 : -1;
loss += as_scalar(cg.forward(loss_expr));
cg.backward(loss_expr);
trainer.update();
}
loss /= 4;
cerr << "E = " << loss << endl;
}
// Output the model and parameter objects to a file.
TextFileSaver saver("xor.model");
saver.save(m);
}
| {
"pile_set_name": "Github"
} |
import { Component } from '@angular/core';
@Component({
selector: 'demo-tabs-vertical-pills',
templateUrl: './vertical-pills.html'
})
export class DemoTabsVerticalPillsComponent {}
| {
"pile_set_name": "Github"
} |
require 'test_helper'
module Workarea
class InventoryTest < TestCase
def test_finds_total_sales_for_one_sku
create_inventory(id: 'SKU1', purchased: 7)
assert_equal(7, Inventory.total_sales('SKU1'))
end
def test_finds_total_sales_for_a_set_of_skus
create_inventory(id: 'SKU1', purchased: 7)
create_inventory(id: 'SKU2', purchased: 5)
assert_equal(12, Inventory.total_sales('SKU1', 'SKU2', 'SKU3'))
end
def test_any_available
assert(Inventory.any_available?('SKU1'))
assert(Inventory.any_available?('SKU1','SKU2','SKU3'))
create_inventory(id: 'SKU1', policy: 'standard', available: 0)
create_inventory(id: 'SKU2', policy: 'standard', available: 0)
refute(Inventory.any_available?('SKU1'))
refute(Inventory.any_available?('SKU1','SKU2'))
assert(Inventory.any_available?('SKU1','SKU2','SKU3'))
end
end
end
| {
"pile_set_name": "Github"
} |
#ifndef TESTENGINE_H
#define TESTENGINE_H
#include <QtTest>
class TestEngine : public QObject {
Q_OBJECT
public:
TestEngine();
private:
QString tmpFileName;
private slots:
void initTestCase();
void testGetFinishTime();
void testCurrentSubtitleIndex();
void testGetTimeWithSubtitleOffset();
void cleanupTestCase();
};
#endif // TESTENGINE_H
| {
"pile_set_name": "Github"
} |
<?php namespace Myth\Auth;
/**
* Sprint
*
* A set of power tools to enhance the CodeIgniter framework and provide consistent workflow.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @package Sprint
* @author Lonnie Ezell
* @copyright Copyright 2014-2015, New Myth Media, LLC (http://newmythmedia.com)
* @license http://opensource.org/licenses/MIT (MIT)
* @link http://sprintphp.com
* @since Version 1.0
*/
interface AuthorizeInterface {
/**
* Returns the latest error string.
*
* @return mixed
*/
public function error();
//--------------------------------------------------------------------
//--------------------------------------------------------------------
// Actions
//--------------------------------------------------------------------
/**
* Checks to see if a user is in a group.
*
* Groups can be either a string, with the name of the group, an INT
* with the ID of the group, or an array of strings/ids that the
* user must belong to ONE of. (It's an OR check not an AND check)
*
* @param $groups
*
* @return bool
*/
public function inGroup($groups, $user_id);
//--------------------------------------------------------------------
/**
* Checks a user's groups to see if they have the specified permission.
*
* @param int|string $permission
* @param int|string $user_id
*
* @return mixed
*/
public function hasPermission($permission, $user_id);
//--------------------------------------------------------------------
/**
* Makes a member a part of a group.
*
* @param $user_id
* @param $group // Either ID or name
*
* @return bool
*/
public function addUserToGroup($user_id, $group);
//--------------------------------------------------------------------
/**
* Removes a single user from a group.
*
* @param $user_id
* @param $group
*
* @return mixed
*/
public function removeUserFromGroup($user_id, $group);
//--------------------------------------------------------------------
/**
* Adds a single permission to a single group.
*
* @param int|string $permission
* @param int|string $group
*
* @return mixed
*/
public function addPermissionToGroup($permission, $group);
//--------------------------------------------------------------------
/**
* Removes a single permission from a group.
*
* @param int|string $permission
* @param int|string $group
*
* @return mixed
*/
public function removePermissionFromGroup($permission, $group);
//--------------------------------------------------------------------
//--------------------------------------------------------------------
// Groups
//--------------------------------------------------------------------
/**
* Grabs the details about a single group.
*
* @param $group
*
* @return object|null
*/
public function group($group);
//--------------------------------------------------------------------
/**
* Grabs an array of all groups.
*
* @return array of objects
*/
public function groups();
//--------------------------------------------------------------------
/**
* @param $name
* @param string $description
*
* @return mixed
*/
public function createGroup($name, $description='');
//--------------------------------------------------------------------
/**
* Deletes a single group.
*
* @param int $group_id
*
* @return bool
*/
public function deleteGroup($group_id);
//--------------------------------------------------------------------
/**
* Updates a single group's information.
*
* @param $id
* @param $name
* @param string $description
*
* @return mixed
*/
public function updateGroup($id, $name, $description='');
//--------------------------------------------------------------------
//--------------------------------------------------------------------
// Permissions
//--------------------------------------------------------------------
/**
* Returns the details about a single permission.
*
* @param int|string $permission
*
* @return object|null
*/
public function permission($permission);
//--------------------------------------------------------------------
/**
* Returns an array of all permissions in the system.
*
* @return mixed
*/
public function permissions();
//--------------------------------------------------------------------
/**
* Creates a single permission.
*
* @param $name
* @param string $description
*
* @return mixed
*/
public function createPermission($name, $description='');
//--------------------------------------------------------------------
/**
* Deletes a single permission and removes that permission from all groups.
*
* @param $permission
*
* @return mixed
*/
public function deletePermission($permission);
//--------------------------------------------------------------------
/**
* Updates the details for a single permission.
*
* @param int $id
* @param string $name
* @param string $description
*
* @return bool
*/
public function updatePermission($id, $name, $description='');
//--------------------------------------------------------------------
}
| {
"pile_set_name": "Github"
} |
{hint: save all files to location: C:\android\workspace\AppZBarcodeScannerViewDemo1\jni\ }
library controls; //[by LAMW: Lazarus Android Module Wizard: 3/28/2019 23:26:19]
{$mode delphi}
uses
Classes, SysUtils, And_jni, And_jni_Bridge, AndroidWidget, Laz_And_Controls,
Laz_And_Controls_Events, unit1;
{%region /fold 'LAMW generated code'}
{ Class: org_lamw_appzbarcodescannerviewdemo1_Controls
Method: pAppOnCreate
Signature: (Landroid/content/Context;Landroid/widget/RelativeLayout;Landroid/content/Intent;)V }
procedure pAppOnCreate(PEnv: PJNIEnv; this: JObject; context: JObject;
layout: JObject; intent: JObject); cdecl;
begin
Java_Event_pAppOnCreate(PEnv, this, context, layout, intent);
AndroidModule1.Init(gApp);
end;
{ Class: org_lamw_appzbarcodescannerviewdemo1_Controls
Method: pAppOnScreenStyle
Signature: ()I }
function pAppOnScreenStyle(PEnv: PJNIEnv; this: JObject): JInt; cdecl;
begin
Result:=Java_Event_pAppOnScreenStyle(PEnv, this);
end;
{ Class: org_lamw_appzbarcodescannerviewdemo1_Controls
Method: pAppOnNewIntent
Signature: (Landroid/content/Intent;)V }
procedure pAppOnNewIntent(PEnv: PJNIEnv; this: JObject; intent: JObject); cdecl;
begin
Java_Event_pAppOnNewIntent(PEnv, this, intent);
end;
{ Class: org_lamw_appzbarcodescannerviewdemo1_Controls
Method: pAppOnDestroy
Signature: ()V }
procedure pAppOnDestroy(PEnv: PJNIEnv; this: JObject); cdecl;
begin
Java_Event_pAppOnDestroy(PEnv, this);
end;
{ Class: org_lamw_appzbarcodescannerviewdemo1_Controls
Method: pAppOnPause
Signature: ()V }
procedure pAppOnPause(PEnv: PJNIEnv; this: JObject); cdecl;
begin
Java_Event_pAppOnPause(PEnv, this);
end;
{ Class: org_lamw_appzbarcodescannerviewdemo1_Controls
Method: pAppOnRestart
Signature: ()V }
procedure pAppOnRestart(PEnv: PJNIEnv; this: JObject); cdecl;
begin
Java_Event_pAppOnRestart(PEnv, this);
end;
{ Class: org_lamw_appzbarcodescannerviewdemo1_Controls
Method: pAppOnResume
Signature: ()V }
procedure pAppOnResume(PEnv: PJNIEnv; this: JObject); cdecl;
begin
Java_Event_pAppOnResume(PEnv, this);
end;
{ Class: org_lamw_appzbarcodescannerviewdemo1_Controls
Method: pAppOnStart
Signature: ()V }
procedure pAppOnStart(PEnv: PJNIEnv; this: JObject); cdecl;
begin
Java_Event_pAppOnStart(PEnv, this);
end;
{ Class: org_lamw_appzbarcodescannerviewdemo1_Controls
Method: pAppOnStop
Signature: ()V }
procedure pAppOnStop(PEnv: PJNIEnv; this: JObject); cdecl;
begin
Java_Event_pAppOnStop(PEnv, this);
end;
{ Class: org_lamw_appzbarcodescannerviewdemo1_Controls
Method: pAppOnBackPressed
Signature: ()V }
procedure pAppOnBackPressed(PEnv: PJNIEnv; this: JObject); cdecl;
begin
Java_Event_pAppOnBackPressed(PEnv, this);
end;
{ Class: org_lamw_appzbarcodescannerviewdemo1_Controls
Method: pAppOnRotate
Signature: (I)I }
function pAppOnRotate(PEnv: PJNIEnv; this: JObject; rotate: JInt): JInt; cdecl;
begin
Result:=Java_Event_pAppOnRotate(PEnv, this, rotate);
end;
{ Class: org_lamw_appzbarcodescannerviewdemo1_Controls
Method: pAppOnConfigurationChanged
Signature: ()V }
procedure pAppOnConfigurationChanged(PEnv: PJNIEnv; this: JObject); cdecl;
begin
Java_Event_pAppOnConfigurationChanged(PEnv, this);
end;
{ Class: org_lamw_appzbarcodescannerviewdemo1_Controls
Method: pAppOnActivityResult
Signature: (IILandroid/content/Intent;)V }
procedure pAppOnActivityResult(PEnv: PJNIEnv; this: JObject; requestCode: JInt;
resultCode: JInt; data: JObject); cdecl;
begin
Java_Event_pAppOnActivityResult(PEnv, this, requestCode, resultCode, data);
end;
{ Class: org_lamw_appzbarcodescannerviewdemo1_Controls
Method: pAppOnCreateOptionsMenu
Signature: (Landroid/view/Menu;)V }
procedure pAppOnCreateOptionsMenu(PEnv: PJNIEnv; this: JObject; menu: JObject);
cdecl;
begin
Java_Event_pAppOnCreateOptionsMenu(PEnv, this, menu);
end;
{ Class: org_lamw_appzbarcodescannerviewdemo1_Controls
Method: pAppOnClickOptionMenuItem
Signature: (Landroid/view/MenuItem;ILjava/lang/String;Z)V }
procedure pAppOnClickOptionMenuItem(PEnv: PJNIEnv; this: JObject;
menuItem: JObject; itemID: JInt; itemCaption: JString; checked: JBoolean);
cdecl;
begin
Java_Event_pAppOnClickOptionMenuItem(PEnv, this, menuItem, itemID,
itemCaption, checked);
end;
{ Class: org_lamw_appzbarcodescannerviewdemo1_Controls
Method: pAppOnPrepareOptionsMenu
Signature: (Landroid/view/Menu;I)Z }
function pAppOnPrepareOptionsMenu(PEnv: PJNIEnv; this: JObject; menu: JObject;
menuSize: JInt): JBoolean; cdecl;
begin
Result:=Java_Event_pAppOnPrepareOptionsMenu(PEnv, this, menu, menuSize);
end;
{ Class: org_lamw_appzbarcodescannerviewdemo1_Controls
Method: pAppOnPrepareOptionsMenuItem
Signature: (Landroid/view/Menu;Landroid/view/MenuItem;I)Z }
function pAppOnPrepareOptionsMenuItem(PEnv: PJNIEnv; this: JObject;
menu: JObject; menuItem: JObject; itemIndex: JInt): JBoolean; cdecl;
begin
Result:=Java_Event_pAppOnPrepareOptionsMenuItem(PEnv, this, menu, menuItem,
itemIndex);
end;
{ Class: org_lamw_appzbarcodescannerviewdemo1_Controls
Method: pAppOnCreateContextMenu
Signature: (Landroid/view/ContextMenu;)V }
procedure pAppOnCreateContextMenu(PEnv: PJNIEnv; this: JObject; menu: JObject);
cdecl;
begin
Java_Event_pAppOnCreateContextMenu(PEnv, this, menu);
end;
{ Class: org_lamw_appzbarcodescannerviewdemo1_Controls
Method: pAppOnClickContextMenuItem
Signature: (Landroid/view/MenuItem;ILjava/lang/String;Z)V }
procedure pAppOnClickContextMenuItem(PEnv: PJNIEnv; this: JObject;
menuItem: JObject; itemID: JInt; itemCaption: JString; checked: JBoolean);
cdecl;
begin
Java_Event_pAppOnClickContextMenuItem(PEnv, this, menuItem, itemID,
itemCaption, checked);
end;
{ Class: org_lamw_appzbarcodescannerviewdemo1_Controls
Method: pOnDraw
Signature: (J)V }
procedure pOnDraw(PEnv: PJNIEnv; this: JObject; pasobj: JLong); cdecl;
begin
Java_Event_pOnDraw(PEnv, this, TObject(pasobj));
end;
{ Class: org_lamw_appzbarcodescannerviewdemo1_Controls
Method: pOnTouch
Signature: (JIIFFFF)V }
procedure pOnTouch(PEnv: PJNIEnv; this: JObject; pasobj: JLong; act: JInt;
cnt: JInt; x1: JFloat; y1: JFloat; x2: JFloat; y2: JFloat); cdecl;
begin
Java_Event_pOnTouch(PEnv, this, TObject(pasobj), act, cnt, x1, y1, x2, y2);
end;
{ Class: org_lamw_appzbarcodescannerviewdemo1_Controls
Method: pOnClickGeneric
Signature: (JI)V }
procedure pOnClickGeneric(PEnv: PJNIEnv; this: JObject; pasobj: JLong;
value: JInt); cdecl;
begin
Java_Event_pOnClickGeneric(PEnv, this, TObject(pasobj), value);
end;
{ Class: org_lamw_appzbarcodescannerviewdemo1_Controls
Method: pAppOnSpecialKeyDown
Signature: (CILjava/lang/String;)Z }
function pAppOnSpecialKeyDown(PEnv: PJNIEnv; this: JObject; keyChar: JChar;
keyCode: JInt; keyCodeString: JString): JBoolean; cdecl;
begin
Result:=Java_Event_pAppOnSpecialKeyDown(PEnv, this, keyChar, keyCode,
keyCodeString);
end;
{ Class: org_lamw_appzbarcodescannerviewdemo1_Controls
Method: pOnDown
Signature: (JI)V }
procedure pOnDown(PEnv: PJNIEnv; this: JObject; pasobj: JLong; value: JInt);
cdecl;
begin
Java_Event_pOnDown(PEnv, this, TObject(pasobj), value);
end;
{ Class: org_lamw_appzbarcodescannerviewdemo1_Controls
Method: pOnClick
Signature: (JI)V }
procedure pOnClick(PEnv: PJNIEnv; this: JObject; pasobj: JLong; value: JInt);
cdecl;
begin
Java_Event_pOnClick(PEnv, this, TObject(pasobj), value);
end;
{ Class: org_lamw_appzbarcodescannerviewdemo1_Controls
Method: pOnLongClick
Signature: (JI)V }
procedure pOnLongClick(PEnv: PJNIEnv; this: JObject; pasobj: JLong; value: JInt
); cdecl;
begin
Java_Event_pOnLongClick(PEnv, this, TObject(pasobj), value);
end;
{ Class: org_lamw_appzbarcodescannerviewdemo1_Controls
Method: pOnDoubleClick
Signature: (JI)V }
procedure pOnDoubleClick(PEnv: PJNIEnv; this: JObject; pasobj: JLong;
value: JInt); cdecl;
begin
Java_Event_pOnDoubleClick(PEnv, this, TObject(pasobj), value);
end;
{ Class: org_lamw_appzbarcodescannerviewdemo1_Controls
Method: pOnChange
Signature: (JLjava/lang/String;I)V }
procedure pOnChange(PEnv: PJNIEnv; this: JObject; pasobj: JLong; txt: JString;
count: JInt); cdecl;
begin
Java_Event_pOnChange(PEnv, this, TObject(pasobj), txt, count);
end;
{ Class: org_lamw_appzbarcodescannerviewdemo1_Controls
Method: pOnChanged
Signature: (JLjava/lang/String;I)V }
procedure pOnChanged(PEnv: PJNIEnv; this: JObject; pasobj: JLong; txt: JString;
count: JInt); cdecl;
begin
Java_Event_pOnChanged(PEnv, this, TObject(pasobj), txt, count);
end;
{ Class: org_lamw_appzbarcodescannerviewdemo1_Controls
Method: pOnEnter
Signature: (J)V }
procedure pOnEnter(PEnv: PJNIEnv; this: JObject; pasobj: JLong); cdecl;
begin
Java_Event_pOnEnter(PEnv, this, TObject(pasobj));
end;
{ Class: org_lamw_appzbarcodescannerviewdemo1_Controls
Method: pOnClose
Signature: (J)V }
procedure pOnClose(PEnv: PJNIEnv; this: JObject; pasobj: JLong); cdecl;
begin
Java_Event_pOnClose(PEnv, this, TObject(pasobj));
end;
{ Class: org_lamw_appzbarcodescannerviewdemo1_Controls
Method: pAppOnViewClick
Signature: (Landroid/view/View;I)V }
procedure pAppOnViewClick(PEnv: PJNIEnv; this: JObject; view: JObject; id: JInt
); cdecl;
begin
Java_Event_pAppOnViewClick(PEnv, this, view, id);
end;
{ Class: org_lamw_appzbarcodescannerviewdemo1_Controls
Method: pAppOnListItemClick
Signature: (Landroid/widget/AdapterView;Landroid/view/View;II)V }
procedure pAppOnListItemClick(PEnv: PJNIEnv; this: JObject; adapter: JObject;
view: JObject; position: JInt; id: JInt); cdecl;
begin
Java_Event_pAppOnListItemClick(PEnv, this, adapter, view, position, id);
end;
{ Class: org_lamw_appzbarcodescannerviewdemo1_Controls
Method: pOnFlingGestureDetected
Signature: (JI)V }
procedure pOnFlingGestureDetected(PEnv: PJNIEnv; this: JObject; pasobj: JLong;
direction: JInt); cdecl;
begin
Java_Event_pOnFlingGestureDetected(PEnv, this, TObject(pasobj), direction);
end;
{ Class: org_lamw_appzbarcodescannerviewdemo1_Controls
Method: pOnPinchZoomGestureDetected
Signature: (JFI)V }
procedure pOnPinchZoomGestureDetected(PEnv: PJNIEnv; this: JObject;
pasobj: JLong; scaleFactor: JFloat; state: JInt); cdecl;
begin
Java_Event_pOnPinchZoomGestureDetected(PEnv, this, TObject(pasobj),
scaleFactor, state);
end;
{ Class: org_lamw_appzbarcodescannerviewdemo1_Controls
Method: pOnLostFocus
Signature: (JLjava/lang/String;)V }
procedure pOnLostFocus(PEnv: PJNIEnv; this: JObject; pasobj: JLong;
text: JString); cdecl;
begin
Java_Event_pOnLostFocus(PEnv, this, TObject(pasobj), text);
end;
{ Class: org_lamw_appzbarcodescannerviewdemo1_Controls
Method: pOnBeforeDispatchDraw
Signature: (JLandroid/graphics/Canvas;I)V }
procedure pOnBeforeDispatchDraw(PEnv: PJNIEnv; this: JObject; pasobj: JLong;
canvas: JObject; tag: JInt); cdecl;
begin
Java_Event_pOnBeforeDispatchDraw(PEnv, this, TObject(pasobj), canvas, tag);
end;
{ Class: org_lamw_appzbarcodescannerviewdemo1_Controls
Method: pOnAfterDispatchDraw
Signature: (JLandroid/graphics/Canvas;I)V }
procedure pOnAfterDispatchDraw(PEnv: PJNIEnv; this: JObject; pasobj: JLong;
canvas: JObject; tag: JInt); cdecl;
begin
Java_Event_pOnAfterDispatchDraw(PEnv, this, TObject(pasobj), canvas, tag);
end;
{ Class: org_lamw_appzbarcodescannerviewdemo1_Controls
Method: pOnLayouting
Signature: (JZ)V }
procedure pOnLayouting(PEnv: PJNIEnv; this: JObject; pasobj: JLong;
changed: JBoolean); cdecl;
begin
Java_Event_pOnLayouting(PEnv, this, TObject(pasobj), changed);
end;
{ Class: org_lamw_appzbarcodescannerviewdemo1_Controls
Method: pAppOnRequestPermissionResult
Signature: (ILjava/lang/String;I)V }
procedure pAppOnRequestPermissionResult(PEnv: PJNIEnv; this: JObject;
requestCode: JInt; permission: JString; grantResult: JInt); cdecl;
begin
Java_Event_pAppOnRequestPermissionResult(PEnv, this, requestCode, permission,
grantResult);
end;
{ Class: org_lamw_appzbarcodescannerviewdemo1_Controls
Method: pOnZBarcodeScannerViewResult
Signature: (JLjava/lang/String;I)V }
procedure pOnZBarcodeScannerViewResult(PEnv: PJNIEnv; this: JObject;
pasobj: JLong; codedata: JString; codetype: JInt); cdecl;
begin
Java_Event_pOnZBarcodeScannerViewResult(PEnv, this, TObject(pasobj),
codedata, codetype);
end;
const NativeMethods: array[0..40] of JNINativeMethod = (
(name: 'pAppOnCreate';
signature: '(Landroid/content/Context;Landroid/widget/RelativeLayout;'
+'Landroid/content/Intent;)V';
fnPtr: @pAppOnCreate; ),
(name: 'pAppOnScreenStyle';
signature: '()I';
fnPtr: @pAppOnScreenStyle; ),
(name: 'pAppOnNewIntent';
signature: '(Landroid/content/Intent;)V';
fnPtr: @pAppOnNewIntent; ),
(name: 'pAppOnDestroy';
signature: '()V';
fnPtr: @pAppOnDestroy; ),
(name: 'pAppOnPause';
signature: '()V';
fnPtr: @pAppOnPause; ),
(name: 'pAppOnRestart';
signature: '()V';
fnPtr: @pAppOnRestart; ),
(name: 'pAppOnResume';
signature: '()V';
fnPtr: @pAppOnResume; ),
(name: 'pAppOnStart';
signature: '()V';
fnPtr: @pAppOnStart; ),
(name: 'pAppOnStop';
signature: '()V';
fnPtr: @pAppOnStop; ),
(name: 'pAppOnBackPressed';
signature: '()V';
fnPtr: @pAppOnBackPressed; ),
(name: 'pAppOnRotate';
signature: '(I)I';
fnPtr: @pAppOnRotate; ),
(name: 'pAppOnConfigurationChanged';
signature: '()V';
fnPtr: @pAppOnConfigurationChanged; ),
(name: 'pAppOnActivityResult';
signature: '(IILandroid/content/Intent;)V';
fnPtr: @pAppOnActivityResult; ),
(name: 'pAppOnCreateOptionsMenu';
signature: '(Landroid/view/Menu;)V';
fnPtr: @pAppOnCreateOptionsMenu; ),
(name: 'pAppOnClickOptionMenuItem';
signature: '(Landroid/view/MenuItem;ILjava/lang/String;Z)V';
fnPtr: @pAppOnClickOptionMenuItem; ),
(name: 'pAppOnPrepareOptionsMenu';
signature: '(Landroid/view/Menu;I)Z';
fnPtr: @pAppOnPrepareOptionsMenu; ),
(name: 'pAppOnPrepareOptionsMenuItem';
signature: '(Landroid/view/Menu;Landroid/view/MenuItem;I)Z';
fnPtr: @pAppOnPrepareOptionsMenuItem; ),
(name: 'pAppOnCreateContextMenu';
signature: '(Landroid/view/ContextMenu;)V';
fnPtr: @pAppOnCreateContextMenu; ),
(name: 'pAppOnClickContextMenuItem';
signature: '(Landroid/view/MenuItem;ILjava/lang/String;Z)V';
fnPtr: @pAppOnClickContextMenuItem; ),
(name: 'pOnDraw';
signature: '(J)V';
fnPtr: @pOnDraw; ),
(name: 'pOnTouch';
signature: '(JIIFFFF)V';
fnPtr: @pOnTouch; ),
(name: 'pOnClickGeneric';
signature: '(JI)V';
fnPtr: @pOnClickGeneric; ),
(name: 'pAppOnSpecialKeyDown';
signature: '(CILjava/lang/String;)Z';
fnPtr: @pAppOnSpecialKeyDown; ),
(name: 'pOnDown';
signature: '(JI)V';
fnPtr: @pOnDown; ),
(name: 'pOnClick';
signature: '(JI)V';
fnPtr: @pOnClick; ),
(name: 'pOnLongClick';
signature: '(JI)V';
fnPtr: @pOnLongClick; ),
(name: 'pOnDoubleClick';
signature: '(JI)V';
fnPtr: @pOnDoubleClick; ),
(name: 'pOnChange';
signature: '(JLjava/lang/String;I)V';
fnPtr: @pOnChange; ),
(name: 'pOnChanged';
signature: '(JLjava/lang/String;I)V';
fnPtr: @pOnChanged; ),
(name: 'pOnEnter';
signature: '(J)V';
fnPtr: @pOnEnter; ),
(name: 'pOnClose';
signature: '(J)V';
fnPtr: @pOnClose; ),
(name: 'pAppOnViewClick';
signature: '(Landroid/view/View;I)V';
fnPtr: @pAppOnViewClick; ),
(name: 'pAppOnListItemClick';
signature: '(Landroid/widget/AdapterView;Landroid/view/View;II)V';
fnPtr: @pAppOnListItemClick; ),
(name: 'pOnFlingGestureDetected';
signature: '(JI)V';
fnPtr: @pOnFlingGestureDetected; ),
(name: 'pOnPinchZoomGestureDetected';
signature: '(JFI)V';
fnPtr: @pOnPinchZoomGestureDetected; ),
(name: 'pOnLostFocus';
signature: '(JLjava/lang/String;)V';
fnPtr: @pOnLostFocus; ),
(name: 'pOnBeforeDispatchDraw';
signature: '(JLandroid/graphics/Canvas;I)V';
fnPtr: @pOnBeforeDispatchDraw; ),
(name: 'pOnAfterDispatchDraw';
signature: '(JLandroid/graphics/Canvas;I)V';
fnPtr: @pOnAfterDispatchDraw; ),
(name: 'pOnLayouting';
signature: '(JZ)V';
fnPtr: @pOnLayouting; ),
(name: 'pAppOnRequestPermissionResult';
signature: '(ILjava/lang/String;I)V';
fnPtr: @pAppOnRequestPermissionResult; ),
(name: 'pOnZBarcodeScannerViewResult';
signature: '(JLjava/lang/String;I)V';
fnPtr: @pOnZBarcodeScannerViewResult; )
);
function RegisterNativeMethodsArray(PEnv: PJNIEnv; className: PChar;
methods: PJNINativeMethod; countMethods: integer): integer;
var
curClass: jClass;
begin
Result:= JNI_FALSE;
curClass:= (PEnv^).FindClass(PEnv, className);
if curClass <> nil then
begin
if (PEnv^).RegisterNatives(PEnv, curClass, methods, countMethods) > 0
then Result:= JNI_TRUE;
end;
end;
function RegisterNativeMethods(PEnv: PJNIEnv; className: PChar): integer;
begin
Result:= RegisterNativeMethodsArray(PEnv, className, @NativeMethods[0], Length
(NativeMethods));
end;
function JNI_OnLoad(VM: PJavaVM; {%H-}reserved: pointer): JInt; cdecl;
var
PEnv: PPointer;
curEnv: PJNIEnv;
begin
PEnv:= nil;
Result:= JNI_VERSION_1_6;
(VM^).GetEnv(VM, @PEnv, Result);
if PEnv <> nil then
begin
curEnv:= PJNIEnv(PEnv);
RegisterNativeMethods(curEnv, 'org/lamw/appzbarcodescannerviewdemo1/'
+'Controls');
end;
gVM:= VM; {AndroidWidget.pas}
end;
procedure JNI_OnUnload(VM: PJavaVM; {%H-}reserved: pointer); cdecl;
var
PEnv: PPointer;
curEnv: PJNIEnv;
begin
PEnv:= nil;
(VM^).GetEnv(VM, @PEnv, JNI_VERSION_1_6);
if PEnv <> nil then
begin
curEnv:= PJNIEnv(PEnv);
(curEnv^).DeleteGlobalRef(curEnv, gjClass);
gjClass:= nil; {AndroidWidget.pas}
gVM:= nil; {AndroidWidget.pas}
end;
gApp.Terminate;
FreeAndNil(gApp);
end;
exports
JNI_OnLoad name 'JNI_OnLoad',
JNI_OnUnload name 'JNI_OnUnload',
pAppOnCreate name 'Java_org_lamw_appzbarcodescannerviewdemo1_Controls_'
+'pAppOnCreate',
pAppOnScreenStyle name 'Java_org_lamw_appzbarcodescannerviewdemo1_Controls_'
+'pAppOnScreenStyle',
pAppOnNewIntent name 'Java_org_lamw_appzbarcodescannerviewdemo1_Controls_'
+'pAppOnNewIntent',
pAppOnDestroy name 'Java_org_lamw_appzbarcodescannerviewdemo1_Controls_'
+'pAppOnDestroy',
pAppOnPause name 'Java_org_lamw_appzbarcodescannerviewdemo1_Controls_'
+'pAppOnPause',
pAppOnRestart name 'Java_org_lamw_appzbarcodescannerviewdemo1_Controls_'
+'pAppOnRestart',
pAppOnResume name 'Java_org_lamw_appzbarcodescannerviewdemo1_Controls_'
+'pAppOnResume',
pAppOnStart name 'Java_org_lamw_appzbarcodescannerviewdemo1_Controls_'
+'pAppOnStart',
pAppOnStop name 'Java_org_lamw_appzbarcodescannerviewdemo1_Controls_'
+'pAppOnStop',
pAppOnBackPressed name 'Java_org_lamw_appzbarcodescannerviewdemo1_Controls_'
+'pAppOnBackPressed',
pAppOnRotate name 'Java_org_lamw_appzbarcodescannerviewdemo1_Controls_'
+'pAppOnRotate',
pAppOnConfigurationChanged name 'Java_org_lamw_appzbarcodescannerviewdemo1_'
+'Controls_pAppOnConfigurationChanged',
pAppOnActivityResult name 'Java_org_lamw_appzbarcodescannerviewdemo1_'
+'Controls_pAppOnActivityResult',
pAppOnCreateOptionsMenu name 'Java_org_lamw_appzbarcodescannerviewdemo1_'
+'Controls_pAppOnCreateOptionsMenu',
pAppOnClickOptionMenuItem name 'Java_org_lamw_appzbarcodescannerviewdemo1_'
+'Controls_pAppOnClickOptionMenuItem',
pAppOnPrepareOptionsMenu name 'Java_org_lamw_appzbarcodescannerviewdemo1_'
+'Controls_pAppOnPrepareOptionsMenu',
pAppOnPrepareOptionsMenuItem name 'Java_org_lamw_appzbarcodescannerviewdemo1'
+'_Controls_pAppOnPrepareOptionsMenuItem',
pAppOnCreateContextMenu name 'Java_org_lamw_appzbarcodescannerviewdemo1_'
+'Controls_pAppOnCreateContextMenu',
pAppOnClickContextMenuItem name 'Java_org_lamw_appzbarcodescannerviewdemo1_'
+'Controls_pAppOnClickContextMenuItem',
pOnDraw name 'Java_org_lamw_appzbarcodescannerviewdemo1_Controls_pOnDraw',
pOnTouch name 'Java_org_lamw_appzbarcodescannerviewdemo1_Controls_pOnTouch',
pOnClickGeneric name 'Java_org_lamw_appzbarcodescannerviewdemo1_Controls_'
+'pOnClickGeneric',
pAppOnSpecialKeyDown name 'Java_org_lamw_appzbarcodescannerviewdemo1_'
+'Controls_pAppOnSpecialKeyDown',
pOnDown name 'Java_org_lamw_appzbarcodescannerviewdemo1_Controls_pOnDown',
pOnClick name 'Java_org_lamw_appzbarcodescannerviewdemo1_Controls_pOnClick',
pOnLongClick name 'Java_org_lamw_appzbarcodescannerviewdemo1_Controls_'
+'pOnLongClick',
pOnDoubleClick name 'Java_org_lamw_appzbarcodescannerviewdemo1_Controls_'
+'pOnDoubleClick',
pOnChange name 'Java_org_lamw_appzbarcodescannerviewdemo1_Controls_pOnChange',
pOnChanged name 'Java_org_lamw_appzbarcodescannerviewdemo1_Controls_'
+'pOnChanged',
pOnEnter name 'Java_org_lamw_appzbarcodescannerviewdemo1_Controls_pOnEnter',
pOnClose name 'Java_org_lamw_appzbarcodescannerviewdemo1_Controls_pOnClose',
pAppOnViewClick name 'Java_org_lamw_appzbarcodescannerviewdemo1_Controls_'
+'pAppOnViewClick',
pAppOnListItemClick name 'Java_org_lamw_appzbarcodescannerviewdemo1_Controls'
+'_pAppOnListItemClick',
pOnFlingGestureDetected name 'Java_org_lamw_appzbarcodescannerviewdemo1_'
+'Controls_pOnFlingGestureDetected',
pOnPinchZoomGestureDetected name 'Java_org_lamw_appzbarcodescannerviewdemo1_'
+'Controls_pOnPinchZoomGestureDetected',
pOnLostFocus name 'Java_org_lamw_appzbarcodescannerviewdemo1_Controls_'
+'pOnLostFocus',
pOnBeforeDispatchDraw name 'Java_org_lamw_appzbarcodescannerviewdemo1_'
+'Controls_pOnBeforeDispatchDraw',
pOnAfterDispatchDraw name 'Java_org_lamw_appzbarcodescannerviewdemo1_'
+'Controls_pOnAfterDispatchDraw',
pOnLayouting name 'Java_org_lamw_appzbarcodescannerviewdemo1_Controls_'
+'pOnLayouting',
pAppOnRequestPermissionResult name 'Java_org_lamw_appzbarcodescannerviewdemo'
+'1_Controls_pAppOnRequestPermissionResult',
pOnZBarcodeScannerViewResult name 'Java_org_lamw_appzbarcodescannerviewdemo1'
+'_Controls_pOnZBarcodeScannerViewResult';
{%endregion}
begin
gApp:= jApp.Create(nil);
gApp.Title:= 'LAMW JNI Android Bridges Library';
gjAppName:= 'org.lamw.appzbarcodescannerviewdemo1';
gjClassName:= 'org/lamw/appzbarcodescannerviewdemo1/Controls';
gApp.AppName:=gjAppName;
gApp.ClassName:=gjClassName;
gApp.Initialize;
gApp.CreateForm(TAndroidModule1, AndroidModule1);
end.
| {
"pile_set_name": "Github"
} |
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Waher.Security.ChaChaPoly.Test
{
/// <summary>
/// Tests taken from https://tools.ietf.org/html/rfc8439, retrieved 2019-05-31
/// </summary>
[TestClass]
public class ChaCha20Tests
{
[TestMethod]
public void Test_01_BlockFunction()
{
// §2.3.2
byte[] Key = new byte[]
{
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f
};
byte[] Nonce = new byte[]
{
0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, 0x4a, 0x00, 0x00, 0x00, 0x00
};
uint BlockCount = 1;
ChaCha20 Cipher = new ChaCha20(Key, BlockCount, Nonce);
byte[] Result = Cipher.GetBytes(64);
Assert.AreEqual("10f1e7e4d13b5915500fdd1fa32071c4c7d1f4c733c068030422aa9ac3d46c4ed2826446079faa0914c2d705d98b02a2b5129cd1de164eb9cbd083e8a2503c4e",
Hashes.BinaryToString(Result));
}
[TestMethod]
public void Test_02_Encrypt()
{
// §2.4.2
byte[] Key = new byte[]
{
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f
};
byte[] Nonce = new byte[]
{
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x4a, 0x00, 0x00, 0x00, 0x00
};
uint BlockCount = 1;
ChaCha20 Cipher = new ChaCha20(Key, BlockCount, Nonce);
byte[] Data = Encoding.ASCII.GetBytes("Ladies and Gentlemen of the class of '99: If I could offer you only one tip for the future, sunscreen would be it.");
Assert.AreEqual("4c616469657320616e642047656e746c656d656e206f662074686520636c617373206f66202739393a204966204920636f756c64206f6666657220796f75206f6e6c79206f6e652074697020666f7220746865206675747572652c2073756e73637265656e20776f756c642062652069742e",
Hashes.BinaryToString(Data));
byte[] Encrypted = Cipher.EncryptOrDecrypt(Data);
Assert.AreEqual("6e2e359a2568f98041ba0728dd0d6981e97e7aec1d4360c20a27afccfd9fae0bf91b65c5524733ab8f593dabcd62b3571639d624e65152ab8f530c359f0861d807ca0dbf500d6a6156a38e088a22b65e52bc514d16ccf806818ce91ab77937365af90bbf74a35be6b40b8eedf2785e42874d",
Hashes.BinaryToString(Encrypted));
}
[TestMethod]
public void Test_03_A1_TestVector_1()
{
// §A.1
byte[] Key = new byte[32];
byte[] Nonce = new byte[12];
uint BlockCount = 0;
ChaCha20 Cipher = new ChaCha20(Key, BlockCount, Nonce);
byte[] Result = Cipher.GetBytes(64);
Assert.AreEqual("76b8e0ada0f13d90405d6ae55386bd28bdd219b8a08ded1aa836efcc8b770dc7da41597c5157488d7724e03fb8d84a376a43b8f41518a11cc387b669b2ee6586",
Hashes.BinaryToString(Result));
}
[TestMethod]
public void Test_04_A1_TestVector_2()
{
// §A.1
byte[] Key = new byte[32];
byte[] Nonce = new byte[12];
uint BlockCount = 1;
ChaCha20 Cipher = new ChaCha20(Key, BlockCount, Nonce);
byte[] Result = Cipher.GetBytes(64);
Assert.AreEqual("9f07e7be5551387a98ba977c732d080dcb0f29a048e3656912c6533e32ee7aed29b721769ce64e43d57133b074d839d531ed1f28510afb45ace10a1f4b794d6f",
Hashes.BinaryToString(Result));
}
[TestMethod]
public void Test_05_A1_TestVector_3()
{
// §A.1
byte[] Key = new byte[32];
Key[31] = 1;
byte[] Nonce = new byte[12];
uint BlockCount = 1;
ChaCha20 Cipher = new ChaCha20(Key, BlockCount, Nonce);
byte[] Result = Cipher.GetBytes(64);
Assert.AreEqual("3aeb5224ecf849929b9d828db1ced4dd832025e8018b8160b82284f3c949aa5a8eca00bbb4a73bdad192b5c42f73f2fd4e273644c8b36125a64addeb006c13a0",
Hashes.BinaryToString(Result));
}
[TestMethod]
public void Test_06_A1_TestVector_4()
{
// §A.1
byte[] Key = new byte[32];
Key[1] = 0xff;
byte[] Nonce = new byte[12];
uint BlockCount = 2;
ChaCha20 Cipher = new ChaCha20(Key, BlockCount, Nonce);
byte[] Result = Cipher.GetBytes(64);
Assert.AreEqual("72d54dfbf12ec44b362692df94137f328fea8da73990265ec1bbbea1ae9af0ca13b25aa26cb4a648cb9b9d1be65b2c0924a66c54d545ec1b7374f4872e99f096",
Hashes.BinaryToString(Result));
}
[TestMethod]
public void Test_07_A1_TestVector_5()
{
// §A.1
byte[] Key = new byte[32];
byte[] Nonce = new byte[12];
Nonce[11] = 2;
uint BlockCount = 0;
ChaCha20 Cipher = new ChaCha20(Key, BlockCount, Nonce);
byte[] Result = Cipher.GetBytes(64);
Assert.AreEqual("c2c64d378cd536374ae204b9ef933fcd1a8b2288b3dfa49672ab765b54ee27c78a970e0e955c14f3a88e741b97c286f75f8fc299e8148362fa198a39531bed6d",
Hashes.BinaryToString(Result));
}
[TestMethod]
public void Test_08_A2_TestVector_1()
{
// §A.2
byte[] Key = new byte[32];
byte[] Nonce = new byte[12];
uint BlockCount = 0;
byte[] Message = new byte[64];
ChaCha20 Cipher = new ChaCha20(Key, BlockCount, Nonce);
byte[] Encrypted = Cipher.EncryptOrDecrypt(Message);
Assert.AreEqual("76b8e0ada0f13d90405d6ae55386bd28bdd219b8a08ded1aa836efcc8b770dc7da41597c5157488d7724e03fb8d84a376a43b8f41518a11cc387b669b2ee6586",
Hashes.BinaryToString(Encrypted));
}
[TestMethod]
public void Test_09_A2_TestVector_2()
{
// §A.2
byte[] Key = new byte[32];
Key[31] = 1;
byte[] Nonce = new byte[12];
Nonce[11] = 2;
uint BlockCount = 1;
byte[] Message = Hashes.StringToBinary("416e79207375626d697373696f6e20746f20746865204945544620696e74656e6465642062792074686520436f6e7472696275746f7220666f72207075626c69636174696f6e20617320616c6c206f722070617274206f6620616e204945544620496e7465726e65742d4472616674206f722052464320616e6420616e792073746174656d656e74206d6164652077697468696e2074686520636f6e74657874206f6620616e204945544620616374697669747920697320636f6e7369646572656420616e20224945544620436f6e747269627574696f6e222e20537563682073746174656d656e747320696e636c756465206f72616c2073746174656d656e747320696e20494554462073657373696f6e732c2061732077656c6c206173207772697474656e20616e6420656c656374726f6e696320636f6d6d756e69636174696f6e73206d61646520617420616e792074696d65206f7220706c6163652c207768696368206172652061646472657373656420746f");
ChaCha20 Cipher = new ChaCha20(Key, BlockCount, Nonce);
byte[] Encrypted = Cipher.EncryptOrDecrypt(Message);
Assert.AreEqual("a3fbf07df3fa2fde4f376ca23e82737041605d9f4f4f57bd8cff2c1d4b7955ec2a97948bd3722915c8f3d337f7d370050e9e96d647b7c39f56e031ca5eb6250d4042e02785ececfa4b4bb5e8ead0440e20b6e8db09d881a7c6132f420e52795042bdfa7773d8a9051447b3291ce1411c680465552aa6c405b7764d5e87bea85ad00f8449ed8f72d0d662ab052691ca66424bc86d2df80ea41f43abf937d3259dc4b2d0dfb48a6c9139ddd7f76966e928e635553ba76c5c879d7b35d49eb2e62b0871cdac638939e25e8a1e0ef9d5280fa8ca328b351c3c765989cbcf3daa8b6ccc3aaf9f3979c92b3720fc88dc95ed84a1be059c6499b9fda236e7e818b04b0bc39c1e876b193bfe5569753f88128cc08aaa9b63d1a16f80ef2554d7189c411f5869ca52c5b83fa36ff216b9c1d30062bebcfd2dc5bce0911934fda79a86f6e698ced759c3ff9b6477338f3da4f9cd8514ea9982ccafb341b2384dd902f3d1ab7ac61dd29c6f21ba5b862f3730e37cfdc4fd806c22f221",
Hashes.BinaryToString(Encrypted));
}
[TestMethod]
public void Test_10_A2_TestVector_3()
{
// §A.2
byte[] Key = Hashes.StringToBinary("1c9240a5eb55d38af333888604f6b5f0473917c1402b80099dca5cbc207075c0");
byte[] Nonce = new byte[12];
Nonce[11] = 2;
uint BlockCount = 42;
byte[] Message = Hashes.StringToBinary("2754776173206272696c6c69672c20616e642074686520736c6974687920746f7665730a446964206779726520616e642067696d626c6520696e2074686520776162653a0a416c6c206d696d737920776572652074686520626f726f676f7665732c0a416e6420746865206d6f6d65207261746873206f757467726162652e");
ChaCha20 Cipher = new ChaCha20(Key, BlockCount, Nonce);
byte[] Encrypted = Cipher.EncryptOrDecrypt(Message);
Assert.AreEqual("62e6347f95ed87a45ffae7426f27a1df5fb69110044c0d73118effa95b01e5cf166d3df2d721caf9b21e5fb14c616871fd84c54f9d65b283196c7fe4f60553ebf39c6402c42234e32a356b3e764312a61a5532055716ead6962568f87d3f3f7704c6a8d1bcd1bf4d50d6154b6da731b187b58dfd728afa36757a797ac188d1",
Hashes.BinaryToString(Encrypted));
}
[TestMethod]
public void Test_11_A4_TestVector_1()
{
// §A.4
byte[] Key = new byte[32];
byte[] Nonce = new byte[12];
ChaCha20 Cipher = new ChaCha20(Key, 0, Nonce);
byte[] Key2 = Cipher.GetBytes(32);
Assert.AreEqual("76b8e0ada0f13d90405d6ae55386bd28bdd219b8a08ded1aa836efcc8b770dc7", Hashes.BinaryToString(Key2));
}
[TestMethod]
public void Test_12_A4_TestVector_2()
{
// §A.4
byte[] Key = Hashes.StringToBinary("0000000000000000000000000000000000000000000000000000000000000001");
byte[] Nonce = Hashes.StringToBinary("000000000000000000000002");
ChaCha20 Cipher = new ChaCha20(Key, 0, Nonce);
byte[] Key2 = Cipher.GetBytes(32);
Assert.AreEqual("ecfa254f845f647473d3cb140da9e87606cb33066c447b87bc2666dde3fbb739", Hashes.BinaryToString(Key2));
}
[TestMethod]
public void Test_13_A4_TestVector_3()
{
// §A.4
byte[] Key = Hashes.StringToBinary("1c9240a5eb55d38af333888604f6b5f0473917c1402b80099dca5cbc207075c0");
byte[] Nonce = Hashes.StringToBinary("000000000000000000000002");
ChaCha20 Cipher = new ChaCha20(Key, 0, Nonce);
byte[] Key2 = Cipher.GetBytes(32);
Assert.AreEqual("965e3bc6f9ec7ed9560808f4d229f94b137ff275ca9b3fcbdd59deaad23310ae", Hashes.BinaryToString(Key2));
}
}
}
| {
"pile_set_name": "Github"
} |
package com.tngtech.jgiven.format;
import static org.assertj.core.api.Assertions.assertThat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.tngtech.jgiven.exception.JGivenWrongUsageException;
public class DateFormatterTest {
Locale defaultLocale;
DateFormatter formatter;
SimpleDateFormat sdf;
@Before
public void setup() {
// Save current default locale
defaultLocale = Locale.getDefault();
formatter = new DateFormatter();
sdf = new SimpleDateFormat( "dd/MM/yy HH:mm:ss" );
}
@After
public void tearDown() {
// Set initial default locale
Locale.setDefault( defaultLocale );
}
@Test
public void testFormat() throws Exception {
Locale.setDefault( Locale.ENGLISH );
Date now = sdf.parse( "21/01/2017 23:50:14" );
String expected = "Sat, 21 Jan 2017 23:50:14";
assertThat( formatter.format( now, new String[] { "EEE, d MMM yyyy HH:mm:ss" } ) ).isEqualTo( expected );
}
@Test
public void testFormat_SpecifyLocale() throws Exception {
Locale.setDefault( Locale.ENGLISH );
Date now = sdf.parse( "21/01/2017 23:50:14" );
Locale locale = Locale.FRANCE;
String expected = "sam., 21 janv. 2017 23:50:14";
assertThat( formatter.format( now, new String[] { "EEE, d MMM yyyy HH:mm:ss", locale.getLanguage() } ) ).isEqualTo( expected );
}
@Test( expected = JGivenWrongUsageException.class )
public void testFormat_DateFormatPatternArgumentIsMissing() throws Exception {
Date now = sdf.parse( "21/01/2017 23:50:14" );
formatter.format( now, new String[] {} );
}
@Test( expected = JGivenWrongUsageException.class )
public void testFormat_DateFormatPatternArgumentIsInvalid() throws Exception {
Date now = sdf.parse( "21/01/2017 23:50:14" );
formatter.format( now, new String[] { "XXXXXXXX" } );
}
}
| {
"pile_set_name": "Github"
} |
#include "SourceTermSplitter.hh"
#include "Framework/MethodStrategyProvider.hh"
#include "FluctSplit/FluctSplit.hh"
#include "FluctSplit/FluctuationSplitData.hh"
//////////////////////////////////////////////////////////////////////////////
using namespace std;
using namespace COOLFluiD::Framework;
using namespace COOLFluiD::MathTools;
//////////////////////////////////////////////////////////////////////////////
namespace COOLFluiD {
namespace FluctSplit {
//////////////////////////////////////////////////////////////////////////////
SourceTermSplitter::SourceTermSplitter(const std::string& name) : Splitter(name)
{
}
//////////////////////////////////////////////////////////////////////////////
SourceTermSplitter::~SourceTermSplitter()
{
}
//////////////////////////////////////////////////////////////////////////////
void SourceTermSplitter::configure ( Config::ConfigArgs& args )
{
Splitter::configure(args);
}
//////////////////////////////////////////////////////////////////////////////
void SourceTermSplitter::setup()
{
Splitter::setup();
}
//////////////////////////////////////////////////////////////////////////////
} // namespace FluctSplit
} // namespace COOLFluiD
//////////////////////////////////////////////////////////////////////////////
| {
"pile_set_name": "Github"
} |
<?php declare(strict_types=1);
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Util;
use PHPUnit\Framework\Error\Deprecated;
use PHPUnit\Framework\Error\Error;
use PHPUnit\Framework\Error\Notice;
use PHPUnit\Framework\Error\Warning;
/**
* @internal This class is not covered by the backward compatibility promise for PHPUnit
*/
final class ErrorHandler
{
/**
* @var bool
*/
private $convertDeprecationsToExceptions;
/**
* @var bool
*/
private $convertErrorsToExceptions;
/**
* @var bool
*/
private $convertNoticesToExceptions;
/**
* @var bool
*/
private $convertWarningsToExceptions;
/**
* @var bool
*/
private $registered = false;
public static function invokeIgnoringWarnings(callable $callable)
{
\set_error_handler(
static function ($errorNumber, $errorString) {
if ($errorNumber === \E_WARNING) {
return;
}
return false;
}
);
$result = $callable();
\restore_error_handler();
return $result;
}
public function __construct(bool $convertDeprecationsToExceptions, bool $convertErrorsToExceptions, bool $convertNoticesToExceptions, bool $convertWarningsToExceptions)
{
$this->convertDeprecationsToExceptions = $convertDeprecationsToExceptions;
$this->convertErrorsToExceptions = $convertErrorsToExceptions;
$this->convertNoticesToExceptions = $convertNoticesToExceptions;
$this->convertWarningsToExceptions = $convertWarningsToExceptions;
}
public function __invoke(int $errorNumber, string $errorString, string $errorFile, int $errorLine): bool
{
/*
* Do not raise an exception when the error suppression operator (@) was used.
*
* @see https://github.com/sebastianbergmann/phpunit/issues/3739
*/
if (!($errorNumber & \error_reporting())) {
return false;
}
switch ($errorNumber) {
case \E_NOTICE:
case \E_USER_NOTICE:
case \E_STRICT:
if (!$this->convertNoticesToExceptions) {
return false;
}
throw new Notice($errorString, $errorNumber, $errorFile, $errorLine);
case \E_WARNING:
case \E_USER_WARNING:
if (!$this->convertWarningsToExceptions) {
return false;
}
throw new Warning($errorString, $errorNumber, $errorFile, $errorLine);
case \E_DEPRECATED:
case \E_USER_DEPRECATED:
if (!$this->convertDeprecationsToExceptions) {
return false;
}
throw new Deprecated($errorString, $errorNumber, $errorFile, $errorLine);
default:
if (!$this->convertErrorsToExceptions) {
return false;
}
throw new Error($errorString, $errorNumber, $errorFile, $errorLine);
}
}
public function register(): void
{
if ($this->registered) {
return;
}
$oldErrorHandler = \set_error_handler($this);
if ($oldErrorHandler !== null) {
\restore_error_handler();
return;
}
$this->registered = true;
}
public function unregister(): void
{
if (!$this->registered) {
return;
}
\restore_error_handler();
}
}
| {
"pile_set_name": "Github"
} |
;===- ./tools/llvm-modextract/LLVMBuild.txt --------------------*- Conf -*--===;
;
; Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
; See https://llvm.org/LICENSE.txt for license information.
; SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
;
;===------------------------------------------------------------------------===;
;
; This is an LLVMBuild description file for the components in this subdirectory.
;
; For more information on the LLVMBuild system, please see:
;
; http://llvm.org/docs/LLVMBuild.html
;
;===------------------------------------------------------------------------===;
[component_0]
type = Tool
name = llvm-modextract
parent = Tools
required_libraries = BitReader BitWriter
| {
"pile_set_name": "Github"
} |
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/install.R
\name{install.SWFTools}
\alias{install.SWFTools}
\alias{install.swftools}
\title{Downloads and installs SWFTools for windows}
\usage{
install.SWFTools(
page_with_download_url = "http://swftools.org/download.html",
...
)
}
\arguments{
\item{page_with_download_url}{the URL of the SWFTools download page.}
\item{...}{extra parameters to pass to \link{install.URL}}
}
\value{
TRUE/FALSE - was the installation successful or not.
}
\description{
Allows the user to downloads and install the latest version of SWFTools for Windows.
}
\details{
SWFTools is a collection of utilities for working with Adobe Flash files (SWF files). The tool collection includes programs for reading SWF files, combining them, and creating them from other content (like images, sound files, videos or sourcecode). SWFTools is released under the GPL.
This function downloads current releases and NOT the Development Snapshots.
This function is useful for saveSWF() in the {animation} package.
}
\examples{
\dontrun{
install.SWFTools() # installs the latest version of SWFTools
}
}
\references{
\itemize{
\item SWFTools homepage: \url{http://swftools.org/}
}
}
| {
"pile_set_name": "Github"
} |
classdef BT7 < PROBLEM
% <problem> <BT>
% Benchmark MOP with bias feature
%------------------------------- Reference --------------------------------
% H. Li, Q. Zhang, and J. Deng, Biased multiobjective optimization and
% decomposition algorithm, IEEE Transactions on Cybernetics, 2017, 47(1):
% 52-66.
%------------------------------- Copyright --------------------------------
% Copyright (c) 2018-2019 BIMK Group. You are free to use the PlatEMO for
% research purposes. All publications which use this platform or any code
% in the platform should acknowledge the use of "PlatEMO" and reference "Ye
% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform
% for evolutionary multi-objective optimization [educational forum], IEEE
% Computational Intelligence Magazine, 2017, 12(4): 73-87".
%--------------------------------------------------------------------------
methods
%% Initialization
function obj = BT7()
obj.Global.M = 2;
if isempty(obj.Global.D)
obj.Global.D = 30;
end
obj.Global.lower = [0,-ones(1,obj.Global.D-1)];
obj.Global.upper = ones(1,obj.Global.D);
obj.Global.encoding = 'real';
end
%% Calculate objective values
function PopObj = CalObj(obj,X)
[N,D] = size(X);
I1 = 2 : 2 : D;
I2 = 3 : 2 : D;
Y = X - repmat(sin(6*pi*X(:,1)),1,D);
PopObj(:,1) = X(:,1) + sum(Y(:,I1).^2+(1-exp(-Y(:,I1).^2/1e-3))/5,2);
PopObj(:,2) = 1-sqrt(X(:,1)) + sum(Y(:,I2).^2+(1-exp(-Y(:,I2).^2/1e-3))/5,2);
end
%% Sample reference points on Pareto front
function P = PF(obj,N)
P(:,1) = (0:1/(N-1):1)';
P(:,2) = 1 - P(:,1).^0.5;
end
end
end | {
"pile_set_name": "Github"
} |
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2017, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
* RFC2195 CRAM-MD5 authentication
* RFC2595 Using TLS with IMAP, POP3 and ACAP
* RFC2831 DIGEST-MD5 authentication
* RFC3501 IMAPv4 protocol
* RFC4422 Simple Authentication and Security Layer (SASL)
* RFC4616 PLAIN authentication
* RFC4752 The Kerberos V5 ("GSSAPI") SASL Mechanism
* RFC4959 IMAP Extension for SASL Initial Client Response
* RFC5092 IMAP URL Scheme
* RFC6749 OAuth 2.0 Authorization Framework
* Draft LOGIN SASL Mechanism <draft-murchison-sasl-login-00.txt>
*
***************************************************************************/
#include "curl_setup.h"
#ifndef CURL_DISABLE_IMAP
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
#ifdef HAVE_UTSNAME_H
#include <sys/utsname.h>
#endif
#ifdef HAVE_NETDB_H
#include <netdb.h>
#endif
#ifdef __VMS
#include <in.h>
#include <inet.h>
#endif
#if (defined(NETWARE) && defined(__NOVELL_LIBC__))
#undef in_addr_t
#define in_addr_t unsigned long
#endif
#include <curl/curl.h>
#include "urldata.h"
#include "sendf.h"
#include "hostip.h"
#include "progress.h"
#include "transfer.h"
#include "escape.h"
#include "http.h" /* for HTTP proxy tunnel stuff */
#include "socks.h"
#include "imap.h"
#include "strtoofft.h"
#include "strcase.h"
#include "vtls/vtls.h"
#include "connect.h"
#include "strerror.h"
#include "select.h"
#include "multiif.h"
#include "url.h"
#include "strcase.h"
#include "curl_sasl.h"
#include "warnless.h"
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
#include "curl_memory.h"
#include "memdebug.h"
/* Local API functions */
static CURLcode imap_regular_transfer(struct connectdata *conn, bool *done);
static CURLcode imap_do(struct connectdata *conn, bool *done);
static CURLcode imap_done(struct connectdata *conn, CURLcode status,
bool premature);
static CURLcode imap_connect(struct connectdata *conn, bool *done);
static CURLcode imap_disconnect(struct connectdata *conn, bool dead);
static CURLcode imap_multi_statemach(struct connectdata *conn, bool *done);
static int imap_getsock(struct connectdata *conn, curl_socket_t *socks,
int numsocks);
static CURLcode imap_doing(struct connectdata *conn, bool *dophase_done);
static CURLcode imap_setup_connection(struct connectdata *conn);
static char *imap_atom(const char *str, bool escape_only);
static CURLcode imap_sendf(struct connectdata *conn, const char *fmt, ...);
static CURLcode imap_parse_url_options(struct connectdata *conn);
static CURLcode imap_parse_url_path(struct connectdata *conn);
static CURLcode imap_parse_custom_request(struct connectdata *conn);
static CURLcode imap_perform_authenticate(struct connectdata *conn,
const char *mech,
const char *initresp);
static CURLcode imap_continue_authenticate(struct connectdata *conn,
const char *resp);
static void imap_get_message(char *buffer, char **outptr);
/*
* IMAP protocol handler.
*/
const struct Curl_handler Curl_handler_imap = {
"IMAP", /* scheme */
imap_setup_connection, /* setup_connection */
imap_do, /* do_it */
imap_done, /* done */
ZERO_NULL, /* do_more */
imap_connect, /* connect_it */
imap_multi_statemach, /* connecting */
imap_doing, /* doing */
imap_getsock, /* proto_getsock */
imap_getsock, /* doing_getsock */
ZERO_NULL, /* domore_getsock */
ZERO_NULL, /* perform_getsock */
imap_disconnect, /* disconnect */
ZERO_NULL, /* readwrite */
PORT_IMAP, /* defport */
CURLPROTO_IMAP, /* protocol */
PROTOPT_CLOSEACTION| /* flags */
PROTOPT_URLOPTIONS
};
#ifdef USE_SSL
/*
* IMAPS protocol handler.
*/
const struct Curl_handler Curl_handler_imaps = {
"IMAPS", /* scheme */
imap_setup_connection, /* setup_connection */
imap_do, /* do_it */
imap_done, /* done */
ZERO_NULL, /* do_more */
imap_connect, /* connect_it */
imap_multi_statemach, /* connecting */
imap_doing, /* doing */
imap_getsock, /* proto_getsock */
imap_getsock, /* doing_getsock */
ZERO_NULL, /* domore_getsock */
ZERO_NULL, /* perform_getsock */
imap_disconnect, /* disconnect */
ZERO_NULL, /* readwrite */
PORT_IMAPS, /* defport */
CURLPROTO_IMAPS, /* protocol */
PROTOPT_CLOSEACTION | PROTOPT_SSL /* flags */
};
#endif
#ifndef CURL_DISABLE_HTTP
/*
* HTTP-proxyed IMAP protocol handler.
*/
static const struct Curl_handler Curl_handler_imap_proxy = {
"IMAP", /* scheme */
Curl_http_setup_conn, /* setup_connection */
Curl_http, /* do_it */
Curl_http_done, /* done */
ZERO_NULL, /* do_more */
ZERO_NULL, /* connect_it */
ZERO_NULL, /* connecting */
ZERO_NULL, /* doing */
ZERO_NULL, /* proto_getsock */
ZERO_NULL, /* doing_getsock */
ZERO_NULL, /* domore_getsock */
ZERO_NULL, /* perform_getsock */
ZERO_NULL, /* disconnect */
ZERO_NULL, /* readwrite */
PORT_IMAP, /* defport */
CURLPROTO_HTTP, /* protocol */
PROTOPT_NONE /* flags */
};
#ifdef USE_SSL
/*
* HTTP-proxyed IMAPS protocol handler.
*/
static const struct Curl_handler Curl_handler_imaps_proxy = {
"IMAPS", /* scheme */
Curl_http_setup_conn, /* setup_connection */
Curl_http, /* do_it */
Curl_http_done, /* done */
ZERO_NULL, /* do_more */
ZERO_NULL, /* connect_it */
ZERO_NULL, /* connecting */
ZERO_NULL, /* doing */
ZERO_NULL, /* proto_getsock */
ZERO_NULL, /* doing_getsock */
ZERO_NULL, /* domore_getsock */
ZERO_NULL, /* perform_getsock */
ZERO_NULL, /* disconnect */
ZERO_NULL, /* readwrite */
PORT_IMAPS, /* defport */
CURLPROTO_HTTP, /* protocol */
PROTOPT_NONE /* flags */
};
#endif
#endif
/* SASL parameters for the imap protocol */
static const struct SASLproto saslimap = {
"imap", /* The service name */
'+', /* Code received when continuation is expected */
'O', /* Code to receive upon authentication success */
0, /* Maximum initial response length (no max) */
imap_perform_authenticate, /* Send authentication command */
imap_continue_authenticate, /* Send authentication continuation */
imap_get_message /* Get SASL response message */
};
#ifdef USE_SSL
static void imap_to_imaps(struct connectdata *conn)
{
/* Change the connection handler */
conn->handler = &Curl_handler_imaps;
/* Set the connection's upgraded to TLS flag */
conn->tls_upgraded = TRUE;
}
#else
#define imap_to_imaps(x) Curl_nop_stmt
#endif
/***********************************************************************
*
* imap_matchresp()
*
* Determines whether the untagged response is related to the specified
* command by checking if it is in format "* <command-name> ..." or
* "* <number> <command-name> ...".
*
* The "* " marker is assumed to have already been checked by the caller.
*/
static bool imap_matchresp(const char *line, size_t len, const char *cmd)
{
const char *end = line + len;
size_t cmd_len = strlen(cmd);
/* Skip the untagged response marker */
line += 2;
/* Do we have a number after the marker? */
if(line < end && ISDIGIT(*line)) {
/* Skip the number */
do
line++;
while(line < end && ISDIGIT(*line));
/* Do we have the space character? */
if(line == end || *line != ' ')
return FALSE;
line++;
}
/* Does the command name match and is it followed by a space character or at
the end of line? */
if(line + cmd_len <= end && strncasecompare(line, cmd, cmd_len) &&
(line[cmd_len] == ' ' || line + cmd_len + 2 == end))
return TRUE;
return FALSE;
}
/***********************************************************************
*
* imap_endofresp()
*
* Checks whether the given string is a valid tagged, untagged or continuation
* response which can be processed by the response handler.
*/
static bool imap_endofresp(struct connectdata *conn, char *line, size_t len,
int *resp)
{
struct IMAP *imap = conn->data->req.protop;
struct imap_conn *imapc = &conn->proto.imapc;
const char *id = imapc->resptag;
size_t id_len = strlen(id);
/* Do we have a tagged command response? */
if(len >= id_len + 1 && !memcmp(id, line, id_len) && line[id_len] == ' ') {
line += id_len + 1;
len -= id_len + 1;
if(len >= 2 && !memcmp(line, "OK", 2))
*resp = 'O';
else if(len >= 2 && !memcmp(line, "NO", 2))
*resp = 'N';
else if(len >= 3 && !memcmp(line, "BAD", 3))
*resp = 'B';
else {
failf(conn->data, "Bad tagged response");
*resp = -1;
}
return TRUE;
}
/* Do we have an untagged command response? */
if(len >= 2 && !memcmp("* ", line, 2)) {
switch(imapc->state) {
/* States which are interested in untagged responses */
case IMAP_CAPABILITY:
if(!imap_matchresp(line, len, "CAPABILITY"))
return FALSE;
break;
case IMAP_LIST:
if((!imap->custom && !imap_matchresp(line, len, "LIST")) ||
(imap->custom && !imap_matchresp(line, len, imap->custom) &&
(strcmp(imap->custom, "STORE") ||
!imap_matchresp(line, len, "FETCH")) &&
strcmp(imap->custom, "SELECT") &&
strcmp(imap->custom, "EXAMINE") &&
strcmp(imap->custom, "SEARCH") &&
strcmp(imap->custom, "EXPUNGE") &&
strcmp(imap->custom, "LSUB") &&
strcmp(imap->custom, "UID") &&
strcmp(imap->custom, "NOOP")))
return FALSE;
break;
case IMAP_SELECT:
/* SELECT is special in that its untagged responses do not have a
common prefix so accept anything! */
break;
case IMAP_FETCH:
if(!imap_matchresp(line, len, "FETCH"))
return FALSE;
break;
case IMAP_SEARCH:
if(!imap_matchresp(line, len, "SEARCH"))
return FALSE;
break;
/* Ignore other untagged responses */
default:
return FALSE;
}
*resp = '*';
return TRUE;
}
/* Do we have a continuation response? This should be a + symbol followed by
a space and optionally some text as per RFC-3501 for the AUTHENTICATE and
APPEND commands and as outlined in Section 4. Examples of RFC-4959 but
some e-mail servers ignore this and only send a single + instead. */
if(imap && !imap->custom && ((len == 3 && !memcmp("+", line, 1)) ||
(len >= 2 && !memcmp("+ ", line, 2)))) {
switch(imapc->state) {
/* States which are interested in continuation responses */
case IMAP_AUTHENTICATE:
case IMAP_APPEND:
*resp = '+';
break;
default:
failf(conn->data, "Unexpected continuation response");
*resp = -1;
break;
}
return TRUE;
}
return FALSE; /* Nothing for us */
}
/***********************************************************************
*
* imap_get_message()
*
* Gets the authentication message from the response buffer.
*/
static void imap_get_message(char *buffer, char **outptr)
{
size_t len = 0;
char *message = NULL;
/* Find the start of the message */
for(message = buffer + 2; *message == ' ' || *message == '\t'; message++)
;
/* Find the end of the message */
for(len = strlen(message); len--;)
if(message[len] != '\r' && message[len] != '\n' && message[len] != ' ' &&
message[len] != '\t')
break;
/* Terminate the message */
if(++len) {
message[len] = '\0';
}
*outptr = message;
}
/***********************************************************************
*
* state()
*
* This is the ONLY way to change IMAP state!
*/
static void state(struct connectdata *conn, imapstate newstate)
{
struct imap_conn *imapc = &conn->proto.imapc;
#if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS)
/* for debug purposes */
static const char * const names[]={
"STOP",
"SERVERGREET",
"CAPABILITY",
"STARTTLS",
"UPGRADETLS",
"AUTHENTICATE",
"LOGIN",
"LIST",
"SELECT",
"FETCH",
"FETCH_FINAL",
"APPEND",
"APPEND_FINAL",
"SEARCH",
"LOGOUT",
/* LAST */
};
if(imapc->state != newstate)
infof(conn->data, "IMAP %p state change from %s to %s\n",
(void *)imapc, names[imapc->state], names[newstate]);
#endif
imapc->state = newstate;
}
/***********************************************************************
*
* imap_perform_capability()
*
* Sends the CAPABILITY command in order to obtain a list of server side
* supported capabilities.
*/
static CURLcode imap_perform_capability(struct connectdata *conn)
{
CURLcode result = CURLE_OK;
struct imap_conn *imapc = &conn->proto.imapc;
imapc->sasl.authmechs = SASL_AUTH_NONE; /* No known auth. mechanisms yet */
imapc->sasl.authused = SASL_AUTH_NONE; /* Clear the auth. mechanism used */
imapc->tls_supported = FALSE; /* Clear the TLS capability */
/* Send the CAPABILITY command */
result = imap_sendf(conn, "CAPABILITY");
if(!result)
state(conn, IMAP_CAPABILITY);
return result;
}
/***********************************************************************
*
* imap_perform_starttls()
*
* Sends the STARTTLS command to start the upgrade to TLS.
*/
static CURLcode imap_perform_starttls(struct connectdata *conn)
{
CURLcode result = CURLE_OK;
/* Send the STARTTLS command */
result = imap_sendf(conn, "STARTTLS");
if(!result)
state(conn, IMAP_STARTTLS);
return result;
}
/***********************************************************************
*
* imap_perform_upgrade_tls()
*
* Performs the upgrade to TLS.
*/
static CURLcode imap_perform_upgrade_tls(struct connectdata *conn)
{
CURLcode result = CURLE_OK;
struct imap_conn *imapc = &conn->proto.imapc;
/* Start the SSL connection */
result = Curl_ssl_connect_nonblocking(conn, FIRSTSOCKET, &imapc->ssldone);
if(!result) {
if(imapc->state != IMAP_UPGRADETLS)
state(conn, IMAP_UPGRADETLS);
if(imapc->ssldone) {
imap_to_imaps(conn);
result = imap_perform_capability(conn);
}
}
return result;
}
/***********************************************************************
*
* imap_perform_login()
*
* Sends a clear text LOGIN command to authenticate with.
*/
static CURLcode imap_perform_login(struct connectdata *conn)
{
CURLcode result = CURLE_OK;
char *user;
char *passwd;
/* Check we have a username and password to authenticate with and end the
connect phase if we don't */
if(!conn->bits.user_passwd) {
state(conn, IMAP_STOP);
return result;
}
/* Make sure the username and password are in the correct atom format */
user = imap_atom(conn->user, false);
passwd = imap_atom(conn->passwd, false);
/* Send the LOGIN command */
result = imap_sendf(conn, "LOGIN %s %s", user ? user : "",
passwd ? passwd : "");
free(user);
free(passwd);
if(!result)
state(conn, IMAP_LOGIN);
return result;
}
/***********************************************************************
*
* imap_perform_authenticate()
*
* Sends an AUTHENTICATE command allowing the client to login with the given
* SASL authentication mechanism.
*/
static CURLcode imap_perform_authenticate(struct connectdata *conn,
const char *mech,
const char *initresp)
{
CURLcode result = CURLE_OK;
if(initresp) {
/* Send the AUTHENTICATE command with the initial response */
result = imap_sendf(conn, "AUTHENTICATE %s %s", mech, initresp);
}
else {
/* Send the AUTHENTICATE command */
result = imap_sendf(conn, "AUTHENTICATE %s", mech);
}
return result;
}
/***********************************************************************
*
* imap_continue_authenticate()
*
* Sends SASL continuation data or cancellation.
*/
static CURLcode imap_continue_authenticate(struct connectdata *conn,
const char *resp)
{
struct imap_conn *imapc = &conn->proto.imapc;
return Curl_pp_sendf(&imapc->pp, "%s", resp);
}
/***********************************************************************
*
* imap_perform_authentication()
*
* Initiates the authentication sequence, with the appropriate SASL
* authentication mechanism, falling back to clear text should a common
* mechanism not be available between the client and server.
*/
static CURLcode imap_perform_authentication(struct connectdata *conn)
{
CURLcode result = CURLE_OK;
struct imap_conn *imapc = &conn->proto.imapc;
saslprogress progress;
/* Check we have enough data to authenticate with and end the
connect phase if we don't */
if(!Curl_sasl_can_authenticate(&imapc->sasl, conn)) {
state(conn, IMAP_STOP);
return result;
}
/* Calculate the SASL login details */
result = Curl_sasl_start(&imapc->sasl, conn, imapc->ir_supported, &progress);
if(!result) {
if(progress == SASL_INPROGRESS)
state(conn, IMAP_AUTHENTICATE);
else if(!imapc->login_disabled && (imapc->preftype & IMAP_TYPE_CLEARTEXT))
/* Perform clear text authentication */
result = imap_perform_login(conn);
else {
/* Other mechanisms not supported */
infof(conn->data, "No known authentication mechanisms supported!\n");
result = CURLE_LOGIN_DENIED;
}
}
return result;
}
/***********************************************************************
*
* imap_perform_list()
*
* Sends a LIST command or an alternative custom request.
*/
static CURLcode imap_perform_list(struct connectdata *conn)
{
CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
struct IMAP *imap = data->req.protop;
char *mailbox;
if(imap->custom)
/* Send the custom request */
result = imap_sendf(conn, "%s%s", imap->custom,
imap->custom_params ? imap->custom_params : "");
else {
/* Make sure the mailbox is in the correct atom format if necessary */
mailbox = imap->mailbox ? imap_atom(imap->mailbox, true) : strdup("");
if(!mailbox)
return CURLE_OUT_OF_MEMORY;
/* Send the LIST command */
result = imap_sendf(conn, "LIST \"%s\" *", mailbox);
free(mailbox);
}
if(!result)
state(conn, IMAP_LIST);
return result;
}
/***********************************************************************
*
* imap_perform_select()
*
* Sends a SELECT command to ask the server to change the selected mailbox.
*/
static CURLcode imap_perform_select(struct connectdata *conn)
{
CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
struct IMAP *imap = data->req.protop;
struct imap_conn *imapc = &conn->proto.imapc;
char *mailbox;
/* Invalidate old information as we are switching mailboxes */
Curl_safefree(imapc->mailbox);
Curl_safefree(imapc->mailbox_uidvalidity);
/* Check we have a mailbox */
if(!imap->mailbox) {
failf(conn->data, "Cannot SELECT without a mailbox.");
return CURLE_URL_MALFORMAT;
}
/* Make sure the mailbox is in the correct atom format */
mailbox = imap_atom(imap->mailbox, false);
if(!mailbox)
return CURLE_OUT_OF_MEMORY;
/* Send the SELECT command */
result = imap_sendf(conn, "SELECT %s", mailbox);
free(mailbox);
if(!result)
state(conn, IMAP_SELECT);
return result;
}
/***********************************************************************
*
* imap_perform_fetch()
*
* Sends a FETCH command to initiate the download of a message.
*/
static CURLcode imap_perform_fetch(struct connectdata *conn)
{
CURLcode result = CURLE_OK;
struct IMAP *imap = conn->data->req.protop;
/* Check we have a UID */
if(!imap->uid) {
failf(conn->data, "Cannot FETCH without a UID.");
return CURLE_URL_MALFORMAT;
}
/* Send the FETCH command */
if(imap->partial)
result = imap_sendf(conn, "FETCH %s BODY[%s]<%s>",
imap->uid,
imap->section ? imap->section : "",
imap->partial);
else
result = imap_sendf(conn, "FETCH %s BODY[%s]",
imap->uid,
imap->section ? imap->section : "");
if(!result)
state(conn, IMAP_FETCH);
return result;
}
/***********************************************************************
*
* imap_perform_append()
*
* Sends an APPEND command to initiate the upload of a message.
*/
static CURLcode imap_perform_append(struct connectdata *conn)
{
CURLcode result = CURLE_OK;
struct IMAP *imap = conn->data->req.protop;
char *mailbox;
/* Check we have a mailbox */
if(!imap->mailbox) {
failf(conn->data, "Cannot APPEND without a mailbox.");
return CURLE_URL_MALFORMAT;
}
/* Check we know the size of the upload */
if(conn->data->state.infilesize < 0) {
failf(conn->data, "Cannot APPEND with unknown input file size\n");
return CURLE_UPLOAD_FAILED;
}
/* Make sure the mailbox is in the correct atom format */
mailbox = imap_atom(imap->mailbox, false);
if(!mailbox)
return CURLE_OUT_OF_MEMORY;
/* Send the APPEND command */
result = imap_sendf(conn, "APPEND %s (\\Seen) {%" CURL_FORMAT_CURL_OFF_T "}",
mailbox, conn->data->state.infilesize);
free(mailbox);
if(!result)
state(conn, IMAP_APPEND);
return result;
}
/***********************************************************************
*
* imap_perform_search()
*
* Sends a SEARCH command.
*/
static CURLcode imap_perform_search(struct connectdata *conn)
{
CURLcode result = CURLE_OK;
struct IMAP *imap = conn->data->req.protop;
/* Check we have a query string */
if(!imap->query) {
failf(conn->data, "Cannot SEARCH without a query string.");
return CURLE_URL_MALFORMAT;
}
/* Send the SEARCH command */
result = imap_sendf(conn, "SEARCH %s", imap->query);
if(!result)
state(conn, IMAP_SEARCH);
return result;
}
/***********************************************************************
*
* imap_perform_logout()
*
* Performs the logout action prior to sclose() being called.
*/
static CURLcode imap_perform_logout(struct connectdata *conn)
{
CURLcode result = CURLE_OK;
/* Send the LOGOUT command */
result = imap_sendf(conn, "LOGOUT");
if(!result)
state(conn, IMAP_LOGOUT);
return result;
}
/* For the initial server greeting */
static CURLcode imap_state_servergreet_resp(struct connectdata *conn,
int imapcode,
imapstate instate)
{
CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
(void)instate; /* no use for this yet */
if(imapcode != 'O') {
failf(data, "Got unexpected imap-server response");
result = CURLE_WEIRD_SERVER_REPLY;
}
else
result = imap_perform_capability(conn);
return result;
}
/* For CAPABILITY responses */
static CURLcode imap_state_capability_resp(struct connectdata *conn,
int imapcode,
imapstate instate)
{
CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
struct imap_conn *imapc = &conn->proto.imapc;
const char *line = data->state.buffer;
size_t wordlen;
(void)instate; /* no use for this yet */
/* Do we have a untagged response? */
if(imapcode == '*') {
line += 2;
/* Loop through the data line */
for(;;) {
while(*line &&
(*line == ' ' || *line == '\t' ||
*line == '\r' || *line == '\n')) {
line++;
}
if(!*line)
break;
/* Extract the word */
for(wordlen = 0; line[wordlen] && line[wordlen] != ' ' &&
line[wordlen] != '\t' && line[wordlen] != '\r' &&
line[wordlen] != '\n';)
wordlen++;
/* Does the server support the STARTTLS capability? */
if(wordlen == 8 && !memcmp(line, "STARTTLS", 8))
imapc->tls_supported = TRUE;
/* Has the server explicitly disabled clear text authentication? */
else if(wordlen == 13 && !memcmp(line, "LOGINDISABLED", 13))
imapc->login_disabled = TRUE;
/* Does the server support the SASL-IR capability? */
else if(wordlen == 7 && !memcmp(line, "SASL-IR", 7))
imapc->ir_supported = TRUE;
/* Do we have a SASL based authentication mechanism? */
else if(wordlen > 5 && !memcmp(line, "AUTH=", 5)) {
size_t llen;
unsigned int mechbit;
line += 5;
wordlen -= 5;
/* Test the word for a matching authentication mechanism */
mechbit = Curl_sasl_decode_mech(line, wordlen, &llen);
if(mechbit && llen == wordlen)
imapc->sasl.authmechs |= mechbit;
}
line += wordlen;
}
}
else if(imapcode == 'O') {
if(data->set.use_ssl && !conn->ssl[FIRSTSOCKET].use) {
/* We don't have a SSL/TLS connection yet, but SSL is requested */
if(imapc->tls_supported)
/* Switch to TLS connection now */
result = imap_perform_starttls(conn);
else if(data->set.use_ssl == CURLUSESSL_TRY)
/* Fallback and carry on with authentication */
result = imap_perform_authentication(conn);
else {
failf(data, "STARTTLS not supported.");
result = CURLE_USE_SSL_FAILED;
}
}
else
result = imap_perform_authentication(conn);
}
else
result = imap_perform_authentication(conn);
return result;
}
/* For STARTTLS responses */
static CURLcode imap_state_starttls_resp(struct connectdata *conn,
int imapcode,
imapstate instate)
{
CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
(void)instate; /* no use for this yet */
if(imapcode != 'O') {
if(data->set.use_ssl != CURLUSESSL_TRY) {
failf(data, "STARTTLS denied");
result = CURLE_USE_SSL_FAILED;
}
else
result = imap_perform_authentication(conn);
}
else
result = imap_perform_upgrade_tls(conn);
return result;
}
/* For SASL authentication responses */
static CURLcode imap_state_auth_resp(struct connectdata *conn,
int imapcode,
imapstate instate)
{
CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
struct imap_conn *imapc = &conn->proto.imapc;
saslprogress progress;
(void)instate; /* no use for this yet */
result = Curl_sasl_continue(&imapc->sasl, conn, imapcode, &progress);
if(!result)
switch(progress) {
case SASL_DONE:
state(conn, IMAP_STOP); /* Authenticated */
break;
case SASL_IDLE: /* No mechanism left after cancellation */
if((!imapc->login_disabled) && (imapc->preftype & IMAP_TYPE_CLEARTEXT))
/* Perform clear text authentication */
result = imap_perform_login(conn);
else {
failf(data, "Authentication cancelled");
result = CURLE_LOGIN_DENIED;
}
break;
default:
break;
}
return result;
}
/* For LOGIN responses */
static CURLcode imap_state_login_resp(struct connectdata *conn,
int imapcode,
imapstate instate)
{
CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
(void)instate; /* no use for this yet */
if(imapcode != 'O') {
failf(data, "Access denied. %c", imapcode);
result = CURLE_LOGIN_DENIED;
}
else
/* End of connect phase */
state(conn, IMAP_STOP);
return result;
}
/* For LIST and SEARCH responses */
static CURLcode imap_state_listsearch_resp(struct connectdata *conn,
int imapcode,
imapstate instate)
{
CURLcode result = CURLE_OK;
char *line = conn->data->state.buffer;
size_t len = strlen(line);
(void)instate; /* No use for this yet */
if(imapcode == '*') {
/* Temporarily add the LF character back and send as body to the client */
line[len] = '\n';
result = Curl_client_write(conn, CLIENTWRITE_BODY, line, len + 1);
line[len] = '\0';
}
else if(imapcode != 'O')
result = CURLE_QUOTE_ERROR; /* TODO: Fix error code */
else
/* End of DO phase */
state(conn, IMAP_STOP);
return result;
}
/* For SELECT responses */
static CURLcode imap_state_select_resp(struct connectdata *conn, int imapcode,
imapstate instate)
{
CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
struct IMAP *imap = conn->data->req.protop;
struct imap_conn *imapc = &conn->proto.imapc;
const char *line = data->state.buffer;
char tmp[20];
(void)instate; /* no use for this yet */
if(imapcode == '*') {
/* See if this is an UIDVALIDITY response */
if(sscanf(line + 2, "OK [UIDVALIDITY %19[0123456789]]", tmp) == 1) {
Curl_safefree(imapc->mailbox_uidvalidity);
imapc->mailbox_uidvalidity = strdup(tmp);
}
}
else if(imapcode == 'O') {
/* Check if the UIDVALIDITY has been specified and matches */
if(imap->uidvalidity && imapc->mailbox_uidvalidity &&
strcmp(imap->uidvalidity, imapc->mailbox_uidvalidity)) {
failf(conn->data, "Mailbox UIDVALIDITY has changed");
result = CURLE_REMOTE_FILE_NOT_FOUND;
}
else {
/* Note the currently opened mailbox on this connection */
imapc->mailbox = strdup(imap->mailbox);
if(imap->custom)
result = imap_perform_list(conn);
else if(imap->query)
result = imap_perform_search(conn);
else
result = imap_perform_fetch(conn);
}
}
else {
failf(data, "Select failed");
result = CURLE_LOGIN_DENIED;
}
return result;
}
/* For the (first line of the) FETCH responses */
static CURLcode imap_state_fetch_resp(struct connectdata *conn, int imapcode,
imapstate instate)
{
CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
struct imap_conn *imapc = &conn->proto.imapc;
struct pingpong *pp = &imapc->pp;
const char *ptr = data->state.buffer;
bool parsed = FALSE;
curl_off_t size = 0;
(void)instate; /* no use for this yet */
if(imapcode != '*') {
Curl_pgrsSetDownloadSize(data, -1);
state(conn, IMAP_STOP);
return CURLE_REMOTE_FILE_NOT_FOUND; /* TODO: Fix error code */
}
/* Something like this is received "* 1 FETCH (BODY[TEXT] {2021}\r" so parse
the continuation data contained within the curly brackets */
while(*ptr && (*ptr != '{'))
ptr++;
if(*ptr == '{') {
char *endptr;
size = curlx_strtoofft(ptr + 1, &endptr, 10);
if(endptr - ptr > 1 && endptr[0] == '}' &&
endptr[1] == '\r' && endptr[2] == '\0')
parsed = TRUE;
}
if(parsed) {
infof(data, "Found %" CURL_FORMAT_CURL_OFF_TU " bytes to download\n",
size);
Curl_pgrsSetDownloadSize(data, size);
if(pp->cache) {
/* At this point there is a bunch of data in the header "cache" that is
actually body content, send it as body and then skip it. Do note
that there may even be additional "headers" after the body. */
size_t chunk = pp->cache_size;
if(chunk > (size_t)size)
/* The conversion from curl_off_t to size_t is always fine here */
chunk = (size_t)size;
result = Curl_client_write(conn, CLIENTWRITE_BODY, pp->cache, chunk);
if(result)
return result;
data->req.bytecount += chunk;
infof(data, "Written %" CURL_FORMAT_CURL_OFF_TU
" bytes, %" CURL_FORMAT_CURL_OFF_TU
" bytes are left for transfer\n", (curl_off_t)chunk,
size - chunk);
/* Have we used the entire cache or just part of it?*/
if(pp->cache_size > chunk) {
/* Only part of it so shrink the cache to fit the trailing data */
memmove(pp->cache, pp->cache + chunk, pp->cache_size - chunk);
pp->cache_size -= chunk;
}
else {
/* Free the cache */
Curl_safefree(pp->cache);
/* Reset the cache size */
pp->cache_size = 0;
}
}
if(data->req.bytecount == size)
/* The entire data is already transferred! */
Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL);
else {
/* IMAP download */
data->req.maxdownload = size;
Curl_setup_transfer(conn, FIRSTSOCKET, size, FALSE, NULL, -1, NULL);
}
}
else {
/* We don't know how to parse this line */
failf(pp->conn->data, "Failed to parse FETCH response.");
result = CURLE_WEIRD_SERVER_REPLY;
}
/* End of DO phase */
state(conn, IMAP_STOP);
return result;
}
/* For final FETCH responses performed after the download */
static CURLcode imap_state_fetch_final_resp(struct connectdata *conn,
int imapcode,
imapstate instate)
{
CURLcode result = CURLE_OK;
(void)instate; /* No use for this yet */
if(imapcode != 'O')
result = CURLE_WEIRD_SERVER_REPLY;
else
/* End of DONE phase */
state(conn, IMAP_STOP);
return result;
}
/* For APPEND responses */
static CURLcode imap_state_append_resp(struct connectdata *conn, int imapcode,
imapstate instate)
{
CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
(void)instate; /* No use for this yet */
if(imapcode != '+') {
result = CURLE_UPLOAD_FAILED;
}
else {
/* Set the progress upload size */
Curl_pgrsSetUploadSize(data, data->state.infilesize);
/* IMAP upload */
Curl_setup_transfer(conn, -1, -1, FALSE, NULL, FIRSTSOCKET, NULL);
/* End of DO phase */
state(conn, IMAP_STOP);
}
return result;
}
/* For final APPEND responses performed after the upload */
static CURLcode imap_state_append_final_resp(struct connectdata *conn,
int imapcode,
imapstate instate)
{
CURLcode result = CURLE_OK;
(void)instate; /* No use for this yet */
if(imapcode != 'O')
result = CURLE_UPLOAD_FAILED;
else
/* End of DONE phase */
state(conn, IMAP_STOP);
return result;
}
static CURLcode imap_statemach_act(struct connectdata *conn)
{
CURLcode result = CURLE_OK;
curl_socket_t sock = conn->sock[FIRSTSOCKET];
int imapcode;
struct imap_conn *imapc = &conn->proto.imapc;
struct pingpong *pp = &imapc->pp;
size_t nread = 0;
/* Busy upgrading the connection; right now all I/O is SSL/TLS, not IMAP */
if(imapc->state == IMAP_UPGRADETLS)
return imap_perform_upgrade_tls(conn);
/* Flush any data that needs to be sent */
if(pp->sendleft)
return Curl_pp_flushsend(pp);
do {
/* Read the response from the server */
result = Curl_pp_readresp(sock, pp, &imapcode, &nread);
if(result)
return result;
/* Was there an error parsing the response line? */
if(imapcode == -1)
return CURLE_WEIRD_SERVER_REPLY;
if(!imapcode)
break;
/* We have now received a full IMAP server response */
switch(imapc->state) {
case IMAP_SERVERGREET:
result = imap_state_servergreet_resp(conn, imapcode, imapc->state);
break;
case IMAP_CAPABILITY:
result = imap_state_capability_resp(conn, imapcode, imapc->state);
break;
case IMAP_STARTTLS:
result = imap_state_starttls_resp(conn, imapcode, imapc->state);
break;
case IMAP_AUTHENTICATE:
result = imap_state_auth_resp(conn, imapcode, imapc->state);
break;
case IMAP_LOGIN:
result = imap_state_login_resp(conn, imapcode, imapc->state);
break;
case IMAP_LIST:
result = imap_state_listsearch_resp(conn, imapcode, imapc->state);
break;
case IMAP_SELECT:
result = imap_state_select_resp(conn, imapcode, imapc->state);
break;
case IMAP_FETCH:
result = imap_state_fetch_resp(conn, imapcode, imapc->state);
break;
case IMAP_FETCH_FINAL:
result = imap_state_fetch_final_resp(conn, imapcode, imapc->state);
break;
case IMAP_APPEND:
result = imap_state_append_resp(conn, imapcode, imapc->state);
break;
case IMAP_APPEND_FINAL:
result = imap_state_append_final_resp(conn, imapcode, imapc->state);
break;
case IMAP_SEARCH:
result = imap_state_listsearch_resp(conn, imapcode, imapc->state);
break;
case IMAP_LOGOUT:
/* fallthrough, just stop! */
default:
/* internal error */
state(conn, IMAP_STOP);
break;
}
} while(!result && imapc->state != IMAP_STOP && Curl_pp_moredata(pp));
return result;
}
/* Called repeatedly until done from multi.c */
static CURLcode imap_multi_statemach(struct connectdata *conn, bool *done)
{
CURLcode result = CURLE_OK;
struct imap_conn *imapc = &conn->proto.imapc;
if((conn->handler->flags & PROTOPT_SSL) && !imapc->ssldone) {
result = Curl_ssl_connect_nonblocking(conn, FIRSTSOCKET, &imapc->ssldone);
if(result || !imapc->ssldone)
return result;
}
result = Curl_pp_statemach(&imapc->pp, FALSE);
*done = (imapc->state == IMAP_STOP) ? TRUE : FALSE;
return result;
}
static CURLcode imap_block_statemach(struct connectdata *conn)
{
CURLcode result = CURLE_OK;
struct imap_conn *imapc = &conn->proto.imapc;
while(imapc->state != IMAP_STOP && !result)
result = Curl_pp_statemach(&imapc->pp, TRUE);
return result;
}
/* Allocate and initialize the struct IMAP for the current Curl_easy if
required */
static CURLcode imap_init(struct connectdata *conn)
{
CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
struct IMAP *imap;
imap = data->req.protop = calloc(sizeof(struct IMAP), 1);
if(!imap)
result = CURLE_OUT_OF_MEMORY;
return result;
}
/* For the IMAP "protocol connect" and "doing" phases only */
static int imap_getsock(struct connectdata *conn, curl_socket_t *socks,
int numsocks)
{
return Curl_pp_getsock(&conn->proto.imapc.pp, socks, numsocks);
}
/***********************************************************************
*
* imap_connect()
*
* This function should do everything that is to be considered a part of the
* connection phase.
*
* The variable 'done' points to will be TRUE if the protocol-layer connect
* phase is done when this function returns, or FALSE if not.
*/
static CURLcode imap_connect(struct connectdata *conn, bool *done)
{
CURLcode result = CURLE_OK;
struct imap_conn *imapc = &conn->proto.imapc;
struct pingpong *pp = &imapc->pp;
*done = FALSE; /* default to not done yet */
/* We always support persistent connections in IMAP */
connkeep(conn, "IMAP default");
/* Set the default response time-out */
pp->response_time = RESP_TIMEOUT;
pp->statemach_act = imap_statemach_act;
pp->endofresp = imap_endofresp;
pp->conn = conn;
/* Set the default preferred authentication type and mechanism */
imapc->preftype = IMAP_TYPE_ANY;
Curl_sasl_init(&imapc->sasl, &saslimap);
/* Initialise the pingpong layer */
Curl_pp_init(pp);
/* Parse the URL options */
result = imap_parse_url_options(conn);
if(result)
return result;
/* Start off waiting for the server greeting response */
state(conn, IMAP_SERVERGREET);
/* Start off with an response id of '*' */
strcpy(imapc->resptag, "*");
result = imap_multi_statemach(conn, done);
return result;
}
/***********************************************************************
*
* imap_done()
*
* The DONE function. This does what needs to be done after a single DO has
* performed.
*
* Input argument is already checked for validity.
*/
static CURLcode imap_done(struct connectdata *conn, CURLcode status,
bool premature)
{
CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
struct IMAP *imap = data->req.protop;
(void)premature;
if(!imap)
return CURLE_OK;
if(status) {
connclose(conn, "IMAP done with bad status"); /* marked for closure */
result = status; /* use the already set error code */
}
else if(!data->set.connect_only && !imap->custom &&
(imap->uid || data->set.upload)) {
/* Handle responses after FETCH or APPEND transfer has finished */
if(!data->set.upload)
state(conn, IMAP_FETCH_FINAL);
else {
/* End the APPEND command first by sending an empty line */
result = Curl_pp_sendf(&conn->proto.imapc.pp, "%s", "");
if(!result)
state(conn, IMAP_APPEND_FINAL);
}
/* Run the state-machine
TODO: when the multi interface is used, this _really_ should be using
the imap_multi_statemach function but we have no general support for
non-blocking DONE operations!
*/
if(!result)
result = imap_block_statemach(conn);
}
/* Cleanup our per-request based variables */
Curl_safefree(imap->mailbox);
Curl_safefree(imap->uidvalidity);
Curl_safefree(imap->uid);
Curl_safefree(imap->section);
Curl_safefree(imap->partial);
Curl_safefree(imap->query);
Curl_safefree(imap->custom);
Curl_safefree(imap->custom_params);
/* Clear the transfer mode for the next request */
imap->transfer = FTPTRANSFER_BODY;
return result;
}
/***********************************************************************
*
* imap_perform()
*
* This is the actual DO function for IMAP. Fetch or append a message, or do
* other things according to the options previously setup.
*/
static CURLcode imap_perform(struct connectdata *conn, bool *connected,
bool *dophase_done)
{
/* This is IMAP and no proxy */
CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
struct IMAP *imap = data->req.protop;
struct imap_conn *imapc = &conn->proto.imapc;
bool selected = FALSE;
DEBUGF(infof(conn->data, "DO phase starts\n"));
if(conn->data->set.opt_no_body) {
/* Requested no body means no transfer */
imap->transfer = FTPTRANSFER_INFO;
}
*dophase_done = FALSE; /* not done yet */
/* Determine if the requested mailbox (with the same UIDVALIDITY if set)
has already been selected on this connection */
if(imap->mailbox && imapc->mailbox &&
!strcmp(imap->mailbox, imapc->mailbox) &&
(!imap->uidvalidity || !imapc->mailbox_uidvalidity ||
!strcmp(imap->uidvalidity, imapc->mailbox_uidvalidity)))
selected = TRUE;
/* Start the first command in the DO phase */
if(conn->data->set.upload)
/* APPEND can be executed directly */
result = imap_perform_append(conn);
else if(imap->custom && (selected || !imap->mailbox))
/* Custom command using the same mailbox or no mailbox */
result = imap_perform_list(conn);
else if(!imap->custom && selected && imap->uid)
/* FETCH from the same mailbox */
result = imap_perform_fetch(conn);
else if(!imap->custom && selected && imap->query)
/* SEARCH the current mailbox */
result = imap_perform_search(conn);
else if(imap->mailbox && !selected &&
(imap->custom || imap->uid || imap->query))
/* SELECT the mailbox */
result = imap_perform_select(conn);
else
/* LIST */
result = imap_perform_list(conn);
if(result)
return result;
/* Run the state-machine */
result = imap_multi_statemach(conn, dophase_done);
*connected = conn->bits.tcpconnect[FIRSTSOCKET];
if(*dophase_done)
DEBUGF(infof(conn->data, "DO phase is complete\n"));
return result;
}
/***********************************************************************
*
* imap_do()
*
* This function is registered as 'curl_do' function. It decodes the path
* parts etc as a wrapper to the actual DO function (imap_perform).
*
* The input argument is already checked for validity.
*/
static CURLcode imap_do(struct connectdata *conn, bool *done)
{
CURLcode result = CURLE_OK;
*done = FALSE; /* default to false */
/* Parse the URL path */
result = imap_parse_url_path(conn);
if(result)
return result;
/* Parse the custom request */
result = imap_parse_custom_request(conn);
if(result)
return result;
result = imap_regular_transfer(conn, done);
return result;
}
/***********************************************************************
*
* imap_disconnect()
*
* Disconnect from an IMAP server. Cleanup protocol-specific per-connection
* resources. BLOCKING.
*/
static CURLcode imap_disconnect(struct connectdata *conn, bool dead_connection)
{
struct imap_conn *imapc = &conn->proto.imapc;
/* We cannot send quit unconditionally. If this connection is stale or
bad in any way, sending quit and waiting around here will make the
disconnect wait in vain and cause more problems than we need to. */
/* The IMAP session may or may not have been allocated/setup at this
point! */
if(!dead_connection && imapc->pp.conn && imapc->pp.conn->bits.protoconnstart)
if(!imap_perform_logout(conn))
(void)imap_block_statemach(conn); /* ignore errors on LOGOUT */
/* Disconnect from the server */
Curl_pp_disconnect(&imapc->pp);
/* Cleanup the SASL module */
Curl_sasl_cleanup(conn, imapc->sasl.authused);
/* Cleanup our connection based variables */
Curl_safefree(imapc->mailbox);
Curl_safefree(imapc->mailbox_uidvalidity);
return CURLE_OK;
}
/* Call this when the DO phase has completed */
static CURLcode imap_dophase_done(struct connectdata *conn, bool connected)
{
struct IMAP *imap = conn->data->req.protop;
(void)connected;
if(imap->transfer != FTPTRANSFER_BODY)
/* no data to transfer */
Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL);
return CURLE_OK;
}
/* Called from multi.c while DOing */
static CURLcode imap_doing(struct connectdata *conn, bool *dophase_done)
{
CURLcode result = imap_multi_statemach(conn, dophase_done);
if(result)
DEBUGF(infof(conn->data, "DO phase failed\n"));
else if(*dophase_done) {
result = imap_dophase_done(conn, FALSE /* not connected */);
DEBUGF(infof(conn->data, "DO phase is complete\n"));
}
return result;
}
/***********************************************************************
*
* imap_regular_transfer()
*
* The input argument is already checked for validity.
*
* Performs all commands done before a regular transfer between a local and a
* remote host.
*/
static CURLcode imap_regular_transfer(struct connectdata *conn,
bool *dophase_done)
{
CURLcode result = CURLE_OK;
bool connected = FALSE;
struct Curl_easy *data = conn->data;
/* Make sure size is unknown at this point */
data->req.size = -1;
/* Set the progress data */
Curl_pgrsSetUploadCounter(data, 0);
Curl_pgrsSetDownloadCounter(data, 0);
Curl_pgrsSetUploadSize(data, -1);
Curl_pgrsSetDownloadSize(data, -1);
/* Carry out the perform */
result = imap_perform(conn, &connected, dophase_done);
/* Perform post DO phase operations if necessary */
if(!result && *dophase_done)
result = imap_dophase_done(conn, connected);
return result;
}
static CURLcode imap_setup_connection(struct connectdata *conn)
{
struct Curl_easy *data = conn->data;
/* Initialise the IMAP layer */
CURLcode result = imap_init(conn);
if(result)
return result;
/* Clear the TLS upgraded flag */
conn->tls_upgraded = FALSE;
/* Set up the proxy if necessary */
if(conn->bits.httpproxy && !data->set.tunnel_thru_httpproxy) {
/* Unless we have asked to tunnel IMAP operations through the proxy, we
switch and use HTTP operations only */
#ifndef CURL_DISABLE_HTTP
if(conn->handler == &Curl_handler_imap)
conn->handler = &Curl_handler_imap_proxy;
else {
#ifdef USE_SSL
conn->handler = &Curl_handler_imaps_proxy;
#else
failf(data, "IMAPS not supported!");
return CURLE_UNSUPPORTED_PROTOCOL;
#endif
}
/* set it up as an HTTP connection instead */
return conn->handler->setup_connection(conn);
#else
failf(data, "IMAP over http proxy requires HTTP support built-in!");
return CURLE_UNSUPPORTED_PROTOCOL;
#endif
}
data->state.path++; /* don't include the initial slash */
return CURLE_OK;
}
/***********************************************************************
*
* imap_sendf()
*
* Sends the formatted string as an IMAP command to the server.
*
* Designed to never block.
*/
static CURLcode imap_sendf(struct connectdata *conn, const char *fmt, ...)
{
CURLcode result = CURLE_OK;
struct imap_conn *imapc = &conn->proto.imapc;
char *taggedfmt;
va_list ap;
DEBUGASSERT(fmt);
/* Calculate the next command ID wrapping at 3 digits */
imapc->cmdid = (imapc->cmdid + 1) % 1000;
/* Calculate the tag based on the connection ID and command ID */
snprintf(imapc->resptag, sizeof(imapc->resptag), "%c%03d",
'A' + curlx_sltosi(conn->connection_id % 26), imapc->cmdid);
/* Prefix the format with the tag */
taggedfmt = aprintf("%s %s", imapc->resptag, fmt);
if(!taggedfmt)
return CURLE_OUT_OF_MEMORY;
/* Send the data with the tag */
va_start(ap, fmt);
result = Curl_pp_vsendf(&imapc->pp, taggedfmt, ap);
va_end(ap);
free(taggedfmt);
return result;
}
/***********************************************************************
*
* imap_atom()
*
* Checks the input string for characters that need escaping and returns an
* atom ready for sending to the server.
*
* The returned string needs to be freed.
*
*/
static char *imap_atom(const char *str, bool escape_only)
{
/* !checksrc! disable PARENBRACE 1 */
const char atom_specials[] = "(){ %*]";
const char *p1;
char *p2;
size_t backsp_count = 0;
size_t quote_count = 0;
bool others_exists = FALSE;
size_t newlen = 0;
char *newstr = NULL;
if(!str)
return NULL;
/* Look for "atom-specials", counting the backslash and quote characters as
these will need escapping */
p1 = str;
while(*p1) {
if(*p1 == '\\')
backsp_count++;
else if(*p1 == '"')
quote_count++;
else if(!escape_only) {
const char *p3 = atom_specials;
while(*p3 && !others_exists) {
if(*p1 == *p3)
others_exists = TRUE;
p3++;
}
}
p1++;
}
/* Does the input contain any "atom-special" characters? */
if(!backsp_count && !quote_count && !others_exists)
return strdup(str);
/* Calculate the new string length */
newlen = strlen(str) + backsp_count + quote_count + (others_exists ? 2 : 0);
/* Allocate the new string */
newstr = (char *) malloc((newlen + 1) * sizeof(char));
if(!newstr)
return NULL;
/* Surround the string in quotes if necessary */
p2 = newstr;
if(others_exists) {
newstr[0] = '"';
newstr[newlen - 1] = '"';
p2++;
}
/* Copy the string, escaping backslash and quote characters along the way */
p1 = str;
while(*p1) {
if(*p1 == '\\' || *p1 == '"') {
*p2 = '\\';
p2++;
}
*p2 = *p1;
p1++;
p2++;
}
/* Terminate the string */
newstr[newlen] = '\0';
return newstr;
}
/***********************************************************************
*
* imap_is_bchar()
*
* Portable test of whether the specified char is a "bchar" as defined in the
* grammar of RFC-5092.
*/
static bool imap_is_bchar(char ch)
{
switch(ch) {
/* bchar */
case ':': case '@': case '/':
/* bchar -> achar */
case '&': case '=':
/* bchar -> achar -> uchar -> unreserved */
case '0': case '1': case '2': case '3': case '4': case '5': case '6':
case '7': case '8': case '9':
case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N':
case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U':
case 'V': case 'W': case 'X': case 'Y': case 'Z':
case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u':
case 'v': case 'w': case 'x': case 'y': case 'z':
case '-': case '.': case '_': case '~':
/* bchar -> achar -> uchar -> sub-delims-sh */
case '!': case '$': case '\'': case '(': case ')': case '*':
case '+': case ',':
/* bchar -> achar -> uchar -> pct-encoded */
case '%': /* HEXDIG chars are already included above */
return true;
default:
return false;
}
}
/***********************************************************************
*
* imap_parse_url_options()
*
* Parse the URL login options.
*/
static CURLcode imap_parse_url_options(struct connectdata *conn)
{
CURLcode result = CURLE_OK;
struct imap_conn *imapc = &conn->proto.imapc;
const char *ptr = conn->options;
imapc->sasl.resetprefs = TRUE;
while(!result && ptr && *ptr) {
const char *key = ptr;
const char *value;
while(*ptr && *ptr != '=')
ptr++;
value = ptr + 1;
while(*ptr && *ptr != ';')
ptr++;
if(strncasecompare(key, "AUTH=", 5))
result = Curl_sasl_parse_url_auth_option(&imapc->sasl,
value, ptr - value);
else
result = CURLE_URL_MALFORMAT;
if(*ptr == ';')
ptr++;
}
switch(imapc->sasl.prefmech) {
case SASL_AUTH_NONE:
imapc->preftype = IMAP_TYPE_NONE;
break;
case SASL_AUTH_DEFAULT:
imapc->preftype = IMAP_TYPE_ANY;
break;
default:
imapc->preftype = IMAP_TYPE_SASL;
break;
}
return result;
}
/***********************************************************************
*
* imap_parse_url_path()
*
* Parse the URL path into separate path components.
*
*/
static CURLcode imap_parse_url_path(struct connectdata *conn)
{
/* The imap struct is already initialised in imap_connect() */
CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
struct IMAP *imap = data->req.protop;
const char *begin = data->state.path;
const char *ptr = begin;
/* See how much of the URL is a valid path and decode it */
while(imap_is_bchar(*ptr))
ptr++;
if(ptr != begin) {
/* Remove the trailing slash if present */
const char *end = ptr;
if(end > begin && end[-1] == '/')
end--;
result = Curl_urldecode(data, begin, end - begin, &imap->mailbox, NULL,
TRUE);
if(result)
return result;
}
else
imap->mailbox = NULL;
/* There can be any number of parameters in the form ";NAME=VALUE" */
while(*ptr == ';') {
char *name;
char *value;
size_t valuelen;
/* Find the length of the name parameter */
begin = ++ptr;
while(*ptr && *ptr != '=')
ptr++;
if(!*ptr)
return CURLE_URL_MALFORMAT;
/* Decode the name parameter */
result = Curl_urldecode(data, begin, ptr - begin, &name, NULL, TRUE);
if(result)
return result;
/* Find the length of the value parameter */
begin = ++ptr;
while(imap_is_bchar(*ptr))
ptr++;
/* Decode the value parameter */
result = Curl_urldecode(data, begin, ptr - begin, &value, &valuelen, TRUE);
if(result) {
free(name);
return result;
}
DEBUGF(infof(conn->data, "IMAP URL parameter '%s' = '%s'\n", name, value));
/* Process the known hierarchical parameters (UIDVALIDITY, UID, SECTION and
PARTIAL) stripping of the trailing slash character if it is present.
Note: Unknown parameters trigger a URL_MALFORMAT error. */
if(strcasecompare(name, "UIDVALIDITY") && !imap->uidvalidity) {
if(valuelen > 0 && value[valuelen - 1] == '/')
value[valuelen - 1] = '\0';
imap->uidvalidity = value;
value = NULL;
}
else if(strcasecompare(name, "UID") && !imap->uid) {
if(valuelen > 0 && value[valuelen - 1] == '/')
value[valuelen - 1] = '\0';
imap->uid = value;
value = NULL;
}
else if(strcasecompare(name, "SECTION") && !imap->section) {
if(valuelen > 0 && value[valuelen - 1] == '/')
value[valuelen - 1] = '\0';
imap->section = value;
value = NULL;
}
else if(strcasecompare(name, "PARTIAL") && !imap->partial) {
if(valuelen > 0 && value[valuelen - 1] == '/')
value[valuelen - 1] = '\0';
imap->partial = value;
value = NULL;
}
else {
free(name);
free(value);
return CURLE_URL_MALFORMAT;
}
free(name);
free(value);
}
/* Does the URL contain a query parameter? Only valid when we have a mailbox
and no UID as per RFC-5092 */
if(imap->mailbox && !imap->uid && *ptr == '?') {
/* Find the length of the query parameter */
begin = ++ptr;
while(imap_is_bchar(*ptr))
ptr++;
/* Decode the query parameter */
result = Curl_urldecode(data, begin, ptr - begin, &imap->query, NULL,
TRUE);
if(result)
return result;
}
/* Any extra stuff at the end of the URL is an error */
if(*ptr)
return CURLE_URL_MALFORMAT;
return CURLE_OK;
}
/***********************************************************************
*
* imap_parse_custom_request()
*
* Parse the custom request.
*/
static CURLcode imap_parse_custom_request(struct connectdata *conn)
{
CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
struct IMAP *imap = data->req.protop;
const char *custom = data->set.str[STRING_CUSTOMREQUEST];
if(custom) {
/* URL decode the custom request */
result = Curl_urldecode(data, custom, 0, &imap->custom, NULL, TRUE);
/* Extract the parameters if specified */
if(!result) {
const char *params = imap->custom;
while(*params && *params != ' ')
params++;
if(*params) {
imap->custom_params = strdup(params);
imap->custom[params - imap->custom] = '\0';
if(!imap->custom_params)
result = CURLE_OUT_OF_MEMORY;
}
}
}
return result;
}
#endif /* CURL_DISABLE_IMAP */
| {
"pile_set_name": "Github"
} |
# Event 4202 - SqlCommandExecute
###### Version: 0
## Description
None
## Data Dictionary
|Standard Name|Field Name|Type|Description|Sample Value|
|---|---|---|---|---|
|TBD|data1|UnicodeString|None|`None`|
|TBD|AppDomain|UnicodeString|None|`None`|
## Tags
* etw_level_Verbose
* etw_keywords_WFInstanceStore
* etw_opcode_Start
* etw_task_SqlCommandExecute | {
"pile_set_name": "Github"
} |
"""IETF usage guidelines plugin
See RFC 8407
"""
import optparse
import sys
import re
from pyang import plugin
from pyang import statements
from pyang import error
from pyang.error import err_add
from pyang.plugins import lint
def pyang_plugin_init():
plugin.register_plugin(IETFPlugin())
class IETFPlugin(lint.LintPlugin):
def __init__(self):
self.found_2119_keywords = False
self.found_8174 = False
self.found_tlp = False
self.mmap = {}
lint.LintPlugin.__init__(self)
self.namespace_prefixes = ['urn:ietf:params:xml:ns:yang:']
self.modulename_prefixes = ['ietf', 'iana']
def add_opts(self, optparser):
optlist = [
optparse.make_option("--ietf",
dest="ietf",
action="store_true",
help="Validate the module(s) according to " \
"IETF rules."),
optparse.make_option("--ietf-help",
dest="ietf_help",
action="store_true",
help="Print help on the IETF checks and exit"),
]
optparser.add_options(optlist)
def setup_ctx(self, ctx):
if ctx.opts.ietf_help:
print_help()
sys.exit(0)
if not ctx.opts.ietf:
return
self._setup_ctx(ctx)
statements.add_validation_fun(
'grammar', ['description'],
lambda ctx, s: self.v_chk_description(ctx, s))
# register our error codes
error.add_error_code(
'IETF_MISSING_RFC8174', 4,
'the module seems to use RFC 2119 keywords, but the required'
+ ' text from RFC 8174 is not found'
+ ' (see pyang --ietf-help for details).')
error.add_error_code(
'IETF_MISSING_TRUST_LEGAL_PROVISIONING', 4,
'RFC 8407: 3.1: '
+ 'The IETF Trust Copyright statement seems to be'
+ ' missing (see pyang --ietf-help for details).')
def pre_validate_ctx(self, ctx, modules):
for mod in modules:
self.mmap[mod.arg] = {
'found_2119_keywords': False,
'found_8174': False}
def v_chk_description(self, ctx, s):
if s.i_module.arg not in self.mmap:
return
arg = re.sub(r'\s+', ' ', s.arg)
if s.parent.keyword == 'module' or s.parent.keyword == 'submodule':
m = re_rfc8174.search(arg)
if m is not None:
self.mmap[s.i_module.arg]['found_8174'] = True
arg = arg[:m.start()] + arg[m.end():]
if re_tlp.search(arg) is None:
err_add(ctx.errors, s.pos,
'IETF_MISSING_TRUST_LEGAL_PROVISIONING', ())
if not self.mmap[s.i_module.arg]['found_2119_keywords']:
if re_2119_keywords.search(arg) is not None:
self.mmap[s.i_module.arg]['found_2119_keywords'] = True
self.mmap[s.i_module.arg]['description_pos'] = s.pos
def post_validate_ctx(self, ctx, modules):
if not ctx.opts.ietf:
return
for mod in modules:
if (self.mmap[mod.arg]['found_2119_keywords']
and not self.mmap[mod.arg]['found_8174']):
pos = self.mmap[mod.arg]['description_pos']
err_add(ctx.errors, pos, 'IETF_MISSING_RFC8174', ())
def print_help():
print("""
Validates the module or submodule according to the IETF rules found
in RFC 8407.
The module's or submodule's description statement must contain the
following text:
Copyright (c) <year> IETF Trust and the persons identified as
authors of the code. All rights reserved.
Redistribution and use in source and binary forms, with or
without modification, is permitted pursuant to, and subject to
the license terms contained in, the Simplified BSD License set
forth in Section 4.c of the IETF Trust's Legal Provisions
Relating to IETF Documents
(https://trustee.ietf.org/license-info).
This version of this YANG module is part of RFC XXXX
(https://www.rfc-editor.org/info/rfcXXXX); see the RFC itself
for full legal notices.
If any description statement in the module or submodule contains
RFC 2119 key words, the module's or submodule's description statement
must contain the following text:
The key words 'MUST', 'MUST NOT', 'REQUIRED', 'SHALL', 'SHALL
NOT', 'SHOULD', 'SHOULD NOT', 'RECOMMENDED', 'NOT RECOMMENDED',
'MAY', and 'OPTIONAL' in this document are to be interpreted as
described in BCP 14 (RFC 2119) (RFC 8174) when, and only when,
they appear in all capitals, as shown here.
""")
rfc8174_str = \
r"""The key words 'MUST', 'MUST NOT', 'REQUIRED', 'SHALL', 'SHALL
NOT', 'SHOULD', 'SHOULD NOT', 'RECOMMENDED', 'NOT RECOMMENDED',
'MAY', and 'OPTIONAL' in this document are to be interpreted as
described in BCP 14 \(RFC 2119\) \(RFC 8174\) when, and only when,
they appear in all capitals, as shown here."""
re_rfc8174 = re.compile(re.sub(r'\s+', ' ', rfc8174_str))
tlp_str = \
r"""Copyright \(c\) [0-9]+ IETF Trust and the persons identified as
authors of the code\. All rights reserved\.
Redistribution and use in source and binary forms, with or
without modification, is permitted pursuant to, and subject
to the license terms contained in, the Simplified BSD License
set forth in Section 4\.c of the IETF Trust's Legal Provisions
Relating to IETF Documents
\(https?://trustee.ietf.org/license-info\)\.
This version of this YANG module is part of
RFC .+(\s+\(https?://www.rfc-editor.org/info/rfc.+\))?; see
the RFC itself for full legal notices\."""
re_tlp = re.compile(re.sub(r'\s+', ' ', tlp_str))
re_2119_keywords = re.compile(
r"\b(MUST|REQUIRED|SHOULD|SHALL|RECOMMENDED|MAY|OPTIONAL)\b")
| {
"pile_set_name": "Github"
} |
/* 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.flowable.http.common.impl;
import static org.assertj.core.api.Assertions.assertThat;
import org.flowable.http.common.api.HttpRequest;
import org.flowable.http.common.api.client.ExecutableHttpRequest;
import org.flowable.http.common.api.client.FlowableHttpClient;
import org.flowable.http.common.impl.apache.ApacheHttpComponentsFlowableHttpClient;
import org.junit.jupiter.api.Test;
/**
* @author Filip Hrisafov
*/
class HttpClientConfigTest {
@Test
void determineHttpClientWhenSet() {
HttpClientConfig config = new HttpClientConfig();
FlowableHttpClient httpClient = new FlowableHttpClient() {
@Override
public ExecutableHttpRequest prepareRequest(HttpRequest request) {
return null;
}
};
config.setHttpClient(httpClient);
assertThat(config.determineHttpClient()).isEqualTo(httpClient);
}
@Test
void determineHttpClientWhenNotSet() {
HttpClientConfig config = new HttpClientConfig();
assertThat(config.determineHttpClient()).isInstanceOf(ApacheHttpComponentsFlowableHttpClient.class);
}
}
| {
"pile_set_name": "Github"
} |
<?php
/**
* CodeIgniter
*
* An open source application development framework for PHP
*
* This content is released under the MIT License (MIT)
*
* Copyright (c) 2014-2019 British Columbia Institute of Technology
* Copyright (c) 2019-2020 CodeIgniter Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @package CodeIgniter
* @author CodeIgniter Dev Team
* @copyright 2019-2020 CodeIgniter Foundation
* @license https://opensource.org/licenses/MIT MIT License
* @link https://codeigniter.com
* @since Version 4.0.0
* @filesource
*/
namespace CodeIgniter\Log\Handlers;
/**
* Expected behavior for a Log handler
*/
interface HandlerInterface
{
/**
* Handles logging the message.
* If the handler returns false, then execution of handlers
* will stop. Any handlers that have not run, yet, will not
* be run.
*
* @param $level
* @param $message
*
* @return boolean
*/
public function handle($level, $message): bool;
//--------------------------------------------------------------------
/**
* Checks whether the Handler will handle logging items of this
* log Level.
*
* @param string $level
*
* @return boolean
*/
public function canHandle(string $level): bool;
//--------------------------------------------------------------------
/**
* Sets the preferred date format to use when logging.
*
* @param string $format
*
* @return HandlerInterface
*/
public function setDateFormat(string $format);
//--------------------------------------------------------------------
}
| {
"pile_set_name": "Github"
} |
#include <gpd/util/eigen_utils.h>
namespace gpd {
namespace util {
Eigen::Matrix3Xd EigenUtils::sliceMatrix(const Eigen::Matrix3Xd &mat,
const std::vector<int> &indices) {
Eigen::Matrix3Xd mat_out(3, indices.size());
for (int j = 0; j < indices.size(); j++) {
mat_out.col(j) = mat.col(indices[j]);
}
return mat_out;
}
Eigen::MatrixXi EigenUtils::sliceMatrix(const Eigen::MatrixXi &mat,
const std::vector<int> &indices) {
Eigen::MatrixXi mat_out(mat.rows(), indices.size());
for (int j = 0; j < indices.size(); j++) {
mat_out.col(j) = mat.col(indices[j]);
}
return mat_out;
}
Eigen::Vector3i EigenUtils::floorVector(const Eigen::Vector3f &a) {
Eigen::Vector3i b;
b << floor(a(0)), floor(a(1)), floor(a(2));
return b;
}
} // namespace util
} // namespace gpd
| {
"pile_set_name": "Github"
} |
import { AppProps } from "next/app";
import { hydrate, setup } from "otion";
import * as React from "react";
import options from "../otion.config";
if (typeof window !== "undefined") {
setup(options);
hydrate();
}
export default function MyApp({ Component, pageProps }: AppProps): JSX.Element {
return <Component {...pageProps} />;
}
| {
"pile_set_name": "Github"
} |
#!/bin/sh
ENABLED=yes
PROCS=motion
ARGS=""
PREARGS=""
DESC=$PROCS
PATH=/opt/sbin:/opt/bin:/opt/usr/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
. /opt/etc/init.d/rc.func
| {
"pile_set_name": "Github"
} |
namespace Storage.Net
{
/// <summary>
/// Helper syntax for creating instances of storage library objects
/// </summary>
public static class StorageFactory
{
private static readonly IKeyValueStorageFactory _tables = new InternalTablesFactory();
private static readonly IBlobStorageFactory _blobs = new InternalBlobsFactory();
private static readonly IMessagingFactory _messages = new InternalMessagingFactory();
private static readonly IModulesFactory _moduleInit = new InternalModuleInitFactory();
private static readonly IConnectionStringFactory _css = new InternalConnectionStringFactory();
/// <summary>
/// Access to creating tables
/// </summary>
public static IKeyValueStorageFactory KeyValue => _tables;
/// <summary>
/// Access to creating blobs
/// </summary>
public static IBlobStorageFactory Blobs => _blobs;
/// <summary>
/// Access to creating messaging
/// </summary>
public static IMessagingFactory Messages => _messages;
/// <summary>
/// Module initialisation
/// </summary>
public static IModulesFactory Modules => _moduleInit;
/// <summary>
/// Connection strings
/// </summary>
public static IConnectionStringFactory ConnectionStrings => _css;
class InternalTablesFactory : IKeyValueStorageFactory
{
}
class InternalBlobsFactory : IBlobStorageFactory
{
}
class InternalMessagingFactory : IMessagingFactory
{
}
class InternalModuleInitFactory : IModulesFactory
{
}
class InternalConnectionStringFactory : IConnectionStringFactory
{
}
}
/// <summary>
/// Crates blob storage implementations
/// </summary>
public interface IBlobStorageFactory
{
}
/// <summary>
/// Creates messaging implementations
/// </summary>
public interface IMessagingFactory
{
}
/// <summary>
/// Crates table storage implementations
/// </summary>
public interface IKeyValueStorageFactory
{
}
/// <summary>
/// Creates connection strings, acts as a helper
/// </summary>
public interface IConnectionStringFactory
{
}
/// <summary>
/// Module initialisation primitives
/// </summary>
public interface IModulesFactory
{
}
} | {
"pile_set_name": "Github"
} |
module.exports = {
siteMetadata: {
title: "Reflex",
description: "Reflex site",
siteUrl: process.env.SITE_URL || "http://localhost:8000",
},
plugins: [
`@reflexjs/gatsby-theme-base`,
`@reflexjs/gatsby-theme-post`,
`@reflexjs/gatsby-theme-video`,
],
}
| {
"pile_set_name": "Github"
} |
<?php
namespace devilbox;
/**
* @requires devilbox::Logger
*/
class Helper
{
/*********************************************************************************
*
* Statics
*
*********************************************************************************/
/**
* Environmental variables from PHP docker
* @var array
*/
private static $_env = null;
/**
* Hostname to IP addresses
* @var array
*/
private static $_ip_address = null;
/**
* Class instance
* @var object
*/
private static $_instance = null;
/**
* Generic singleton instance getter.
* Make sure to overwrite this in your class
* for a more complex initialization.
*
* @param string $hostname Hostname
* @param array $data Additional data (if required)
* @return object|null
*/
public static function getInstance()
{
if (self::$_instance === null) {
self::$_instance = new self();
}
return self::$_instance;
}
/*********************************************************************************
*
* Private constructor for singleton
*
*********************************************************************************/
/**
* DO NOT CALL ME!
* Use singleton getInstance() instead.
*/
private function __construct()
{
}
/*********************************************************************************
*
* Public Helper Functions
*
*********************************************************************************/
/**
* Get Docker environment variables from docker-compose.yml
* Only values from php docker can be retrieved here, so make
* sure they are passed to it.
*
* Values are cached in static context.
*
* @param string $variable Variable name
* @return string Variable value
*/
public function getEnv($variable)
{
if (self::$_env === null) {
$output = array();
// Translate PHP Docker environmental variables to $ENV
exec('/usr/bin/env', $output);
foreach ($output as $var) {
$tmp = explode('=', $var);
self::$_env[$tmp[0]] = $tmp[1];
}
}
if (!isset(self::$_env[$variable])) {
loadClass('Logger')->error('Environment variable not found: \''.$variable.'\'');
return null;
}
return self::$_env[$variable];
}
/**
* Retrieve the IP address of the container.
*
* @return string|boolean IP address or false
*/
public function getIpAddress($hostname)
{
// Request was already done before and is cached
if (isset(self::$_ip_address[$hostname])) {
return self::$_ip_address[$hostname];
}
// New request, generic check
// Note the traiing dot to prevent recursive lookups
//$ip = $this->exec('ping -c 1 '.$hostname.'. 2>/dev/null | grep -Eo \'[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\' | head -1');
$ip = gethostbyname($hostname.'');
if (filter_var($ip, FILTER_VALIDATE_IP) === false) {
//loadClass('Logger')->error('Retrieving the IP address of host \''.$hostname.'\' failed: '.$ip);
self::$_ip_address[$hostname] = false;
} else {
self::$_ip_address[$hostname] = $ip;
}
return self::$_ip_address[$hostname];
}
/**
* Shorter version to regex select a string.
*
* @param string $regex Regex
* @param string $string String to look in to
* @return bool|string Returns false on error otherwise the string
*/
public function egrep($regex, $string)
{
$match = array();
$error = preg_match($regex, $string, $match);
if ($error === false) {
loadClass('Logger')->error('Error matching regex: \''.$regex. '\' in string: \''.$string.'\'');
return false;
}
return isset($match[0]) ? $match[0] : false;
}
/**
* Executes shell commands on the PHP-FPM Host
*
* @param string $cmd Command
* @param integer $exit_code Reference to exit code
* @return string
*/
public function exec($cmd, &$exit_code = -1)
{
$output = array();
exec($cmd, $output, $exit_code);
return implode ("\n", $output);
}
public function redirect($url)
{
header('Location: '.$url);
exit;
}
/*********************************************************************************
*
* Login Helper Functions
*
*********************************************************************************/
public function login($username, $password)
{
$dvl_password = loadClass('Helper')->getEnv('DEVILBOX_UI_PASSWORD');
if ($username == 'devilbox' && $password == $dvl_password) {
$_SESSION['auth'] = 1;
return true;
}
return false;
}
public function logout()
{
if (isset($_SESSION['auth'])) {
$_SESSION['auth'] = 0;
unset($_SESSION['auth']);
}
}
public function isLoginProtected()
{
// No password protection enabled
if (loadClass('Helper')->getEnv('DEVILBOX_UI_PROTECT') != 1) {
return false;
}
return true;
}
public function isloggedIn()
{
// No password protection enabled
if (!$this->isLoginProtected()) {
return true;
}
// Alredy logged in
if (isset($_SESSION['auth']) && $_SESSION['auth'] == 1) {
return true;
}
return false;
}
public function authPage()
{
if (!$this->isloggedIn()) {
$this->redirect('/login.php');
}
}
}
| {
"pile_set_name": "Github"
} |
{% extends 'ace_common/edx_ace/common/base_body.html' %}
{% load i18n %}
{% load static %}
{% block content %}
<table width="100%" align="left" border="0" cellpadding="0" cellspacing="0" role="presentation">
<tr>
<td>
<h1>
{% trans "Password Reset" as tmsg %}{{ tmsg | force_escape }}
</h1>
<p style="color: rgba(0,0,0,.75);">
{% filter force_escape %}
{% blocktrans %}You're receiving this e-mail because you requested a password reset for your user account at {{ platform_name }}.{% endblocktrans %}
{% endfilter %}
<br />
</p>
{% if failed %}
<p style="color: rgba(0,0,0,.75);">
{% filter force_escape %}
{% blocktrans %}However, there is currently no user account associated with your email address: {{ email_address }}.{% endblocktrans %}
{% endfilter %}
<br />
</p>
<p style="color: rgba(0,0,0,.75);">
{% trans "If you did not request this change, you can ignore this email." as tmsg %}{{ tmsg | force_escape }}
<br />
</p>
{% else %}
<p style="color: rgba(0,0,0,.75);">
{% trans "If you didn't request this change, you can disregard this email - we have not yet reset your password." as tmsg %}{{ tmsg | force_escape }}
<br />
</p>
{# xss-lint: disable=django-trans-missing-escape #}
{% trans "Change my Password" as course_cta_text %}
{# email client support for style sheets is pretty spotty, so we have to inline all of these styles #}
<a href="{{ reset_link }}" style="
color: #ffffff;
text-decoration: none;
border-radius: 4px;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
background-color: #005686;
border-top: 12px solid #005686;
border-bottom: 12px solid #005686;
border-right: 50px solid #005686;
border-left: 50px solid #005686;
display: inline-block;
">
{# old email clients require the use of the font tag :( #}
<font color="#ffffff"><b>{{ course_cta_text }}</b></font>
</a>
{% endif %}
</td>
</tr>
</table>
{% endblock %}
| {
"pile_set_name": "Github"
} |
// Promise testing support
angular.module('ngMock')
.config(function ($provide) {
$provide.decorator('$q', function ($delegate, $rootScope) {
$delegate.flush = function() {
$rootScope.$digest();
};
// Add callbacks to the promise that expose the resolved value/error
function expose(promise) {
// Don't add hooks to the same promise twice (shouldn't happen anyway)
if (!promise.hasOwnProperty('$$resolved')) {
promise.$$resolved = false;
promise.then(function (value) {
promise.$$resolved = { success: true, value: value };
}, function (error) {
promise.$$resolved = { success: false, error: error };
});
// We need to expose() any then()ed promises recursively
var qThen = promise.then;
promise.then = function () {
return expose(qThen.apply(this, arguments));
};
}
return promise;
}
// Wrap functions that return a promise
angular.forEach([ 'when', 'all', 'reject'], function (name) {
var qFunc = $delegate[name];
$delegate[name] = function () {
return expose(qFunc.apply(this, arguments));
};
});
// Wrap defer()
var qDefer = $delegate.defer;
$delegate.defer = function () {
var deferred = qDefer();
expose(deferred.promise);
return deferred;
}
return $delegate;
});
});
function testablePromise(promise) {
if (!promise || !promise.then) throw new Error('Expected a promise, but got ' + jasmine.pp(promise) + '.');
if (!isDefined(promise.$$resolved)) throw new Error('Promise has not been augmented by ngMock');
return promise;
}
function resolvedPromise(promise) {
var result = testablePromise(promise).$$resolved;
if (!result) throw new Error('Promise is not resolved yet');
return result;
}
function resolvedValue(promise) {
var result = resolvedPromise(promise);
if (!result.success) throw result.error;
return result.value;
}
function resolvedError(promise) {
var result = resolvedPromise(promise);
if (result.success) throw new Error('Promise was expected to fail but returned ' + jasmin.pp(res.value) + '.');
return result.error;
}
beforeEach(function () {
this.addMatchers({
toBeResolved: function() {
return !!testablePromise(this.actual).$$resolved;
}
});
});
// Misc test utils
function caught(fn) {
try {
fn();
return null;
} catch (e) {
return e;
}
}
// Utils for test from core angular
var noop = angular.noop,
toJson = angular.toJson;
beforeEach(module('ui.router.compat'));
| {
"pile_set_name": "Github"
} |
namespace Merchello.Tests.IntegrationTests.EntityCollections
{
using System;
using System.Linq;
using Merchello.Core;
using Merchello.Core.EntityCollections;
using Merchello.Core.EntityCollections.Providers;
using Merchello.Core.Models;
using Merchello.Core.Services;
using Merchello.Tests.Base.DataMakers;
using Merchello.Tests.Base.TestHelpers;
using NUnit.Framework;
[TestFixture]
public class StaticInvoiceCollectionProviderTests : MerchelloAllInTestBase
{
private IEntityCollectionService _entityCollectionService;
private IInvoiceService _invoiceService;
private Guid _providerKey;
private IEntityCollectionProviderResolver _resolver;
[TestFixtureSetUp]
public override void FixtureSetup()
{
base.FixtureSetup();
_entityCollectionService = DbPreTestDataWorker.EntityCollectionService;
_invoiceService = DbPreTestDataWorker.InvoiceService;
_resolver = EntityCollectionProviderResolver.Current;
_providerKey = _resolver.GetProviderKey<StaticInvoiceCollectionProvider>();
}
[SetUp]
public void Setup()
{
DbPreTestDataWorker.DeleteAllEntityCollections();
DbPreTestDataWorker.DeleteAllInvoices();
}
[Test]
public void Can_Create_An_Entity_Collection()
{
//// Arrage
//// Act
var collection = _entityCollectionService.CreateEntityCollectionWithKey(
EntityType.Invoice,
_providerKey,
"Test Collection");
//// Assert
Assert.NotNull(collection);
Assert.IsTrue(collection.HasIdentity);
Assert.AreEqual("Test Collection", collection.Name);
var provider = collection.ResolveProvider();
Assert.NotNull(provider);
Assert.IsTrue(provider.GetManagedCollections().Any());
}
[Test]
public void Can_Add_Invoices_To_Collections()
{
//// Arrange
var billTo = new Address() { Address1 = "test", CountryCode = "US", PostalCode = "11111" };
var invoice = _invoiceService.CreateInvoice(Core.Constants.InvoiceStatus.Unpaid);
invoice.SetBillingAddress(billTo);
_invoiceService.Save(invoice);
var invoice2 = _invoiceService.CreateInvoice(Core.Constants.InvoiceStatus.Unpaid);
invoice2.SetBillingAddress(billTo);
_invoiceService.Save(invoice2);
var invoice3 = _invoiceService.CreateInvoice(Core.Constants.InvoiceStatus.Unpaid);
_invoiceService.Save(invoice3);
invoice3.SetBillingAddress(billTo);
var invoice4 = _invoiceService.CreateInvoice(Core.Constants.InvoiceStatus.Unpaid);
invoice4.SetBillingAddress(billTo);
_invoiceService.Save(invoice4);
var collection1 = _entityCollectionService.CreateEntityCollectionWithKey(
EntityType.Invoice,
_providerKey,
"Invoice Collection1");
var provider1 = collection1.ResolveProvider<StaticInvoiceCollectionProvider>();
Assert.NotNull(provider1);
Assert.AreEqual(typeof(StaticInvoiceCollectionProvider), provider1.GetType());
var collection2 = _entityCollectionService.CreateEntityCollectionWithKey(
EntityType.Invoice,
_providerKey,
"Invoice Collection2");
var provider2 = collection2.ResolveProvider<StaticInvoiceCollectionProvider>();
Assert.NotNull(provider2);
Assert.AreEqual(typeof(StaticInvoiceCollectionProvider), provider2.GetType());
invoice.AddToCollection(collection1);
invoice2.AddToCollection(collection1);
invoice3.AddToCollection(collection1);
invoice4.AddToCollection(collection1);
invoice3.AddToCollection(collection2);
invoice4.AddToCollection(collection2);
//// Assert
var c1Invoices = collection1.GetEntities<IInvoice>().ToArray();
var c2Invoices = collection2.GetEntities<IInvoice>().ToArray();
Assert.IsTrue(c1Invoices.Any());
Assert.IsTrue(c2Invoices.Any());
Assert.Greater(c1Invoices.Count(), c2Invoices.Count());
var i1 = c1Invoices.First();
Assert.IsTrue(i1.GetCollectionsContaining().Any());
}
[Test]
public void Can_Remove_Invoices_From_A_Collection()
{
//// Arrange
//// Arrange
var billTo = new Address() { Address1 = "test", CountryCode = "US", PostalCode = "11111" };
var invoice = _invoiceService.CreateInvoice(Core.Constants.InvoiceStatus.Unpaid);
invoice.SetBillingAddress(billTo);
_invoiceService.Save(invoice);
var invoice2 = _invoiceService.CreateInvoice(Core.Constants.InvoiceStatus.Unpaid);
invoice2.SetBillingAddress(billTo);
_invoiceService.Save(invoice2);
var invoice3 = _invoiceService.CreateInvoice(Core.Constants.InvoiceStatus.Unpaid);
_invoiceService.Save(invoice3);
invoice3.SetBillingAddress(billTo);
var invoice4 = _invoiceService.CreateInvoice(Core.Constants.InvoiceStatus.Unpaid);
invoice4.SetBillingAddress(billTo);
_invoiceService.Save(invoice4);
var collection1 = _entityCollectionService.CreateEntityCollectionWithKey(
EntityType.Invoice,
_providerKey,
"Invoice Collection1");
invoice.AddToCollection(collection1);
invoice2.AddToCollection(collection1);
invoice3.AddToCollection(collection1);
invoice4.AddToCollection(collection1);
var provider = collection1.ResolveProvider<StaticInvoiceCollectionProvider>();
Assert.NotNull(provider);
//// Act
var cinvoices = collection1.GetEntities<IInvoice>().ToArray();
Assert.AreEqual(4, cinvoices.Count());
var remove = cinvoices.First();
var key = remove.Key;
remove.RemoveFromCollection(collection1);
//// Assert
var afterRemove = collection1.GetEntities<IInvoice>().ToArray();
Assert.AreEqual(3, afterRemove.Count());
Assert.False(afterRemove.Any(x => x.Key == key));
Assert.IsFalse(collection1.Exists(remove));
Assert.IsFalse(remove.GetCollectionsContaining().Any());
}
}
} | {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright (C) 2016 Álinson Santos Xavier <[email protected]>
~
~ This file is part of Loop Habit Tracker.
~
~ Loop Habit Tracker is free software: you can redistribute it and/or modify
~ it under the terms of the GNU General Public License as published by the
~ Free Software Foundation, either version 3 of the License, or (at your
~ option) any later version.
~
~ Loop Habit Tracker is distributed in the hope that it will be useful, but
~ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
~ or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
~ more details.
~
~ You should have received a copy of the GNU General Public License along
~ with this program. If not, see <http://www.gnu.org/licenses/>.
-->
<resources>
<string name="app_name">Loop Habit Tracker</string>
<string name="main_activity_title">Habits</string>
<string name="action_settings">Settings</string>
<string name="edit">Edit</string>
<string name="delete">Delete</string>
<string name="archive">Archive</string>
<string name="unarchive">Unarchive</string>
<string name="add_habit">Add habit</string>
<string name="color_picker_default_title">Change color</string>
<string name="toast_habit_created">Habit created</string>
<string name="toast_habit_deleted">Habits deleted</string>
<string name="toast_habit_changed">Habit changed</string>
<string name="toast_habit_archived">Habits archived</string>
<string name="toast_habit_unarchived">Habits unarchived</string>
<string name="title_activity_show_habit" translatable="false"/>
<string name="overview">Overview</string>
<string name="habit_strength">Habit strength</string>
<string name="history">History</string>
<string name="clear">Clear</string>
<string name="times_every">times in</string>
<string name="days">days</string>
<string name="reminder">Reminder</string>
<string name="save">Save</string>
<string name="streaks">Streaks</string>
<string name="no_habits_found">You have no active habits</string>
<string name="long_press_to_toggle">Press-and-hold to check or uncheck</string>
<string name="reminder_off">Off</string>
<string name="create_habit">Create habit</string>
<string name="edit_habit">Edit habit</string>
<string name="check">Check</string>
<string name="snooze">Later</string>
<string name="intro_title_1">Welcome</string>
<string name="intro_description_1">Loop Habit Tracker helps you create and maintain good habits.</string>
<string name="intro_title_2">Create some new habits</string>
<string name="intro_description_2">Every day, after performing your habit, put a checkmark on the app.</string>
<string name="intro_title_4">Track your progress</string>
<string name="intro_description_4">Detailed graphs show you how your habits improved over time.</string>
<string name="interval_15_minutes">15 minutes</string>
<string name="interval_30_minutes">30 minutes</string>
<string name="interval_1_hour">1 hour</string>
<string name="interval_2_hour">2 hours</string>
<string name="interval_4_hour">4 hours</string>
<string name="interval_8_hour">8 hours</string>
<string name="interval_24_hour">24 hours</string>
<string name="interval_always_ask">Always ask</string>
<string name="interval_custom">Custom...</string>
<string name="pref_toggle_title">Toggle with short press</string>
<string name="pref_toggle_description">Put checkmarks with a single tap instead of press-and-hold. More convenient, but might cause accidental toggles.</string>
<string name="pref_snooze_interval_title">Snooze interval on reminders</string>
<string name="pref_rate_this_app">Rate this app on Google Play</string>
<string name="pref_send_feedback">Send feedback to developer</string>
<string name="pref_view_source_code">View source code at GitHub</string>
<string name="links">Links</string>
<string name="name">Name</string>
<string name="settings">Settings</string>
<string name="snooze_interval">Snooze interval</string>
<string name="select_snooze_delay">Select snooze delay</string>
<string name="hint_title">Did you know?</string>
<string name="hint_drag">To rearrange the entries, press-and-hold on the name of the habit, then drag it to the correct place.</string>
<string name="hint_landscape">You can see more days by putting your phone in landscape mode.</string>
<string name="delete_habits">Delete Habits</string>
<string name="delete_habits_message">The habits will be permanently deleted. This action cannot be undone.</string>
<string name="habit_not_found">Habit deleted / not found</string>
<string name="weekends">Weekends</string>
<string name="any_weekday">Monday to Friday</string>
<string name="any_day">Any day of the week</string>
<string name="select_weekdays">Select days</string>
<string name="export_to_csv">Export as CSV</string>
<string name="done_label">Done</string>
<string name="clear_label">Clear</string>
<string name="select_hours">Select hours</string>
<string name="select_minutes">Select minutes</string>
<string-array name="hints">
<item>@string/hint_drag</item>
<item>@string/hint_landscape</item>
</string-array>
<string name="about">About</string>
<string name="translators">Translators</string>
<string name="developers">Developers</string>
<string name="version_n">Version %s</string>
<string name="frequency">Frequency</string>
<string name="checkmark">Checkmark</string>
<string name="checkmark_stack_widget" formatted="false">Checkmark Stack Widget</string>
<string name="frequency_stack_widget" formatted="false">Frequency Stack Widget</string>
<string name="score_stack_widget" formatted="false">Score Stack Widget</string>
<string name="history_stack_widget" formatted="false">History Stack Widget</string>
<string name="streaks_stack_widget" formatted="false">Streaks Stack Widget</string>
<string name="best_streaks">Best streaks</string>
<string name="every_day">Every day</string>
<string name="every_week">Every week</string>
<string name="help">Help & FAQ</string>
<string name="could_not_export">Failed to export data.</string>
<string name="could_not_import">Failed to import data.</string>
<string name="file_not_recognized">File not recognized.</string>
<string name="habits_imported">Habits imported successfully.</string>
<string name="import_data">Import data</string>
<string name="export_full_backup">Export full backup</string>
<string name="import_data_summary">Supports full backups exported by this app, as well as files generated by Tickmate, HabitBull or Rewire. See FAQ for more information.</string>
<string name="export_as_csv_summary">Generates files that can be opened by spreadsheet software such as Microsoft Excel or OpenOffice Calc. This file cannot be imported back.</string>
<string name="export_full_backup_summary">Generates a file that contains all your data. This file can be imported back.</string>
<string name="bug_report_failed">Failed to generate bug report.</string>
<string name="generate_bug_report">Generate bug report</string>
<string name="troubleshooting">Troubleshooting</string>
<string name="help_translate">Help translate this app</string>
<string name="night_mode">Dark theme</string>
<string name="use_pure_black">Use pure black in dark theme</string>
<string name="pure_black_description">Replaces gray backgrounds with pure black in dark theme. Reduces battery usage in phones with AMOLED display.</string>
<string name="interface_preferences">Interface</string>
<string name="reverse_days">Reverse order of days</string>
<string name="reverse_days_description">Show days in reverse order on the main screen.</string>
<string name="day">Day</string>
<string name="week">Week</string>
<string name="month">Month</string>
<string name="quarter">Quarter</string>
<string name="year">Year</string>
<string name="total">Total</string>
<string name="yes_or_no">Yes or No</string>
<string name="every_x_days">Every %d days</string>
<string name="every_x_weeks">Every %d weeks</string>
<string name="score">Score</string>
<string name="reminder_sound">Reminder sound</string>
<string name="none">None</string>
<string name="filter">Filter</string>
<string name="hide_completed">Hide completed</string>
<string name="hide_archived">Hide archived</string>
<string name="sticky_notifications">Make notifications sticky</string>
<string name="sticky_notifications_description">Prevents notifications from being swiped away.</string>
<string name="led_notifications">Notification light</string>
<string name="led_notifications_description">Shows a blinking light for reminders. Only available in phones with LED notification lights.</string>
<string name="repair_database">Repair database</string>
<string name="database_repaired">Database repaired.</string>
<string name="uncheck">Uncheck</string>
<string name="toggle">Toggle</string>
<string name="action">Action</string>
<string name="habit">Habit</string>
<string name="sort">Sort</string>
<string name="manually">Manually</string>
<string name="by_name">By name</string>
<string name="by_color">By color</string>
<string name="by_score">By score</string>
<string name="export">Export</string>
<string name="long_press_to_edit">Press-and-hold to change the value</string>
<string name="change_value">Change value</string>
<string name="calendar">Calendar</string>
<string name="unit">Unit</string>
<string name="example_question_boolean">e.g. Did you exercise today?</string>
<string name="question">Question</string>
<string name="target">Target</string>
<string name="yes">Yes</string>
<string name="no">No</string>
<string name="customize_notification_summary">Change sound, vibration, light and other notification settings</string>
<string name="customize_notification">Customize notifications</string>
<string name="pref_view_privacy">View privacy policy</string>
<string name="view_all_contributors">View all contributors…</string>
<string name="database">Database</string>
<string name="widget_opacity_title">Widget opacity</string>
<string name="widget_opacity_description">Makes widgets more transparent or more opaque in your home screen.</string>
<string name="first_day_of_the_week">First day of the week</string>
<string name="default_reminder_question">Have you completed this habit today?</string>
<string name="notes">Notes</string>
<string name="example_notes">(Optional)</string>
<string name="yes_or_no_example">e.g. Did you wake up early today? Did you exercise? Did you play chess?</string>
<string name="measurable">Measurable</string>
<string name="measurable_example">e.g. How many miles did you run today? How many pages did you read? How many calories did you eat?</string>
<string name="x_times_per_week">%d times per week</string>
<string name="x_times_per_month">%d times per month</string>
<string name="yes_or_no_short_example">e.g. Exercise</string>
<string name="color">Color</string>
<string name="example_target">e.g. 15</string>
<string name="measurable_short_example">e.g. Run</string>
<string name="measurable_question_example">e.g. How many miles did you run today?</string>
<string name="measurable_units_example">e.g. miles</string>
<string name="every_month">Every month</string>
<string name="validation_cannot_be_blank">Cannot be blank</string>
<string name="today">Today</string>
<string name="enter">Enter</string>
<string name="no_habits">No habits found</string>
<string name="no_numerical_habits">No measurable habits found</string>
<string name="no_boolean_habits">No yes-or-no habits found</string>
<string name="increment">Increment</string>
<string name="decrement">Decrement</string>
</resources> | {
"pile_set_name": "Github"
} |
// Copyright 2019 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Flags: --harmony-top-level-await --harmony-dynamic-import
import * as m1 from 'modules-skip-1-top-level-await-cycle.mjs'
import * as m2 from 'modules-skip-2-top-level-await-cycle.mjs'
import * as m3 from 'modules-skip-3-top-level-await-cycle.mjs'
assertSame(m1.m1.m.m.life, m1.m2.m.m.life);
assertSame(m1.m1.m.m.life, m2.m.m.life);
assertSame(m1.m1.m.m.life, m3.m.m.life);
let m4 = await import('modules-skip-1.mjs');
assertSame(m1.m1.m.m.life, m4.life);
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.internal.net.http;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CoderResult;
import java.nio.charset.CodingErrorAction;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.Flow;
import java.util.concurrent.Flow.Subscriber;
import java.util.concurrent.Flow.Subscription;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import jdk.internal.net.http.common.Demand;
import java.net.http.HttpResponse.BodySubscriber;
import jdk.internal.net.http.common.MinimalFuture;
import jdk.internal.net.http.common.SequentialScheduler;
/** An adapter between {@code BodySubscriber} and {@code Flow.Subscriber<String>}. */
public final class LineSubscriberAdapter<S extends Subscriber<? super String>,R>
implements BodySubscriber<R> {
private final CompletableFuture<R> cf = new MinimalFuture<>();
private final S subscriber;
private final Function<? super S, ? extends R> finisher;
private final Charset charset;
private final String eol;
private final AtomicBoolean subscribed = new AtomicBoolean();
private volatile LineSubscription downstream;
private LineSubscriberAdapter(S subscriber,
Function<? super S, ? extends R> finisher,
Charset charset,
String eol) {
if (eol != null && eol.isEmpty())
throw new IllegalArgumentException("empty line separator");
this.subscriber = Objects.requireNonNull(subscriber);
this.finisher = Objects.requireNonNull(finisher);
this.charset = Objects.requireNonNull(charset);
this.eol = eol;
}
@Override
public void onSubscribe(Subscription subscription) {
Objects.requireNonNull(subscription);
if (!subscribed.compareAndSet(false, true)) {
subscription.cancel();
return;
}
downstream = LineSubscription.create(subscription,
charset,
eol,
subscriber,
cf);
subscriber.onSubscribe(downstream);
}
@Override
public void onNext(List<ByteBuffer> item) {
Objects.requireNonNull(item);
try {
downstream.submit(item);
} catch (Throwable t) {
onError(t);
}
}
@Override
public void onError(Throwable throwable) {
Objects.requireNonNull(throwable);
try {
downstream.signalError(throwable);
} finally {
cf.completeExceptionally(throwable);
}
}
@Override
public void onComplete() {
try {
downstream.signalComplete();
} finally {
cf.complete(finisher.apply(subscriber));
}
}
@Override
public CompletionStage<R> getBody() {
return cf;
}
public static <S extends Subscriber<? super String>, R> LineSubscriberAdapter<S, R>
create(S subscriber, Function<? super S, ? extends R> finisher, Charset charset, String eol)
{
if (eol != null && eol.isEmpty())
throw new IllegalArgumentException("empty line separator");
return new LineSubscriberAdapter<>(Objects.requireNonNull(subscriber),
Objects.requireNonNull(finisher),
Objects.requireNonNull(charset),
eol);
}
static final class LineSubscription implements Flow.Subscription {
final Flow.Subscription upstreamSubscription;
final CharsetDecoder decoder;
final String newline;
final Demand downstreamDemand;
final ConcurrentLinkedDeque<ByteBuffer> queue;
final SequentialScheduler scheduler;
final Flow.Subscriber<? super String> upstream;
final CompletableFuture<?> cf;
private final AtomicReference<Throwable> errorRef = new AtomicReference<>();
private final AtomicLong demanded = new AtomicLong();
private volatile boolean completed;
private volatile boolean cancelled;
private final char[] chars = new char[1024];
private final ByteBuffer leftover = ByteBuffer.wrap(new byte[64]);
private final CharBuffer buffer = CharBuffer.wrap(chars);
private final StringBuilder builder = new StringBuilder();
private String nextLine;
private LineSubscription(Flow.Subscription s,
CharsetDecoder dec,
String separator,
Flow.Subscriber<? super String> subscriber,
CompletableFuture<?> completion) {
downstreamDemand = new Demand();
queue = new ConcurrentLinkedDeque<>();
upstreamSubscription = Objects.requireNonNull(s);
decoder = Objects.requireNonNull(dec);
newline = separator;
upstream = Objects.requireNonNull(subscriber);
cf = Objects.requireNonNull(completion);
scheduler = SequentialScheduler.synchronizedScheduler(this::loop);
}
@Override
public void request(long n) {
if (cancelled) return;
if (downstreamDemand.increase(n)) {
scheduler.runOrSchedule();
}
}
@Override
public void cancel() {
cancelled = true;
upstreamSubscription.cancel();
}
public void submit(List<ByteBuffer> list) {
queue.addAll(list);
demanded.decrementAndGet();
scheduler.runOrSchedule();
}
public void signalComplete() {
completed = true;
scheduler.runOrSchedule();
}
public void signalError(Throwable error) {
if (errorRef.compareAndSet(null,
Objects.requireNonNull(error))) {
scheduler.runOrSchedule();
}
}
// This method looks at whether some bytes where left over (in leftover)
// from decoding the previous buffer when the previous buffer was in
// underflow. If so, it takes bytes one by one from the new buffer 'in'
// and combines them with the leftover bytes until 'in' is exhausted or a
// character was produced in 'out', resolving the previous underflow.
// Returns true if the buffer is still in underflow, false otherwise.
// However, in both situation some chars might have been produced in 'out'.
private boolean isUnderFlow(ByteBuffer in, CharBuffer out, boolean endOfInput)
throws CharacterCodingException {
int limit = leftover.position();
if (limit == 0) {
// no leftover
return false;
} else {
CoderResult res = null;
while (in.hasRemaining()) {
leftover.position(limit);
leftover.limit(++limit);
leftover.put(in.get());
leftover.position(0);
res = decoder.decode(leftover, out,
endOfInput && !in.hasRemaining());
int remaining = leftover.remaining();
if (remaining > 0) {
assert leftover.position() == 0;
leftover.position(remaining);
} else {
leftover.position(0);
}
leftover.limit(leftover.capacity());
if (res.isUnderflow() && remaining > 0 && in.hasRemaining()) {
continue;
}
if (res.isError()) {
res.throwException();
}
assert !res.isOverflow();
return false;
}
return !endOfInput;
}
}
// extract characters from start to end and remove them from
// the StringBuilder
private static String take(StringBuilder b, int start, int end) {
assert start == 0;
String line;
if (end == start) return "";
line = b.substring(start, end);
b.delete(start, end);
return line;
}
// finds end of line, returns -1 if not found, or the position after
// the line delimiter if found, removing the delimiter in the process.
private static int endOfLine(StringBuilder b, String eol, boolean endOfInput) {
int len = b.length();
if (eol != null) { // delimiter explicitly specified
int i = b.indexOf(eol);
if (i >= 0) {
// remove the delimiter and returns the position
// of the char after it.
b.delete(i, i + eol.length());
return i;
}
} else { // no delimiter specified, behaves as BufferedReader::readLine
boolean crfound = false;
for (int i = 0; i < len; i++) {
char c = b.charAt(i);
if (c == '\n') {
// '\n' or '\r\n' found.
// remove the delimiter and returns the position
// of the char after it.
b.delete(crfound ? i - 1 : i, i + 1);
return crfound ? i - 1 : i;
} else if (crfound) {
// previous char was '\r', c != '\n'
assert i != 0;
// remove the delimiter and returns the position
// of the char after it.
b.delete(i - 1, i);
return i - 1;
}
crfound = c == '\r';
}
if (crfound && endOfInput) {
// remove the delimiter and returns the position
// of the char after it.
b.delete(len - 1, len);
return len - 1;
}
}
return endOfInput && len > 0 ? len : -1;
}
// Looks at whether the StringBuilder contains a line.
// Returns null if more character are needed.
private static String nextLine(StringBuilder b, String eol, boolean endOfInput) {
int next = endOfLine(b, eol, endOfInput);
return (next > -1) ? take(b, 0, next) : null;
}
// Attempts to read the next line. Returns the next line if
// the delimiter was found, null otherwise. The delimiters are
// consumed.
private String nextLine()
throws CharacterCodingException {
assert nextLine == null;
LINES:
while (nextLine == null) {
boolean endOfInput = completed && queue.isEmpty();
nextLine = nextLine(builder, newline,
endOfInput && leftover.position() == 0);
if (nextLine != null) return nextLine;
ByteBuffer b;
BUFFERS:
while ((b = queue.peek()) != null) {
if (!b.hasRemaining()) {
queue.poll();
continue BUFFERS;
}
BYTES:
while (b.hasRemaining()) {
buffer.position(0);
buffer.limit(buffer.capacity());
boolean endofInput = completed && queue.size() <= 1;
if (isUnderFlow(b, buffer, endofInput)) {
assert !b.hasRemaining();
if (buffer.position() > 0) {
buffer.flip();
builder.append(buffer);
}
continue BUFFERS;
}
CoderResult res = decoder.decode(b, buffer, endofInput);
if (res.isError()) res.throwException();
if (buffer.position() > 0) {
buffer.flip();
builder.append(buffer);
continue LINES;
}
if (res.isUnderflow() && b.hasRemaining()) {
//System.out.println("underflow: adding " + b.remaining() + " bytes");
leftover.put(b);
assert !b.hasRemaining();
continue BUFFERS;
}
}
}
assert queue.isEmpty();
if (endOfInput) {
// Time to cleanup: there may be some undecoded leftover bytes
// We need to flush them out.
// The decoder has been configured to replace malformed/unmappable
// chars with some replacement, in order to behave like
// InputStreamReader.
leftover.flip();
buffer.position(0);
buffer.limit(buffer.capacity());
// decode() must be called just before flush, even if there
// is nothing to decode. We must do this even if leftover
// has no remaining bytes.
CoderResult res = decoder.decode(leftover, buffer, endOfInput);
if (buffer.position() > 0) {
buffer.flip();
builder.append(buffer);
}
if (res.isError()) res.throwException();
// Now call decoder.flush()
buffer.position(0);
buffer.limit(buffer.capacity());
res = decoder.flush(buffer);
if (buffer.position() > 0) {
buffer.flip();
builder.append(buffer);
}
if (res.isError()) res.throwException();
// It's possible that we reach here twice - just for the
// purpose of checking that no bytes were left over, so
// we reset leftover/decoder to make the function reentrant.
leftover.position(0);
leftover.limit(leftover.capacity());
decoder.reset();
// if some chars were produced then this call will
// return them.
return nextLine = nextLine(builder, newline, endOfInput);
}
return null;
}
return null;
}
// The main sequential scheduler loop.
private void loop() {
try {
while (!cancelled) {
Throwable error = errorRef.get();
if (error != null) {
cancelled = true;
scheduler.stop();
upstream.onError(error);
cf.completeExceptionally(error);
return;
}
if (nextLine == null) nextLine = nextLine();
if (nextLine == null) {
if (completed) {
scheduler.stop();
if (leftover.position() != 0) {
// Underflow: not all bytes could be
// decoded, but no more bytes will be coming.
// This should not happen as we should already
// have got a MalformedInputException, or
// replaced the unmappable chars.
errorRef.compareAndSet(null,
new IllegalStateException(
"premature end of input ("
+ leftover.position()
+ " undecoded bytes)"));
continue;
} else {
upstream.onComplete();
}
return;
} else if (demanded.get() == 0
&& !downstreamDemand.isFulfilled()) {
long incr = Math.max(1, downstreamDemand.get());
demanded.addAndGet(incr);
upstreamSubscription.request(incr);
continue;
} else return;
}
assert nextLine != null;
assert newline != null && !nextLine.endsWith(newline)
|| !nextLine.endsWith("\n") || !nextLine.endsWith("\r");
if (downstreamDemand.tryDecrement()) {
String forward = nextLine;
nextLine = null;
upstream.onNext(forward);
} else return; // no demand: come back later
}
} catch (Throwable t) {
try {
upstreamSubscription.cancel();
} finally {
signalError(t);
}
}
}
static LineSubscription create(Flow.Subscription s,
Charset charset,
String lineSeparator,
Flow.Subscriber<? super String> upstream,
CompletableFuture<?> cf) {
return new LineSubscription(Objects.requireNonNull(s),
Objects.requireNonNull(charset).newDecoder()
// use the same decoder configuration than
// java.io.InputStreamReader
.onMalformedInput(CodingErrorAction.REPLACE)
.onUnmappableCharacter(CodingErrorAction.REPLACE),
lineSeparator,
Objects.requireNonNull(upstream),
Objects.requireNonNull(cf));
}
}
}
| {
"pile_set_name": "Github"
} |
error: this operation will always return zero. This is likely not the intended outcome
--> $DIR/erasing_op.rs:6:5
|
LL | x * 0;
| ^^^^^
|
= note: `-D clippy::erasing-op` implied by `-D warnings`
error: this operation will always return zero. This is likely not the intended outcome
--> $DIR/erasing_op.rs:7:5
|
LL | 0 & x;
| ^^^^^
error: this operation will always return zero. This is likely not the intended outcome
--> $DIR/erasing_op.rs:8:5
|
LL | 0 / x;
| ^^^^^
error: aborting due to 3 previous errors
| {
"pile_set_name": "Github"
} |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package camelinaction;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.spring.CamelSpringTestSupport;
import org.junit.Test;
import org.springframework.context.support.AbstractXmlApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* The sample example as {@link AggregateABCEagerTest} but using Spring XML instead.
* <p/>
* Please see code comments in the other example.
*
* @see camelinaction.MyEndAggregationStrategy
* @version $Revision$
*/
public class SpringAggregateABCEagerTest extends CamelSpringTestSupport {
@Override
protected AbstractXmlApplicationContext createApplicationContext() {
return new ClassPathXmlApplicationContext("META-INF/spring/aggregate-abc-eager.xml");
}
@Test
public void testABCEager() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:result");
// we expect ABC in the published message
// notice: Only 1 message is expected
mock.expectedBodiesReceived("ABC");
// send the first message
template.sendBodyAndHeader("direct:start", "A", "myId", 1);
// send the 2nd message with the same correlation key
template.sendBodyAndHeader("direct:start", "B", "myId", 1);
// the F message has another correlation key
template.sendBodyAndHeader("direct:start", "F", "myId", 2);
// now we have 3 messages with the same correlation key
// and the Aggregator should publish the message
template.sendBodyAndHeader("direct:start", "C", "myId", 1);
// and now the END message to trigger completion
template.sendBodyAndHeader("direct:start", "END", "myId", 1);
assertMockEndpointsSatisfied();
}
}
| {
"pile_set_name": "Github"
} |
TET no. 0:
0.0, 0.5, 0.5
0.0, 0.0, 0.0
1.0, 0.0, 0.0
0.0, 1.0, 0.0
TET no. 1:
0.0, 0.5, 0.5
1.0, 0.0, 0.0
0.0, 0.0, 0.0
0.0, 0.0, 1.0
| {
"pile_set_name": "Github"
} |
/**
*
* WARNING! This file was autogenerated by:
* _ _ _ _ __ __
* | | | | | | |\ \ / /
* | | | | |_| | \ V /
* | | | | _ | / \
* | |_| | | | |/ /^\ \
* \___/\_| |_/\/ \/
*
* This file was autogenerated by UnrealHxGenerator using UHT definitions.
* It only includes UPROPERTYs and UFUNCTIONs. Do not modify it!
* In order to add more definitions, create or edit a type with the same name/package, but with an `_Extra` suffix
**/
package unreal;
/**
A drawing canvas.
**/
@:glueCppIncludes("Engine/Canvas.h")
@:uextern @:uclass extern class UCanvas extends unreal.UObject {
/**
Helper class to render 2d graphs on canvas
**/
@:uproperty public var ReporterGraph : unreal.UReporterGraph;
/**
Default texture to use
**/
@:uproperty public var GradientTexture0 : unreal.UTexture2D;
@:uproperty public var DefaultTexture : unreal.UTexture2D;
/**
Internal.
**/
@:uproperty public var ColorModulate : unreal.FPlane;
/**
Zero-based actual dimensions X.
**/
@:uproperty public var SizeY : unreal.Int32;
/**
Don't bilinear filter.
**/
@:uproperty public var SizeX : unreal.Int32;
/**
Whether to center the text vertically (about CurY)
**/
@:uproperty public var bNoSmooth : Bool;
/**
Whether to center the text horizontally (about CurX)
**/
@:uproperty public var bCenterY : Bool;
/**
Color for drawing.
**/
@:uproperty public var bCenterX : Bool;
/**
Bottom right clipping region.
**/
@:uproperty public var DrawColor : unreal.FColor;
/**
Bottom right clipping region.
**/
@:uproperty public var ClipY : unreal.Float32;
/**
Origin for drawing in Y.
**/
@:uproperty public var ClipX : unreal.Float32;
/**
Origin for drawing in X.
**/
@:uproperty public var OrgY : unreal.Float32;
/**
Modifiable properties.
**/
@:uproperty public var OrgX : unreal.Float32;
/**
Draws a line on the Canvas.
@param ScreenPositionA Starting position of the line in screen space.
@param ScreenPositionB Ending position of the line in screen space.
@param Thickness How many pixels thick this line should be.
@param RenderColor Color to render the line.
**/
@:ufunction(BlueprintCallable) @:final public function K2_DrawLine(ScreenPositionA : unreal.FVector2D, ScreenPositionB : unreal.FVector2D, Thickness : unreal.Float32 = 1.000000, @:opt("(R=1.000000,G=1.000000,B=1.000000,A=1.000000)") RenderColor : unreal.FLinearColor) : Void;
/**
Draws a texture on the Canvas.
@param RenderTexture Texture to use when rendering. If no texture is set then this will use the default white texture.
@param ScreenPosition Screen space position to render the texture.
@param ScreenSize Screen space size to render the texture.
@param CoordinatePosition Normalized UV starting coordinate to use when rendering the texture.
@param CoordinateSize Normalized UV size coordinate to use when rendering the texture.
@param RenderColor Color to use when rendering the texture.
@param BlendMode Blending mode to use when rendering the texture.
@param Rotation Rotation, in degrees, to render the texture.
@param PivotPoint Normalized pivot point to use when rotating the texture.
**/
@:ufunction(BlueprintCallable) @:final public function K2_DrawTexture(RenderTexture : unreal.UTexture, ScreenPosition : unreal.FVector2D, ScreenSize : unreal.FVector2D, CoordinatePosition : unreal.FVector2D, @:opt("(X=1.000,Y=1.000)") CoordinateSize : unreal.FVector2D, @:opt("(R=1.000000,G=1.000000,B=1.000000,A=1.000000)") RenderColor : unreal.FLinearColor, BlendMode : unreal.EBlendMode = BLEND_Translucent, Rotation : unreal.Float32 = 0.000000, @:opt("(X=0.500,Y=0.500)") PivotPoint : unreal.FVector2D) : Void;
/**
Draws a material on the Canvas.
@param RenderMaterial Material to use when rendering. Remember that only the emissive channel is able to be rendered as no lighting is performed when rendering to the Canvas.
@param ScreenPosition Screen space position to render the texture.
@param ScreenSize Screen space size to render the texture.
@param CoordinatePosition Normalized UV starting coordinate to use when rendering the texture.
@param CoordinateSize Normalized UV size coordinate to use when rendering the texture.
@param Rotation Rotation, in degrees, to render the texture.
@param PivotPoint Normalized pivot point to use when rotating the texture.
**/
@:ufunction(BlueprintCallable) @:final public function K2_DrawMaterial(RenderMaterial : unreal.UMaterialInterface, ScreenPosition : unreal.FVector2D, ScreenSize : unreal.FVector2D, CoordinatePosition : unreal.FVector2D, @:opt("(X=1.000,Y=1.000)") CoordinateSize : unreal.FVector2D, Rotation : unreal.Float32 = 0.000000, @:opt("(X=0.500,Y=0.500)") PivotPoint : unreal.FVector2D) : Void;
/**
Draws text on the Canvas.
@param RenderFont Font to use when rendering the text. If this is null, then a default engine font is used.
@param RenderText Text to render on the Canvas.
@param ScreenPosition Screen space position to render the text.
@param RenderColor Color to render the text.
@param Kerning Horizontal spacing adjustment to modify the spacing between each letter.
@param ShadowColor Color to render the shadow of the text.
@param ShadowOffset Pixel offset relative to the screen space position to render the shadow of the text.
@param bCentreX If true, then interpret the screen space position X coordinate as the center of the rendered text.
@param bCentreY If true, then interpret the screen space position Y coordinate as the center of the rendered text.
@param bOutlined If true, then the text should be rendered with an outline.
@param OutlineColor Color to render the outline for the text.
**/
@:ufunction(BlueprintCallable) @:final public function K2_DrawText(RenderFont : unreal.UFont, RenderText : unreal.FString, ScreenPosition : unreal.FVector2D, @:opt("(R=1.000000,G=1.000000,B=1.000000,A=1.000000)") RenderColor : unreal.FLinearColor, Kerning : unreal.Float32 = 0.000000, @:opt("(R=0.000000,G=0.000000,B=0.000000,A=1.000000)") ShadowColor : unreal.FLinearColor, @:opt("(X=1.000,Y=1.000)") ShadowOffset : unreal.FVector2D, bCentreX : Bool = false, bCentreY : Bool = false, bOutlined : Bool = false, @:opt("(R=0.000000,G=0.000000,B=0.000000,A=1.000000)") OutlineColor : unreal.FLinearColor) : Void;
/**
Draws a 3x3 grid border with tiled frame and tiled interior on the Canvas.
@param BorderTexture Texture to use for border.
@param BackgroundTexture Texture to use for border background.
@param LeftBorderTexture Texture to use for the tiling left border.
@param RightBorderTexture Texture to use for the tiling right border.
@param TopBorderTexture Texture to use for the tiling top border.
@param BottomBorderTexture Texture to use for the tiling bottom border.
@param ScreenPosition Screen space position to render the texture.
@param ScreenSize Screen space size to render the texture.
@param CoordinatePosition Normalized UV starting coordinate to use when rendering the border texture.
@param CoordinateSize Normalized UV size coordinate to use when rendering the border texture.
@param RenderColor Color to tint the border.
@param BorderScale Scale of the border.
@param BackgroundScale Scale of the background.
@param Rotation Rotation, in degrees, to render the texture.
@param PivotPoint Normalized pivot point to use when rotating the texture.
@param CornerSize Frame corner size in percent of frame texture (should be < 0.5f).
**/
@:ufunction(BlueprintCallable) @:final public function K2_DrawBorder(BorderTexture : unreal.UTexture, BackgroundTexture : unreal.UTexture, LeftBorderTexture : unreal.UTexture, RightBorderTexture : unreal.UTexture, TopBorderTexture : unreal.UTexture, BottomBorderTexture : unreal.UTexture, ScreenPosition : unreal.FVector2D, ScreenSize : unreal.FVector2D, CoordinatePosition : unreal.FVector2D, @:opt("(X=1.000,Y=1.000)") CoordinateSize : unreal.FVector2D, @:opt("(R=1.000000,G=1.000000,B=1.000000,A=1.000000)") RenderColor : unreal.FLinearColor, @:opt("(X=0.100,Y=0.100)") BorderScale : unreal.FVector2D, @:opt("(X=0.100,Y=0.100)") BackgroundScale : unreal.FVector2D, Rotation : unreal.Float32 = 0.000000, @:opt("(X=0.500,Y=0.500)") PivotPoint : unreal.FVector2D, CornerSize : unreal.FVector2D) : Void;
/**
Draws an unfilled box on the Canvas.
@param ScreenPosition Screen space position to render the text.
@param ScreenSize Screen space size to render the texture.
@param Thickness How many pixels thick the box lines should be.
**/
@:ufunction(BlueprintCallable) @:final public function K2_DrawBox(ScreenPosition : unreal.FVector2D, ScreenSize : unreal.FVector2D, Thickness : unreal.Float32 = 1.000000) : Void;
/**
Draws a set of triangles on the Canvas.
@param RenderTexture Texture to use when rendering the triangles. If no texture is set, then the default white texture is used.
@param Triangles Triangles to render.
**/
@:ufunction(BlueprintCallable) @:final public function K2_DrawTriangle(RenderTexture : unreal.UTexture, Triangles : unreal.TArray<unreal.FCanvasUVTri>) : Void;
/**
Draws a set of triangles on the Canvas.
@param RenderMaterial Material to use when rendering. Remember that only the emissive channel is able to be rendered as no lighting is performed when rendering to the Canvas.
@param Triangles Triangles to render.
**/
@:ufunction(BlueprintCallable) @:final public function K2_DrawMaterialTriangle(RenderMaterial : unreal.UMaterialInterface, Triangles : unreal.TArray<unreal.FCanvasUVTri>) : Void;
/**
Draws a polygon on the Canvas.
@param RenderTexture Texture to use when rendering the triangles. If no texture is set, then the default white texture is used.
@param ScreenPosition Screen space position to render the text.
@param Radius How large in pixels this polygon should be.
@param NumberOfSides How many sides this polygon should have. This should be above or equal to three.
@param RenderColor Color to tint the polygon.
**/
@:ufunction(BlueprintCallable) @:final public function K2_DrawPolygon(RenderTexture : unreal.UTexture, ScreenPosition : unreal.FVector2D, @:opt("(X=1.000,Y=1.000)") Radius : unreal.FVector2D, NumberOfSides : unreal.Int32 = 3, @:opt("(R=1.000000,G=1.000000,B=1.000000,A=1.000000)") RenderColor : unreal.FLinearColor) : Void;
/**
Performs a projection of a world space coordinates using the projection matrix set up for the Canvas.
@param WorldLocation World space location to project onto the Canvas rendering plane.
@return Returns a vector where X, Y defines a screen space position representing the world space location.
**/
@:ufunction(BlueprintCallable) @:final public function K2_Project(WorldLocation : unreal.FVector) : unreal.FVector;
/**
Performs a deprojection of a screen space coordinate using the projection matrix set up for the Canvas.
@param ScreenPosition Screen space position to deproject to the World.
@param WorldOrigin Vector which is the world position of the screen space position.
@param WorldDirection Vector which can be used in a trace to determine what is "behind" the screen space position. Useful for object picking.
**/
@:ufunction(BlueprintCallable) @:final public function K2_Deproject(ScreenPosition : unreal.FVector2D, WorldOrigin : unreal.PRef<unreal.FVector>, WorldDirection : unreal.PRef<unreal.FVector>) : Void;
/**
Returns the wrapped text size in screen space coordinates.
@param RenderFont Font to use when determining the size of the text. If this is null, then a default engine font is used.
@param RenderText Text to determine the size of.
@return Returns the screen space size of the text.
**/
@:ufunction(BlueprintCallable) @:final public function K2_StrLen(RenderFont : unreal.UFont, RenderText : unreal.FString) : unreal.FVector2D;
/**
Returns the clipped text size in screen space coordinates.
@param RenderFont Font to use when determining the size of the text. If this is null, then a default engine font is used.
@param RenderText Text to determine the size of.
@param Scale Scale of the font to use when determining the size of the text.
@return Returns the screen space size of the text.
**/
@:ufunction(BlueprintCallable) @:final public function K2_TextSize(RenderFont : unreal.UFont, RenderText : unreal.FString, @:opt("(X=1.000,Y=1.000)") Scale : unreal.FVector2D) : unreal.FVector2D;
}
| {
"pile_set_name": "Github"
} |
one in two && three in four
one in two &&& three in four
one in two and three in four | {
"pile_set_name": "Github"
} |
"""auxiliary utility to get the dataset for demo"""
import numpy as np
from collections import namedtuple
from sklearn.datasets import fetch_mldata
import cPickle
import sys
import os
from subprocess import call
class ArrayPacker(object):
"""Dataset packer for iterator"""
def __init__(self, X, Y):
self.images = X
self.labels = Y
self.ptr = 0
def next_batch(self, batch_size):
if self.ptr + batch_size >= self.labels.shape[0]:
self.ptr = 0
X = self.images[self.ptr:self.ptr+batch_size]
Y = self.labels[self.ptr:self.ptr+batch_size]
self.ptr += batch_size
return X, Y
MNISTData = namedtuple("MNISTData", ["train", "test"])
def get_mnist(flatten=False, onehot=False):
mnist = fetch_mldata('MNIST original')
np.random.seed(1234) # set seed for deterministic ordering
p = np.random.permutation(mnist.data.shape[0])
X = mnist.data[p]
Y = mnist.target[p]
X = X.astype(np.float32) / 255.0
if flatten:
X = X.reshape((70000, 28 * 28))
else:
X = X.reshape((70000, 1, 28, 28))
if onehot:
onehot = np.zeros((Y.shape[0], 10))
onehot[np.arange(Y.shape[0]), Y.astype(np.int32)] = 1
Y = onehot
X_train = X[:60000]
Y_train = Y[:60000]
X_test = X[60000:]
Y_test = Y[60000:]
return MNISTData(train=ArrayPacker(X_train, Y_train),
test=ArrayPacker(X_test, Y_test))
CIFAR10Data = namedtuple("CIFAR10Data", ["train", "test"])
def load_batch(fpath, label_key='labels'):
f = open(fpath, 'rb')
if sys.version_info < (3,):
d = cPickle.load(f)
else:
d = cPickle.load(f, encoding="bytes")
# decode utf8
for k, v in d.items():
del(d[k])
d[k.decode("utf8")] = v
f.close()
data = d["data"]
labels = d[label_key]
data = data.reshape(data.shape[0], 3, 32, 32).astype(np.float32)
labels = np.array(labels, dtype="float32")
return data, labels
def get_cifar10(swap_axes=False):
path = "cifar-10-batches-py"
if not os.path.exists(path):
tar_file = "cifar-10-python.tar.gz"
origin = "http://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz"
if os.path.exists(tar_file):
need_download = False
else:
need_download = True
if need_download:
call(["wget", origin])
call(["tar", "-xvf", "cifar-10-python.tar.gz"])
else:
call(["tar", "-xvf", "cifar-10-python.tar.gz"])
nb_train_samples = 50000
X_train = np.zeros((nb_train_samples, 3, 32, 32), dtype="float32")
y_train = np.zeros((nb_train_samples,), dtype="float32")
for i in range(1, 6):
fpath = os.path.join(path, 'data_batch_' + str(i))
data, labels = load_batch(fpath)
X_train[(i - 1) * 10000: i * 10000, :, :, :] = data
y_train[(i - 1) * 10000: i * 10000] = labels
fpath = os.path.join(path, 'test_batch')
X_test, y_test = load_batch(fpath)
if swap_axes:
X_train = np.swapaxes(X_train, 1, 3)
X_test = np.swapaxes(X_test, 1, 3)
return CIFAR10Data(train=ArrayPacker(X_train, y_train),
test=ArrayPacker(X_test, y_test))
| {
"pile_set_name": "Github"
} |
using Amazon.Lambda.Core;
using Amazon.Lambda.APIGatewayEvents;
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]
namespace HelloWorld
{
public class Function
{
public static APIGatewayProxyResponse <AWS_LAMBDA_RUN_METHOD_GUTTER_MARK>FunctionHandler</AWS_LAMBDA_RUN_METHOD_GUTTER_MARK>(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context)
{
return new APIGatewayProxyResponse();
}
}
} | {
"pile_set_name": "Github"
} |
#links_bar li {
margin:1em;
padding:0.4em;
font-size:large;
display:inline;
cursor:pointer;
border:none;
border-radius:0px;
transition:.2s linear;
text-align:center;
}
| {
"pile_set_name": "Github"
} |
/*
* NMH's Simple C Compiler, 2012
* ungetc()
*/
#include <stdio.h>
#include <unistd.h>
int ungetc(int c, FILE *f) {
if (f->ch != EOF) return EOF;
f->iom &= ~_FERROR;
return f->ch = c;
}
| {
"pile_set_name": "Github"
} |
from django.apps import AppConfig
class WagtailMenusConfig(AppConfig):
name = 'wagtailmenus'
verbose_name = 'WagtailMenus'
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration>
<configuration>
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<root level="warn">
<appender-ref ref="CONSOLE" />
</root>
</configuration>
| {
"pile_set_name": "Github"
} |
@{
ViewBag.Title = "Workflow - CallCustomServiceWeb";
string appWebUrl = ViewBag.AppWebUrl as string;
}
<div>
<h2>App Web List</h2>
<p>Click the link below to view the Part Suppliers List</p>
<h5><a href="@(appWebUrl)Lists/Part Suppliers" target="_blank">Part Suppliers</a></h5>
</div>
<div>
<h2>Create a Part Supplier</h2>
@Html.Action("CreateGet", "PartSuppliers")
</div>
@section scripts{
<script type="text/javascript">
function chromeLoaded() {
$('#chromeControl_bottomheader').remove();
$('body').show();
}
//function callback to render chrome after SP.UI.Controls.js loads
function renderSPChrome() {
//Set the chrome options
var options = {
'appTitle': "@ViewBag.Title",
'onCssLoaded': 'chromeLoaded()'
};
//Load the Chrome Control in the chrome_ctrl_placeholder element of the page
var chromeNavigation = new SP.UI.Controls.Navigation('chrome_ctrl_placeholder', options);
chromeNavigation.setVisible(true);
}
</script>
} | {
"pile_set_name": "Github"
} |
#region License
// https://github.com/TheBerkin/Rant
//
// Copyright (c) 2017 Nicholas Fleck
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in the
// Software without restriction, including without limitation the rights to use, copy,
// modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#endregion
namespace Rant.Vocabulary.Querying
{
/// <summary>
/// Defines carrier types for queries.
/// </summary>
public enum CarrierComponentType : byte
{
/// <summary>
/// Select the same entry every time.
/// </summary>
Match,
/// <summary>
/// Share no classes.
/// </summary>
Dissociative,
/// <summary>
/// Share no classes with a match carrier entry.
/// </summary>
MatchDissociative,
/// <summary>
/// Classes must exactly match.
/// </summary>
Associative,
/// <summary>
/// Classes must exactly match those of a match carrier entry.
/// </summary>
MatchAssociative,
/// <summary>
/// Have at least one different class.
/// </summary>
Divergent,
/// <summary>
/// Have at least one different class than a match carrier entry.
/// </summary>
MatchDivergent,
/// <summary>
/// Share at least one class.
/// </summary>
Relational,
/// <summary>
/// Share at least one class with a match carrier entry.
/// </summary>
MatchRelational,
/// <summary>
/// Never choose the same entry twice.
/// </summary>
Unique,
/// <summary>
/// Choose an entry that is different from a match carrier entry.
/// </summary>
MatchUnique,
/// <summary>
/// Choose terms that rhyme.
/// </summary>
Rhyme
}
} | {
"pile_set_name": "Github"
} |
#!/bin/sh
sugardatadir=@prefix@/share/sugar/data
if [ "$(id -u)" -eq 0 ] || [ "$(id -ru)" -eq 0 ] ; then
echo Refusing to run as root.
exit 3
fi
# Set default profile dir
if test -z "$SUGAR_HOME"; then
export SUGAR_HOME=$HOME/.sugar
fi
if test -z "$SUGAR_PROFILE"; then
export SUGAR_PROFILE=default
fi
if test -z "$SUGAR_SCALING"; then
export SUGAR_SCALING=72
fi
if test -z "$SUGAR_GROUP_LABELS"; then
export SUGAR_GROUP_LABELS="$sugardatadir/group-labels.defaults"
fi
if test -z "$SUGAR_MIME_DEFAULTS"; then
export SUGAR_MIME_DEFAULTS="$sugardatadir/mime.defaults"
fi
if test -z "$SUGAR_ACTIVITIES_HIDDEN"; then
export SUGAR_ACTIVITIES_HIDDEN="$sugardatadir/activities.hidden"
fi
export GTK2_RC_FILES="@prefix@/share/sugar/data/sugar-$SUGAR_SCALING.gtkrc"
if ! test -f "$GTK2_RC_FILES"; then
echo "sugar: ERROR: Gtk theme for scaling $SUGAR_SCALING not available in path $GTK2_RC_FILES"
exit 1
fi
# Set default language
export LANG="${LANG:-en_US.utf8}"
export LANGUAGE="${LANGUAGE:-${LANG}}"
# Set Sugar's telepathy accounts directory
export MC_ACCOUNT_DIR="$HOME/.sugar/$SUGAR_PROFILE/accounts"
# Source language settings and debug definitions
if [ -f ~/.i18n ]; then
. ~/.i18n
fi
profile_dir=$SUGAR_HOME/$SUGAR_PROFILE
debug_file_path=$profile_dir/debug
if [ -f "$debug_file_path" ]; then
. "$debug_file_path"
else
mkdir -p "$profile_dir"
cat > "$debug_file_path" << EOF
# Uncomment the following lines to turn on many sugar debugging
# log files and features.
#export LM_DEBUG=net
#export GABBLE_DEBUG=all
#export GABBLE_LOGFILE=$HOME/.sugar/$SUGAR_PROFILE/logs/telepathy-gabble.log
#export SALUT_DEBUG=all
#export SALUT_LOGFILE=$HOME/.sugar/$SUGAR_PROFILE/logs/telepathy-salut.log
#export GIBBER_DEBUG=all
#export WOCKY_DEBUG=all
#export MC_LOGFILE=$HOME/.sugar/$SUGAR_PROFILE/logs/mission-control.log
#export MC_DEBUG=all
#export PRESENCESERVICE_DEBUG=1
#export SUGAR_LOGGER_LEVEL=debug
# Uncomment the following line to enable core dumps.
#ulimit -c unlimited
EOF
fi
exec python3 -m jarabe.main
| {
"pile_set_name": "Github"
} |
0.738
1.000
1.000
1.000
0.933
0.947
1.000
0.933
0.833
0.909
0.933
0.952
0.632
0.941
0.933
1.000
0.667
0.526
0.952
0.952
0.400
0.952
0.870
0.571
0.632
0.667
0.750
0.600
0.588
0.375
0.545
0.741
0.588
0.667
0.400
0.429
0.211
0.429
0.667
0.667
0.600
0.632
0.571
0.600
0.545
0.353
0.667
0.625
0.522
0.471
0.300
0.444
0.625
0.632
0.400
0.556
0.267
0.286
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>CSS Test: Line-height using inches with a minimum plus one value, 1in</title>
<link rel="author" title="Microsoft" href="http://www.microsoft.com/" />
<link rel="help" href="http://www.w3.org/TR/CSS21/visudet.html#propdef-line-height" />
<link rel="help" href="http://www.w3.org/TR/CSS21/visudet.html#leading" />
<link rel="match" href="line-height-006-ref.xht" />
<meta name="flags" content="ahem" />
<meta name="assert" content="The 'line-height' property sets a minimum plus one length value in inches." />
<link rel="stylesheet" type="text/css" href="/fonts/ahem.css" />
<style type="text/css">
div
{
font: 20px/1 Ahem;
position: relative;
width: 1em;
}
#div2, #div3
{
background: black;
}
#div2
{
line-height: 1in;
}
#div3
{
height: 1in;
left: 1.1em;
position: absolute;
top: 0;
}
</style>
</head>
<body>
<p>Test passes if the 2 black vertical stripes have the <strong>same height</strong>.</p>
<div id="div1">
<div id="div2">X</div>
<div id="div3"></div>
</div>
</body>
</html>
| {
"pile_set_name": "Github"
} |
/*****************************************************************************
* Product: Linker script for STM32F746NG, GNU-ARM linker
* Last Updated for Version: 5.9.8
* Date of the Last Update: 2017-09-13
*
* Q u a n t u m L e a P s
* ---------------------------
* innovating embedded systems
*
* Copyright (C) Quantum Leaps, LLC. All rights reserved.
*
* This program is open source software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alternatively, this program may be distributed and modified under the
* terms of Quantum Leaps commercial licenses, which expressly supersede
* the GNU General Public License and are specifically designed for
* licensees interested in retaining the proprietary status of their code.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact information:
* https://state-machine.com
* mailto:[email protected]
*****************************************************************************/
OUTPUT_FORMAT("elf32-littlearm", "elf32-bigarm", "elf32-littlearm")
OUTPUT_ARCH(arm)
ENTRY(Reset_Handler) /* entry Point */
MEMORY { /* memory map of STM32F746NG */
ROM (rx) : ORIGIN = 0x08000000, LENGTH = 1024K
RAM (xrw) : ORIGIN = 0x20000000, LENGTH = 320K
}
/* The size of the stack used by the application. NOTE: you need to adjust */
STACK_SIZE = 1024;
/* The size of the heap used by the application. NOTE: you need to adjust */
HEAP_SIZE = 0;
SECTIONS {
.isr_vector : { /* the vector table goes FIRST into ROM */
KEEP(*(.isr_vector)) /* vector table */
. = ALIGN(4);
} >ROM
.text : { /* code and constants */
. = ALIGN(4);
*(.text) /* .text sections (code) */
*(.text*) /* .text* sections (code) */
*(.rodata) /* .rodata sections (constants, strings, etc.) */
*(.rodata*) /* .rodata* sections (constants, strings, etc.) */
KEEP (*(.init))
KEEP (*(.fini))
. = ALIGN(4);
} >ROM
.preinit_array : {
PROVIDE_HIDDEN (__preinit_array_start = .);
KEEP (*(.preinit_array*))
PROVIDE_HIDDEN (__preinit_array_end = .);
} >ROM
.init_array : {
PROVIDE_HIDDEN (__init_array_start = .);
KEEP (*(SORT(.init_array.*)))
KEEP (*(.init_array*))
PROVIDE_HIDDEN (__init_array_end = .);
} >ROM
.fini_array : {
PROVIDE_HIDDEN (__fini_array_start = .);
KEEP (*(.fini_array*))
KEEP (*(SORT(.fini_array.*)))
PROVIDE_HIDDEN (__fini_array_end = .);
} >ROM
_etext = .; /* global symbols at end of code */
.stack : {
__stack_start__ = .;
. = . + STACK_SIZE;
. = ALIGN(4);
__stack_end__ = .;
} >RAM
.data : AT (_etext) {
__data_load = LOADADDR (.data);
__data_start = .;
*(.data) /* .data sections */
*(.data*) /* .data* sections */
. = ALIGN(4);
__data_end__ = .;
_edata = __data_end__;
} >RAM
.bss : {
__bss_start__ = .;
*(.bss)
*(.bss*)
*(COMMON)
. = ALIGN(4);
_ebss = .; /* define a global symbol at bss end */
__bss_end__ = .;
} >RAM
__exidx_start = .;
.ARM.exidx : { *(.ARM.exidx* .gnu.linkonce.armexidx.*) } >RAM
__exidx_end = .;
PROVIDE ( end = _ebss );
PROVIDE ( _end = _ebss );
PROVIDE ( __end__ = _ebss );
.heap : {
__heap_start__ = .;
. = . + HEAP_SIZE;
. = ALIGN(4);
__heap_end__ = .;
} >RAM
/* Remove information from the standard libraries */
/DISCARD/ : {
libc.a ( * )
libm.a ( * )
libgcc.a ( * )
}
}
| {
"pile_set_name": "Github"
} |
package beast.evolution.speciation;
import java.util.ArrayList;
import java.util.List;
import beast.core.CalculationNode;
import beast.core.Description;
import beast.core.Input;
import beast.evolution.tree.Tree;
@Description("Finds height of highest tree among a set of trees")
public class TreeTopFinder extends CalculationNode {
final public Input<List<Tree>> treeInputs = new Input<>("tree", "set of trees to search among", new ArrayList<>());
List<Tree> trees;
double oldHeight;
double height;
@Override
public void initAndValidate() {
oldHeight = Double.NaN;
trees = treeInputs.get();
height = calcHighestTreeHeight();
}
public double getHighestTreeHeight() {
return calcHighestTreeHeight();
}
private double calcHighestTreeHeight() {
double top = 0;
for (Tree tree : trees) {
top = Math.max(tree.getRoot().getHeight(), top);
}
return top;
}
@Override
protected boolean requiresRecalculation() {
double top = calcHighestTreeHeight();
if (top != height) {
height = top;
return true;
}
return false;
}
@Override
protected void store() {
oldHeight = height;
super.store();
}
@Override
protected void restore() {
height = oldHeight;
super.restore();
}
}
| {
"pile_set_name": "Github"
} |
# This source code was written by the Go contributors.
# The master list of contributors is in the main Go distribution,
# visible at http://tip.golang.org/CONTRIBUTORS.
| {
"pile_set_name": "Github"
} |
StartChar: utilde
Encoding: 361 361 285
GlifName: utilde
Width: 1140
VWidth: 0
Flags: W
HStem: -16 134<365.617 664.383> 1224 124<528.899 677.017> 1304 124<353.203 501.101>
VStem: 120 150<220.243 1082> 208 614 760 150<220.243 1082>
LayerCount: 2
Back
Fore
Refer: 182 732 N 1 0 0 1 108 0 2
Refer: 65 117 N 1 0 0 1 0 0 3
EndChar
| {
"pile_set_name": "Github"
} |
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.*;
public class SearchSorted2DTest {
private boolean expected;
private List<List<Integer>> matrix;
private int x;
@Test
public void search1() throws Exception {
expected = false;
matrix = Arrays.asList(
Arrays.asList(1,2,3,4),
Arrays.asList(5,6,7,8),
Arrays.asList(7,8,9,10),
Arrays.asList(11,12,13,14)
);
x = 15;
test(expected, matrix, x);
}
@Test
public void search2() throws Exception {
expected = true;
matrix = Arrays.asList(
Arrays.asList(1,2,3,4),
Arrays.asList(5,6,7,8),
Arrays.asList(7,8,9,10),
Arrays.asList(11,12,13,14)
);
x = 4;
test(expected, matrix, x);
}
@Test
public void search3() throws Exception {
expected = true;
matrix = Arrays.asList(
Arrays.asList(1,2,3,4),
Arrays.asList(5,6,7,8),
Arrays.asList(7,8,9,10),
Arrays.asList(11,12,13,14)
);
x = 9;
test(expected, matrix, x);
}
private void test(boolean expected, List<List<Integer>> matrix, int x) {
assertEquals(expected, SearchSorted2D.search(matrix, x));
}
} | {
"pile_set_name": "Github"
} |
fileFormatVersion: 2
guid: 6e8e0a5480ab2584a8a2b94a99fc06af
timeCreated: 1549065306
licenseType: Pro
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 100100000
userData:
assetBundleName:
assetBundleVariant:
| {
"pile_set_name": "Github"
} |
fileFormatVersion: 2
guid: 1cc08f5424a1e49499023c590c0c524c
TextureImporter:
fileIDToRecycleName: {}
externalObjects: {}
serializedVersion: 9
mipmaps:
mipMapMode: 0
enableMipMap: 1
sRGBTexture: 1
linearTexture: 0
fadeOut: 0
borderMipMap: 0
mipMapsPreserveCoverage: 0
alphaTestReferenceValue: 0.5
mipMapFadeDistanceStart: 1
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
isReadable: 0
streamingMipmaps: 0
streamingMipmapsPriority: 0
grayScaleToAlpha: 0
generateCubemap: 6
cubemapConvolution: 0
seamlessCubemap: 0
textureFormat: 1
maxTextureSize: 2048
textureSettings:
serializedVersion: 2
filterMode: -1
aniso: -1
mipBias: -100
wrapU: -1
wrapV: -1
wrapW: -1
nPOTScale: 1
lightmap: 0
compressionQuality: 50
spriteMode: 0
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spritePixelsToUnits: 100
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 0
spriteTessellationDetail: -1
textureType: 0
textureShape: 1
singleChannelComponent: 0
maxTextureSizeSet: 0
compressionQualitySet: 0
textureFormatSet: 0
platformSettings:
- serializedVersion: 2
buildTarget: DefaultTexturePlatform
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
spriteSheet:
serializedVersion: 2
sprites: []
outline: []
physicsShape: []
bones: []
spriteID:
vertices: []
indices:
edges: []
weights: []
spritePackingTag:
pSDRemoveMatte: 0
pSDShowRemoveMatteOption: 0
userData:
assetBundleName:
assetBundleVariant:
| {
"pile_set_name": "Github"
} |
// resource-d3d12.h
#pragma once
#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#include <Windows.h>
#undef WIN32_LEAN_AND_MEAN
#undef NOMINMAX
#include <dxgi1_4.h>
#include <d3d12.h>
#include "../../slang-com-ptr.h"
#include "../d3d/d3d-util.h"
namespace gfx {
// Enables more conservative barriers - restoring the state of resources after they are used.
// Should not need to be enabled in normal builds, as the barriers should correctly sync resources
// If enabling fixes an issue it implies regular barriers are not correctly used.
#define SLANG_ENABLE_CONSERVATIVE_RESOURCE_BARRIERS 0
struct D3D12BarrierSubmitter
{
enum { MAX_BARRIERS = 8 };
/// Expand one space to hold a barrier
SLANG_FORCE_INLINE D3D12_RESOURCE_BARRIER& expandOne() { return (m_numBarriers < MAX_BARRIERS) ? m_barriers[m_numBarriers++] : _expandOne(); }
/// Flush barriers to command list
SLANG_FORCE_INLINE void flush() { if (m_numBarriers > 0) _flush(); }
/// Transition resource from prevState to nextState
void transition(ID3D12Resource* resource, D3D12_RESOURCE_STATES prevState, D3D12_RESOURCE_STATES nextState);
/// Ctor
SLANG_FORCE_INLINE D3D12BarrierSubmitter(ID3D12GraphicsCommandList* commandList) : m_numBarriers(0), m_commandList(commandList) { }
/// Dtor
SLANG_FORCE_INLINE ~D3D12BarrierSubmitter() { flush(); }
protected:
D3D12_RESOURCE_BARRIER& _expandOne();
void _flush();
ID3D12GraphicsCommandList* m_commandList;
int m_numBarriers;
D3D12_RESOURCE_BARRIER m_barriers[MAX_BARRIERS];
};
/*! \brief A class to simplify using Dx12 fences.
A fence is a mechanism to track GPU work. This is achieved by having a counter that the CPU holds
called the current value. Calling nextSignal will increase the CPU counter, and add a fence
with that value to the commandQueue. When the GPU has completed all the work before the fence it will
update the completed value. This is typically used when
the CPU needs to know the GPU has finished some piece of work has completed. To do this the CPU
can check the completed value, and when it is greater or equal to the value returned by nextSignal the
CPU will know that all the work prior to when the nextSignal was added to the queue will have completed.
NOTE! This cannot be used across threads, as for amongst other reasons SetEventOnCompletion
only works with a single value.
Signal on the CommandQueue updates the fence on the GPU side. Signal on the fence object changes
the value on the CPU side (not used here).
Useful article describing how Dx12 synchronization works:
https://msdn.microsoft.com/en-us/library/windows/desktop/dn899217%28v=vs.85%29.aspx
*/
class D3D12CounterFence
{
public:
/// Must be called before used
SlangResult init(ID3D12Device* device, uint64_t initialValue = 0);
/// Increases the counter, signals the queue and waits for the signal to be hit
void nextSignalAndWait(ID3D12CommandQueue* queue);
/// Signals with next counter value. Returns the value the signal was called on
uint64_t nextSignal(ID3D12CommandQueue* commandQueue);
/// Get the current value
SLANG_FORCE_INLINE uint64_t getCurrentValue() const { return m_currentValue; }
/// Get the completed value
SLANG_FORCE_INLINE uint64_t getCompletedValue() const { return m_fence->GetCompletedValue(); }
/// Waits for the the specified value
void waitUntilCompleted(uint64_t completedValue);
/// Ctor
D3D12CounterFence() :m_event(nullptr), m_currentValue(0) {}
/// Dtor
~D3D12CounterFence();
protected:
HANDLE m_event;
Slang::ComPtr<ID3D12Fence> m_fence;
UINT64 m_currentValue;
};
/** The base class for resource types allows for tracking of state. It does not allow for setting of the resource though, such that
an interface can return a D3D12ResourceBase, and a client cant manipulate it's state, but it cannot replace/change the actual resource */
struct D3D12ResourceBase
{
/// Add a transition if necessary to the list
void transition(D3D12_RESOURCE_STATES nextState, D3D12BarrierSubmitter& submitter);
/// Get the current state
SLANG_FORCE_INLINE D3D12_RESOURCE_STATES getState() const { return m_state; }
/// Get the associated resource
SLANG_FORCE_INLINE ID3D12Resource* getResource() const { return m_resource; }
/// True if a resource is set
SLANG_FORCE_INLINE bool isSet() const { return m_resource != nullptr; }
/// Coercible into ID3D12Resource
SLANG_FORCE_INLINE operator ID3D12Resource*() const { return m_resource; }
/// restore previous state
#if SLANG_ENABLE_CONSERVATIVE_RESOURCE_BARRIERS
SLANG_FORCE_INLINE Void restore(D3D12BarrierSubmitter& submitter) { transition(m_prevState, submitter); }
#else
SLANG_FORCE_INLINE void restore(D3D12BarrierSubmitter& submitter) { SLANG_UNUSED(submitter) }
#endif
/// Given the usage, flags, and format will return the most suitable format. Will return DXGI_UNKNOWN if combination is not possible
static DXGI_FORMAT calcFormat(D3DUtil::UsageType usage, ID3D12Resource* resource);
/// Ctor
SLANG_FORCE_INLINE D3D12ResourceBase() :
m_state(D3D12_RESOURCE_STATE_COMMON),
m_prevState(D3D12_RESOURCE_STATE_COMMON),
m_resource(nullptr)
{}
protected:
/// This is protected so as clients cannot slice the class, and so state tracking is lost
~D3D12ResourceBase() {}
ID3D12Resource* m_resource; ///< The resource (ref counted)
D3D12_RESOURCE_STATES m_state; ///< The current tracked expected state, if all associated transitions have completed on ID3D12CommandList
D3D12_RESOURCE_STATES m_prevState; ///< The previous state
};
struct D3D12Resource : public D3D12ResourceBase
{
/// Dtor
~D3D12Resource()
{
if (m_resource)
{
m_resource->Release();
}
}
/// Initialize as committed resource
Slang::Result initCommitted(ID3D12Device* device, const D3D12_HEAP_PROPERTIES& heapProps, D3D12_HEAP_FLAGS heapFlags, const D3D12_RESOURCE_DESC& resourceDesc, D3D12_RESOURCE_STATES initState, const D3D12_CLEAR_VALUE * clearValue);
/// Set a resource with an initial state
void setResource(ID3D12Resource* resource, D3D12_RESOURCE_STATES initialState);
/// Make the resource null
void setResourceNull();
/// Returns the attached resource (with any ref counts) and sets to nullptr on this.
ID3D12Resource* detach();
/// Swaps the resource contents with the contents of the smart pointer
void swap(Slang::ComPtr<ID3D12Resource>& resourceInOut);
/// Sets the current state of the resource (the current state is taken to be the future state once the command list has executed)
/// NOTE! This must be used with care, otherwise state tracking can be made incorrect.
void setState(D3D12_RESOURCE_STATES state);
/// Set the debug name on a resource
static void setDebugName(ID3D12Resource* resource, const char* name);
/// Set the the debug name on the resource
void setDebugName(const wchar_t* name);
/// Set the debug name
void setDebugName(const char* name);
};
} // renderer_test
| {
"pile_set_name": "Github"
} |
// Package pty provides functions for working with Unix terminals.
package pty
import (
"errors"
"os"
)
// ErrUnsupported is returned if a function is not
// available on the current platform.
var ErrUnsupported = errors.New("unsupported")
// Opens a pty and its corresponding tty.
func Open() (pty, tty *os.File, err error) {
return open()
}
| {
"pile_set_name": "Github"
} |
<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<style>
blockquote { background-color: #FFFAAE; padding: 7px; }
table { border-collapse: collapse; }
thead td { border-bottom: 1px solid; }
tfoot td { border-top: 1px solid; }
.tableclass1 { background-color: lime; }
.tableclass1 thead { color: yellow; background-color: green; }
.tableclass1 tfoot { color: yellow; background-color: green; }
.tableclass1 .even td { background-color: #80FF7F; }
.tableclass1 .first td {border-top: 1px solid; }
td.num { text-align: right; }
pre { background-color: #E0E0E0; padding: 5px; }
</style>
<title>Markmin markup language</title>
</head>
<body>
<h1>Markmin markup language</h1><h2>About</h2><p>This is a new markup language that we call markmin designed to produce high quality scientific papers and books and also put them online. We provide serializers for html, latex and pdf. It is implemented in the <code>markmin2html</code> function in the <code>markmin2html.py</code>.</p><p>Example of usage:</p><pre><code>m = "Hello **world** [[link http://web2py.com]]"
from markmin2html import markmin2html
print markmin2html(m)
from markmin2latex import markmin2latex
print markmin2latex(m)
from markmin2pdf import markmin2pdf # requires pdflatex
print markmin2pdf(m)</code></pre>
<h2>Why?</h2><p>We wanted a markup language with the following requirements:</p><ul><li>less than 300 lines of functional code</li><li>easy to read</li><li>secure</li><li>support table, ul, ol, code</li><li>support html5 video and audio elements (html serialization only)</li><li>can align images and resize them</li><li>can specify class for tables and code elements</li><li>can add anchors</li><li>does not use _ for markup (since it creates odd behavior)</li><li>automatically links urls</li><li>fast</li><li>easy to extend</li><li>supports latex and pdf including references</li><li>allows to describe the markup in the markup (this document is generated from markmin syntax)</li></ul><p>(results depend on text but in average for text ~100K markmin is 30% faster than markdown, for text ~10K it is 10x faster)</p><p>The <a href="http://www.lulu.com/shop/massimo-di-pierro/web2py-5th-edition/paperback/product-20745116.html">web2py book</a> published by lulu, for example, was entirely generated with markmin2pdf from the online <a href="http://www.web2py.com/book">web2py wiki</a></p><h2>Download</h2><ul><li><a href="http://web2py.googlecode.com/hg/gluon/contrib/markmin/markmin2html.py">http://web2py.googlecode.com/hg/gluon/contrib/markmin/markmin2html.py</a></li><li><a href="http://web2py.googlecode.com/hg/gluon/contrib/markmin/markmin2latex.py">http://web2py.googlecode.com/hg/gluon/contrib/markmin/markmin2latex.py</a></li><li><a href="http://web2py.googlecode.com/hg/gluon/contrib/markmin/markmin2pdf.py">http://web2py.googlecode.com/hg/gluon/contrib/markmin/markmin2pdf.py</a></li></ul><p>markmin2html.py and markmin2latex.py are single files and have no web2py dependence. Their license is BSD.</p><h2>Examples</h2><h3>Bold, italic, code and links</h3><table><thead><tr class="first"><td><strong>SOURCE</strong></td><td><strong>OUTPUT</strong></td></tr></thead><tbody><tr class="first"><td><code># title</code></td><td><strong>title</strong></td></tr><tr class="even"><td><code>## section</code></td><td><strong>section</strong></td></tr><tr><td><code>### subsection</code></td><td><strong>subsection</strong></td></tr><tr class="even"><td><code>**bold**</code></td><td><strong>bold</strong></td></tr><tr><td><code>''italic''</code></td><td><em>italic</em></td></tr><tr class="even"><td><code>~~strikeout~~</code></td><td><del>strikeout</del></td></tr><tr><td><code>``verbatim``</code></td><td><code>verbatim</code></td></tr><tr class="even"><td><code>``color with **bold**``:red</code></td><td><span style="color: red">color with <strong>bold</strong></span></td></tr><tr><td><code>``many colors``:color[blue:#ffff00]</code></td><td><span style="color: blue;background-color: #ffff00;">many colors</span></td></tr><tr class="even"><td><code>http://google.com</code></td><td><a href="http://google.com">http://google.com</a></td></tr><tr><td><code>[[**click** me #myanchor]]</code></td><td><a href="#markmin_myanchor"><strong>click</strong> me</a></td></tr><tr class="even"><td><code>[[click me [extra info] #myanchor popup]]</code></td><td><a href="#markmin_myanchor" title="extra info" target="_blank">click me</a></td></tr></tbody></table><h3>More on links</h3><p>The format is always <code>[[title link]]</code> or <code>[[title [extra] link]]</code>. Notice you can nest bold, italic, strikeout and code inside the link <code>title</code>.</p><h3>Anchors <a name="markmin_myanchor"></a></h3><p>You can place an anchor anywhere in the text using the syntax <code>[[name]]</code> where <em>name</em> is the name of the anchor. You can then link the anchor with <a href="#markmin_myanchor">link</a>, i.e. <code>[[link #myanchor]]</code> or <a href="#markmin_myanchor" title="extra info">link with an extra info</a>, i.e. <code>[[link with an extra info [extra info] #myanchor]]</code>.</p><h3>Images</h3><p><img src="http://www.web2py.com/examples/static/web2py_logo.png" alt="alt-string for the image" title="the image title" style="float:right" width="200px" /> This paragraph has an image aligned to the right with a width of 200px. Its is placed using the code</p><p><code>[[alt-string for the image [the image title] http://www.web2py.com/examples/static/web2py_logo.png right 200px]]</code>.</p><h3>Unordered Lists</h3><pre><code>- Dog
- Cat
- Mouse</code></pre><p>is rendered as</p><ul><li>Dog</li><li>Cat</li><li>Mouse</li></ul><p>Two new lines between items break the list in two lists.</p><h3>Ordered Lists</h3><pre><code>+ Dog
+ Cat
+ Mouse</code></pre><p>is rendered as</p><ol><li>Dog</li><li>Cat</li><li>Mouse</li></ol><h3>Multilevel Lists</h3><pre><code>+ Dogs
-- red
-- brown
-- black
+ Cats
-- fluffy
-- smooth
-- bald
+ Mice
-- small
-- big
-- huge</code></pre><p>is rendered as</p><ol><li>Dogs<ul><li>red</li><li>brown</li><li>black</li></ul></li><li>Cats<ul><li>fluffy</li><li>smooth</li><li>bald</li></ul></li><li>Mice<ul><li>small</li><li>big</li><li>huge</li></ul></li></ol><h3>Tables (with optional header and/or footer)</h3><p>Something like this</p><pre><code>-----------------
**A**|**B**|**C**
=================
0 | 0 | X
0 | X | 0
X | 0 | 0
=================
**D**|**F**|**G**
-----------------:abc[id]</code></pre> is a table and is rendered as<table class="abc" id="markmin_id"><thead><tr class="first"><td><strong>A</strong></td><td><strong>B</strong></td><td><strong>C</strong></td></tr></thead><tbody><tr class="first"><td class="num">0</td><td class="num">0</td><td>X</td></tr><tr class="even"><td class="num">0</td><td>X</td><td class="num">0</td></tr><tr><td>X</td><td class="num">0</td><td class="num">0</td></tr></tbody><tfoot><tr class="first"><td><strong>D</strong></td><td><strong>F</strong></td><td><strong>G</strong></td></tr></tfoot></table> Four or more dashes delimit the table and | separates the columns. The <code>:abc</code>, <code>:id[abc_1]</code> or <code>:abc[abc_1]</code> at the end sets the class and/or id for the table and it is optional.<h3>Blockquote</h3><p>A table with a single cell is rendered as a blockquote:</p><blockquote>Hello world</blockquote><p>Blockquote can contain headers, paragraphs, lists and tables:</p><pre><code>-----
This is a paragraph in a blockquote
+ item 1
+ item 2
-- item 2.1
-- item 2.2
+ item 3
---------
0 | 0 | X
0 | X | 0
X | 0 | 0
---------:tableclass1
-----</code></pre><p>is rendered as:</p><blockquote>This is a paragraph in a blockquote<ol><li>item 1</li><li>item 2<ul><li>item 2.1</li><li>item 2.2</li></ul></li><li>item 3</li></ol><table class="tableclass1"><tbody><tr class="first"><td class="num">0</td><td class="num">0</td><td>X</td></tr><tr class="even"><td class="num">0</td><td>X</td><td class="num">0</td></tr><tr><td>X</td><td class="num">0</td><td class="num">0</td></tr></tbody></table></blockquote><h3>Code, <code><code></code>, escaping and extra stuff</h3><pre><code class="python">def test():
return "this is Python code"</code></pre><p>Optionally a ` inside a <code>``...``</code> block can be inserted escaped with !`!.</p><p><strong>NOTE:</strong> You can escape markmin constructions ('',``,**,~~,[,{,]},$,@) with '\' character: so \`\` can replace !`!`! escape string</p><p>The <code>:python</code> after the markup is also optional. If present, by default, it is used to set the class of the <code> block. The behavior can be overridden by passing an argument <code>extra</code> to the <code>render</code> function. For example:</p><pre><code class="python">markmin2html("``aaa``:custom",
extra=dict(custom=lambda text: 'x'+text+'x'))</code></pre><p>generates</p><code class="python">'xaaax'</code><p>(the <code>``...``:custom</code> block is rendered by the <code>custom=lambda</code> function passed to <code>render</code>).</p><h3>Html5 support</h3><p>Markmin also supports the <video> and <audio> html5 tags using the notation:</p><pre><code>[[message link video]]
[[message link audio]]
[[message [title] link video]]
[[message [title] link audio]]</code></pre> where <code>message</code> will be shown in brousers without HTML5 video/audio tags support.<h3>Latex and other extensions</h3><p>Formulas can be embedded into HTML with <em>$$<code>formula</code>$$</em>. You can use Google charts to render the formula:</p><pre><code>LATEX = '<img src="http://chart.apis.google.com/chart?cht=tx&chl=%s" />'
markmin2html(text,{'latex':lambda code: LATEX % code.replace('"','\"')})</code></pre><h3>Code with syntax highlighting</h3><p>This requires a syntax highlighting tool, such as the web2py CODE helper.</p><pre><code>extra={'code_cpp':lambda text: CODE(text,language='cpp').xml(),
'code_java':lambda text: CODE(text,language='java').xml(),
'code_python':lambda text: CODE(text,language='python').xml(),
'code_html':lambda text: CODE(text,language='html').xml()}</code></pre> or simple:<pre><code>extra={'code':lambda text,lang='python': CODE(text,language=lang).xml()}</code></pre><pre><code>markmin2html(text,extra=extra)</code></pre><p>Code can now be marked up as in this example:</p><pre><code>``
<html><body>example</body></html>
``:code_html</code></pre> OR<pre><code>``
<html><body>example</body></html>
``:code[html]</code></pre><h3>Citations and References</h3><p>Citations are treated as internal links in html and proper citations in latex if there is a final section called "References". Items like</p><pre><code>- [[key]] value</code></pre><p>in the References will be translated into Latex</p><pre><code>\bibitem{key} value</code></pre><p>Here is an example of usage:</p><pre><code>As shown in Ref.``mdipierro``:cite
<h1>This is a test block with new features:</h1><p>This is a blockquote with a list with tables in it:</p><blockquote class="blockquoteclass" id="markmin_blockquoteid">This is a paragraph before list. You can continue paragraph on the next lines.<br />This is an ordered list with tables:<ol><li>Item 1</li><li>Item 2</li><li><table class="tableclass1" id="markmin_tableid1"><tbody><tr class="first"><td>aa</td><td>bb</td><td>cc</td></tr><tr class="even"><td class="num">11</td><td class="num">22</td><td class="num">33</td></tr></tbody></table></li><li>Item 4 <table class="tableclass1"><thead><tr class="first"><td>T1</td><td>T2</td><td>t3</td></tr></thead><tbody><tr class="first"><td>aaa</td><td>bbb</td><td>ccc</td></tr><tr class="even"><td>ddd</td><td>fff</td><td>ggg</td></tr><tr><td class="num">123</td><td class="num">0</td><td class="num">5.0</td></tr></tbody></table></li></ol></blockquote><p>This this a new paragraph with a table. Table has header, footer, sections, odd and even rows:</p><table class="tableclass1" id="markmin_tableid2"><thead><tr class="first"><td><strong>Title 1</strong></td><td><strong>Title 2</strong></td><td><strong>Title 3</strong></td></tr></thead><tbody><tr class="first"><td>data 1</td><td>data 2</td><td class="num">2.00</td></tr><tr class="even"><td>data 3</td><td>data4(long)</td><td class="num">23.00</td></tr><tr><td></td><td>data 5</td><td class="num">33.50</td></tr><tr class="first"><td>New section</td><td>New data</td><td class="num">5.00</td></tr><tr class="even"><td>data 1</td><td>data2(long)</td><td class="num">100.45</td></tr><tr><td></td><td>data 3</td><td class="num">12.50</td></tr><tr class="even"><td>data 4</td><td>data 5</td><td class="num">.33</td></tr><tr><td>data 6</td><td>data7(long)</td><td class="num">8.01</td></tr><tr class="even"><td></td><td>data 8</td><td class="num">514</td></tr></tbody><tfoot><tr class="first"><td>Total:</td><td>9 items</td><td>698,79</td></tr></tfoot></table><h2>Multilevel lists</h2><p>Now lists can be multilevel:</p><ol><li>Ordered item 1 on level 1. You can continue item text on next strings<ol><li><p>Ordered item 1 of sublevel 2 with a paragraph (paragraph can start with point after plus or minus characters, e.g. <strong>++.</strong> or <strong>--.</strong>)</p><li><p>This is another item. But with 3 paragraphs, blockquote and sublists:</p><p>This is the second paragraph in the item. You can add paragraphs to an item, using point notation, where first characters in the string are sequence of points with space between them and another string. For example, this paragraph (in sublevel 2) starts with two points:</p><code>.. This is the second paragraph...</code><blockquote><h3>this is a blockquote in a list</h3>You can use blockquote with headers, paragraphs, tables and lists in it:<br />Tables can have or have not header and footer. This table is defined without any header and footer in it:<table><tbody><tr class="first"><td>red</td><td>fox</td><td class="num">0</td></tr><tr class="even"><td>blue</td><td>dolphin</td><td class="num">1000</td></tr><tr><td>green</td><td>leaf</td><td class="num">10000</td></tr></tbody></table></blockquote><p>This is yet another paragraph in the item.</p><ul><li>This is an item of unordered list <strong>(sublevel 3)</strong></li><li>This is the second item of the unordered list <em>(sublevel 3)</em><ol><ol><ol><li>This is a single item of ordered list in sublevel 6</li></ol></ol><p>and this is a paragraph in sublevel 4</p></ol></li><li><p>This is a new item with paragraph in sublevel 3.</p><ol><li>Start ordered list in sublevel 4 with code block: <pre><code>line 1
line 2
line 3</code></pre></li><li><p>Yet another item with code block:</p><pre><code> line 1
line 2
line 3</code></pre> This item finishes with this paragraph.</li></ol><p>Item in sublevel 3 can be continued with paragraphs.</p><pre><code> this is another
code block
in the
sublevel 3 item</code></pre></li></ul><ol><li>The last item in sublevel 3</li></ol><p>This is a continuous paragraph for item 2 in sublevel 2. You can use such structure to create difficult structured documents.</p><li>item 3 in sublevel 2</li></li></li></ol><ul><li>item 1 in sublevel 2 (new unordered list)</li><li>item 2 in sublevel 2</li><li>item 3 in sublevel 2</li></ul><ol><li>item 1 in sublevel 2 (new ordered list)</li><li>item 2 in sublevel 2</li><li>item 3 in sublevle 2</li></ol></li><li>item 2 in level 1</li><li>item 3 in level 1</li></ol><ul><li>new unordered list (item 1 in level 1)</li><li>level 2 in level 1</li><li>level 3 in level 1</li><li>level 4 in level 1</li></ul><h2>This is the last section of the test</h2><p>Single paragraph with '----' in it will be turned into separator:</p><hr /><p>And this is the last paragraph in the test. Be happy!</p>
## References
- [[mdipierro]] web2py Manual, 5th Edition, lulu.com</code></pre><h3>Caveats</h3><p><code><ul/></code>, <code><ol/></code>, <code><code/></code>, <code><table/></code>, <code><blockquote/></code>, <code><h1/></code>, ..., <code><h6/></code> do not have <code><p>...</p></code> around them.</p>
</body>
</html>
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/btn_flash_auto_normal"/>
<item android:drawable="@drawable/btn_flash_auto_press" android:state_pressed="true"/>
</selector> | {
"pile_set_name": "Github"
} |
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2008-2018 FIRST. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
#pragma once
namespace frc {
enum class AnalogTriggerType {
kInWindow = 0,
kState = 1,
kRisingPulse = 2,
kFallingPulse = 3
};
} // namespace frc
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="LaunchTheme" parent="@android:style/Theme.Black.NoTitleBar">
<item name="android:windowBackground">@drawable/launch_background</item>
</style>
<style name="NormalTheme" parent="@android:style/Theme.Black.NoTitleBar">
<item name="android:windowBackground">@android:color/white</item>
</style>
</resources>
| {
"pile_set_name": "Github"
} |
#!/bin/bash
exec 2>&1
exec chpst -u <%= node.zabbix.web.user %> php-cgi -b <%= @options[:socket] %> -c <%= node.zabbix.conf_dir %>/php.ini
| {
"pile_set_name": "Github"
} |
local module = {}
local shared = require "ai.shared"
local function wolfStayAlive (parentnode)
end
function module.register()
local name = "ANIMAL_WOLF"
local rootNode = AI.createTree(name):createRoot("PrioritySelector", name)
wolfStayAlive(rootNode)
shared.hunt(rootNode)
shared.increasePopulation(rootNode)
shared.idle(rootNode)
shared.die(rootNode)
end
return module
| {
"pile_set_name": "Github"
} |
package com.puppycrawl.tools.checkstyle.checks.javadoc.atclauseorder;
/** Javadoc for import */
import java.io.Serializable;
/**
* Some javadoc.
*
* @since Some javadoc.
* @version 1.0 //warn //warn
* @deprecated Some javadoc.
* @see Some javadoc. //warn
* @author max //warn
*/
class InputAtclauseOrderIncorrect implements Serializable
{
/**
* The client's first name.
* @serial
*/
private String fFirstName;
/**
* The client's first name.
* @serial
*/
private String sSecondName;
/**
* The client's first name.
* @serialField
*/
private String tThirdName;
/**
* Some text.
* @param aString Some text.
* @return Some text.
* @serialData Some javadoc.
* @deprecated Some text.
* @throws Exception Some text. //warn
*/
String method(String aString) throws Exception
{
return "null";
}
/**
* Some text.
* @serialData Some javadoc.
* @return Some text. //warn
* @param aString Some text. //warn
* @throws Exception Some text.
*/
String method1(String aString) throws Exception
{
return "null";
}
/**
* Some text.
* @throws Exception Some text.
* @param aString Some text. //warn
*/
void method2(String aString) throws Exception {}
/**
* Some text.
* @deprecated Some text.
* @throws Exception Some text. //warn
*/
void method3() throws Exception {}
/**
* Some text.
* @return Some text.
* @throws Exception Some text.
*/
String method4() throws Exception
{
return "null";
}
/**
* Some text.
* @deprecated Some text.
* @return Some text. //warn
* @param aString Some text. //warn
*/
String method5(String aString)
{
return "null";
}
/**
* Some text.
* @param aString Some text.
* @return Some text.
* @serialData Some javadoc.
* @param aInt Some text. //warn
* @throws Exception Some text.
* @param aBoolean Some text. //warn
* @deprecated Some text.
*/
String method6(String aString, int aInt, boolean aBoolean) throws Exception
{
return "null";
}
/**
* Some javadoc.
*
* @version 1.0
* @since Some javadoc.
* @serialData Some javadoc.
* @author max //warn
*/
class InnerClassWithAnnotations
{
/**
* Some text.
* @return Some text.
* @deprecated Some text.
* @param aString Some text. //warn
* @throws Exception Some text.
*/
String method(String aString) throws Exception
{
return "null";
}
/**
* Some text.
* @throws Exception Some text.
* @return Some text. //warn
* @param aString Some text. //warn
*/
String method1(String aString) throws Exception
{
return "null";
}
/**
* Some text.
* @serialData Some javadoc.
* @param aString Some text. //warn
* @throws Exception Some text.
*/
void method2(String aString) throws Exception {}
/**
* Some text.
* @deprecated Some text.
* @throws Exception Some text. //warn
*/
void method3() throws Exception {}
/**
* Some text.
* @throws Exception Some text.
* @serialData Some javadoc.
* @return Some text. //warn
*/
String method4() throws Exception
{
return "null";
}
/**
* Some text.
* @param aString Some text.
* @deprecated Some text.
* @return Some text. //warn
*/
String method5(String aString)
{
return "null";
}
/**
* Some text.
* @param aString Some text.
* @return Some text.
* @param aInt Some text. //warn
* @throws Exception Some text.
* @param aBoolean Some text. //warn
* @deprecated Some text.
*/
String method6(String aString, int aInt, boolean aBoolean) throws Exception
{
return "null";
}
}
InnerClassWithAnnotations anon = new InnerClassWithAnnotations()
{
/**
* Some text.
* @throws Exception Some text.
* @param aString Some text. //warn
* @serialData Some javadoc.
* @deprecated Some text.
* @return Some text. //warn
*/
String method(String aString) throws Exception
{
return "null";
}
/**
* Some text.
* @param aString Some text.
* @throws Exception Some text.
* @return Some text. //warn
*/
String method1(String aString) throws Exception
{
return "null";
}
/**
* Some text.
* @throws Exception Some text.
* @param aString Some text. //warn
*/
void method2(String aString) throws Exception {}
/**
* Some text.
* @deprecated Some text.
* @throws Exception Some text. //warn
*/
void method3() throws Exception {}
/**
* Some text.
* @throws Exception Some text.
* @return Some text. //warn
*/
String method4() throws Exception
{
return "null";
}
/**
* Some text.
* @deprecated Some text.
* @return Some text. //warn
* @param aString Some text. //warn
*/
String method5(String aString)
{
return "null";
}
/**
* Some text.
* @param aString Some text.
* @return Some text.
* @param aInt Some text. //warn
* @throws Exception Some text.
* @param aBoolean Some text. //warn
* @deprecated Some text.
*/
String method6(String aString, int aInt, boolean aBoolean) throws Exception
{
return "null";
}
};
}
/**
* Some javadoc.
*
* @since Some javadoc.
* @version 1.0 //warn //warn
* @deprecated Some javadoc.
* @see Some javadoc. //warn
* @author max //warn
*/
enum Foo4 {}
/**
* Some javadoc.
*
* @version 1.0
* @since Some javadoc.
* @serialData Some javadoc.
* @author max //warn
*/
interface FooIn {
/**
* @value tag without specified order by default
*/
int CONSTANT = 0;
}
| {
"pile_set_name": "Github"
} |
# Event 274 - MFCaptureEngineSinkTask
###### Version: 0
## Description
None
## Data Dictionary
|Standard Name|Field Name|Type|Description|Sample Value|
|---|---|---|---|---|
|TBD|SinkPointer|Pointer|None|`None`|
|TBD|SamplePointer|Pointer|None|`None`|
|TBD|SinkStreamIndex|UInt32|None|`None`|
|TBD|Timestamp|UInt64|None|`None`|
|TBD|RefTimestamp|UInt64|None|`None`|
## Tags
* etw_level_Informational
* etw_task_MFCaptureEngineSinkTask | {
"pile_set_name": "Github"
} |
$ext = ".html"
$extno = 8
$Directory = Resolve-Path $Args[0]
$LineEnding = 1 # WdLineEndingType 1 = CROnly
$Encoding = 65001 # Codepage for UTF8
$testFileDepth = 2
$AbsPath = @(Get-ChildItem -path $Directory -Recurse -Exclude *.txt, *.skip, "*.html", "*.rtf","*.odt","*.doc")
:htmlMain for ($i = 0; $i -lt $AbsPath.length; $i++) {
$AbsPathI = Resolve-Path $AbsPath[$i] | Select-Object -ExpandProperty Path
if (Test-Path ($AbsPathI + $ext) -PathType Leaf ) { continue htmlMain }
if (Test-Path ($AbsPathI + ".skip")) { continue htmlMain }
$Word = New-Object -ComObject Word.Application
try {
$Doc = $Word.Documents.Open($AbsPathI, $False, $True, $False, "WordJS", "WordJS")
$Doc.SaveAs(($AbsPathI + $ext), $extno, $False, "", $False, "", $False, $False, $False, $False, $False, $Encoding, $False, $False, $LineEnding)
$Doc.Close()
Remove-Item -Force -Recurse ($AbsPathI + "_files")
$list = $AbsPathI -split '\\'
$index = $list.IndexOf('test_files')
$secondHalf = ($list | Select-Object -last ($list.Length - $index - $testFileDepth)) -join '\'
$leaf = $secondHalf | Split-Path -Leaf
$secondHalf = ($secondHalf | Split-Path -Parent) + "\" + $leaf + $ext
$fileName = $leaf + $ext
$htmlPath = Join-Path -Path "./test_files/html" $secondHalf;
$current = (Split-Path $AbsPathI -Parent) + "\" + $fileName
Write-Output $current
New-Item -ItemType File -Path $htmlPath -Force
Move-Item -Path $current -Destination $htmlPath -Force
}
catch {
Write-Output "Skipping (has pwd)"
}
Stop-Process -Name "winword"
}
$AbsPath = @(Get-ChildItem -path $Directory -Recurse -Exclude *.txt, *.skip, *.docx, "*.rtf","*.odt","*.doc")
:txtMain for ($i = 0; $i -lt $AbsPath.length; $i++) {
$AbsPathI = Resolve-Path $AbsPath[$i] | Select-Object -ExpandProperty Path
Write-Output $AbsPathI
if (Test-Path ($AbsPathI + ".txt") -PathType Leaf ) { continue txtMain }
if (Test-Path ($AbsPathI + ".skip")) { continue txtMain }
$Word = New-Object -ComObject Word.Application
try {
$Doc = $Word.Documents.Open($AbsPathI, $False, $True, $False, "WordJS", "WordJS")
$Doc.SaveAs(($AbsPathI + ".txt"), 7, $False, "", $False, "", $False, $False, $False, $False, $False, $Encoding, $False, $False, $LineEnding)
$Doc.Close()
}
catch {
Write-Output "Skipping (has pwd): $AbsPathI"
}
Stop-Process -Name "winword"
} | {
"pile_set_name": "Github"
} |
# -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant.configure(2) do |config|
config.vm.guest = :windows
config.vm.communicator = "winrm"
config.vm.provider "virtualbox" do |vb|
vb.customize ["modifyvm", :id, "--hardwareuuid", "02f110e7-369a-4bbc-bbe6-6f0b6864ccb6"]
vb.gui = true
vb.memory = "1024"
end
config.vm.provider 'hyperv' do |hv|
hv.ip_address_timeout = 240
end
end
| {
"pile_set_name": "Github"
} |
00:02 When you've got a bunch of prospective customers using your product and engaging with it,
00:05 you'd like to see them move from prospective into actually paying customers.
00:08 So I wanted to go over some non-intuitive parts of pricing pages
00:12 that will help you to think past just the basic design of the page.
00:16 Once again, we'll take a look at a few examples.
00:20 I've used MailChimp as an example throughout many of these videos,
00:23 and their pricing page is also a really great example as well.
00:26 They only have three options here. Now technically MailChimp
00:30 has more of a spectrum from free to really expensive paid accounts,
00:36 but they've made the smart decision
00:39 to keep things really simple on their pricing page.
00:41 On the left, you've got free, which hopefully by the point
00:44 that people are actually looking at the pricing page,
00:47 they are already on the free account, so they know where they sit
00:50 and they are probably considering going up to a paid account.
00:52 And one of the non-intuitive things about the psychology of pricing pages
00:56 is that you want the gaps between pricing plans to be meaningful,
01:01 it does very little if growing business and pro marketer
01:05 were only separated by five dollars per month,
01:07 well that will introduce his hesitation- should they go for the less expensive plan
01:12 or should they go for the more expensive one,
01:14 it's only hypothetically a five dollar a month difference in that example,
01:18 so they may just say I don't know what to pick,
01:20 and they'll close the browser and say I'll decide on it later, and maybe later is never.
01:25 So what you actually see here, is a huge gulf between growing business and pro marketer,
01:30 it makes it really easy to make the decision.
01:34 If you're in a large company, chances are you are just gonna pick the pro marketer,
01:37 you know that it's easier to get that larger plan through your procurement and legal team,
01:41 rather than some tiny little amount that could be put on a credit card each month.
01:45 But if you're running your own business, or just getting started with your startup,
01:48 the growing business plan is probably going to be the one for you.
01:51 So that's the first thing to learn from these pricing pages.
01:55 Make sure that the difference between the pricing plans is distinct enough
02:00 that people don't have to hesitate when trying to decide;
02:03 it should be very clear to them which category do they fall into.
02:07 We've also used Zendesk as an example and there is a slightly different model,
02:10 this one might also fit in yours if you're considering a per seat licensing agreement,
02:15 so for example you multiply each of these plans by a hundred,
02:19 if you had in their terms a hundred agents, while each of these columns
02:23 doesn't look like it's that big of a difference from one to the other,
02:26 when you're considering per seat, it's going to add up very quickly.
02:29 One thing that's great about this page is that it shows you
02:32 when you move from left to right, you get every single thing plus new features on top of it.
02:38 So if you're considering team vs professional,
02:43 you can very quickly see the biggest features that may impact your decision
02:47 whether you should choose one or the other.
02:49 In the worst case scenario a pricing page would make you decide
02:52 which features that you want to mix and match make it too complicated to see,
02:57 well if I upgrade from the 19 dollar a month plan to the 49 dollar a month plan,
03:04 do I actually lose some features?
03:06 This is very clean for deciding what do you need based on the state of your business.
03:09 One thing I don't like about this, but I understand why Zendesk did it,
03:13 because they have many customers across a wide spectrum,
03:18 but in some businesses you really want people to make a decision
03:21 that you are in heavily influencing,
03:24 so for example you want to highlight one of these plans
03:27 the one that is actually most applicable to the vast majority of your audience.
03:32 Dropbox does this with its pricing plan page,
03:35 where it talks about the most popular plan.
03:38 It just highlights this one on the left is the most popular,
03:41 so if you're undecided or you're not deciding for a business,
03:44 you'll just know ok that's the plan that I need to choose.
03:47 Let's take a look at one more example.
03:50 On Swiftype's pricing their amounts ratchet up quickly,
03:53 and they're really pushing people towards the business class.
03:56 Chances are most of their prospective customers
03:58 are going to choose business anyway, and they're trying to catch
04:01 some of the lower and startups with a basic plan,
04:03 and that's why they have it, just in case.
04:06 But really they're trying to push most businesses to choose that
04:09 pretty much 1,000 dollar a month plan.
04:11 When you're designing your own pricing page, you know your own business,
04:14 what is the plan that you would prefer your users to choose?
04:18 If it's a 100 dollars a month, then one way to subtly influence people
04:23 choosing that 100 dollars a month would be to create a 500 dollar a month plan
04:27 with all the same features plus maybe one or two features
04:31 that aren't that useful for the majority of your prospective customers.
04:34 That way they feel like they're getting a really great deal
04:38 with a 100 dollar a month plan, because they're only paying a 100 dollars a month
04:41 versus 500 dollars a month, and they don't need those couple extra features
04:45 that aren't that big of a deal.
04:47 So that's one way you can subtly influence and guide customers
04:50 towards a certain pricing plan that's not only going to be something
04:52 that they can't make an easy decision on, they can just immediately
04:56 put in their credit card or they can decide right there on the spot,
04:58 but also it fits the pricing model that works best for your application and your business.
05:04 If you're just getting started, you may not really be sure about the really large accounts,
05:08 and so that's why a lot of these pricing pages include a custom plan
05:12 with a contact sales button just in case a really large customer is interested
05:17 in some enterprise features that maybe aren't even built out yet,
05:21 but they want to explore that through a direct conversation.
05:25 As we are deciding how to put together your pricing plan,
05:28 and move customers down the funnel from sign up to usage
05:32 to actually paying for your product or service,
05:35 we should take a look at a lot of different pricing plans that are out there,
05:39 see which ones are closest to your business,
05:42 which ones are similar to the business model that you've created.
05:45 One way to see them quickly at a glance is to go to pricingpages.xyz,
05:51 there is a really great list of curated pricing plans,
05:55 that you can scroll through and see
05:58 how many companies out there are positioning their own pricing.
06:02 Those are some examples of growth hacking and ways to market your business,
06:07 so you can start to move customers from awareness
06:10 which is hopefully generated by your content marketing,
06:12 through the evaluation, sign up process,
06:16 getting them using your product and ultimately paying for it.
06:19 So you can start generating some revenue and keep your business self-sustaining. | {
"pile_set_name": "Github"
} |
<?xml version="1.0"?>
<DDDefinition xmlns="http://www.cern.ch/cms/DDL" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.cern.ch/cms/DDL ../../../../DetectorDescription/Schema/DDLSchema.xsd">
<ConstantsSection label="hgcal.xml" eval="true">
<Constant name="WaferSize" value="167.4408*mm"/>
<Constant name="WaferThickness" value="0.30*mm"/>
<Constant name="SensorSeparation" value="1.00*mm"/>
<Constant name="MouseBite" value="5.00*mm"/>
<Constant name="CellThicknessFine" value="0.12*mm"/>
<Constant name="CellThicknessCoarse1" value="0.20*mm"/>
<Constant name="CellThicknessCoarse2" value="0.30*mm"/>
<Constant name="ScintillatorThickness" value="3.0*mm"/>
<Constant name="NumberOfCellsFine" value="12"/>
<Constant name="NumberOfCellsCoarse" value="8"/>
<Constant name="FirstMixedLayer" value="9"/>
<Constant name="rad100200P0" value="-2.152079E-05"/>
<Constant name="rad100200P1" value="3.040344E-02"/>
<Constant name="rad100200P2" value="-1.610902E+01"/>
<Constant name="rad100200P3" value="3.793400E+03"/>
<Constant name="rad100200P4" value="-3.348690E+05"/>
<Constant name="rad200300P0" value="-5.18494E-07"/>
<Constant name="rad200300P1" value="8.93133E-04"/>
<Constant name="rad200300P2" value="-5.70664E-01"/>
<Constant name="rad200300P3" value="1.59796E+02"/>
<Constant name="rad200300P4" value="-1.64217E+04"/>
<Constant name="zMinForRadPar" value="330.0*cm"/>
<Constant name="ChoiceType" value="0"/>
<Constant name="NCornerCut" value="2"/>
<Constant name="FracAreaMin" value="0.2"/>
<Constant name="radMixL0" value="1365.0*mm"/>
<Constant name="radMixL1" value="1304.0*mm"/>
<Constant name="radMixL2" value="1190.0*mm"/>
<Constant name="radMixL3" value="1190.0*mm"/>
<Constant name="radMixL4" value="1147.0*mm"/>
<Constant name="radMixL5" value="1051.0*mm"/>
<Constant name="radMixL6" value="902.0*mm"/>
<Constant name="radMixL7" value="902.0*mm"/>
<Constant name="radMixL8" value="902.0*mm"/>
<Constant name="radMixL9" value="902.0*mm"/>
<Constant name="radMixL10" value="902.0*mm"/>
<Constant name="radMixL11" value="902.0*mm"/>
<Constant name="radMixL12" value="902.0*mm"/>
<Constant name="radMixL13" value="902.0*mm"/>
<Constant name="radMixL14" value="902.0*mm"/>
<Constant name="radMixL15" value="902.0*mm"/>
<Constant name="slope1" value="[etaMax:slope]"/>
<Constant name="slope2" value="tan(19.3*deg)"/>
<Constant name="slope3" value="tan(53.0*deg)"/>
<Constant name="zHGCal1" value="3190.50*mm"/>
<Constant name="zHGCal2" value="3878.51*mm"/>
<Constant name="zHGCal4" value="5137.70*mm"/>
<Constant name="rMinHGCal1" value="[slope1]*[zHGCal1]"/>
<Constant name="rMinHGCal2" value="[slope1]*[zHGCal2]"/>
<Constant name="rMinHGCal4" value="[slope1]*[zHGCal4]"/>
<Constant name="rMaxHGCal1" value="1568.325*mm"/>
<Constant name="rMaxHGCal2" value="([rMaxHGCal1]+(([zHGCal2]-[zHGCal1])*[slope2]))"/>
<Constant name="rMaxHGCal3" value="2670.25*mm"/>
<Constant name="rMaxHGCal4" value="[rMaxHGCal3]"/>
<Constant name="zHGCal3" value="([zHGCal2]+([rMaxHGCal3]-[rMaxHGCal2])/[slope3])"/>
<Constant name="rMinHGCal3" value="[slope1]*[zHGCal3]"/>
<Constant name="zMinEE" value="3190.5*mm"/>
<Constant name="zMaxEE" value="([zMinEE]+339.8*mm)"/>
<Constant name="zMinHEsil" value="[zMaxEE]"/>
<Constant name="zMaxHEsil" value="([zMinHEsil]+397.0*mm)"/>
<Constant name="zMinHEmix" value="[zMaxHEsil]"/>
<Constant name="zMaxHEmix" value="([zMinHEmix]+1210.4*mm)"/>
<Constant name="rMinEEMin" value="[slope1]*[zMinEE]"/>
<Constant name="rMinEEMax" value="[slope1]*[zMaxEE]"/>
<Constant name="rMinHEsilMin" value="[slope1]*[zMinHEsil]"/>
<Constant name="rMinHEsilMax" value="[slope1]*[zMaxHEsil]"/>
<Constant name="rMinHEmixMin" value="[slope1]*[zMinHEmix]"/>
<Constant name="rMinHEmixMax" value="[slope1]*[zMaxHEmix]"/>
<Constant name="rMaxEEMin" value="([rMaxHGCal1]+(([zMinEE]-[zHGCal1])*[slope2]))"/>
<Constant name="rMaxEEMax" value="([rMaxHGCal1]+(([zMaxEE]-[zHGCal1])*[slope2]))"/>
<Constant name="rMaxHEsilMin" value="([rMaxHGCal1]+(([zMinHEsil]-[zHGCal1])*[slope2]))"/>
<Constant name="rMaxHEsilMax" value="([rMaxHGCal2]+(([zMaxHEsil]-[zHGCal2])*[slope3]))"/>
<Constant name="rMaxHEmixMin" value="([rMaxHGCal2]+(([zMinHEmix]-[zHGCal2])*[slope3]))"/>
<Constant name="rMaxHEmixMax" value="[rMaxHGCal3]"/>
</ConstantsSection>
<SolidSection label="hgcal.xml">
<Polycone name="HGCal" startPhi="0*deg" deltaPhi="360*deg">
<ZSection z="[zHGCal1]" rMin="[rMinHGCal1]" rMax="[rMaxHGCal1]"/>
<ZSection z="[zHGCal2]" rMin="[rMinHGCal2]" rMax="[rMaxHGCal2]"/>
<ZSection z="[zHGCal3]" rMin="[rMinHGCal3]" rMax="[rMaxHGCal3]"/>
<ZSection z="[zHGCal4]" rMin="[rMinHGCal4]" rMax="[rMaxHGCal4]"/>
</Polycone>
<Polycone name="HGCalHEmix" startPhi="0*deg" deltaPhi="360*deg">
<ZSection z="[zMinHEmix]" rMin="[rMinHEmixMin]" rMax="[rMaxHEmixMin]"/>
<ZSection z="[zHGCal3]" rMin="[rMinHGCal3]" rMax="[rMaxHGCal3]"/>
<ZSection z="[zMaxHEmix]" rMin="[rMinHEmixMax]" rMax="[rMaxHEmixMax]"/>
</Polycone>
</SolidSection>
<LogicalPartSection label="hgcal.xml">
<LogicalPart name="HGCal" category="unspecified">
<rSolid name="HGCal"/>
<rMaterial name="materials:Air"/>
</LogicalPart>
<LogicalPart name="HGCalHEmix" category="unspecified">
<rSolid name="HGCalHEmix"/>
<rMaterial name="materials:Air"/>
</LogicalPart>
</LogicalPartSection>
<PosPartSection label="hgcal.xml">
<PosPart copyNumber="1">
<rParent name="cms:CMSE"/>
<rChild name="hgcal:HGCal"/>
<rRotation name="rotations:000D"/>
</PosPart>
<PosPart copyNumber="1">
<rParent name="hgcal:HGCal"/>
<rChild name="hgcal:HGCalHEmix"/>
<rRotation name="rotations:000D"/>
</PosPart>
</PosPartSection>
</DDDefinition>
| {
"pile_set_name": "Github"
} |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.beam.sdk.extensions.sql.meta.provider.bigquery;
import static org.apache.beam.sdk.schemas.Schema.FieldType.INT64;
import static org.apache.beam.sdk.schemas.Schema.FieldType.STRING;
import static org.apache.beam.sdk.schemas.Schema.toSchema;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import com.google.api.services.bigquery.model.TableFieldSchema;
import com.google.api.services.bigquery.model.TableRow;
import com.google.api.services.bigquery.model.TableSchema;
import java.util.stream.Stream;
import org.apache.beam.sdk.extensions.sql.SqlTransform;
import org.apache.beam.sdk.extensions.sql.impl.BeamTableStatistics;
import org.apache.beam.sdk.extensions.sql.meta.BeamSqlTable;
import org.apache.beam.sdk.extensions.sql.meta.Table;
import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO;
import org.apache.beam.sdk.io.gcp.bigquery.TableRowJsonCoder;
import org.apache.beam.sdk.io.gcp.bigquery.TestBigQuery;
import org.apache.beam.sdk.schemas.Schema;
import org.apache.beam.sdk.testing.TestPipeline;
import org.apache.beam.sdk.transforms.Create;
import org.apache.beam.vendor.calcite.v1_20_0.com.google.common.collect.ImmutableList;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Integration tests form writing to BigQuery with Beam SQL. */
@RunWith(JUnit4.class)
public class BigQueryRowCountIT {
private static final Schema SOURCE_SCHEMA =
Schema.builder().addNullableField("id", INT64).addNullableField("name", STRING).build();
private static final String FAKE_JOB_NAME = "testPipelineOptionInjectionFakeJobName";
@Rule public transient TestPipeline pipeline = TestPipeline.create();
@Rule public transient TestPipeline readingPipeline = TestPipeline.create();
@Rule public transient TestBigQuery bigQuery = TestBigQuery.create(SOURCE_SCHEMA);
@Test
public void testEmptyTable() {
BigQueryTableProvider provider = new BigQueryTableProvider();
Table table = getTable("testTable", bigQuery.tableSpec());
BeamSqlTable sqlTable = provider.buildBeamSqlTable(table);
BeamTableStatistics size = sqlTable.getTableStatistics(TestPipeline.testingPipelineOptions());
assertNotNull(size);
assertEquals(0d, size.getRowCount(), 0.1);
}
@Test
public void testNonEmptyTable() {
BigQueryTableProvider provider = new BigQueryTableProvider();
Table table = getTable("testTable", bigQuery.tableSpec());
pipeline
.apply(
Create.of(
new TableRow().set("id", 1).set("name", "name1"),
new TableRow().set("id", 2).set("name", "name2"),
new TableRow().set("id", 3).set("name", "name3"))
.withCoder(TableRowJsonCoder.of()))
.apply(
BigQueryIO.writeTableRows()
.to(bigQuery.tableSpec())
.withSchema(
new TableSchema()
.setFields(
ImmutableList.of(
new TableFieldSchema().setName("id").setType("INTEGER"),
new TableFieldSchema().setName("name").setType("STRING"))))
.withoutValidation());
pipeline.run().waitUntilFinish();
BeamSqlTable sqlTable = provider.buildBeamSqlTable(table);
BeamTableStatistics size1 = sqlTable.getTableStatistics(TestPipeline.testingPipelineOptions());
assertNotNull(size1);
assertEquals(3d, size1.getRowCount(), 0.1);
}
/** This tests if the pipeline options are injected in the path of SQL Transform. */
@Test
public void testPipelineOptionInjection() {
BigQueryTestTableProvider provider = new BigQueryTestTableProvider();
Table table = getTable("testTable", bigQuery.tableSpec());
provider.addTable("testTable", table);
pipeline
.apply(
Create.of(
new TableRow().set("id", 1).set("name", "name1"),
new TableRow().set("id", 2).set("name", "name2"),
new TableRow().set("id", 3).set("name", "name3"))
.withCoder(TableRowJsonCoder.of()))
.apply(
BigQueryIO.writeTableRows()
.to(bigQuery.tableSpec())
.withSchema(
new TableSchema()
.setFields(
ImmutableList.of(
new TableFieldSchema().setName("id").setType("INTEGER"),
new TableFieldSchema().setName("name").setType("STRING"))))
.withoutValidation());
pipeline.run().waitUntilFinish();
// changing pipeline options
readingPipeline.getOptions().setJobName(FAKE_JOB_NAME);
// Reading from the table should update the statistics of bigQuery table
readingPipeline.apply(
SqlTransform.query(" select * from testTable ")
.withDefaultTableProvider("bigquery", provider));
readingPipeline.run().waitUntilFinish();
BigQueryTestTable sqlTable = (BigQueryTestTable) provider.buildBeamSqlTable(table);
assertEquals(FAKE_JOB_NAME, sqlTable.getJobName());
}
@Test
public void testFakeTable() {
BigQueryTableProvider provider = new BigQueryTableProvider();
Table table = getTable("fakeTable", "project:dataset.table");
BeamSqlTable sqlTable = provider.buildBeamSqlTable(table);
BeamTableStatistics size = sqlTable.getTableStatistics(TestPipeline.testingPipelineOptions());
assertTrue(size.isUnknown());
}
private static Table getTable(String name, String location) {
return Table.builder()
.name(name)
.comment(name + " table")
.location(location)
.schema(
Stream.of(Schema.Field.nullable("id", INT64), Schema.Field.nullable("name", STRING))
.collect(toSchema()))
.type("bigquery")
.build();
}
}
| {
"pile_set_name": "Github"
} |
export * from './controls/siteBreadcrumb/index';
| {
"pile_set_name": "Github"
} |
---
# ===========================================================
# OWASP SAMM2 Coverage Question template/sample
# ===========================================================
#Link to the activity that this question helps measure
activity: bcc960e835aa4ad58a9d39a272cbf6f1
#Link to the answer set that contains the potential answers for this question
answerset: f77bd45a28c8493dbba6e53b2eafa20f
#Unique identifier (GUID) used to refer to this maturity level.
#Please generate another identifier for your specific maturity level.
id: b5d33583538b4878bb4674a5f838b8ea
#One-sentence description of the criterium
text: Is the build process fully automated?
#Order of this question for the activity (in case there would be multiple)
order: 1
#Qualifying Criterion
quality:
- The build process itself doesn't require any human interaction
- Your build tools are hardened as per best practice and vendor guidance
- You encrypt the secrets required by the build tools and control access based on
the principle of least privilege
#Type Classification of the Document
type: Question
| {
"pile_set_name": "Github"
} |
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var prefix = 'fab';
var iconName = 'themeisle';
var width = 512;
var height = 512;
var ligatures = [];
var unicode = 'f2b2';
var svgPathData = 'M208 88.286c0-10 6.286-21.714 17.715-21.714 11.142 0 17.714 11.714 17.714 21.714 0 10.285-6.572 21.714-17.714 21.714C214.286 110 208 98.571 208 88.286zm304 160c0 36.001-11.429 102.286-36.286 129.714-22.858 24.858-87.428 61.143-120.857 70.572l-1.143.286v32.571c0 16.286-12.572 30.571-29.143 30.571-10 0-19.429-5.714-24.572-14.286-5.427 8.572-14.856 14.286-24.856 14.286-10 0-19.429-5.714-24.858-14.286-5.142 8.572-14.571 14.286-24.57 14.286-10.286 0-19.429-5.714-24.858-14.286-5.143 8.572-14.571 14.286-24.571 14.286-18.857 0-29.429-15.714-29.429-32.857-16.286 12.285-35.715 19.428-56.571 19.428-22 0-43.429-8.285-60.286-22.857 10.285-.286 20.571-2.286 30.285-5.714-20.857-5.714-39.428-18.857-52-36.286 21.37 4.645 46.209 1.673 67.143-11.143-22-22-56.571-58.857-68.572-87.428C1.143 321.714 0 303.714 0 289.429c0-49.714 20.286-160 86.286-160 10.571 0 18.857 4.858 23.143 14.857a158.792 158.792 0 0 1 12-15.428c2-2.572 5.714-5.429 7.143-8.286 7.999-12.571 11.714-21.142 21.714-34C182.571 45.428 232 17.143 285.143 17.143c6 0 12 .285 17.714 1.143C313.714 6.571 328.857 0 344.572 0c14.571 0 29.714 6 40 16.286.857.858 1.428 2.286 1.428 3.428 0 3.714-10.285 13.429-12.857 16.286 4.286 1.429 15.714 6.858 15.714 12 0 2.857-2.857 5.143-4.571 7.143 31.429 27.714 49.429 67.143 56.286 108 4.286-5.143 10.285-8.572 17.143-8.572 10.571 0 20.857 7.144 28.571 14.001C507.143 187.143 512 221.714 512 248.286zM188 89.428c0 18.286 12.571 37.143 32.286 37.143 19.714 0 32.285-18.857 32.285-37.143 0-18-12.571-36.857-32.285-36.857-19.715 0-32.286 18.858-32.286 36.857zM237.714 194c0-19.714 3.714-39.143 8.571-58.286-52.039 79.534-13.531 184.571 68.858 184.571 21.428 0 42.571-7.714 60-20 2-7.429 3.714-14.857 3.714-22.572 0-14.286-6.286-21.428-20.572-21.428-4.571 0-9.143.857-13.429 1.714-63.343 12.668-107.142 3.669-107.142-63.999zm-41.142 254.858c0-11.143-8.858-20.857-20.286-20.857-11.429 0-20 9.715-20 20.857v32.571c0 11.143 8.571 21.142 20 21.142 11.428 0 20.286-9.715 20.286-21.142v-32.571zm49.143 0c0-11.143-8.572-20.857-20-20.857-11.429 0-20.286 9.715-20.286 20.857v32.571c0 11.143 8.857 21.142 20.286 21.142 11.428 0 20-10 20-21.142v-32.571zm49.713 0c0-11.143-8.857-20.857-20.285-20.857-11.429 0-20.286 9.715-20.286 20.857v32.571c0 11.143 8.857 21.142 20.286 21.142 11.428 0 20.285-9.715 20.285-21.142v-32.571zm49.715 0c0-11.143-8.857-20.857-20.286-20.857-11.428 0-20.286 9.715-20.286 20.857v32.571c0 11.143 8.858 21.142 20.286 21.142 11.429 0 20.286-10 20.286-21.142v-32.571zM421.714 286c-30.857 59.142-90.285 102.572-158.571 102.572-96.571 0-160.571-84.572-160.571-176.572 0-16.857 2-33.429 6-49.714-20 33.715-29.714 72.572-29.714 111.429 0 60.286 24.857 121.715 71.429 160.857 5.143-9.714 14.857-16.286 26-16.286 10 0 19.428 5.714 24.571 14.286 5.429-8.571 14.571-14.286 24.858-14.286 10 0 19.428 5.714 24.571 14.286 5.429-8.571 14.857-14.286 24.858-14.286 10 0 19.428 5.714 24.857 14.286 5.143-8.571 14.571-14.286 24.572-14.286 10.857 0 20.857 6.572 25.714 16 43.427-36.286 68.569-92 71.426-148.286zm10.572-99.714c0-53.714-34.571-105.714-92.572-105.714-30.285 0-58.571 15.143-78.857 36.857C240.862 183.812 233.41 254 302.286 254c28.805 0 97.357-28.538 84.286 36.857 28.857-26 45.714-65.714 45.714-104.571z';
exports.definition = {
prefix: prefix,
iconName: iconName,
icon: [
width,
height,
ligatures,
unicode,
svgPathData
]};
exports.faThemeisle = exports.definition;
exports.prefix = prefix;
exports.iconName = iconName;
exports.width = width;
exports.height = height;
exports.ligatures = ligatures;
exports.unicode = unicode;
exports.svgPathData = svgPathData; | {
"pile_set_name": "Github"
} |
import * as assert from 'assert'
import * as React from 'react'
import { render, unmountComponentAtNode } from 'react-dom'
import { act } from 'react-dom/test-utils'
import { Cmd, none } from '../src/Cmd'
import { Html, map, program, programWithFlags, run } from '../src/React'
import * as App from './helpers/app'
import { delayedAssert } from './helpers/utils'
describe('React', () => {
describe('map()', () => {
it('should map an Html<A> into an Html<msg>', () => {
const log: string[] = []
const dispatch = (msg: App.Msg) => log.push(msg.type)
const btn01: Html<App.Msg> = dispatch => <button onClick={() => dispatch({ type: 'FOO' })}>Test</button>
const btn02 = map<App.Msg, App.Msg>(() => ({ type: 'BAR' }))(btn01)
btn01(dispatch).props.onClick()
btn02(dispatch).props.onClick()
assert.deepStrictEqual(log, ['FOO', 'BAR'])
})
})
describe('program()', () => {
it('should return the Model/Cmd/Sub/Html streams and Dispatch function for React - no subscription', () => {
const [container, teardown] = makeEntryPoint()
const [renderings, renderer] = makeRenderer(container)
const { dispatch, html$ } = program(App.init, App.update, viewWithMount)
html$.subscribe(v => renderer(v(dispatch)))
dispatch({ type: 'FOO' })
dispatch({ type: 'BAR' })
dispatch({ type: 'DO-THE-THING!' })
assert.deepStrictEqual(renderings, ['', 'foo', 'bar'])
teardown()
})
it('should return the Model/Cmd/Sub/Html streams and Dispatch function for React - with subscription', () => {
const [container, teardown] = makeEntryPoint()
const [renderings, renderer] = makeRenderer(container)
const subs: App.Msg[] = []
const { sub$, html$, dispatch } = program(App.init, App.update, viewWithMount, App.subscriptions)
html$.subscribe(v => renderer(v(dispatch)))
sub$.subscribe(v => subs.push(v))
dispatch({ type: 'FOO' })
dispatch({ type: 'BAR' })
dispatch({ type: 'SUB' })
assert.deepStrictEqual(subs, [{ type: 'LISTEN' }])
assert.deepStrictEqual(renderings, ['', 'foo', 'bar', 'sub'])
teardown()
})
})
describe('programWithFlags()', () => {
it('should return a function which returns a program() with flags on `init` for React', () => {
const [container, teardown] = makeEntryPoint()
const [renderings, renderer] = makeRenderer(container)
const initWithFlags = (f: string): [App.Model, Cmd<App.Msg>] => [{ x: f }, none]
const withFlags = programWithFlags(initWithFlags, App.update, viewWithMount, App.subscriptions)
const { dispatch, html$ } = withFlags('start!')
html$.subscribe(v => renderer(v(dispatch)))
assert.deepStrictEqual(renderings, ['start!'])
teardown()
})
})
describe('run()', () => {
it('should run the React Program', () => {
const [container, teardown] = makeEntryPoint()
const [renderings, renderer] = makeRenderer(container)
const p = program(App.init, App.update, view, App.subscriptions)
run(p, renderer)
p.dispatch({ type: 'FOO' })
p.dispatch({ type: 'SUB' })
p.dispatch({ type: 'BAR' })
p.dispatch({ type: 'DO-THE-THING!' })
return delayedAssert(() => {
assert.deepStrictEqual(renderings, ['', 'foo', 'sub', 'listen', 'bar', 'foo'])
teardown()
})
})
it('should run the React Program - with commands in init and on component mount', () => {
const [container, teardown] = makeEntryPoint()
const [renderings, renderer] = makeRenderer(container)
const p = program(App.initWithCmd, App.update, viewWithMount, App.subscriptions)
run(p, renderer)
// use timeout in order to better simulate a real case
const to = setTimeout(() => {
p.dispatch({ type: 'FOO' })
p.dispatch({ type: 'SUB' })
p.dispatch({ type: 'BAR' })
p.dispatch({ type: 'DO-THE-THING!' })
clearTimeout(to)
}, 250)
return delayedAssert(() => {
assert.deepStrictEqual(renderings, ['', 'baz', 'foo', 'foo', 'sub', 'listen', 'bar', 'foo'])
teardown()
}, 500)
})
})
})
// --- Utilities
function view(model: App.Model): Html<App.Msg> {
return dispatch => <Component value={model.x} onClick={() => dispatch({ type: 'FOO' })} />
}
function viewWithMount(model: App.Model): Html<App.Msg> {
return dispatch => (
<Component
value={model.x}
onClick={() => dispatch({ type: 'FOO' })}
onMount={() => dispatch({ type: 'DO-THE-THING!' })}
/>
)
}
interface ComponentProps {
value: string
onClick: () => void
onMount?: () => void
}
function Component({ value, onClick, onMount }: ComponentProps): JSX.Element {
// the component would dispatch a message on mount which will execute a command
// in case `onMount` callback is defined
React.useEffect(() => {
if (typeof onMount !== 'undefined') {
return onMount()
}
}, [])
return <button onClick={onClick}>{value}</button>
}
function makeEntryPoint(): [HTMLDivElement, () => void] {
const container = document.createElement('div')
document.body.appendChild(container)
return [
container,
() => {
unmountComponentAtNode(container)
container.remove()
}
]
}
type Contents = Array<string | null>
function makeRenderer(container: HTMLDivElement): [Contents, (dom: React.ReactElement<any>) => void] {
const log: Contents = []
return [
log,
dom => {
act(() => {
render(dom, container)
})
log.push(container.textContent)
}
]
}
| {
"pile_set_name": "Github"
} |
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: >
White Space and Line Terminator between RelationalExpression and "in" and
between "in" and ShiftExpression are allowed
es5id: 11.8.7_A1
description: Checking by using eval
---*/
//CHECK#1
if (eval("'MAX_VALUE'\u0009in\u0009Number") !== true) {
$ERROR('#1: "MAX_VALUE"\\u0009in\\u0009Number === true');
}
//CHECK#2
if (eval("'MAX_VALUE'\u000Bin\u000BNumber") !== true) {
$ERROR('#2: "MAX_VALUE"\\u000Bin\\u000BNumber === true');
}
//CHECK#3
if (eval("'MAX_VALUE'\u000Cin\u000CNumber") !== true) {
$ERROR('#3: "MAX_VALUE"\\u000Cin\\u000CNumber === true');
}
//CHECK#4
if (eval("'MAX_VALUE'\u0020in\u0020Number") !== true) {
$ERROR('#4: "MAX_VALUE"\\u0020in\\u0020Number === true');
}
//CHECK#5
if (eval("'MAX_VALUE'\u00A0in\u00A0Number") !== true) {
$ERROR('#5: "MAX_VALUE"\\u00A0in\\u00A0Number === true');
}
//CHECK#6
if (eval("'MAX_VALUE'\u000Ain\u000ANumber") !== true) {
$ERROR('#6: "MAX_VALUE"\\u000Ain\\u000ANumber === true');
}
//CHECK#7
if (eval("'MAX_VALUE'\u000Din\u000DNumber") !== true) {
$ERROR('#7: "MAX_VALUE"\\u000Din\\u000DNumber === true');
}
//CHECK#8
if (eval("'MAX_VALUE'\u2028in\u2028Number") !== true) {
$ERROR('#8: "MAX_VALUE"\\u2028in\\u2028Number === true');
}
//CHECK#9
if (eval("'MAX_VALUE'\u2029in\u2029Number") !== true) {
$ERROR('#9: "MAX_VALUE"\\u2029in\\u2029Number === true');
}
//CHECK#10
if (eval("'MAX_VALUE'\u0009\u000B\u000C\u0020\u00A0\u000A\u000D\u2028\u2029in\u0009\u000B\u000C\u0020\u00A0\u000A\u000D\u2028\u2029Number") !== true) {
$ERROR('#10: "MAX_VALUE"\\u0009\\u000B\\u000C\\u0020\\u00A0\\u000A\\u000D\\u2028\\u2029in\\u0009\\u000B\\u000C\\u0020\\u00A0\\u000A\\u000D\\u2028\\u2029Number === true');
}
| {
"pile_set_name": "Github"
} |
<?php
/**
* @copyright Copyright (c) 2017 Julius Härtl <[email protected]>
*
* @author Julius Härtl <[email protected]>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCA\Deck\Db;
use JsonSerializable;
class AssignedUsers extends RelationalEntity implements JsonSerializable {
public $id;
protected $participant;
protected $cardId;
protected $type;
public const TYPE_USER = Acl::PERMISSION_TYPE_USER;
public const TYPE_GROUP = Acl::PERMISSION_TYPE_GROUP;
public const TYPE_CIRCLE = Acl::PERMISSION_TYPE_CIRCLE;
public function __construct() {
$this->addType('id', 'integer');
$this->addType('cardId', 'integer');
$this->addType('type', 'integer');
$this->addResolvable('participant');
}
}
| {
"pile_set_name": "Github"
} |
<?php
namespace Modules\Media\Http\Controllers\Admin;
use Modules\Core\Http\Controllers\Admin\AdminBaseController;
use Modules\Media\Image\ThumbnailManager;
use Modules\Media\Repositories\FileRepository;
class MediaGridController extends AdminBaseController
{
/**
* @var FileRepository
*/
private $file;
/**
* @var ThumbnailManager
*/
private $thumbnailsManager;
public function __construct(FileRepository $file, ThumbnailManager $thumbnailsManager)
{
parent::__construct();
$this->file = $file;
$this->thumbnailsManager = $thumbnailsManager;
}
/**
* A grid view for the upload button
* @return \Illuminate\View\View
*/
public function index()
{
$files = $this->file->allForGrid();
$thumbnails = $this->thumbnailsManager->all();
return view('media::admin.grid.general', compact('files', 'thumbnails'));
}
/**
* A grid view of uploaded files used for the wysiwyg editor
* @return \Illuminate\View\View
*/
public function ckIndex()
{
$files = $this->file->allForGrid();
$thumbnails = $this->thumbnailsManager->all();
return view('media::admin.grid.ckeditor', compact('files', 'thumbnails'));
}
}
| {
"pile_set_name": "Github"
} |
//
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard.
//
#import "ECLogHandler.h"
@class NSMutableDictionary;
@interface ECLogHandlerASL : ECLogHandler
{
struct __asl_object_s *_aslClient;
NSMutableDictionary *_aslMsgs;
}
@property(nonatomic) struct __asl_object_s *aslClient; // @synthesize aslClient=_aslClient;
@property(retain, nonatomic) NSMutableDictionary *aslMsgs; // @synthesize aslMsgs=_aslMsgs;
- (void)dealloc;
- (id)init;
- (void)logFromChannel:(id)arg1 withObject:(id)arg2 arguments:(struct __va_list_tag [1])arg3 context:(CDStruct_5b5d1a5d *)arg4;
@end
| {
"pile_set_name": "Github"
} |
package com.nolanlawson.logcat.util;
import java.util.Arrays;
import android.util.Log;
/**
* Easier way to interact with logcat.
* @author nolan
*/
public class UtilLogger {
public static final boolean DEBUG_MODE = false;
private String tag;
public UtilLogger(String tag) {
this.tag = tag;
}
public UtilLogger(Class<?> clazz) {
this.tag = clazz.getSimpleName();
}
public void i(String format, Object... more) {
Log.i(tag, String.format(format, more));
}
public void i(Exception e, String format, Object... more) {
Log.i(tag, String.format(format, more), e);
}
public void w(Exception e, String format, Object... more) {
Log.w(tag, String.format(format, more), e);
}
public void w(String format, Object... more) {
Log.w(tag, String.format(format, more));
}
public void e(String format, Object... more) {
Log.e(tag, String.format(format, more));
}
public void e(Exception e, String format, Object... more) {
Log.e(tag, String.format(format, more), e);
}
public void d(String format, Object... more) {
if (DEBUG_MODE) {
for (int i = 0; i < more.length; i++) {
if (more[i] instanceof int[]) {
more[i] = Arrays.toString((int[])more[i]);
}
}
Log.d(tag, String.format(format, more));
}
}
public void d(Exception e, String format, Object... more) {
if (DEBUG_MODE) {
for (int i = 0; i < more.length; i++) {
if (more[i] instanceof int[]) {
more[i] = Arrays.toString((int[])more[i]);
}
}
Log.d(tag, String.format(format, more), e);
}
}
}
| {
"pile_set_name": "Github"
} |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Collections.Generic;
namespace Microsoft.Bot.Schema
{
/// <summary>
/// A reaction to a Message Activity.
/// </summary>
public interface IMessageReactionActivity : IActivity
{
/// <summary>
/// Gets or sets reactions added to the activity.
/// </summary>
/// <value>
/// Reactions added to the activity.
/// </value>
#pragma warning disable CA2227 // Collection properties should be read only (we can't change this without breaking binary compat)
IList<MessageReaction> ReactionsAdded { get; set; }
#pragma warning restore CA2227 // Collection properties should be read only
/// <summary>
/// Gets or sets reactions removed from the activity.
/// </summary>
/// <value>
/// Reactions removed from the activity.
/// </value>
#pragma warning disable CA2227 // Collection properties should be read only (we can't change this without breaking binary compat)
IList<MessageReaction> ReactionsRemoved { get; set; }
#pragma warning restore CA2227 // Collection properties should be read only
}
}
| {
"pile_set_name": "Github"
} |
#ifndef TAPIOCA_H
#define TAPIOCA_H
#include <QWidget>
#include <QMenuBar>
#include <QLineEdit>
#include <QLayout>
#include <QToolBar>
#include <QFormLayout>
#include <QDockWidget>
#include <QTextEdit>
#include <QListWidget>
#include <QLabel>
#include <QTreeWidget>
#include <QTreeWidgetItem>
#include <QFileSystemModel>
#include <iostream>
#include <QModelIndex>
#include <QStringListModel>
#include <stdio.h>
#include <dirent.h>
#include <regex.h>
#include <string>
#include <QDebug>
#include <QDirModel>
#include <QLCDNumber>
#include <QSlider>
#include <QDockWidget>
#include <QPushButton>
#include <QMainWindow>
#include <QButtonGroup>
#include <QProcess>
#include "MainWindow.h"
#include "NewProject.h"
#include "Tapioca.h"
#include "Console.h"
class Tapioca : public QWidget
{
Q_OBJECT
public:
Tapioca(QList <QString>, QList <QString>, QString);
QList<QString> listImages;
QMessageBox msgBox2;
QString msg1();
QDialog qDi;
signals:
void signal_a();
public slots:
void mm3d();
void mulScaleC();
void allC();
void lineC();
void fileC();
void graphC();
void georephC();
void stopped();
QString getTxt();
void msg();
void readyReadStandardOutput();
private:
QButtonGroup *modeGroupBox;
QCheckBox* imagesCheckBox;
QList<QCheckBox*> listeCasesImages;
Console cons;
QString sendCons;
QTextEdit *rPC;
QFileInfo fichier;
QCheckBox *ExpTxtQt;
QTextEdit *ByPQt;
QTextEdit *PostFixQt;
QTextEdit *NbMinPtQt;
QTextEdit *DLRQt;
// QTextEdit *Pat2Qt;
QTextEdit *DetectQt;
QTextEdit *MatchQt;
QCheckBox *NoMaxQt;
QCheckBox *NoMinQt;
QCheckBox *NoUnknownQt;
QTextEdit *RatioQt;
QTextEdit *ImInitQtQt;
std::string ExpTxtVar;
std::string ByPVar;
std::string PostFixVar;
std::string NbMinPtVar;
std::string DLRVar;
std::string DetectVar;
std::string MatchVar;
std::string NoMaxVar;
std::string NoMinVar;
std::string NoUnknownVar;
std::string RatioVar;
std::string ImInitVar;
QTextEdit *Qtr ;
QRadioButton *mulScale;
QRadioButton *all;
QRadioButton *line;
QRadioButton *file;
QRadioButton *graph;
QRadioButton *georeph;
QMessageBox msgBox;
QTextEdit *qtt ;
std::string mode;
std::string images;
QTextEdit *regularE;
QVBoxLayout *boxLayoutV ;
QVBoxLayout *boxLayoutVOp ;
QLabel *ql;
QLabel *labelSizeWm;
QLabel *labelSizeWM;
QLabel *labelOptions;
QTextEdit *resom;
QTextEdit *resoM;
std::string resom_str;
std::string resoM_str;
QCheckBox* boxTxt;
std::string txt;
std::string cmd;
std::string path_s;
QString p_stdout;
QProcess p;
std::string recup;
};
#endif // TAPIOCA_H
| {
"pile_set_name": "Github"
} |
// board.h
#ifndef BOARD_H
#define BOARD_H
// includes
#include "colour.h"
#include "piece.h"
#include "square.h"
#include "util.h"
// constants
const int Empty = 0;
const int Edge = Knight64; // HACK: uncoloured knight
const int WP = WhitePawn256;
const int WN = WhiteKnight256;
const int WB = WhiteBishop256;
const int WR = WhiteRook256;
const int WQ = WhiteQueen256;
const int WK = WhiteKing256;
const int BP = BlackPawn256;
const int BN = BlackKnight256;
const int BB = BlackBishop256;
const int BR = BlackRook256;
const int BQ = BlackQueen256;
const int BK = BlackKing256;
const int FlagsNone = 0;
const int FlagsWhiteKingCastle = 1 << 0;
const int FlagsWhiteQueenCastle = 1 << 1;
const int FlagsBlackKingCastle = 1 << 2;
const int FlagsBlackQueenCastle = 1 << 3;
const int StackSize = 4096;
// macros
#define KING_POS(board,colour) ((board)->piece[colour][0])
// types
struct board_t {
int piece_material[ColourNb]; // Thomas
int square[SquareNb];
int pos[SquareNb];
sq_t piece[ColourNb][17]; // was 32
int piece_size[ColourNb];
sq_t pawn[ColourNb][9]; // was 16
int pawn_size[ColourNb];
int piece_nb;
int number[12]; // was 16
int pawn_file[ColourNb][FileNb];
bool turn;
int flags;
int ep_square;
int ply_nb;
int sp; // TODO: MOVE ME?
int cap_sq;
int opening;
int endgame;
int pvalue; //Ryan
uint64 key;
uint64 pawn_key;
uint64 material_key;
uint64 stack[StackSize];
};
// functions
extern bool board_is_ok (const board_t * board);
extern void board_clear (board_t * board);
extern void board_copy (board_t * dst, const board_t * src);
extern void board_init_list (board_t * board);
extern bool board_is_legal (const board_t * board);
extern bool board_is_check (const board_t * board);
extern bool board_is_mate (const board_t * board);
extern bool board_is_stalemate (board_t * board);
extern bool board_is_repetition (const board_t * board);
extern int board_material (const board_t * board);
extern int board_opening (const board_t * board);
extern int board_endgame (const board_t * board);
#endif // !defined BOARD_H
// end of board.h
| {
"pile_set_name": "Github"
} |
// MESSAGE DATA_LOG PACKING
#define MAVLINK_MSG_ID_DATA_LOG 177
typedef struct __mavlink_data_log_t
{
float fl_1; ///< Log value 1
float fl_2; ///< Log value 2
float fl_3; ///< Log value 3
float fl_4; ///< Log value 4
float fl_5; ///< Log value 5
float fl_6; ///< Log value 6
} mavlink_data_log_t;
#define MAVLINK_MSG_ID_DATA_LOG_LEN 24
#define MAVLINK_MSG_ID_177_LEN 24
#define MAVLINK_MESSAGE_INFO_DATA_LOG { \
"DATA_LOG", \
6, \
{ { "fl_1", NULL, MAVLINK_TYPE_FLOAT, 0, 0, offsetof(mavlink_data_log_t, fl_1) }, \
{ "fl_2", NULL, MAVLINK_TYPE_FLOAT, 0, 4, offsetof(mavlink_data_log_t, fl_2) }, \
{ "fl_3", NULL, MAVLINK_TYPE_FLOAT, 0, 8, offsetof(mavlink_data_log_t, fl_3) }, \
{ "fl_4", NULL, MAVLINK_TYPE_FLOAT, 0, 12, offsetof(mavlink_data_log_t, fl_4) }, \
{ "fl_5", NULL, MAVLINK_TYPE_FLOAT, 0, 16, offsetof(mavlink_data_log_t, fl_5) }, \
{ "fl_6", NULL, MAVLINK_TYPE_FLOAT, 0, 20, offsetof(mavlink_data_log_t, fl_6) }, \
} \
}
/**
* @brief Pack a data_log message
* @param system_id ID of this system
* @param component_id ID of this component (e.g. 200 for IMU)
* @param msg The MAVLink message to compress the data into
*
* @param fl_1 Log value 1
* @param fl_2 Log value 2
* @param fl_3 Log value 3
* @param fl_4 Log value 4
* @param fl_5 Log value 5
* @param fl_6 Log value 6
* @return length of the message in bytes (excluding serial stream start sign)
*/
static inline uint16_t mavlink_msg_data_log_pack(uint8_t system_id, uint8_t component_id, mavlink_message_t* msg,
float fl_1, float fl_2, float fl_3, float fl_4, float fl_5, float fl_6)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
char buf[24];
_mav_put_float(buf, 0, fl_1);
_mav_put_float(buf, 4, fl_2);
_mav_put_float(buf, 8, fl_3);
_mav_put_float(buf, 12, fl_4);
_mav_put_float(buf, 16, fl_5);
_mav_put_float(buf, 20, fl_6);
memcpy(_MAV_PAYLOAD_NON_CONST(msg), buf, 24);
#else
mavlink_data_log_t packet;
packet.fl_1 = fl_1;
packet.fl_2 = fl_2;
packet.fl_3 = fl_3;
packet.fl_4 = fl_4;
packet.fl_5 = fl_5;
packet.fl_6 = fl_6;
memcpy(_MAV_PAYLOAD_NON_CONST(msg), &packet, 24);
#endif
msg->msgid = MAVLINK_MSG_ID_DATA_LOG;
return mavlink_finalize_message(msg, system_id, component_id, 24, 167);
}
/**
* @brief Pack a data_log message on a channel
* @param system_id ID of this system
* @param component_id ID of this component (e.g. 200 for IMU)
* @param chan The MAVLink channel this message was sent over
* @param msg The MAVLink message to compress the data into
* @param fl_1 Log value 1
* @param fl_2 Log value 2
* @param fl_3 Log value 3
* @param fl_4 Log value 4
* @param fl_5 Log value 5
* @param fl_6 Log value 6
* @return length of the message in bytes (excluding serial stream start sign)
*/
static inline uint16_t mavlink_msg_data_log_pack_chan(uint8_t system_id, uint8_t component_id, uint8_t chan,
mavlink_message_t* msg,
float fl_1,float fl_2,float fl_3,float fl_4,float fl_5,float fl_6)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
char buf[24];
_mav_put_float(buf, 0, fl_1);
_mav_put_float(buf, 4, fl_2);
_mav_put_float(buf, 8, fl_3);
_mav_put_float(buf, 12, fl_4);
_mav_put_float(buf, 16, fl_5);
_mav_put_float(buf, 20, fl_6);
memcpy(_MAV_PAYLOAD_NON_CONST(msg), buf, 24);
#else
mavlink_data_log_t packet;
packet.fl_1 = fl_1;
packet.fl_2 = fl_2;
packet.fl_3 = fl_3;
packet.fl_4 = fl_4;
packet.fl_5 = fl_5;
packet.fl_6 = fl_6;
memcpy(_MAV_PAYLOAD_NON_CONST(msg), &packet, 24);
#endif
msg->msgid = MAVLINK_MSG_ID_DATA_LOG;
return mavlink_finalize_message_chan(msg, system_id, component_id, chan, 24, 167);
}
/**
* @brief Encode a data_log struct into a message
*
* @param system_id ID of this system
* @param component_id ID of this component (e.g. 200 for IMU)
* @param msg The MAVLink message to compress the data into
* @param data_log C-struct to read the message contents from
*/
static inline uint16_t mavlink_msg_data_log_encode(uint8_t system_id, uint8_t component_id, mavlink_message_t* msg, const mavlink_data_log_t* data_log)
{
return mavlink_msg_data_log_pack(system_id, component_id, msg, data_log->fl_1, data_log->fl_2, data_log->fl_3, data_log->fl_4, data_log->fl_5, data_log->fl_6);
}
/**
* @brief Send a data_log message
* @param chan MAVLink channel to send the message
*
* @param fl_1 Log value 1
* @param fl_2 Log value 2
* @param fl_3 Log value 3
* @param fl_4 Log value 4
* @param fl_5 Log value 5
* @param fl_6 Log value 6
*/
#ifdef MAVLINK_USE_CONVENIENCE_FUNCTIONS
static inline void mavlink_msg_data_log_send(mavlink_channel_t chan, float fl_1, float fl_2, float fl_3, float fl_4, float fl_5, float fl_6)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
char buf[24];
_mav_put_float(buf, 0, fl_1);
_mav_put_float(buf, 4, fl_2);
_mav_put_float(buf, 8, fl_3);
_mav_put_float(buf, 12, fl_4);
_mav_put_float(buf, 16, fl_5);
_mav_put_float(buf, 20, fl_6);
_mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_DATA_LOG, buf, 24, 167);
#else
mavlink_data_log_t packet;
packet.fl_1 = fl_1;
packet.fl_2 = fl_2;
packet.fl_3 = fl_3;
packet.fl_4 = fl_4;
packet.fl_5 = fl_5;
packet.fl_6 = fl_6;
_mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_DATA_LOG, (const char *)&packet, 24, 167);
#endif
}
#endif
// MESSAGE DATA_LOG UNPACKING
/**
* @brief Get field fl_1 from data_log message
*
* @return Log value 1
*/
static inline float mavlink_msg_data_log_get_fl_1(const mavlink_message_t* msg)
{
return _MAV_RETURN_float(msg, 0);
}
/**
* @brief Get field fl_2 from data_log message
*
* @return Log value 2
*/
static inline float mavlink_msg_data_log_get_fl_2(const mavlink_message_t* msg)
{
return _MAV_RETURN_float(msg, 4);
}
/**
* @brief Get field fl_3 from data_log message
*
* @return Log value 3
*/
static inline float mavlink_msg_data_log_get_fl_3(const mavlink_message_t* msg)
{
return _MAV_RETURN_float(msg, 8);
}
/**
* @brief Get field fl_4 from data_log message
*
* @return Log value 4
*/
static inline float mavlink_msg_data_log_get_fl_4(const mavlink_message_t* msg)
{
return _MAV_RETURN_float(msg, 12);
}
/**
* @brief Get field fl_5 from data_log message
*
* @return Log value 5
*/
static inline float mavlink_msg_data_log_get_fl_5(const mavlink_message_t* msg)
{
return _MAV_RETURN_float(msg, 16);
}
/**
* @brief Get field fl_6 from data_log message
*
* @return Log value 6
*/
static inline float mavlink_msg_data_log_get_fl_6(const mavlink_message_t* msg)
{
return _MAV_RETURN_float(msg, 20);
}
/**
* @brief Decode a data_log message into a struct
*
* @param msg The message to decode
* @param data_log C-struct to decode the message contents into
*/
static inline void mavlink_msg_data_log_decode(const mavlink_message_t* msg, mavlink_data_log_t* data_log)
{
#if MAVLINK_NEED_BYTE_SWAP
data_log->fl_1 = mavlink_msg_data_log_get_fl_1(msg);
data_log->fl_2 = mavlink_msg_data_log_get_fl_2(msg);
data_log->fl_3 = mavlink_msg_data_log_get_fl_3(msg);
data_log->fl_4 = mavlink_msg_data_log_get_fl_4(msg);
data_log->fl_5 = mavlink_msg_data_log_get_fl_5(msg);
data_log->fl_6 = mavlink_msg_data_log_get_fl_6(msg);
#else
memcpy(data_log, _MAV_PAYLOAD(msg), 24);
#endif
}
| {
"pile_set_name": "Github"
} |
// The MIT License (MIT)
// Copyright © 2017 Ivan Varabei ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
extension UIButton {
typealias UIButtonTargetClosure = () -> ()
private class ClosureWrapper: NSObject {
let closure: UIButtonTargetClosure
init(_ closure: @escaping UIButtonTargetClosure) {
self.closure = closure
}
}
private struct AssociatedKeys {
static var targetClosure = "targetClosure"
}
private var targetClosure: UIButtonTargetClosure? {
get {
guard let closureWrapper = objc_getAssociatedObject(self, &AssociatedKeys.targetClosure) as? ClosureWrapper else { return nil }
return closureWrapper.closure
}
set(newValue) {
guard let newValue = newValue else { return }
objc_setAssociatedObject(self, &AssociatedKeys.targetClosure, ClosureWrapper(newValue), objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
func target(_ action: @escaping UIButtonTargetClosure) {
targetClosure = action
addTarget(self, action: #selector(UIButton.targetAction), for: .touchUpInside)
}
@objc func targetAction() {
guard let targetClosure = targetClosure else { return }
targetClosure()
}
}
extension UIButton {
func setTitle(_ title: String, color: UIColor? = nil) {
self.setTitle(title, for: .normal)
if let color = color {
self.setTitleColor(color)
}
}
func setTitleColor(_ color: UIColor) {
self.setTitleColor(color, for: .normal)
self.setTitleColor(color.withAlphaComponent(0.7), for: .highlighted)
}
func setImage(_ image: UIImage) {
self.setImage(image, for: .normal)
self.imageView?.contentMode = .scaleAspectFit
}
func removeAllTargets() {
self.removeTarget(nil, action: nil, for: .allEvents)
}
func showText(_ text: String, withComplection completion: (() -> Void)! = {}) {
let baseText = self.titleLabel?.text ?? " "
SPAnimation.animate(0.2, animations: {
self.titleLabel?.alpha = 0
}, withComplection: {
self.setTitle(text, for: .normal)
SPAnimation.animate(0.2, animations: {
self.titleLabel?.alpha = 1
}, withComplection: {
SPAnimation.animate(0.2, animations: {
self.titleLabel?.alpha = 0
}, delay: 0.35,
withComplection: {
self.setTitle(baseText, for: .normal)
SPAnimation.animate(0.2, animations: {
self.titleLabel?.alpha = 1
}, withComplection: {
completion()
})
})
})
})
}
func setAnimatableText(_ text: String, withComplection completion: (() -> Void)! = {}) {
SPAnimation.animate(0.3, animations: {
self.titleLabel?.alpha = 0
}, withComplection: {
self.setTitle(text, for: .normal)
SPAnimation.animate(0.3, animations: {
self.titleLabel?.alpha = 1
}, withComplection: {
completion()
})
})
}
func hideContent(completion: (() -> Void)! = {}) {
SPAnimation.animate(0.25, animations: {
self.titleLabel?.alpha = 0
}, withComplection: {
completion()
})
}
func showContent(completion: (() -> Void)! = {}) {
SPAnimation.animate(0.25, animations: {
self.titleLabel?.alpha = 1
}, withComplection: {
completion()
})
}
}
| {
"pile_set_name": "Github"
} |
#
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2000-2007 Donald N. Allingham
# Copyright (C) 2008 Brian G. Matherly
# Copyright (C) 2010 Gary Burton
# Copyright (C) 2010 Jakim Friant
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
"""Tools/Utilities/Relationship Calculator"""
#-------------------------------------------------------------------------
#
# Standard python modules
#
#-------------------------------------------------------------------------
#-------------------------------------------------------------------------
#
# GNOME libraries
#
#-------------------------------------------------------------------------
from gi.repository import Gdk
from gi.repository import Gtk
#-------------------------------------------------------------------------
#
# Gramps modules
#
#-------------------------------------------------------------------------
from gramps.gen.const import GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext
from gramps.gen.display.name import displayer as name_displayer
from gramps.gui.managedwindow import ManagedWindow
from gramps.gui.views.treemodels import PeopleBaseModel, PersonTreeModel
from gramps.plugins.lib.libpersonview import BasePersonView
from gramps.gen.relationship import get_relationship_calculator
from gramps.gen.const import URL_MANUAL_PAGE
from gramps.gui.display import display_help
from gramps.gui.dialog import ErrorDialog
from gramps.gui.plug import tool
from gramps.gui.glade import Glade
#-------------------------------------------------------------------------
#
# Constants
#
#-------------------------------------------------------------------------
column_names = [column[0] for column in BasePersonView.COLUMNS]
WIKI_HELP_PAGE = URL_MANUAL_PAGE + "_-_Tools"
WIKI_HELP_SEC = _('Relationship Calculator')
#-------------------------------------------------------------------------
#
#
#
#-------------------------------------------------------------------------
class RelCalc(tool.Tool, ManagedWindow):
def __init__(self, dbstate, user, options_class, name, callback=None):
uistate = user.uistate
"""
Relationship calculator class.
"""
tool.Tool.__init__(self, dbstate, options_class, name)
ManagedWindow.__init__(self,uistate,[],self.__class__)
#set the columns to see
for data in BasePersonView.CONFIGSETTINGS:
if data[0] == 'columns.rank':
colord = data[1]
elif data[0] == 'columns.visible':
colvis = data[1]
elif data[0] == 'columns.size':
colsize = data[1]
self.colord = []
for col, size in zip(colord, colsize):
if col in colvis:
self.colord.append((1, col, size))
else:
self.colord.append((0, col, size))
self.dbstate = dbstate
self.relationship = get_relationship_calculator(glocale)
self.relationship.connect_db_signals(dbstate)
self.glade = Glade()
self.person = self.db.get_person_from_handle(
uistate.get_active('Person'))
name = ''
if self.person:
name = name_displayer.display(self.person)
self.title = _('Relationship calculator: %(person_name)s'
) % {'person_name' : name}
window = self.glade.toplevel
self.titlelabel = self.glade.get_object('title')
self.set_window(window, self.titlelabel,
_('Relationship to %(person_name)s'
) % {'person_name' : name},
self.title)
self.setup_configs('interface.relcalc', 600, 400)
self.tree = self.glade.get_object("peopleList")
self.text = self.glade.get_object("text1")
self.textbuffer = Gtk.TextBuffer()
self.text.set_buffer(self.textbuffer)
self.model = PersonTreeModel(self.db, uistate)
self.tree.set_model(self.model)
self.tree.connect('key-press-event', self._key_press)
self.selection = self.tree.get_selection()
self.selection.set_mode(Gtk.SelectionMode.SINGLE)
#keep reference of column so garbage collection works
self.columns = []
for pair in self.colord:
if not pair[0]:
continue
name = column_names[pair[1]]
column = Gtk.TreeViewColumn(name, Gtk.CellRendererText(),
markup=pair[1])
column.set_resizable(True)
column.set_min_width(60)
column.set_sizing(Gtk.TreeViewColumnSizing.GROW_ONLY)
self.tree.append_column(column)
#keep reference of column so garbage collection works
self.columns.append(column)
self.sel = self.tree.get_selection()
self.changedkey = self.sel.connect('changed',self.on_apply_clicked)
self.closebtn = self.glade.get_object("button5")
self.closebtn.connect('clicked', self.close)
help_btn = self.glade.get_object("help_btn")
help_btn.connect('clicked', lambda x: display_help(WIKI_HELP_PAGE,
WIKI_HELP_SEC))
if not self.person:
self.window.hide()
ErrorDialog(_('Active person has not been set'),
_('You must select an active person for this '
'tool to work properly.'),
parent=uistate.window)
self.close()
return
self.show()
def close(self, *obj):
""" Close relcalc tool. Remove non-gtk connections so garbage
collection can do its magic.
"""
self.relationship.disconnect_db_signals(self.dbstate)
self.sel.disconnect(self.changedkey)
ManagedWindow.close(self, *obj)
def build_menu_names(self, obj):
return (_("Relationship Calculator tool"),None)
def on_apply_clicked(self, obj):
model, iter_ = self.tree.get_selection().get_selected()
if not iter_:
return
other_person = None
handle = model.get_handle_from_iter(iter_)
if handle:
other_person = self.db.get_person_from_handle(handle)
if other_person is None:
self.textbuffer.set_text("")
return
#now determine the relation, and print it out
rel_strings, common_an = self.relationship.get_all_relationships(
self.db, self.person, other_person)
p1 = name_displayer.display(self.person)
p2 = name_displayer.display(other_person)
text = []
if other_person is None:
pass
elif self.person.handle == other_person.handle:
rstr = _("%(person)s and %(active_person)s are the same person.") % {
'person': p1,
'active_person': p2
}
text.append((rstr, ""))
elif len(rel_strings) == 0:
rstr = _("%(person)s and %(active_person)s are not related.") % {
'person': p2,
'active_person': p1
}
text.append((rstr, ""))
for rel_string, common in zip(rel_strings, common_an):
rstr = _("%(person)s is the %(relationship)s of %(active_person)s."
) % {'person': p2,
'relationship': rel_string,
'active_person': p1
}
length = len(common)
if length == 1:
person = self.db.get_person_from_handle(common[0])
if common[0] in [other_person.handle, self.person.handle]:
commontext = ''
else :
name = name_displayer.display(person)
commontext = " " + _("Their common ancestor is %s.") % name
elif length == 2:
p1c = self.db.get_person_from_handle(common[0])
p2c = self.db.get_person_from_handle(common[1])
p1str = name_displayer.display(p1c)
p2str = name_displayer.display(p2c)
commontext = " " + _("Their common ancestors are %(ancestor1)s and %(ancestor2)s.") % {
'ancestor1': p1str,
'ancestor2': p2str
}
elif length > 2:
index = 0
commontext = " " + _("Their common ancestors are: ")
for person_handle in common:
person = self.db.get_person_from_handle(person_handle)
if index:
# TODO for Arabic, should the next comma be translated?
commontext += ", "
commontext += name_displayer.display(person)
index += 1
commontext += "."
else:
commontext = ""
text.append((rstr, commontext))
textval = ""
for val in text:
textval += "%s %s\n" % (val[0], val[1])
self.textbuffer.set_text(textval)
def _key_press(self, obj, event):
if event.keyval in (Gdk.KEY_Return, Gdk.KEY_KP_Enter):
store, paths = self.selection.get_selected_rows()
if paths and len(paths[0]) == 1 :
if self.tree.row_expanded(paths[0]):
self.tree.collapse_row(paths[0])
else:
self.tree.expand_row(paths[0], 0)
return True
return False
#------------------------------------------------------------------------
#
#
#
#------------------------------------------------------------------------
class RelCalcOptions(tool.ToolOptions):
"""
Defines options and provides handling interface.
"""
def __init__(self, name,person_id=None):
tool.ToolOptions.__init__(self, name,person_id)
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.