text:
package com.microsoft.bingads.examples.v9;

import java.util.concurrent.ExecutionException;
import java.net.*;
import java.io.*;

import com.microsoft.bingads.*;
import com.microsoft.bingads.PasswordAuthentication;
import com.microsoft.bingads.reporting.AdApiError;
import com.microsoft.bingads.reporting.AdApiFaultDetail_Exception;
import com.microsoft.bingads.reporting.ApiFaultDetail_Exception;
import com.microsoft.bingads.reporting.BatchError;
import com.microsoft.bingads.reporting.OperationError;
import com.microsoft.bingads.reporting.*;

public class ReportRequests extends ExampleBaseV9 {

    static AuthorizationData authorizationData;
    static ReportingServiceManager ReportingServiceManager;

    // The directory for the report file.
    static java.lang.String FileDirectory = "c:\\reports\\";

    // The name of the report file.
    static java.lang.String ResultFileName = "result";

    // The report file extension type.
    static ReportFormat ReportFileFormat = ReportFormat.CSV;

    public static void main(String[] args) {

    	// Confirm that the download folder exists; otherwise, exit.

    	String folder = FileDirectory.substring(0, FileDirectory.lastIndexOf('\\'));
        File dir = new File(folder);

        if (!dir.exists())
        {
            System.out.println("The output folder does not exist. Ensure that the " +
                "folder exists and try again.");
            return;
        }

        try
        {
            authorizationData = new AuthorizationData();
            authorizationData.setDeveloperToken(DeveloperToken);
            authorizationData.setAuthentication(new PasswordAuthentication(UserName, Password));
            authorizationData.setCustomerId(CustomerId);
            authorizationData.setAccountId(AccountId);

            ReportingServiceManager = new ReportingServiceManager(authorizationData);
            ReportingServiceManager.setStatusPollIntervalInMilliseconds(5000);

            // You can submit one of the example reports, or build your own.
	    ReportRequest reportRequest = getKeywordPerformanceReportRequest();

	    ReportingDownloadParameters reportingDownloadParameters = new ReportingDownloadParameters();
	    reportingDownloadParameters.setReportRequest(reportRequest);
	    reportingDownloadParameters.setResultFileDirectory(new File(FileDirectory));
	    reportingDownloadParameters.setResultFileName(ResultFileName);
	    reportingDownloadParameters.setOverwriteResultFile(true);

            // Option A - Background Completion with ReportingServiceManager
            // You can submit a download or upload request and the ReportingServiceManager will automatically
            // return results. The ReportingServiceManager abstracts the details of checking for result file
            // completion, and you don't have to write any code for results polling.

            outputStatusMessage("Awaiting Background Completion . . .");
            backgroundCompletion(reportingDownloadParameters);

            // Option B - Submit and Download with ReportingServiceManager
            // Submit the download request and then use the ReportingOperation result to
            // track status until the report is complete e.g. either using
            // trackAsync or GetStatusAsync.

            outputStatusMessage("Awaiting Submit and Download . . .");
            submitAndDownload(reportRequest);

            // Option C - Download Results with ReportingServiceManager
            // If for any reason you have to resume from a previous application state,
            // you can use an existing download request identifier and use it
            // to download the result file. Use TrackAsync to indicate that the application
            // should wait to ensure that the download status is completed.

            // For example you might have previously retrieved a request ID using SubmitDownloadAsync.
            ReportingDownloadOperation reportingDownloadOperation = ReportingServiceManager.submitDownloadAsync(reportRequest, null).get();
            java.lang.String requestId = reportingDownloadOperation.getRequestId();

            // Given the request ID above, you can resume the workflow and download the report.
            // The report request identifier is valid for two days.
            // If you do not download the report within two days, you must request the report again.
            outputStatusMessage("Awaiting Download Results . . .");
            downloadResults(requestId);

        } catch (ExecutionException ee) {
			Throwable cause = ee.getCause();
			if (cause instanceof AdApiFaultDetail_Exception) {
				AdApiFaultDetail_Exception ex = (AdApiFaultDetail_Exception)cause;
				outputStatusMessage("The operation failed with the following faults:\n");

				for (AdApiError error : ex.getFaultInfo().getErrors().getAdApiErrors())
				{
					outputStatusMessage("AdApiError\n");
					outputStatusMessage(String.format("Code: %d\nError Code: %s\nMessage: %s\n\n",
							error.getCode(), error.getErrorCode(), error.getMessage()));
				}
			} else if (cause instanceof ApiFaultDetail_Exception) {
				ApiFaultDetail_Exception ex = (ApiFaultDetail_Exception)cause;
				outputStatusMessage("The operation failed with the following faults:\n");

				for (BatchError error : ex.getFaultInfo().getBatchErrors().getBatchErrors())
				{
					outputStatusMessage(String.format("BatchError at Index: %d\n", error.getIndex()));
					outputStatusMessage(String.format("Code: %d\nMessage: %s\n\n", error.getCode(), error.getMessage()));
				}

				for (OperationError error : ex.getFaultInfo().getOperationErrors().getOperationErrors())
				{
					outputStatusMessage("OperationError\n");
					outputStatusMessage(String.format("Code: %d\nMessage: %s\n\n", error.getCode(), error.getMessage()));
				}
			} else {
				ee.printStackTrace();
			}
		} catch (OAuthTokenRequestException ex) {
			outputStatusMessage(String.format("Couldn't get OAuth tokens. Error: {0}. Description: {1}",
					ex.getDetails().getError(), ex.getDetails().getDescription()));
			ex.printStackTrace();
		} catch (ReportingOperationInProgressException ex) {
			outputStatusMessage("The result file for the reporting operation is not yet available for download.");
			ex.printStackTrace();
		} catch (ReportingOperationCouldNotBeCompletedException ex) {
			outputStatusMessage(String.format("ReportingOperationCouldNotBeCompletedException Message: {0}", ex.getMessage()));
			ex.printStackTrace();
		} catch (InterruptedException ex) {
			ex.printStackTrace();
		} catch (IOException ex) {
			ex.printStackTrace();
		} catch (URISyntaxException ex) {
			ex.printStackTrace();
		}

    }

    // You can submit a download or upload request and the ReportingServiceManager will automatically
    // return results. The ReportingServiceManager abstracts the details of checking for result file
    // completion, and you don't have to write any code for results polling.
    private static void backgroundCompletion(ReportingDownloadParameters reportingDownloadParameters)
    		throws ExecutionException, InterruptedException {
		File resultFile = ReportingServiceManager.downloadFileAsync(
				reportingDownloadParameters,
				null).get();

		outputStatusMessage(String.format("Download result file: %s\n", resultFile.getName()));
    }

    // Submit the download request and then use the ReportingDownloadOperation result to
    // track status yourself using GetStatusAsync.
    private static void submitAndDownload(ReportRequest reportRequest)
    		throws ExecutionException, InterruptedException, URISyntaxException, IOException {
		ReportingDownloadOperation reportingDownloadOperation = ReportingServiceManager.submitDownloadAsync(
				reportRequest,
				null).get();

		ReportingOperationStatus reportingOperationStatus = reportingDownloadOperation.trackAsync(null).get();

		// You can use trackAsync to poll until complete as shown above,
		// or use custom polling logic with getStatusAsync as shown below.

//		ReportingOperationStatus reportingOperationStatus;
//
//		for (int i = 0; i < 24; i++)
//		{
//		    Thread.sleep(5000);
//		    reportingOperationStatus = reportingDownloadOperation.getStatusAsync(null).get();
//		    if (reportingOperationStatus.getStatus() == ReportRequestStatusType.SUCCESS)
//		    {
//		        break;
//		    }
//		}

		File resultFile = reportingDownloadOperation.downloadResultFileAsync(
		    new File(FileDirectory),
		    ResultFileName,
		    true, // Set this value to true if you want to decompress the ZIP file.
		    true,  // Set this value true if you want to overwrite the named file.
		    null).get();

		outputStatusMessage(String.format("Download result file: %s\n", resultFile.getName()));

    }

    // If for any reason you have to resume from a previous application state,
    // you can use an existing download request identifier and use it
    // to download the result file. Use TrackAsync to indicate that the application
    // should wait to ensure that the download status is completed.
    private static void downloadResults(java.lang.String requestId)
    		throws ExecutionException, InterruptedException, URISyntaxException, IOException {

		ReportingDownloadOperation reportingDownloadOperation = new ReportingDownloadOperation(requestId, authorizationData);

		reportingDownloadOperation.setStatusPollIntervalInMilliseconds(5000);

		// You can use trackAsync to poll until complete as shown here,
	    // or use custom polling logic with getStatusAsync.

		ReportingOperationStatus reportingOperationStatus = reportingDownloadOperation.trackAsync(null).get();

		File resultFile = reportingDownloadOperation.downloadResultFileAsync(
		    new File(FileDirectory),
		    ResultFileName,
		    true, // Set this value to true if you want to decompress the ZIP file
		    true,  // Set this value true if you want to overwrite the named file.
		    null).get();

		outputStatusMessage(String.format("Download result file: %s", resultFile.getName()));
		outputStatusMessage(String.format("Status: %s", reportingOperationStatus.getStatus()));
		outputStatusMessage(String.format("TrackingId: %s\n", reportingOperationStatus.getTrackingId()));
    }

    private static ReportRequest getKeywordPerformanceReportRequest(){
    	KeywordPerformanceReportRequest report = new KeywordPerformanceReportRequest();

        report.setFormat(ReportFileFormat);
        report.setReportName("My Keyword Performance Report");
        report.setReturnOnlyCompleteData(false);
        report.setAggregation(ReportAggregation.DAILY);

        ArrayOflong accountIds = new ArrayOflong();
        accountIds.getLongs().add(authorizationData.getAccountId());

        report.setScope(new AccountThroughAdGroupReportScope());
        report.getScope().setAccountIds(accountIds);
        report.getScope().setCampaigns(null);
        report.getScope().setAdGroups(null);

        report.setTime(new ReportTime());
        report.getTime().setPredefinedTime(ReportTimePeriod.YESTERDAY);

        // You may either use a custom date range or predefined time.
        //report.getTime().setCustomDateRangeStart(new Date());
        //report.getTime().getCustomDateRangeStart().setMonth(9);
        //report.getTime().getCustomDateRangeStart().setDay(1);
        //report.getTime().getCustomDateRangeStart().setYear(2017);
        //report.getTime().setCustomDateRangeEnd(new Date());
        //report.getTime().getCustomDateRangeEnd().setMonth(9);
        //report.getTime().getCustomDateRangeEnd().setDay(30);
        //report.getTime().getCustomDateRangeEnd().setYear(2017);

        // If you specify a filter, results may differ from data you see in the Bing Ads web application
        //report.setFilter(new KeywordPerformanceReportFilter());
        //ArrayList<DeviceTypeReportFilter> deviceTypes = new ArrayList<DeviceTypeReportFilter>();
        //deviceTypes.add(DeviceTypeReportFilter.COMPUTER);
        //deviceTypes.add(DeviceTypeReportFilter.SMART_PHONE);
        //report.getFilter().setDeviceType(deviceTypes);

        // Specify the attribute and data report columns.

        ArrayOfKeywordPerformanceReportColumn keywordPerformanceReportColumns = new ArrayOfKeywordPerformanceReportColumn();
        keywordPerformanceReportColumns.getKeywordPerformanceReportColumns().add(KeywordPerformanceReportColumn.TIME_PERIOD);
        keywordPerformanceReportColumns.getKeywordPerformanceReportColumns().add(KeywordPerformanceReportColumn.ACCOUNT_ID);
        keywordPerformanceReportColumns.getKeywordPerformanceReportColumns().add(KeywordPerformanceReportColumn.CAMPAIGN_ID);
        keywordPerformanceReportColumns.getKeywordPerformanceReportColumns().add(KeywordPerformanceReportColumn.KEYWORD);
        keywordPerformanceReportColumns.getKeywordPerformanceReportColumns().add(KeywordPerformanceReportColumn.KEYWORD_ID);
        keywordPerformanceReportColumns.getKeywordPerformanceReportColumns().add(KeywordPerformanceReportColumn.DEVICE_TYPE);
        keywordPerformanceReportColumns.getKeywordPerformanceReportColumns().add(KeywordPerformanceReportColumn.BID_MATCH_TYPE);
        keywordPerformanceReportColumns.getKeywordPerformanceReportColumns().add(KeywordPerformanceReportColumn.CLICKS);
        keywordPerformanceReportColumns.getKeywordPerformanceReportColumns().add(KeywordPerformanceReportColumn.IMPRESSIONS);
        keywordPerformanceReportColumns.getKeywordPerformanceReportColumns().add(KeywordPerformanceReportColumn.CTR);
        keywordPerformanceReportColumns.getKeywordPerformanceReportColumns().add(KeywordPerformanceReportColumn.AVERAGE_CPC);
        keywordPerformanceReportColumns.getKeywordPerformanceReportColumns().add(KeywordPerformanceReportColumn.SPEND);
        keywordPerformanceReportColumns.getKeywordPerformanceReportColumns().add(KeywordPerformanceReportColumn.QUALITY_SCORE);
        report.setColumns(keywordPerformanceReportColumns);

        // You may optionally sort by any KeywordPerformanceReportColumn, and optionally
        // specify the maximum number of rows to return in the sorted report.

        KeywordPerformanceReportSort keywordPerformanceReportSort = new KeywordPerformanceReportSort();
        keywordPerformanceReportSort.setSortColumn(KeywordPerformanceReportColumn.CLICKS);
        keywordPerformanceReportSort.setSortOrder(SortOrder.ASCENDING);
        ArrayOfKeywordPerformanceReportSort keywordPerformanceReportSorts = new ArrayOfKeywordPerformanceReportSort();
        keywordPerformanceReportSorts.getKeywordPerformanceReportSorts().add(keywordPerformanceReportSort);
        report.setSort(keywordPerformanceReportSorts);

        report.setMaxRows(10);

        return report;
    }
}


text:
#pragma once
#include <aws/sagemaker/SageMaker_EXPORTS.h>
#include <aws/sagemaker/model/CognitoMemberDefinition.h>
#include <aws/sagemaker/model/OidcMemberDefinition.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace SageMaker
{
namespace Model
{

  /**
   *
Defines an Amazon Cognito or your own OIDC IdP user group that is part of a
   * work team.

See Also:
   AWS
   * API Reference

   */
  class AWS_SAGEMAKER_API MemberDefinition
  {
  public:
    MemberDefinition();
    MemberDefinition(Aws::Utils::Json::JsonView jsonValue);
    MemberDefinition& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The Amazon Cognito user group that is part of the work team.

     */
    inline const CognitoMemberDefinition& GetCognitoMemberDefinition() const{ return m_cognitoMemberDefinition; }

    /**
     *
The Amazon Cognito user group that is part of the work team.

     */
    inline bool CognitoMemberDefinitionHasBeenSet() const { return m_cognitoMemberDefinitionHasBeenSet; }

    /**
     *
The Amazon Cognito user group that is part of the work team.

     */
    inline void SetCognitoMemberDefinition(const CognitoMemberDefinition& value) { m_cognitoMemberDefinitionHasBeenSet = true; m_cognitoMemberDefinition = value; }

    /**
     *
The Amazon Cognito user group that is part of the work team.

     */
    inline void SetCognitoMemberDefinition(CognitoMemberDefinition&& value) { m_cognitoMemberDefinitionHasBeenSet = true; m_cognitoMemberDefinition = std::move(value); }

    /**
     *
The Amazon Cognito user group that is part of the work team.

     */
    inline MemberDefinition& WithCognitoMemberDefinition(const CognitoMemberDefinition& value) { SetCognitoMemberDefinition(value); return *this;}

    /**
     *
The Amazon Cognito user group that is part of the work team.

     */
    inline MemberDefinition& WithCognitoMemberDefinition(CognitoMemberDefinition&& value) { SetCognitoMemberDefinition(std::move(value)); return *this;}

    /**
     *
A list user groups that exist in your OIDC Identity Provider (IdP). One to
     * ten groups can be used to create a single private work team. When you add a user
     * group to the list of Groups, you can add that user group to one or
     * more private work teams. If you add a user group to a private work team, all
     * workers in that user group are added to the work team.

     */
    inline const OidcMemberDefinition& GetOidcMemberDefinition() const{ return m_oidcMemberDefinition; }

    /**
     *
A list user groups that exist in your OIDC Identity Provider (IdP). One to
     * ten groups can be used to create a single private work team. When you add a user
     * group to the list of Groups, you can add that user group to one or
     * more private work teams. If you add a user group to a private work team, all
     * workers in that user group are added to the work team.

     */
    inline bool OidcMemberDefinitionHasBeenSet() const { return m_oidcMemberDefinitionHasBeenSet; }

    /**
     *
A list user groups that exist in your OIDC Identity Provider (IdP). One to
     * ten groups can be used to create a single private work team. When you add a user
     * group to the list of Groups, you can add that user group to one or
     * more private work teams. If you add a user group to a private work team, all
     * workers in that user group are added to the work team.

     */
    inline void SetOidcMemberDefinition(const OidcMemberDefinition& value) { m_oidcMemberDefinitionHasBeenSet = true; m_oidcMemberDefinition = value; }

    /**
     *
A list user groups that exist in your OIDC Identity Provider (IdP). One to
     * ten groups can be used to create a single private work team. When you add a user
     * group to the list of Groups, you can add that user group to one or
     * more private work teams. If you add a user group to a private work team, all
     * workers in that user group are added to the work team.

     */
    inline void SetOidcMemberDefinition(OidcMemberDefinition&& value) { m_oidcMemberDefinitionHasBeenSet = true; m_oidcMemberDefinition = std::move(value); }

    /**
     *
A list user groups that exist in your OIDC Identity Provider (IdP). One to
     * ten groups can be used to create a single private work team. When you add a user
     * group to the list of Groups, you can add that user group to one or
     * more private work teams. If you add a user group to a private work team, all
     * workers in that user group are added to the work team.

     */
    inline MemberDefinition& WithOidcMemberDefinition(const OidcMemberDefinition& value) { SetOidcMemberDefinition(value); return *this;}

    /**
     *
A list user groups that exist in your OIDC Identity Provider (IdP). One to
     * ten groups can be used to create a single private work team. When you add a user
     * group to the list of Groups, you can add that user group to one or
     * more private work teams. If you add a user group to a private work team, all
     * workers in that user group are added to the work team.

     */
    inline MemberDefinition& WithOidcMemberDefinition(OidcMemberDefinition&& value) { SetOidcMemberDefinition(std::move(value)); return *this;}

  private:

    CognitoMemberDefinition m_cognitoMemberDefinition;
    bool m_cognitoMemberDefinitionHasBeenSet;

    OidcMemberDefinition m_oidcMemberDefinition;
    bool m_oidcMemberDefinitionHasBeenSet;
  };

} // namespace Model
} // namespace SageMaker
} // namespace Aws

redpajama_set_name: RedPajamaGithub


text:
<?php
$this->breadcrumbs=array(
	'Creacion Usuarios'=>array('index'),
	'Create',
);

$this->menu=array(
	array('label'=>'List CreacionUsuario', 'url'=>array('index')),
	array('label'=>'Manage CreacionUsuario', 'url'=>array('admin')),
);
?>

Create CreacionUsuario

<?php echo $this->renderPartial('_form', array('model'=>$model)); ?>


text:
from examples.ForestFire.forest_fire.server import server

server.launch()


text:
do { \
_Pragma("clang diagnostic push") \
_Pragma("clang diagnostic ignored \"-Warc-performSelector-leaks\"") \
Stuff; \
_Pragma("clang diagnostic pop") \
} while (0)

//exception
#define IgnoreException(Stuff)\
@try { \
Stuff \
} \
@catch (NSException *exception) {}

//
#define SafeSyncOnMainThread(Stuff)\
if([NSThread isMainThread]){\
Stuff\
}\
else{\
dispatch_sync(dispatch_get_main_queue(), ^{\
Stuff\
});\
}\

#define FloatEqual(_first, _second) (fabsf( _first - _second ) < FLT_EPSILON)
#define IsKindOfClass(_object, _class) [_object isKindOfClass:[_class class]]

//time
#define SECOND_MINUTE   60
#define SECOND_HOUR     (60 * SECOND_MINUTE)
#define SECOND_DAY      (24 * SECOND_HOUR)

//block
#define Weak(__Obj__) weak_##__Obj__
#define DefineWeak(__Obj__) __weak typeof(__Obj__) Weak(__Obj__) = __Obj__
#define Strong(__Obj__) strong_##__Obj__
#define DefineStrong(__Obj__) __strong typeof(__Obj__) Strong(__Obj__) = __Obj__

//text size
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000
#define SIM_TEXTSIZE(text, font) [text length] > 0 ? [text \
sizeWithAttributes:@{NSFontAttributeName:font}] : CGSizeZero;
#else
#define SIM_TEXTSIZE(text, font) [text length] > 0 ? [text sizeWithFont:font] : CGSizeZero;
#endif

#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000
#define SIM_MULTILINE_TEXTSIZE(text, font, maxSize, mode) [text length] > 0 ? [text \
boundingRectWithSize:maxSize options:(NSStringDrawingUsesLineFragmentOrigin) \
attributes:@{NSFontAttributeName:font} context:nil].size : CGSizeZero;
#else
#define SIM_MULTILINE_TEXTSIZE(text, font, maxSize, mode) ([text length] > 0 ? [text \
sizeWithFont:font constrainedToSize:maxSize lineBreakMode:mode] : CGSizeZero);
#endif

#define SIM_MULTILINE_TEXTSIZE2(text, font, maxSize)  \
SIM_MULTILINE_TEXTSIZE(text, font, maxSize, NSLineBreakByWordWrapping)

//text trim
#define SIM_TRIM_EMPTY(_string_) [_string_ stringByTrimmingCharactersInSet:[NSMutableCharacterSet whitespaceAndNewlineCharacterSet]]

//custom setting
#define SimDefineValue(_name_, _type_)  \
void setValue_##_name_(_type_ value);

#define SimImpValue(_name_, _type_)  \
static _type_ _name_ = nil; \
void setValue_##_name_(_type_ value) \
{ \
_name_ = value; \
}

#define SimValue(_name_, _default_)  _name_ ? : _default_
#define SimSetValue(_name_, _value_)        setValue_##_name_(_value_);

#endif


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>Dumping Variables — Zend Framework 2 2.3.0dev documentation</title>

    <link rel="stylesheet" href="../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />

    <link rel="top" title="Zend Framework 2 2.3.0dev documentation" href="../index.html" />

Navigation

          index

Zend Framework 2 2.3.0dev documentation »

Dumping Variables¶

The static method <tt class="docutils literal">Zend\Debug\Debug::dump()</tt> prints or returns information about an expression. This simple technique
of debugging is common because it is easy to use in an ad hoc fashion and requires no initialization, special
tools, or debugging environment.

Example of dump() method

1

Zend\Debug\Debug::dump($var, $label = null, $echo = true);

The <tt class="docutils literal">$var</tt> argument specifies the expression or variable about which the <tt class="docutils literal">Zend\Debug\Debug::dump()</tt> method outputs
information.

The <tt class="docutils literal">$label</tt> argument is a string to be prepended to the output of <tt class="docutils literal">Zend\Debug\Debug::dump()</tt>. It may be useful, for
example, to use labels if you are dumping information about multiple variables on a given screen.

The boolean <tt class="docutils literal">$echo</tt> argument specifies whether the output of <tt class="docutils literal">Zend\Debug\Debug::dump()</tt> is echoed or not. If
<tt class="docutils literal">TRUE</tt>, the output is echoed. Regardless of the value of the <tt class="docutils literal">$echo</tt> argument, the return value of this method
contains the output.

It may be helpful to understand that <tt class="docutils literal">Zend\Debug\Debug::dump()</tt> method wraps the PHP function var_dump(). If the
output stream is detected as a web presentation, the output of <tt class="docutils literal">var_dump()</tt> is escaped using
htmlspecialchars() and wrapped with (X)HTML <tt class="docutils literal"><pre></tt> tags.

Tip

Debugging with ZendLog

Using <tt class="docutils literal">Zend\Debug\Debug::dump()</tt> is best for ad hoc debugging during software development. You can add code to dump
a variable and then remove the code very quickly.

Also consider the ZendLog component when writing more permanent debugging code. For
example, you can use the <tt class="docutils literal">DEBUG</tt> log level and the stream log writer to
output the string returned by <tt class="docutils literal">Zend\Debug\Debug::dump()</tt>.

This Page

        Show Source

Edit Source

            Note: You need to stay logged into your GitHub account to contribute to the documentation.

Quick search

    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

Navigation

          index

Zend Framework 2 2.3.0dev documentation »

        © Copyright 2013, Zend Technologies Ltd..
      Created using Sphinx 1.2b3.

Edit this document

        The source code of this file is hosted on GitHub. Everyone can
        update and fix errors in this document with few clicks -
        no downloads needed.

            Login with your GitHub account.

            Go to

                Dumping Variables
             on GitHub.

            Edit file contents using GitHub's text editor in your web browser

            Fill in the Commit message text box at the end of the page telling why
            you did the changes. Press Propose file change button next to it when done.

            On Send a pull request page you don't need to fill in text anymore. Just
            press Send pull request button.

            Your changes are now queued for review under project's Pull requests tab on GitHub.


text:
<resources>
    <string name="app_name">指尖资讯</string>

    <string name="click_login">点击头像登录</string>
    <string name="hint_name">用户名/Email/手机号</string>
    <string name="hint_password">密码</string>

    <string name="user_login">用户登录</string>
    <string name="login">登录</string>
    <string name="error_login_empty">用户名/Email/手机号不能为空</string>
    <string name="error_pswd_empty">密码不能为空</string>

    <string name="action_settings">Settings</string>
    <string name="transition__img">切换动画</string>
    <string name="open">打开</string>
    <string name="close">关闭</string>
    <string name="news">新闻资讯</string>
    <string name="image">图片咯</string>
    <string name="joke">开心一下</string>
    <string name="music">音乐鉴赏</string>
    <string name="chat">聊天机器人</string>
    <string name="wx">微信精选</string>
    <string name="edit">编辑</string>
    <string name="share">分享</string>
    <string name="loading">正在加载</string>
    <string name="none_net">网络未连接,点击重试</string>
    <string name="none_net_show_action">网络未连接</string>
    <string name="set">设置</string>
    <string name="action_search">search</string>
    <string name="again_press_exit">再按一次退出程序</string>
</resources>


text:
package com.stevenhu.lit;

import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends Activity implements OnClickListener
{
	//´´½¨Òì²½¼ÓÔØͼƬÀà¶ÔÏó
	private AsyncImageLoader mImageLoader = new AsyncImageLoader();

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button get = (Button)findViewById(R.id.get_image);
        get.setOnClickListener(this);
    }

    private void loadImage(final String url, final int id)
    {
    	ImageView imageView = (ImageView)findViewById(id);
    	ImageCallbackImpl callbackImpl = new ImageCallbackImpl(imageView);
    	Drawable cacheImage = mImageLoader.loadDrawable(url, callbackImpl);
    	//Èô»º´æÖдæÔÚ£¬Ö±½ÓÈ¡³öÀ´ÏÔʾ
    	if (cacheImage != null)
    	{
    		imageView.setImageDrawable(cacheImage);
    	}
    }

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v.getId() == R.id.get_image)
		{
			//´ÓÍøÂçÉÏ»ñÈ¡º£ÔôÍõµÄÈýÕÅͼƬÏÔʾ
			loadImage("http://wenwen.soso.com/p/20111003/20111003194816-1615366606.jpg", R.id.one);
	        loadImage("http://t10.baidu.com/it/u=2492256852,4267838923&fm=23&gp=0.jpg", R.id.two);
	        loadImage("http://wenwen.soso.com/p/20100410/20100410102416-1948049438.jpg", R.id.three);
		}

	}

}


text:
// Copyright (c) 2021 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
//
#ifndef BITCOIN_TEST_UTIL_CHAINSTATE_H
#define BITCOIN_TEST_UTIL_CHAINSTATE_H

#include <clientversion.h>
#include <fs.h>
#include <logging.h>
#include <node/context.h>
#include <node/utxo_snapshot.h>
#include <rpc/blockchain.h>
#include <test/util/setup_common.h>
#include <validation.h>

#include <univalue.h>

const auto NoMalleation = [](AutoFile& file, node::SnapshotMetadata& meta){};

/**
 * Create and activate a UTXO snapshot, optionally providing a function to
 * malleate the snapshot.
 *
 * If `reset_chainstate` is true, reset the original chainstate back to the genesis
 * block. This allows us to simulate more realistic conditions in which a snapshot is
 * loaded into an otherwise mostly-uninitialized datadir. It also allows us to test
 * conditions that would otherwise cause shutdowns based on the IBD chainstate going
 * past the snapshot it generated.
 */
template<typename F = decltype(NoMalleation)>
static bool
CreateAndActivateUTXOSnapshot(
    TestingSetup* fixture,
    F malleation = NoMalleation,
    bool reset_chainstate = false,
    bool in_memory_chainstate = false)
{
    node::NodeContext& node = fixture->m_node;
    fs::path root = fixture->m_path_root;

    // Write out a snapshot to the test's tempdir.
    //
    int height;
    WITH_LOCK(::cs_main, height = node.chainman->ActiveHeight());
    fs::path snapshot_path = root / fs::u8path(tfm::format("test_snapshot.%d.dat", height));
    FILE* outfile{fsbridge::fopen(snapshot_path, "wb")};
    AutoFile auto_outfile{outfile};

    UniValue result = CreateUTXOSnapshot(
        node, node.chainman->ActiveChainstate(), auto_outfile, snapshot_path, snapshot_path);
    LogPrintf(
        "Wrote UTXO snapshot to %s: %s", fs::PathToString(snapshot_path.make_preferred()), result.write());

    // Read the written snapshot in and then activate it.
    //
    FILE* infile{fsbridge::fopen(snapshot_path, "rb")};
    AutoFile auto_infile{infile};
    node::SnapshotMetadata metadata;
    auto_infile >> metadata;

    malleation(auto_infile, metadata);

    if (reset_chainstate) {
        {
            // What follows is code to selectively reset chainstate data without
            // disturbing the existing BlockManager instance, which is needed to
            // recognize the headers chain previously generated by the chainstate we're
            // removing. Without those headers, we can't activate the snapshot below.
            //
            // This is a stripped-down version of node::LoadChainstate which
            // preserves the block index.
            LOCK(::cs_main);
            uint256 gen_hash = node.chainman->ActiveChainstate().m_chain[0]->GetBlockHash();
            node.chainman->ResetChainstates();
            node.chainman->InitializeChainstate(node.mempool.get());
            Chainstate& chain = node.chainman->ActiveChainstate();
            Assert(chain.LoadGenesisBlock());
            // These cache values will be corrected shortly in `MaybeRebalanceCaches`.
            chain.InitCoinsDB(1 << 20, true, false, "");
            chain.InitCoinsCache(1 << 20);
            chain.CoinsTip().SetBestBlock(gen_hash);
            chain.setBlockIndexCandidates.insert(node.chainman->m_blockman.LookupBlockIndex(gen_hash));
            chain.LoadChainTip();
            node.chainman->MaybeRebalanceCaches();
        }
        BlockValidationState state;
        if (!node.chainman->ActiveChainstate().ActivateBestChain(state)) {
            throw std::runtime_error(strprintf("ActivateBestChain failed. (%s)", state.ToString()));
        }
        Assert(
            0 == WITH_LOCK(node.chainman->GetMutex(), return node.chainman->ActiveHeight()));
    }

    return node.chainman->ActivateSnapshot(auto_infile, metadata, in_memory_chainstate);
}

#endif // BITCOIN_TEST_UTIL_CHAINSTATE_H


text:
require 'mixlib/shellout'
require 'ocpm/config'
require 'ocpm/log'

class OCPM
  class << self
    def command(cmd)
      OCPM::Log.debug("Running command: #{cmd}")
      command = Mixlib::ShellOut.new(cmd)
      command.run_command
      status = command.status
      stdout = command.stdout
      stderr = command.stderr
      unless status.success?
        OCPM::Log.fatal("Command #{cmd} failed with status code #{status.exitstatus}")
        OCPM::Log.fatal("---STDOUT---")
        OCPM::Log.fatal(stdout)
        OCPM::Log.fatal("---STDERR---")
        OCPM::Log.fatal(stderr)
        raise RuntimeError, "Command #{cmd} failed with status code #{status.exitstatus}"
      end
      OCPM::Log.debug("---STDOUT---")
      OCPM::Log.debug(stdout)
      OCPM::Log.debug("---STDERR---")
      OCPM::Log.debug(stderr)
      return stdout, stderr
    end

    def command_per_line(cmd, &block)
      o, e = command(cmd)
      o.split("\n").each do |line|
        block.call(line)
      end
    end
  end
end


text:
using System;
using System.Security.Principal;
using System.Threading;
using System.Web;
using System.Web.Security;
using Microsoft.Web.Infrastructure.DynamicModuleHelper;
using NuGetGallery;

[assembly: WebActivator.PreApplicationStartMethod(typeof(AuthenticationModule), "Start")]

namespace NuGetGallery
{
    public class AuthenticationModule : IHttpModule
    {
        public void Init(HttpApplication context)
        {
            context.AuthenticateRequest += OnAuthenticateRequest;
        }

        public void Dispose()
        {
        }

        public static void Start()
        {
            DynamicModuleUtility.RegisterModule(typeof(AuthenticationModule));
        }

        private void OnAuthenticateRequest(object sender, EventArgs e)
        {
            var context = HttpContext.Current;
            var request = HttpContext.Current.Request;
            if (request.IsAuthenticated)
            {
                HttpCookie authCookie = request.Cookies[FormsAuthentication.FormsCookieName];
                if (authCookie != null)
                {
                    FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
                    var roles = authTicket.UserData.Split('|');
                    var user = new GenericPrincipal(context.User.Identity, roles);
                    context.User = Thread.CurrentPrincipal = user;
                }
            }
        }
    }
}


text:
<!DOCTYPE html>

    <title>PostType Enum Reference</title>
    <link rel="stylesheet" type="text/css" href="../css/jazzy.css" />
    <link rel="stylesheet" type="text/css" href="../css/highlight.css" />
    <meta charset='utf-8'>

SwiftStack Docs (52% documented)

View on GitHub

        SwiftStack Reference

        PostType Enum Reference

            Classes

                APIClient

                – RequestError

                – APIError

                – BackoffBehavior

                APIResponse

                Answer

                Comment

                Content

                Post

                – Notice

                Privilege

                Question

                – ClosedDetails

                – MigrationInfo

                – Timeline

                Revision

                – RevisionType

                Site

                – Related

                – State

                – SiteType

                – Styling

                SuggestedEdit

                User

                – UserInfoType

                – UserType

            Enums

                PostType

            Protocols

                DictionaryConvertible

                JsonConvertible

                StringRepresentable

            Structs

                BadgeCount

                JsonHelper

            Typealiases

                EncodedArray

                EncodedDictionary

PostType

public enum PostType: String, StringRepresentable

Defines the type of a post. Either a question or an answer

Author

    FelixSFD

                    answer

Undocumented

Declaration

Swift

public enum PostType: String, StringRepresentable

                        Show on GitHub

                    question

Undocumented

Declaration

Swift

public enum PostType: String, StringRepresentable

                        Show on GitHub

© 2017 NobodyNada & FelixSFD. All rights reserved. (Last updated: 2017-02-25)

Generated by jazzy ♪♫ v0.7.3, a Realm project.


text: {{ page.description | markdownify }}


text:
layout: post
title: Why I Love Extension Methods
date: 2009-11-30 09:52:08.000000000 +01:00
categories: []
tags:
- .NET
- Extension Methods
- Html Agility Pack
status: publish
type: post
published: true
meta: {}
author:
  login: admin
  email: pvlerick@gmail.com
  display_name: Philippe
  first_name: Philippe
  last_name: Vlérick
excerpt: !ruby/object:Hpricot::Doc
  options: {}
---

The other day, I was using for the first time the Html Agility Pack library.

The method I use the most is the SelectNodes to which you give an XPath and that returns an HtlmNodeCollection containing the resulting HtmlNodes or null if no node where found.

I don't know if this is a design decision, but returning null when there is no match is not very nice. If you use the expression as is in a foreach statement, it will throw a NullReferenceException if no match.

A simple solution is to use the coalescing operator next to the function's call, in order to give the foreach an empty Enumerable to avoid the exception.

htmlNode.SelectNodes(xpath) ?? Enumerable.Empty<HtmlNode>()

This is working well, but it's a bit ugly to repeat that in every foreach statement.

This is where Extension Methods are so enjoyable. Let's just add a new method to our HtmlNode friend that returns an empty enumerable when SelectNodes return null.

internal static class HtmlAgilityPackExtension
{
    internal static IEnumerable<HtmlNode> SelectNodesOrEmpty(this HtmlNode htmlNode, String xpath)
    {
        return htmlNode.SelectNodes(xpath) ?? Enumerable.Empty<HtmlNode>();
    }
}

There we go. From now on, I can simply foreach over a SelectNodesOrEmpty result of any HtmlNode, with no fear of any exception.


text:
CC            = gcc
CXX           = g++
DEFINES       = -DQT_WEBKIT -DCUCURESTORAGE_LIBRARY -DQT_NO_DEBUG -DQT_CORE_LIB -DQT_SHARED
CFLAGS        = -pipe -O2 -Wall -W -D_REENTRANT -fPIC $(DEFINES)
CXXFLAGS      = -pipe -O2 -Wall -W -D_REENTRANT -fPIC $(DEFINES)
INCPATH       = -I/usr/share/qt4/mkspecs/linux-g++ -I. -I/usr/include/qt4/QtCore -I/usr/include/qt4 -I../CuCareModel -I.
LINK          = g++
LFLAGS        = -Wl,-O1 -shared -Wl,-soname,libCuCareStorage.so.1
LIBS          = $(SUBLIBS)  -L/usr/lib/i386-linux-gnu -L/home/baltar/cucare/CuCareStorage/../CuCareModel/ -lCuCareModel -lQtCore -lpthread
AR            = ar cqs
RANLIB        =
QMAKE         = /usr/bin/qmake-qt4
TAR           = tar -cf
COMPRESS      = gzip -9f
COPY          = cp -f
SED           = sed
COPY_FILE     = $(COPY)
COPY_DIR      = $(COPY) -r
STRIP         = strip
INSTALL_FILE  = install -m 644 -p
INSTALL_DIR   = $(COPY_DIR)
INSTALL_PROGRAM = install -m 755 -p
DEL_FILE      = rm -f
SYMLINK       = ln -f -s
DEL_DIR       = rmdir
MOVE          = mv -f
CHK_DIR_EXISTS= test -d
MKDIR         = mkdir -p

####### Output directory

OBJECTS_DIR   = ./

####### Files

SOURCES       = StorageObject.cpp \
		sqlite3.c \
		Sqlite3Database.cpp \
		Repository.cpp \
		RepoModel.cpp \
		QueryResult.cpp \
		Database.cpp
OBJECTS       = StorageObject.o \
		sqlite3.o \
		Sqlite3Database.o \
		Repository.o \
		RepoModel.o \
		QueryResult.o \
		Database.o
DIST          = /usr/share/qt4/mkspecs/common/unix.conf \
		/usr/share/qt4/mkspecs/common/linux.conf \
		/usr/share/qt4/mkspecs/common/gcc-base.conf \
		/usr/share/qt4/mkspecs/common/gcc-base-unix.conf \
		/usr/share/qt4/mkspecs/common/g++-base.conf \
		/usr/share/qt4/mkspecs/common/g++-unix.conf \
		/usr/share/qt4/mkspecs/qconfig.pri \
		/usr/share/qt4/mkspecs/modules/qt_phonon.pri \
		/usr/share/qt4/mkspecs/modules/qt_webkit_version.pri \
		/usr/share/qt4/mkspecs/features/qt_functions.prf \
		/usr/share/qt4/mkspecs/features/qt_config.prf \
		/usr/share/qt4/mkspecs/features/exclusive_builds.prf \
		/usr/share/qt4/mkspecs/features/default_pre.prf \
		/usr/share/qt4/mkspecs/features/release.prf \
		/usr/share/qt4/mkspecs/features/default_post.prf \
		/usr/share/qt4/mkspecs/features/unix/gdb_dwarf_index.prf \
		/usr/share/qt4/mkspecs/features/warn_on.prf \
		/usr/share/qt4/mkspecs/features/qt.prf \
		/usr/share/qt4/mkspecs/features/unix/thread.prf \
		/usr/share/qt4/mkspecs/features/moc.prf \
		/usr/share/qt4/mkspecs/features/resources.prf \
		/usr/share/qt4/mkspecs/features/uic.prf \
		/usr/share/qt4/mkspecs/features/yacc.prf \
		/usr/share/qt4/mkspecs/features/lex.prf \
		/usr/share/qt4/mkspecs/features/include_source_dir.prf \
		CuCareStorage.pro
QMAKE_TARGET  = CuCareStorage
DESTDIR       =
TARGET        = libCuCareStorage.so.1.0.0
TARGETA       = libCuCareStorage.a
TARGETD       = libCuCareStorage.so.1.0.0
TARGET0       = libCuCareStorage.so
TARGET1       = libCuCareStorage.so.1
TARGET2       = libCuCareStorage.so.1.0

first: all
####### Implicit rules

.SUFFIXES: .o .c .cpp .cc .cxx .C

.cpp.o:
	$(CXX) -c $(CXXFLAGS) $(INCPATH) -o "$@" "$<"

.cc.o:
	$(CXX) -c $(CXXFLAGS) $(INCPATH) -o "$@" "$<"

.cxx.o:
	$(CXX) -c $(CXXFLAGS) $(INCPATH) -o "$@" "$<"

.C.o:
	$(CXX) -c $(CXXFLAGS) $(INCPATH) -o "$@" "$<"

.c.o:
	$(CC) -c $(CFLAGS) $(INCPATH) -o "$@" "$<"

####### Build rules

all: Makefile  $(TARGET)

$(TARGET): /home/baltar/cucare/CuCareStorage/../CuCareModel/libCuCareModel.a $(OBJECTS) $(SUBLIBS) $(OBJCOMP)
	-$(DEL_FILE) $(TARGET) $(TARGET0) $(TARGET1) $(TARGET2)
	$(LINK) $(LFLAGS) -o $(TARGET) $(OBJECTS) $(LIBS) $(OBJCOMP)
	-ln -s $(TARGET) $(TARGET0)
	-ln -s $(TARGET) $(TARGET1)
	-ln -s $(TARGET) $(TARGET2)

staticlib: $(TARGETA)

$(TARGETA): /home/baltar/cucare/CuCareStorage/../CuCareModel/libCuCareModel.a $(OBJECTS) $(OBJCOMP)
	-$(DEL_FILE) $(TARGETA)
	$(AR) $(TARGETA) $(OBJECTS)

Makefile: CuCareStorage.pro  /usr/share/qt4/mkspecs/linux-g++/qmake.conf /usr/share/qt4/mkspecs/common/unix.conf \
		/usr/share/qt4/mkspecs/common/linux.conf \
		/usr/share/qt4/mkspecs/common/gcc-base.conf \
		/usr/share/qt4/mkspecs/common/gcc-base-unix.conf \
		/usr/share/qt4/mkspecs/common/g++-base.conf \
		/usr/share/qt4/mkspecs/common/g++-unix.conf \
		/usr/share/qt4/mkspecs/qconfig.pri \
		/usr/share/qt4/mkspecs/modules/qt_phonon.pri \
		/usr/share/qt4/mkspecs/modules/qt_webkit_version.pri \
		/usr/share/qt4/mkspecs/features/qt_functions.prf \
		/usr/share/qt4/mkspecs/features/qt_config.prf \
		/usr/share/qt4/mkspecs/features/exclusive_builds.prf \
		/usr/share/qt4/mkspecs/features/default_pre.prf \
		/usr/share/qt4/mkspecs/features/release.prf \
		/usr/share/qt4/mkspecs/features/default_post.prf \
		/usr/share/qt4/mkspecs/features/unix/gdb_dwarf_index.prf \
		/usr/share/qt4/mkspecs/features/warn_on.prf \
		/usr/share/qt4/mkspecs/features/qt.prf \
		/usr/share/qt4/mkspecs/features/unix/thread.prf \
		/usr/share/qt4/mkspecs/features/moc.prf \
		/usr/share/qt4/mkspecs/features/resources.prf \
		/usr/share/qt4/mkspecs/features/uic.prf \
		/usr/share/qt4/mkspecs/features/yacc.prf \
		/usr/share/qt4/mkspecs/features/lex.prf \
		/usr/share/qt4/mkspecs/features/include_source_dir.prf \
		/usr/lib/i386-linux-gnu/libQtCore.prl
	$(QMAKE) -spec /usr/share/qt4/mkspecs/linux-g++ -o Makefile CuCareStorage.pro
/usr/share/qt4/mkspecs/common/unix.conf:
/usr/share/qt4/mkspecs/common/linux.conf:
/usr/share/qt4/mkspecs/common/gcc-base.conf:
/usr/share/qt4/mkspecs/common/gcc-base-unix.conf:
/usr/share/qt4/mkspecs/common/g++-base.conf:
/usr/share/qt4/mkspecs/common/g++-unix.conf:
/usr/share/qt4/mkspecs/qconfig.pri:
/usr/share/qt4/mkspecs/modules/qt_phonon.pri:
/usr/share/qt4/mkspecs/modules/qt_webkit_version.pri:
/usr/share/qt4/mkspecs/features/qt_functions.prf:
/usr/share/qt4/mkspecs/features/qt_config.prf:
/usr/share/qt4/mkspecs/features/exclusive_builds.prf:
/usr/share/qt4/mkspecs/features/default_pre.prf:
/usr/share/qt4/mkspecs/features/release.prf:
/usr/share/qt4/mkspecs/features/default_post.prf:
/usr/share/qt4/mkspecs/features/unix/gdb_dwarf_index.prf:
/usr/share/qt4/mkspecs/features/warn_on.prf:
/usr/share/qt4/mkspecs/features/qt.prf:
/usr/share/qt4/mkspecs/features/unix/thread.prf:
/usr/share/qt4/mkspecs/features/moc.prf:
/usr/share/qt4/mkspecs/features/resources.prf:
/usr/share/qt4/mkspecs/features/uic.prf:
/usr/share/qt4/mkspecs/features/yacc.prf:
/usr/share/qt4/mkspecs/features/lex.prf:
/usr/share/qt4/mkspecs/features/include_source_dir.prf:
/usr/lib/i386-linux-gnu/libQtCore.prl:
qmake:  FORCE
	@$(QMAKE) -spec /usr/share/qt4/mkspecs/linux-g++ -o Makefile CuCareStorage.pro

dist:
	@$(CHK_DIR_EXISTS) .tmp/CuCareStorage1.0.0 || $(MKDIR) .tmp/CuCareStorage1.0.0
	$(COPY_FILE) --parents $(SOURCES) $(DIST) .tmp/CuCareStorage1.0.0/ && $(COPY_FILE) --parents StorageObject.h sqlite3.h Sqlite3Database.h Repository.h RepoModel.h QueryResult.h Database.h .tmp/CuCareStorage1.0.0/ && $(COPY_FILE) --parents StorageObject.cpp sqlite3.c Sqlite3Database.cpp Repository.cpp RepoModel.cpp QueryResult.cpp Database.cpp .tmp/CuCareStorage1.0.0/ && (cd `dirname .tmp/CuCareStorage1.0.0` && $(TAR) CuCareStorage1.0.0.tar CuCareStorage1.0.0 && $(COMPRESS) CuCareStorage1.0.0.tar) && $(MOVE) `dirname .tmp/CuCareStorage1.0.0`/CuCareStorage1.0.0.tar.gz . && $(DEL_FILE) -r .tmp/CuCareStorage1.0.0

clean:compiler_clean
	-$(DEL_FILE) $(OBJECTS)
	-$(DEL_FILE) *~ core *.core

####### Sub-libraries

distclean: clean
	-$(DEL_FILE) $(TARGET)
	-$(DEL_FILE) $(TARGET0) $(TARGET1) $(TARGET2) $(TARGETA)
	-$(DEL_FILE) Makefile

check: first

mocclean: compiler_moc_header_clean compiler_moc_source_clean

mocables: compiler_moc_header_make_all compiler_moc_source_make_all

compiler_moc_header_make_all:
compiler_moc_header_clean:
compiler_rcc_make_all:
compiler_rcc_clean:
compiler_image_collection_make_all: qmake_image_collection.cpp
compiler_image_collection_clean:
	-$(DEL_FILE) qmake_image_collection.cpp
compiler_moc_source_make_all:
compiler_moc_source_clean:
compiler_uic_make_all:
compiler_uic_clean:
compiler_yacc_decl_make_all:
compiler_yacc_decl_clean:
compiler_yacc_impl_make_all:
compiler_yacc_impl_clean:
compiler_lex_make_all:
compiler_lex_clean:
compiler_clean:

####### Compile

StorageObject.o: StorageObject.cpp StorageObject.h
	$(CXX) -c $(CXXFLAGS) $(INCPATH) -o StorageObject.o StorageObject.cpp

sqlite3.o: sqlite3.c
	$(CC) -c $(CFLAGS) $(INCPATH) -o sqlite3.o sqlite3.c

Sqlite3Database.o: Sqlite3Database.cpp Sqlite3Database.h \
		Database.h \
		sqlite3.h \
		QueryResult.h
	$(CXX) -c $(CXXFLAGS) $(INCPATH) -o Sqlite3Database.o Sqlite3Database.cpp

Repository.o: Repository.cpp Repository.h \
		StorageObject.h \
		Database.h \
		sqlite3.h \
		QueryResult.h \
		RepoModel.h \
		../CuCareModel/ModelFiles.h \
		../CuCareModel/Address.h \
		../CuCareModel/AdminAssistant.h \
		../CuCareModel/User.h \
		../CuCareModel/Date.h \
		../CuCareModel/ContactInfo.h \
		../CuCareModel/ModelObject.h \
		../CuCareModel/Consultation.h \
		../CuCareModel/Time.h \
		../CuCareModel/Followup.h \
		../CuCareModel/HealthCard.h \
		../CuCareModel/MedicalTest.h \
		../CuCareModel/ResultantFollowup.h \
		../CuCareModel/MedicationRenewal.h \
		../CuCareModel/Patient.h \
		../CuCareModel/Physician.h \
		../CuCareModel/Referral.h \
		../CuCareModel/ReturnConsultation.h \
		../CuCareModel/SysAdmin.h \
		Sqlite3Database.h
	$(CXX) -c $(CXXFLAGS) $(INCPATH) -o Repository.o Repository.cpp

RepoModel.o: RepoModel.cpp RepoModel.h \
		../CuCareModel/ModelFiles.h \
		../CuCareModel/Address.h \
		../CuCareModel/AdminAssistant.h \
		../CuCareModel/User.h \
		../CuCareModel/Date.h \
		../CuCareModel/ContactInfo.h \
		../CuCareModel/ModelObject.h \
		../CuCareModel/Consultation.h \
		../CuCareModel/Time.h \
		../CuCareModel/Followup.h \
		../CuCareModel/HealthCard.h \
		../CuCareModel/MedicalTest.h \
		../CuCareModel/ResultantFollowup.h \
		../CuCareModel/MedicationRenewal.h \
		../CuCareModel/Patient.h \
		../CuCareModel/Physician.h \
		../CuCareModel/Referral.h \
		../CuCareModel/ReturnConsultation.h \
		../CuCareModel/SysAdmin.h \
		Database.h \
		sqlite3.h \
		QueryResult.h \
		../CuCareModel/Property.h \
		../CuCareModel/Utility.h
	$(CXX) -c $(CXXFLAGS) $(INCPATH) -o RepoModel.o RepoModel.cpp

QueryResult.o: QueryResult.cpp QueryResult.h
	$(CXX) -c $(CXXFLAGS) $(INCPATH) -o QueryResult.o QueryResult.cpp

Database.o: Database.cpp Database.h \
		sqlite3.h \
		QueryResult.h
	$(CXX) -c $(CXXFLAGS) $(INCPATH) -o Database.o Database.cpp

####### Install

install_target: first FORCE
	@$(CHK_DIR_EXISTS) $(INSTALL_ROOT)/usr/lib/ || $(MKDIR) $(INSTALL_ROOT)/usr/lib/
	-$(INSTALL_PROGRAM) "$(TARGET)" "$(INSTALL_ROOT)/usr/lib/$(TARGET)"
	-$(STRIP) --strip-unneeded "$(INSTALL_ROOT)/usr/lib/$(TARGET)"
	-$(SYMLINK) "$(TARGET)" "$(INSTALL_ROOT)/usr/lib/$(TARGET0)"
	-$(SYMLINK) "$(TARGET)" "$(INSTALL_ROOT)/usr/lib/$(TARGET1)"
	-$(SYMLINK) "$(TARGET)" "$(INSTALL_ROOT)/usr/lib/$(TARGET2)"

uninstall_target:  FORCE
	-$(DEL_FILE) "$(INSTALL_ROOT)/usr/lib/$(TARGET)"
	 -$(DEL_FILE) "$(INSTALL_ROOT)/usr/lib/$(TARGET0)"
	 -$(DEL_FILE) "$(INSTALL_ROOT)/usr/lib/$(TARGET1)"
	 -$(DEL_FILE) "$(INSTALL_ROOT)/usr/lib/$(TARGET2)"
	-$(DEL_DIR) $(INSTALL_ROOT)/usr/lib/

install:  install_target  FORCE

uninstall: uninstall_target   FORCE

FORCE:


text:
<#
# Copyright (c) 2014 All Rights Reserved by the SDL Group.
#
# 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.
#>

function Get-ISHCD
{
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true,ParameterSetName="From FTP")]
        [string]$FTPHost,
        [Parameter(Mandatory=$true,ParameterSetName="From FTP")]
        [pscredential]$Credential,
        [Parameter(Mandatory=$true,ParameterSetName="From FTP")]
        [ValidatePattern(".+\.[0-9]+\.0\.[0-9]+\.[0-9]+.*\.exe")]
        [string]$FTPPath,
        [Parameter(Mandatory=$true,ParameterSetName="From AWS S3")]
        [string]$BucketName,
        [Parameter(Mandatory=$true,ParameterSetName="From AWS S3")]
        [ValidatePattern(".+\.[0-9]+\.0\.[0-9]+\.[0-9]+.*\.exe")]
        [string]$Key,
        [Parameter(Mandatory=$false,ParameterSetName="From AWS S3")]
        [string]$AccessKey,
        [Parameter(Mandatory=$false,ParameterSetName="From AWS S3")]
        [string]$ProfileName,
        [Parameter(Mandatory=$false,ParameterSetName="From AWS S3")]
        [string]$ProfileLocation,
        [Parameter(Mandatory=$false,ParameterSetName="From AWS S3")]
        [string]$Region,
        [Parameter(Mandatory=$false,ParameterSetName="From AWS S3")]
        [string]$SecretKey,
        [Parameter(Mandatory=$false,ParameterSetName="From AWS S3")]
        [string]$SessionToken,
        [Parameter(Mandatory=$true,ParameterSetName="From Azure FileStorage")]
        [string]$ShareName,
        [Parameter(Mandatory=$true,ParameterSetName="From Azure FileStorage")]
        [ValidatePattern(".+\.[0-9]+\.0\.[0-9]+\.[0-9]+.*\.exe")]
        [string]$Path,
        [Parameter(Mandatory=$true,ParameterSetName="From Azure BlobStorage")]
        [string]$ContainerName,
        [Parameter(Mandatory=$true,ParameterSetName="From Azure BlobStorage")]
        [ValidatePattern(".+\.[0-9]+\.0\.[0-9]+\.[0-9]+.*\.exe")]
        [string]$BlobName,
        [Parameter(Mandatory=$true,ParameterSetName="From Azure FileStorage")]
        [Parameter(Mandatory=$true,ParameterSetName="From Azure BlobStorage")]
        [string]$StorageAccountName,
        [Parameter(Mandatory=$true,ParameterSetName="From Azure FileStorage")]
        [Parameter(Mandatory=$true,ParameterSetName="From Azure BlobStorage")]
        [string]$StorageAccountKey,
        [Parameter(Mandatory=$false,ParameterSetName="From FTP")]
        [Parameter(Mandatory=$false,ParameterSetName="From AWS S3")]
        [Parameter(Mandatory=$false,ParameterSetName="From Azure FileStorage")]
        [Parameter(Mandatory=$false,ParameterSetName="From Azure BlobStorage")]
        [switch]$Expand=$false,
        [Parameter(Mandatory=$false,ParameterSetName="From FTP")]
        [Parameter(Mandatory=$false,ParameterSetName="From AWS S3")]
        [Parameter(Mandatory=$false,ParameterSetName="From Azure FileStorage")]
        [Parameter(Mandatory=$false,ParameterSetName="From Azure BlobStorage")]
        [switch]$Force=$false,
        [Parameter(Mandatory=$true,ParameterSetName="List")]
        [switch]$ListAvailable
    )

    begin
    {
        if($PSCmdlet.ParameterSetName -ne "List")
        {
            . $PSScriptRoot\Private\Test-RunningAsElevated.ps1
            Test-RunningAsElevated -StopCallerPSCmdlet $PSCmdlet
        }

        . $PSScriptRoot\Get-ISHServerFolderPath.ps1
    }

    process
    {
        $localPath=Get-ISHServerFolderPath
        switch ($PSCmdlet.ParameterSetName)
        {
            'From FTP' {
                . $PSScriptRoot\Private\Get-ISHFTPItem.ps1

                $newItem=Get-ISHFTPItem -FTPHost $FTPHost -Credential $Credential -Path $FTPPath -LocalPath $localPath -Force:$Force
                if($Expand)
                {
                    . $PSScriptRoot\Expand-ISHCD.ps1
                    Expand-ISHCD -FileName $newItem.Name
                }
                break
            }
            'From AWS S3' {
                . $PSScriptRoot\Private\Get-ISHS3Object.ps1
                $hash=@{
                    BucketName=$BucketName
                    LocalFolder=$localPath
                    AccessKey=$AccessKey
                    ProfileName=$ProfileName
                    ProfileLocation=$ProfileLocation
                    Region=$Region
                    SecretKey=$SecretKey
                    SessionToken=$SessionToken
                }

                $newItem=Get-ISHS3Object -Key $Key @hash -Force:$Force
                if($Expand)
                {
                    . $PSScriptRoot\Expand-ISHCD.ps1
                    Expand-ISHCD -FileName $newItem.Name
                }
                break
            }
            'From Azure FileStorage' {
                . $PSScriptRoot\Private\Get-ISHAzureFileObject.ps1
                $hash=@{
                    ShareName=$ShareName
                    LocalFolder=$localPath
                    StorageAccountName=$StorageAccountName
                    StorageAccountKey=$StorageAccountKey
                }

                $newItem=Get-ISHAzureFileObject -Path $Path @hash -Force:$Force
                if($Expand)
                {
                    . $PSScriptRoot\Expand-ISHCD.ps1
                    Expand-ISHCD -FileName $newItem.Name
                }
                break
            }
            'From Azure BlobStorage' {
                . $PSScriptRoot\Private\Get-ISHAzureBlobObject.ps1
                $hash=@{
                    ContainerName=$ContainerName
                    LocalFolder=$localPath
                    StorageAccountName=$StorageAccountName
                    StorageAccountKey=$StorageAccountKey
                }

                $newItem=Get-ISHAzureBlobObject -BlobName $BlobName @hash -Force:$Force
                if($Expand)
                {
                    . $PSScriptRoot\Expand-ISHCD.ps1
                    Expand-ISHCD -FileName $newItem.Name
                }
                break
            }
            'List' {
                function RemoveSDLSegments([string]$path)
                {
                    return $path.Replace(".Test","").Replace(".Prod","")
                }
                $regEx=".+\.(?<Major>[0-9]+)\.0\.(?<Build>[0-9]+)\.(?<Revision>[0-9]+)(\.Test)*(\.Prod)*.+\.exe"
                $availableItems=@()
                $ishCDPath="C:\IshCD"
                Get-ChildItem -Path $localPath -File |Where-Object -Property Name -Match $regEx|ForEach-Object {
                    $hash=[ordered]@{
                        Name=$_.Name
                        Major=[int]$Matches["Major"]
                        Minor=0
                        Build=[int]$Matches["Build"]
                        Revision=[int]$Matches["Revision"]
                        IsExpanded=$false
                        ExpandedPath=$null
                    }

                    $ishVersion="$($hash.Major).0.$($hash.Revision)"
                    Write-Debug "ishVersion=$ishVersion"
                    $expandPath="$ishCDPath\$ishVersion"
                    Write-Debug "expandPath=$expandPath"
                    $testPath=Join-Path -Path $expandPath -ChildPath ($_.Name.Replace(".exe",""))
                    $testPath=RemoveSDLSegments($testPath)
                    $hash.IsExpanded=Test-Path $testPath -PathType Container
                    if($hash.IsExpanded)
                    {
                        $hash.ExpandedPath=$testPath
                    }
                    $availableItems+=New-Object -TypeName PSObject -Property $hash
                }
                if(Test-Path -Path $ishCDPath -PathType Container)
                {
                    if($PSVersionTable.PSVersion.Major -ge 5)
                    {
                        $childItems=Get-ChildItem -Path $ishCDPath -Recurse -Directory -Depth 1
                    }
                    else
                    {
                        $childItems=Get-ChildItem -Path $ishCDPath -Recurse -Directory
                    }
                }
                else
                {
                    $childItems=$null
                }
                $childItems |Where-Object -Property Name -Match ($regEx.Replace("\.exe","")) | ForEach-Object {
                    $directoryName=$_.Name
                    if($availableItems |Where-Object {
                        ((RemoveSDLSegments($_.Name).Replace(".exe","")) -eq $directoryName)
                    })
                    {
                        return
                    }
                    $hash=[ordered]@{
                        Name=$_.Name
                        Major=[int]$Matches["Major"]
                        Minor=0
                        Build=[int]$Matches["Build"]
                        Revision=[int]$Matches["Revision"]
                        IsExpanded=$true
                        ExpandedPath=$_.FullName
                    }
                    $availableItems+=New-Object -TypeName PSObject -Property $hash
                }
                $availableItems
                break
            }
        }
    }

    end
    {

    }
}


text:
.class public Lcom/samsung/android/contextaware/utilbundle/CaAkmManager;
.super Ljava/lang/Object;
.source "CaAkmManager.java"

# static fields
.field private static final SETTING_FILE_NAME:Ljava/lang/String; = "/data/misc/akmd_set.txt"

.field private static volatile instance:Lcom/samsung/android/contextaware/utilbundle/CaAkmManager;

# direct methods
.method public constructor <init>()V
    .locals 0

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

.method public static getInstance()Lcom/samsung/android/contextaware/utilbundle/CaAkmManager;
    .locals 2

    sget-object v0, Lcom/samsung/android/contextaware/utilbundle/CaAkmManager;->instance:Lcom/samsung/android/contextaware/utilbundle/CaAkmManager;

    if-nez v0, :cond_1

    const-class v1, Lcom/samsung/android/contextaware/utilbundle/CaAkmManager;

    monitor-enter v1

    :try_start_0
    sget-object v0, Lcom/samsung/android/contextaware/utilbundle/CaAkmManager;->instance:Lcom/samsung/android/contextaware/utilbundle/CaAkmManager;

    if-nez v0, :cond_0

    new-instance v0, Lcom/samsung/android/contextaware/utilbundle/CaAkmManager;

    invoke-direct {v0}, Lcom/samsung/android/contextaware/utilbundle/CaAkmManager;-><init>()V

    sput-object v0, Lcom/samsung/android/contextaware/utilbundle/CaAkmManager;->instance:Lcom/samsung/android/contextaware/utilbundle/CaAkmManager;
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    :cond_0
    monitor-exit v1

    :cond_1
    sget-object v0, Lcom/samsung/android/contextaware/utilbundle/CaAkmManager;->instance:Lcom/samsung/android/contextaware/utilbundle/CaAkmManager;

    return-object v0

    :catchall_0
    move-exception v0

    monitor-exit v1

    throw v0
.end method

.method private loadIntValue(Ljava/lang/String;)I
    .locals 1

    const/4 v0, 0x0

    return v0
.end method

.method private saveIntValue(Ljava/lang/String;I)V
    .locals 0

    return-void
.end method

# virtual methods
.method public final getOrientationValueNames()[Ljava/lang/String;
    .locals 3

    const/4 v0, 0x7

    new-array v0, v0, [Ljava/lang/String;

    const-string/jumbo v1, "HSUC_HDST_FORM0"

    const/4 v2, 0x0

    aput-object v1, v0, v2

    const-string/jumbo v1, "HSUC_HO_FORM0.x"

    const/4 v2, 0x1

    aput-object v1, v0, v2

    const-string/jumbo v1, "HSUC_HO_FORM0.y"

    const/4 v2, 0x2

    aput-object v1, v0, v2

    const-string/jumbo v1, "HSUC_HO_FORM0.z"

    const/4 v2, 0x3

    aput-object v1, v0, v2

    const-string/jumbo v1, "HFLUCV_HREF_FORM0.x"

    const/4 v2, 0x4

    aput-object v1, v0, v2

    const-string/jumbo v1, "HFLUCV_HREF_FORM0.y"

    const/4 v2, 0x5

    aput-object v1, v0, v2

    const-string/jumbo v1, "HFLUCV_HREF_FORM0.z"

    const/4 v2, 0x6

    aput-object v1, v0, v2

    return-object v0
.end method

.method public final loadOrientationInfo()Landroid/os/Bundle;
    .locals 8

    new-instance v1, Landroid/os/Bundle;

    invoke-direct {v1}, Landroid/os/Bundle;-><init>()V

    invoke-virtual {p0}, Lcom/samsung/android/contextaware/utilbundle/CaAkmManager;->getOrientationValueNames()[Ljava/lang/String;

    move-result-object v2

    const/4 v4, 0x0

    array-length v5, v2

    :goto_0
    if-ge v4, v5, :cond_0

    aget-object v0, v2, v4

    invoke-direct {p0, v0}, Lcom/samsung/android/contextaware/utilbundle/CaAkmManager;->loadIntValue(Ljava/lang/String;)I

    move-result v3

    invoke-virtual {v1, v0, v3}, Landroid/os/Bundle;->putInt(Ljava/lang/String;I)V

    new-instance v6, Ljava/lang/StringBuilder;

    invoke-direct {v6}, Ljava/lang/StringBuilder;-><init>()V

    invoke-virtual {v6, v0}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v6

    const-string/jumbo v7, " : "

    invoke-virtual {v6, v7}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v6

    invoke-static {v3}, Ljava/lang/Integer;->toString(I)Ljava/lang/String;

    move-result-object v7

    invoke-virtual {v6, v7}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v6

    invoke-virtual {v6}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v6

    invoke-static {v6}, Lcom/samsung/android/contextaware/utilbundle/logger/CaLogger;->info(Ljava/lang/String;)V

    add-int/lit8 v4, v4, 0x1

    goto :goto_0

    :cond_0
    return-object v1
.end method

.method public final saveOrientationInfo(Landroid/os/Bundle;)V
    .locals 7

    if-eqz p1, :cond_0

    invoke-virtual {p1}, Landroid/os/Bundle;->isEmpty()Z

    move-result v3

    if-eqz v3, :cond_1

    :cond_0
    const-string/jumbo v3, "can\'t save the orientation information"

    invoke-static {v3}, Lcom/samsung/android/contextaware/utilbundle/logger/CaLogger;->error(Ljava/lang/String;)V

    return-void

    :cond_1
    invoke-virtual {p0}, Lcom/samsung/android/contextaware/utilbundle/CaAkmManager;->getOrientationValueNames()[Ljava/lang/String;

    move-result-object v1

    const/4 v3, 0x0

    array-length v4, v1

    :goto_0
    if-ge v3, v4, :cond_2

    aget-object v0, v1, v3

    invoke-virtual {p1, v0}, Landroid/os/Bundle;->getInt(Ljava/lang/String;)I

    move-result v2

    invoke-direct {p0, v0, v2}, Lcom/samsung/android/contextaware/utilbundle/CaAkmManager;->saveIntValue(Ljava/lang/String;I)V

    new-instance v5, Ljava/lang/StringBuilder;

    invoke-direct {v5}, Ljava/lang/StringBuilder;-><init>()V

    invoke-virtual {v5, v0}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v5

    const-string/jumbo v6, " : "

    invoke-virtual {v5, v6}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v5

    invoke-static {v2}, Ljava/lang/Integer;->toString(I)Ljava/lang/String;

    move-result-object v6

    invoke-virtual {v5, v6}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v5

    invoke-virtual {v5}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v5

    invoke-static {v5}, Lcom/samsung/android/contextaware/utilbundle/logger/CaLogger;->info(Ljava/lang/String;)V

    add-int/lit8 v3, v3, 0x1

    goto :goto_0

    :cond_2
    return-void
.end method


text:
package layout

import (
	"crypto/sha256"
	"encoding/hex"
	"io"
	"os"
	"path/filepath"

	"github.com/pkg/errors"
)

// Move the file or directory at src to dst. Conceptually, this is equivalent to executing "mv src dst". dst must not
// already exist and the path up to it must already exist. Uses os.Rename to execute the move, which means that there
// may be platform-specific restrictions such as not being able to move the directory between different volumes.
func Move(src, dst string) error {
	if err := verifyDstPathSafe(dst); err != nil {
		return errors.Wrapf(err, "cannot move directory to path %s", dst)
	}
	if err := os.Rename(src, dst); err != nil {
		return errors.Wrapf(err, "failed to rename %s to %s", src, dst)
	}
	return nil
}

// CopyDir recursively copies the src directory to the path specified by dst. dst must not already exist and the path up
// to it must already exist.
func CopyDir(src, dst string) error {
	if err := verifyDstPathSafe(dst); err != nil {
		return errors.Wrapf(err, "cannot copy directory to path %s", dst)
	}

	srcInfo, err := os.Stat(src)
	if err != nil {
		return errors.Wrapf(err, "failed to stat source directory %s", src)
	}

	if err := os.Mkdir(dst, srcInfo.Mode()); err != nil {
		return errors.Wrapf(err, "failed to create destination directory %s", dst)
	}

	files, err := os.ReadDir(src)
	if err != nil {
		return errors.Wrapf(err, "failed to read directory %s", src)
	}

	for _, f := range files {
		srcPath := filepath.Join(src, f.Name())
		dstPath := filepath.Join(dst, f.Name())

		if f.IsDir() {
			err = CopyDir(srcPath, dstPath)
		} else {
			err = CopyFile(srcPath, dstPath)
		}

		if err != nil {
			return errors.Wrapf(err, "failed to copy %s to %s", srcPath, dstPath)
		}
	}

	return nil
}

// CopyFile copies the file at src to dst. src must specify a regular file (non-directory, no special mode) that exists,
// and dst must specify a path that does not yet exist, but whose parent directory does exist. The copied file will have
// the same permissions as the original.
func CopyFile(src, dst string) (rErr error) {
	srcInfo, err := os.Stat(src)
	if err != nil {
		return errors.Wrapf(err, "failed to stat source file %s", src)
	}
	if !srcInfo.Mode().IsRegular() {
		return errors.Wrapf(err, "source file %s is not a regular file, had mode: %v", src, srcInfo.Mode())
	}
	srcPerms := srcInfo.Mode().Perm()

	srcFile, err := os.Open(src)
	if err != nil {
		return errors.Wrapf(err, "failed to open %s", src)
	}
	defer func() {
		if err := srcFile.Close(); err != nil {
			rErr = errors.Wrapf(err, "failed to close %s in defer", src)
		}
	}()

	if err := verifyDstPathSafe(dst); err != nil {
		return errors.Wrapf(err, "cannot copy to destination path %s", dst)
	}

	dstFile, err := os.Create(dst)
	if err != nil {
		return errors.Wrapf(err, "failed to open %s", dst)
	}
	defer func() {
		if err := dstFile.Close(); err != nil {
			rErr = errors.Wrapf(err, "failed to close %s in defer", dstFile.Name())
		}
	}()

	if _, err := io.Copy(dstFile, srcFile); err != nil {
		return errors.Wrapf(err, "failed to copy %s to %s", src, dst)
	}

	if err := dstFile.Chmod(srcPerms); err != nil {
		return errors.Wrapf(err, "failed to chmod %s to have permissions %v", dst, srcPerms)
	}

	return nil
}

// SyncDir syncs the contents of the provided directories such that the content of dstDir matches that of srcDir (except
// for files that match a name in the provided skip slice).
func SyncDir(srcDir, dstDir string, skip []string) (bool, error) {
	modified := false

	srcFiles, err := os.ReadDir(srcDir)
	if err != nil {
		return modified, errors.Wrapf(err, "failed to read directory %s", srcDir)
	}
	srcFilesMap := toMap(srcFiles)

	dstFiles, err := os.ReadDir(dstDir)
	if err != nil {
		return modified, errors.Wrapf(err, "failed to read directory %s", dstDir)
	}
	dstFilesMap := toMap(dstFiles)

	skipSet := toSet(skip)
	for dstFileName, dstFileInfo := range dstFilesMap {
		if _, ok := skipSet[dstFileName]; ok {
			// skip if file name is in skip list
			continue
		}

		remove := false
		srcFilePath := filepath.Join(srcDir, dstFileName)
		dstFilePath := filepath.Join(dstDir, dstFileName)

		if currSrcFileInfo, ok := srcFilesMap[dstFileName]; !ok {
			// if dst exists but src does not, remove dst
			remove = true
		} else if dstFileInfo.IsDir() != currSrcFileInfo.IsDir() {
			// if dst file and src file are different types, remove dst
			remove = true
		} else if !dstFileInfo.IsDir() {
			srcChecksum, err := Checksum(srcFilePath)
			if err != nil {
				return modified, errors.Wrapf(err, "failed to compute checksum for %s", srcFilePath)
			}
			dstChecksum, err := Checksum(dstFilePath)
			if err != nil {
				return modified, errors.Wrapf(err, "failed to compute checksum for %s", dstFilePath)
			}

			// if dst and src are both files and their checksums differ, remove dst
			if srcChecksum != dstChecksum {
				remove = true
			}
		} else {
			// if dst and src both exist and are both directories, sync them recursively
			recursiveModified, err := SyncDir(srcFilePath, dstFilePath, skip)
			if err != nil {
				return modified, errors.Wrapf(err, "failed to sync %s with %s", dstFilePath, srcFilePath)
			}
			modified = modified || recursiveModified
		}

		// remove path if it was marked for removal
		if remove {
			if err := os.RemoveAll(dstFilePath); err != nil {
				return modified, errors.Wrapf(err, "failed to remove %s", dstFilePath)
			}
			modified = true
		}
	}

	for srcFileName, srcFileInfo := range srcFilesMap {
		if _, ok := skipSet[srcFileName]; ok {
			// skip if file name is in skip list
			continue
		}

		srcFilePath := filepath.Join(srcDir, srcFileName)
		dstFilePath := filepath.Join(dstDir, srcFileName)

		if _, err := os.Stat(dstFilePath); os.IsNotExist(err) {
			// if path does not exist at destination, copy source version
			var err error
			if srcFileInfo.IsDir() {
				err = CopyDir(srcFilePath, dstFilePath)
			} else {
				err = CopyFile(srcFilePath, dstFilePath)
			}
			if err != nil {
				return modified, errors.Wrapf(err, "failed to copy %s to %s", srcFilePath, dstFilePath)
			}
			modified = true
		} else if err != nil {
			return modified, errors.Wrapf(err, "failed to stat %s", dstFilePath)
		}
	}

	return modified, nil
}

func toSet(input []string) map[string]struct{} {
	s := make(map[string]struct{}, len(input))
	for _, curr := range input {
		s[curr] = struct{}{}
	}
	return s
}

func toMap(input []os.DirEntry) map[string]os.DirEntry {
	m := make(map[string]os.DirEntry, len(input))
	for _, curr := range input {
		m[curr.Name()] = curr
	}
	return m
}

func Checksum(p string) (string, error) {
	f, err := os.Open(p)
	if err != nil {
		return "", errors.Wrapf(err, "failed to open %s", p)
	}
	h := sha256.New()
	if _, err := io.Copy(h, f); err != nil {
		return "", errors.Wrapf(err, "failed to copy file to hash buffer")
	}
	return hex.EncodeToString(h.Sum(nil)), nil
}

// SyncDirAdditive copies all of the files and directories in src that are not in dst. Directories that are present in
// both are handled recursively. Basically a recursive merge with source preservation.
func SyncDirAdditive(src, dst string) error {
	srcInfos, err := os.ReadDir(src)
	if err != nil {
		return errors.Wrapf(err, "failed to open %s", src)
	}

	for _, srcInfo := range srcInfos {
		srcPath := filepath.Join(src, srcInfo.Name())
		dstPath := filepath.Join(dst, srcInfo.Name())

		if dstInfo, err := os.Stat(dstPath); os.IsNotExist(err) {
			// safe to copy
			if srcInfo.IsDir() {
				err = CopyDir(srcPath, dstPath)
			} else {
				err = CopyFile(srcPath, dstPath)
			}
			if err != nil {
				return errors.Wrapf(err, "failed to copy %s to %s", srcPath, dstPath)
			}
		} else if err != nil {
			return errors.Wrapf(err, "failed to stat %s", dstPath)
		} else if srcInfo.IsDir() && dstInfo.IsDir() {
			// if source and destination are both directories, sync recursively
			if err = SyncDirAdditive(srcPath, dstPath); err != nil {
				return errors.Wrapf(err, "failed to sync %s to %s", srcPath, dstPath)
			}
		}
	}
	return nil
}

func VerifyDirExists(dir string) error {
	return verifyPath(dir, filepath.Base(dir), true, false)
}

func verifyPath(p, expectedName string, isDir bool, optional bool) error {
	if filepath.Base(p) != expectedName {
		return errors.Errorf("%s is not a path to %s", p, expectedName)
	}

	if fi, err := os.Stat(p); err != nil {
		if os.IsNotExist(err) {
			if !optional {
				return errors.Wrapf(err, "%s does not exist", p)
			}
			// path does not exist, but it is optional so is okay
			return nil
		}
		return errors.Wrapf(err, "failed to stat %s", p)
	} else if currIsDir := fi.IsDir(); currIsDir != isDir {
		return errors.Errorf("IsDir for %s returned wrong value: expected %v, was %v", p, isDir, currIsDir)
	}

	return nil
}

// verifyDstPathSafe verifies that the provided destination path does not exist, but that the path to its parent does.
func verifyDstPathSafe(dst string) error {
	if _, err := os.Stat(dst); !os.IsNotExist(err) {
		return errors.Wrapf(err, "destination path %s already exists", dst)
	}
	if _, err := os.Stat(filepath.Dir(dst)); os.IsNotExist(err) {
		return errors.Wrapf(err, "parent directory of destination path %s does not exist", dst)
	}
	return nil
}


text:
<?xml version="1.0" encoding="ISO-8859-1" standalone="no"?>
<database name="migration_command">

        <column name="id" required="true" primaryKey="true" autoIncrement="true" type="INTEGER" description="Book Id"/>
        <column name="title" type="VARCHAR" required="true" primaryString="true"/>
        <column name="table2_id" type="INTEGER"/>
        <foreign-key foreignTable="table2" onDelete="setnull" onUpdate="cascade">
            <reference local="table2_id" foreign="id"/>
        </foreign-key>

        <column name="id" required="true" primaryKey="true" autoIncrement="true" type="INTEGER"/>
        <column name="title" type="VARCHAR"/>
      <column name="created_at" required="false" type="TIMESTAMP"/>

</database>


text:
package org.apache.spark.sql.execution.datasources.json

import org.apache.spark.sql.QueryTest
import org.apache.spark.sql.catalyst.json.JSONOptions
import org.apache.spark.sql.test.SharedSQLContext

/**
 * Test cases for various [[JSONOptions]].
 */
class JsonParsingOptionsSuite extends QueryTest with SharedSQLContext {
  import testImplicits._

  test("allowComments off") {
    val str = """{'name': /* hello */ 'Reynold Xin'}"""
    val df = spark.read.json(Seq(str).toDS())

    assert(df.schema.head.name == "_corrupt_record")
  }

  test("allowComments on") {
    val str = """{'name': /* hello */ 'Reynold Xin'}"""
    val df = spark.read.option("allowComments", "true").json(Seq(str).toDS())

    assert(df.schema.head.name == "name")
    assert(df.first().getString(0) == "Reynold Xin")
  }

  test("allowSingleQuotes off") {
    val str = """{'name': 'Reynold Xin'}"""
    val df = spark.read.option("allowSingleQuotes", "false").json(Seq(str).toDS())

    assert(df.schema.head.name == "_corrupt_record")
  }

  test("allowSingleQuotes on") {
    val str = """{'name': 'Reynold Xin'}"""
    val df = spark.read.json(Seq(str).toDS())

    assert(df.schema.head.name == "name")
    assert(df.first().getString(0) == "Reynold Xin")
  }

  test("allowUnquotedFieldNames off") {
    val str = """{name: 'Reynold Xin'}"""
    val df = spark.read.json(Seq(str).toDS())

    assert(df.schema.head.name == "_corrupt_record")
  }

  test("allowUnquotedFieldNames on") {
    val str = """{name: 'Reynold Xin'}"""
    val df = spark.read.option("allowUnquotedFieldNames", "true").json(Seq(str).toDS())

    assert(df.schema.head.name == "name")
    assert(df.first().getString(0) == "Reynold Xin")
  }

  test("allowNumericLeadingZeros off") {
    val str = """{"age": 0018}"""
    val df = spark.read.json(Seq(str).toDS())

    assert(df.schema.head.name == "_corrupt_record")
  }

  test("allowNumericLeadingZeros on") {
    val str = """{"age": 0018}"""
    val df = spark.read.option("allowNumericLeadingZeros", "true").json(Seq(str).toDS())

    assert(df.schema.head.name == "age")
    assert(df.first().getLong(0) == 18)
  }

  // The following two tests are not really working - need to look into Jackson's
  // JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS.
  ignore("allowNonNumericNumbers off") {
    val str = """{"age": NaN}"""
    val df = spark.read.json(Seq(str).toDS())

    assert(df.schema.head.name == "_corrupt_record")
  }

  ignore("allowNonNumericNumbers on") {
    val str = """{"age": NaN}"""
    val df = spark.read.option("allowNonNumericNumbers", "true").json(Seq(str).toDS())

    assert(df.schema.head.name == "age")
    assert(df.first().getDouble(0).isNaN)
  }

  test("allowBackslashEscapingAnyCharacter off") {
    val str = """{"name": "Cazen Lee", "price": "\$10"}"""
    val df = spark.read.option("allowBackslashEscapingAnyCharacter", "false").json(Seq(str).toDS())

    assert(df.schema.head.name == "_corrupt_record")
  }

  test("allowBackslashEscapingAnyCharacter on") {
    val str = """{"name": "Cazen Lee", "price": "\$10"}"""
    val df = spark.read.option("allowBackslashEscapingAnyCharacter", "true").json(Seq(str).toDS())

    assert(df.schema.head.name == "name")
    assert(df.schema.last.name == "price")
    assert(df.first().getString(0) == "Cazen Lee")
    assert(df.first().getString(1) == "$10")
  }
}


text:
import util from './util.js';
import Parser from './parser/javascript.js';
import _ from 'lodash';

export default class Regexper {
  constructor(root) {
    this.root = root;
    this.buggyHash = false;
    this.form = root.querySelector('#regexp-form');
    this.field = root.querySelector('#regexp-input');
    this.error = root.querySelector('#error');
    this.warnings = root.querySelector('#warnings');

    this.links = this.form.querySelector('ul');
    this.permalink = this.links.querySelector('a[data-glyph="link-intact"]');
    this.download = this.links.querySelector('a[data-glyph="data-transfer-download"]');

    this.svgContainer = root.querySelector('#regexp-render');
  }

  // Event handler for key presses in the regular expression form field.
  keypressListener(event) {
    // Pressing Shift-Enter displays the expression.
    if (event.shiftKey && event.keyCode === 13) {
      event.returnValue = false;
      if (event.preventDefault) {
        event.preventDefault();
      }

      this.form.dispatchEvent(util.customEvent('submit'));
    }
  }

  // Event handler for key presses while focused anywhere in the application.
  documentKeypressListener(event) {
    // Pressing escape will cancel a currently running render.
    if (event.keyCode === 27 && this.running) {
      this.running.cancel();
    }
  }

  // Event handler for submission of the regular expression. Changes the URL
  // hash which leads to the expression being rendered.
  submitListener(event) {
    event.returnValue = false;
    if (event.preventDefault) {
      event.preventDefault();
    }

    try {
      this._setHash(this.field.value);
    }
    catch(e) {
      // Failed to set the URL hash (probably because the expression is too
      // long). Turn off display of the permalink and just show the expression.
      this.permalinkEnabled = false;
      this.showExpression(this.field.value);
    }
  }

  // Event handler for URL hash changes. Starts rendering of the expression.
  hashchangeListener() {
    var expr = this._getHash();

    if (expr instanceof Error) {
      this.state = 'has-error';
      this.error.innerHTML = 'Malformed expression in URL';
      window._gaq.push(['_trackEvent', 'visualization', 'malformed URL']);
    } else {
      this.permalinkEnabled = true;
      this.showExpression(expr);
    }
  }

  // Binds all event listeners.
  bindListeners() {
    this.field.addEventListener('keypress', this.keypressListener.bind(this));
    this.form.addEventListener('submit', this.submitListener.bind(this));
    this.root.addEventListener('keyup', this.documentKeypressListener.bind(this));
    window.addEventListener('hashchange', this.hashchangeListener.bind(this));
  }

  // Detect if https://bugzilla.mozilla.org/show_bug.cgi?id=483304 is in effect
  detectBuggyHash() {
    var url;

    if (typeof window.URL === 'function') {
      try {
        url = new URL('http://regexper.com/#%25');
        this.buggyHash = (url.hash === '#%');
      }
      catch(e) {
        this.buggyHash = false;
      }
    }
  }

  // Set the URL hash. This method exists to facilitate automated testing
  // (since changing the URL can throw off most JavaScript testing tools).
  _setHash(hash) {
    location.hash = encodeURIComponent(hash);
  }

  // Retrieve the current URL hash. This method is also mostly for supporting
  // automated testing, but also does some basic error handling for malformed
  // URLs.
  _getHash() {
    var hash;
    try {
      hash = location.hash.slice(1)
      return this.buggyHash ? hash : decodeURIComponent(hash);
    }
    catch(e) {
      return e;
    }
  }

  // Currently state of the application. Useful values are:
  //  - `''` - State of the application when the page initially loads
  //  - `'is-loading'` - Displays the loading indicator
  //  - `'has-error'` - Displays the error message
  //  - `'has-results'` - Displays rendered results
  set state(state) {
    this.root.className = state;
  }

  get state() {
    return this.root.className;
  }

  // Start the rendering of a regular expression.
  //
  // - __expression__ - Regular expression to display.
  showExpression(expression) {
    this.field.value = expression;
    this.state = '';

    if (expression !== '') {
      this.renderRegexp(expression).catch(util.exposeError);
    }
  }

  // Creates a blob URL for linking to a rendered regular expression image.
  //
  // - __content__ - SVG image markup.
  buildBlobURL(content) {
    // Blob object has to stick around for IE, so the instance is stored on the
    // `window` object.
    window.blob = new Blob([content], { type: 'image/svg+xml' });
    return URL.createObjectURL(window.blob);
  }

  // Update the URLs of the 'download' and 'permalink' links.
  updateLinks() {
    var classes = _.without(this.links.className.split(' '), ['hide-download', 'hide-permalink']);

    // Create the 'download' image URL.
    try {
      this.download.parentNode.style.display = null;
      this.download.href = this.buildBlobURL(this.svgContainer.querySelector('.svg').innerHTML);
    }
    catch(e) {
      // Blobs or URLs created from a blob URL don't work in the current
      // browser. Giving up on the download link.
      classes.push('hide-download');
    }

    // Create the 'permalink' URL.
    if (this.permalinkEnabled) {
      this.permalink.parentNode.style.display = null;
      this.permalink.href = location.toString();
    } else {
      classes.push('hide-permalink');
    }

    this.links.className = classes.join(' ');
  }

  // Display any warnings that were generated while rendering a regular expression.
  //
  // - __warnings__ - Array of warning messages to display.
  displayWarnings(warnings) {
    this.warnings.innerHTML = _.map(warnings, warning => {
      return `<li class="oi with-text" data-glyph="warning">${warning}</li>`;
    }).join('');
  }

  // Render regular expression
  //
  // - __expression__ - Regular expression to render
  renderRegexp(expression) {
    var parseError = false,
        startTime, endTime;

    // When a render is already in progress, cancel it and try rendering again
    // after a short delay (canceling a render is not instantaneous).
    if (this.running) {
      this.running.cancel();

      return util.wait(10).then(() => {
        return this.renderRegexp(expression);
      });
    }

    this.state = 'is-loading';
    window._gaq.push(['_trackEvent', 'visualization', 'start']);
    startTime = new Date().getTime();

    this.running = new Parser(this.svgContainer);

    return this.running
      // Parse the expression.
      .parse(expression)
      // Display any error messages from the parser and abort the render.
      .catch(message => {
        this.state = 'has-error';
        this.error.innerHTML = '';
        this.error.appendChild(document.createTextNode(message));

        parseError = true;

        throw message;
      })
      // When parsing is successful, render the parsed expression.
      .then(parser => {
        return parser.render();
      })
      // Once rendering is complete:
      //  - Update links
      //  - Display any warnings
      //  - Track the completion of the render and how long it took
      .then(() => {
        this.state = 'has-results';
        this.updateLinks();
        this.displayWarnings(this.running.warnings);
        window._gaq.push(['_trackEvent', 'visualization', 'complete']);

        endTime = new Date().getTime();
        window._gaq.push(['_trackTiming', 'visualization', 'total time', endTime - startTime]);
      })
      // Handle any errors that happened during the rendering pipeline.
      // Swallows parse errors and render cancellations. Any other exceptions
      // are allowed to continue on to be tracked by the global error handler.
      .catch(message => {
        if (message === 'Render cancelled') {
          window._gaq.push(['_trackEvent', 'visualization', 'cancelled']);
          this.state = '';
        } else if (parseError) {
          window._gaq.push(['_trackEvent', 'visualization', 'parse error']);
        } else {
          throw message;
        }
      })
      // Finally, mark rendering as complete (and pass along any exceptions
      // that were thrown).
      .then(
        () => {
          this.running = false;
        },
        message => {
          this.running = false;
          throw message;
        }
      );
  }
}


text:
export default function embed(node, graph, _nodeMap, _stack) {
  graph = graph['@graph'] || graph;
  _stack = _stack || [];
  _nodeMap = _nodeMap || (Array.isArray(graph) ? graph.reduce((_nodeMap, node) => {
    _nodeMap[node['@id']] = node;
    return _nodeMap;
  }, {}) : graph); // if not an array, if assume that it's a nodeMap

  if (typeof node === 'string') {
    return embedMatch(node, graph, _nodeMap, _stack);
  } else if (Array.isArray(node)) {
    return node.map(n => embed(n, graph, _nodeMap, _stack));
  } else {
    let keys = Object.keys(node);
    if (keys.length === 1 && keys[0] === '@id') {
      return embedMatch(node, graph, _nodeMap, _stack);
    } else {
      return keys.reduce((tree, p) => {
        let value = node[p];
        if (typeof value === 'string') {
          tree[p] = embedMatch(value, graph, _nodeMap, _stack);
        } else {
          tree[p] = embed(value, graph, _nodeMap, _stack);
        }
        return tree;
      }, {});
    }
  }
};

function embedMatch(value, graph, _nodeMap, _stack) {
  let key = value['@id'] || value;
  let match = ~key.indexOf(':') && _nodeMap[key]; // restrict keys to CURIE (this is fragile but better than nothing)
  if (match) {
    if (has(_stack, match['@id'])) {
      return value;
    } else {
      _stack.push(match['@id']);
      let framed = embed(match, graph, _nodeMap, _stack);
      _stack.pop();
      return framed;
    }
  } else {
    return value;
  }
}

function has(stack, id) {
  for (let item of stack) {
    if (item === id) {
      return true;
    }
  }
  return false;
}


text:
$.register_module({
    name: 'og.api.rest.compressor',
    dependencies: ['og.api.common', 'og.api.rest'],
    obj: function () {
        var common = og.api.common, api = og.api.rest, str = common.str, check = common.check;
        return { // all requests that begin with /compressor
            root: 'compressor',
            get: function (config) {
                var root = this.root, method = [root, 'decompress'], data = {}, meta;
                meta = check({bundle: {method: root + '#get', config: config}, required: [{all_of: ['content']}]});
                meta.type = 'POST';
                data.content = config.content.replace(/\-/g, '=').replace(/\_/g, '\/').replace(/\./g, '+');
                return api.request(method, {data: data, meta: meta});
            },
            put: function (config) {
                var root = this.root, method = [root, 'compress'], data = {}, meta;
                meta = check({bundle: {method: root + '#put', config: config}, required: [{all_of: ['content']}]});
                meta.type = 'POST';
                data.content = JSON.stringify(config.content);
                return api.request(method, {data: data, meta: meta});
            },
            del: common.not_available_del
        };
    }
});


text:
using System;
using System.Linq.Expressions;
using Remotion.Linq.Parsing;
using Remotion.Utilities;

namespace Remotion.Linq.Clauses.Expressions
{
  /// <summary>
  /// Represents an <see cref="Expression"/> that holds a subquery. The subquery is held by <see cref="QueryModel"/> in its parsed form.
  /// </summary>
  public sealed class SubQueryExpression : Expression
  {
#if NET_3_5
    public const ExpressionType ExpressionType = (ExpressionType) 100002;
#endif

#if !NET_3_5
    private readonly Type _type;
#endif

    public SubQueryExpression (QueryModel queryModel)
#if NET_3_5
        : base (ExpressionType, queryModel.GetOutputDataInfo().DataType)
#endif
    {
      ArgumentUtility.CheckNotNull ("queryModel", queryModel);

#if !NET_3_5
      _type = queryModel.GetOutputDataInfo().DataType;
#endif
      QueryModel = queryModel;
    }

#if !NET_3_5
    public override ExpressionType NodeType
    {
      get { return ExpressionType.Extension; }
    }

    public override Type Type
    {
      get { return _type; }
    }
#endif

    public QueryModel QueryModel { get; private set; }

#if !NET_3_5
    public override string ToString ()
    {
      return "{" + QueryModel + "}";
    }

    protected override Expression Accept (ExpressionVisitor visitor)
    {
      ArgumentUtility.CheckNotNull ("visitor", visitor);

      var relinqVisitor = visitor as RelinqExpressionVisitor;
      if (relinqVisitor == null)
        return base.Accept (visitor);

      return relinqVisitor.VisitSubQuery (this);
    }
#endif
  }
}


text:
   --       |  Description
 ---------- | ------------------------------
 Name       | PT_Demo_MIMXRT1050-EVK
 Function   | Demo application of 2 protothread tasks: Task 1 controls the LEDs blinking; Task 2 print task infomation periodically
 Platform   | PT_Demo_MIMXRT1050-EVK
 MCU        | i.MX RT 1052
 Type       | ARM Cortex-M7
 Frequency  | 600MHz
 RAM        | 512K bytes
 ROM        | 16M bytes
 peripheral | LED * 1
   --       | Button * 3

 ![MIMXRT1050-EVK](../../Documents/Pic/Board/MIMXRT1050-EVK-DEVICE.jpg)

 ![MIMXRT1050-EVK-Screen](../../Documents/Pic/Board/MIMXRT1050-EVK-DEVICE2.jpg)


text: export * from '@apollo/client';


text:
package edu.cmu.ece.privacylens;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.Test;

import edu.cmu.ece.privacylens.Util;

/**
 * I'm using a comparison to the output hash, which has to be regenerated whenever the ToggleBean generates different
 * output. I would like to use an html snippet validator. Where is one?
 *
 */
public class ToggleBeanTest {
    /** Class logger. */
    @SuppressWarnings("unused")
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private final boolean setupTest = false;

    private ToggleBean buildBase() {
        final ToggleBean bean = new ToggleBean();
        bean.setExplanation("Explanation text");
        bean.setExplanationIcon("explanation icon");
        bean.setTextDiv("attributeReleaseAttribute");
        bean.setImageDiv("attributeReleaseControl");
        bean.setParameter("parameter");
        bean.setText("text");
        return bean;
    }

    /** Test whether a toggle set to true works */
    @Test
    public void testTrue() {
        final ToggleBean bean = buildBase();
        bean.setImageFalse("false image");
        bean.setImageTrue("true image");
        bean.setValue(true);
        bean.setImmutable(false);
        Assert.assertTrue(bean.validate());

        if (setupTest) {
            logger.error(bean.getHtml());
        } else {
            Assert.assertEquals("b971f6ef00c7cbc9ebb1ef4c4926068bf3cad2e08b27898c3aad0a3d58d8ba84",
                    Util.hash(bean.getHtml()));
        }
    }

    /** Test whether a toggle set to false works */
    @Test
    public void testFalse() {
        final ToggleBean bean = buildBase();
        bean.setImageFalse("false image");
        bean.setImageTrue("true image");
        bean.setValue(false);
        bean.setImmutable(false);
        Assert.assertTrue(bean.validate());

        if (setupTest) {
            logger.error(Util.hash(bean.getHtml()));
        } else {
            Assert.assertEquals("098357846f458fd7cbb61a8bfd55373f95a5f068879dd7d4c0dc4a16b53c0d85",
                    Util.hash(bean.getHtml()));
        }
    }

    /** Test whether an immutable toggle set to true works. */
    @Test
    public void testImmuTrue() {
        final ToggleBean bean = buildBase();
        bean.setImageTrue("true image");
        bean.setValue(true);
        bean.setImmutable(true);
        Assert.assertTrue(bean.validate());

        if (setupTest) {
            logger.error(Util.hash(bean.getHtml()));
        } else {
            Assert.assertEquals("90f3f10f141debbcfdbd84dd5a2e9079be33d2ced7a0c4b8b0f8ae7a4dea1de7",
                    Util.hash(bean.getHtml()));
        }
    }

    /** Test whether an immutable toggle set to false works. */
    @Test
    public void testImmuFalse() {
        final ToggleBean bean = buildBase();
        bean.setImageFalse("false image");
        bean.setValue(false);
        bean.setImmutable(true);
        Assert.assertTrue(bean.validate());

        if (setupTest) {
            logger.error(Util.hash(bean.getHtml()));
        } else {

            Assert.assertEquals("b50dbcad64d10edc6b194193a7d85d7121215d2e34bf7b421b3d7909e62299d5",
                    Util.hash(bean.getHtml()));
        }
    }
}


text:
FROM yiisoftware/yii2-php:7.4-apache

# Change document root for Apache
RUN sed -i -e 's|/app/web|/app/backend/web|g' /etc/apache2/sites-available/000-default.conf


text:
export interface KakapoRequestOptions {
    params: any;
    query: any;
    body?: any;
    headers: any;
}

export class KakapoRequest {
    params: any;
    query: any;
    body: any | null;
    headers: any;

    constructor(options: KakapoRequestOptions) {
      this.params = options.params || {};
      this.query = options.query || {};
      this.body = options.body || null;
      this.headers = options.headers || {};
    }
}