/*
 * *
 *  Copyright (C) 2014 Open Whisper Systems
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program. If not, see <http://www.gnu.org/licenses/>.
 * /
 */

package org.anhonesteffort.flock;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.RemoteException;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.chiralcode.colorpicker.ColorPicker;

import org.anhonesteffort.flock.util.guava.Optional;
import org.anhonesteffort.flock.sync.calendar.LocalCalendarStore;
import org.anhonesteffort.flock.sync.calendar.LocalEventCollection;

import java.util.LinkedList;
import java.util.List;

/**
 * Programmer: rhodey
 */
public class ImportCalendarsFragment extends AccountAndKeyRequiredFragment
    implements CompoundButton.OnCheckedChangeListener
{
  private static final String TAG = "org.anhonesteffort.flock.ImportCalendarsFragment";

  private AsyncTask     asyncTask;
  private ListView      localCalendarListView;
  private SetupActivity setupActivity;
  private AlertDialog   alertDialog;

  private List<LocalEventCollection> selectedCalendars;
  private List<CalendarForCopy>      calendarsForCopyService = new LinkedList<CalendarForCopy>();
  private boolean                    list_is_initializing    = false;
  private int                        indexOfCalendarToPrompt = -1;

  @Override
  public void onAttach(Activity activity) {
    super.onAttach(activity);

    if (activity instanceof SetupActivity)
      this.setupActivity = (SetupActivity) activity;
  }

  @Override
  public View onCreateView(LayoutInflater inflater,
                           ViewGroup      container,
                           Bundle         savedInstanceState)
  {
    View fragmentView = inflater.inflate(R.layout.fragment_simple_list, container, false);

    if (!accountAndKeyAvailable())
      return fragmentView;

    initButtons();

    return fragmentView;
  }

  @Override
  public void onResume() {
    super.onResume();

    if (!accountAndKeyAvailable())
      return ;

    initializeList();
  }

  @Override
  public void onPause() {
    super.onPause();

    if (alertDialog != null)
      alertDialog.dismiss();

    if (asyncTask != null && !asyncTask.isCancelled())
      asyncTask.cancel(true);
  }

  private void handleBackgroundImportStarted() {
    Log.d(TAG, "handleBackgroundImportStarted()");

    if (selectedCalendars.size() > 0) {
      String toastMessage = getString(R.string.started_background_import_of_calendars, selectedCalendars.size());
      Toast.makeText(getActivity(), toastMessage, Toast.LENGTH_SHORT).show();
    }

    if (setupActivity != null)
      setupActivity.updateFragmentUsingState(SetupActivity.STATE_SELECT_REMOTE_ADDRESSBOOK);
    else
      getActivity().finish();
  }

  private void handlePromptComplete(LocalEventCollection importCalendar,
                                    String               calendarName,
                                    int                  calendarColor)
  {
    try {

      calendarsForCopyService.add(
          new CalendarForCopy(
              importCalendar.getAccount(),
              importCalendar.getLocalId(),
              calendarName,
              calendarColor,
              importCalendar.getComponentIds().size()
          )
      );

      indexOfCalendarToPrompt++;
      handlePromptForNextCalendarNameAndColors();

    } catch (RemoteException e) {
      indexOfCalendarToPrompt = -1;
      selectedCalendars.clear();
      initializeList();
    }
  }

  private void handlePromptForCalendar(final LocalEventCollection importCalendar) throws RemoteException {
          LayoutInflater      inflater        = getActivity().getLayoutInflater();
          View                view            = inflater.inflate(R.layout.dialog_calendar_edit, null);
    final EditText            displayNameEdit = (EditText   ) view.findViewById(R.id.dialog_display_name);
    final ColorPicker         colorPicker     = (ColorPicker) view.findViewById(R.id.dialog_calendar_color);
          AlertDialog.Builder builder         = new AlertDialog.Builder(getActivity());

    Optional<String> displayName = importCalendar.getDisplayName();
    if (displayName.isPresent())
      displayNameEdit.setText(displayName.get());

    Optional<Integer> color = importCalendar.getColor();
    if (color.isPresent())
      colorPicker.setColor(color.get());

    builder.setView(view).setTitle(R.string.title_calendar_properties);
    builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {

      @Override
      public void onClick(DialogInterface dialog, int id) {
        if (TextUtils.isEmpty(displayNameEdit.getText().toString())) {
          Toast.makeText(getActivity(),
                         R.string.display_name_cannot_be_empty,
                         Toast.LENGTH_LONG).show();
        }
        else {
          handlePromptComplete(importCalendar,
                               displayNameEdit.getText().toString(),
                               colorPicker.getColor());
        }
      }

    });

    builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

      @Override
      public void onClick(DialogInterface dialog, int which) {
        indexOfCalendarToPrompt = -1;
        selectedCalendars.clear();
        initializeList();
      }

    });

    builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
      @Override
      public void onCancel(DialogInterface dialog) {
        indexOfCalendarToPrompt = -1;
        selectedCalendars.clear();
        initializeList();
      }
    });

    alertDialog = builder.show();
  }

  private void handlePromptForNextCalendarNameAndColors() {
    Log.d(TAG, "handlePromptForNextCalendarNameAndColors()");

    if (indexOfCalendarToPrompt == -1)
      indexOfCalendarToPrompt = 0;

    try {

      if (indexOfCalendarToPrompt < selectedCalendars.size())
        handlePromptForCalendar(selectedCalendars.get(indexOfCalendarToPrompt));
      else if (calendarsForCopyService.size() > 0) {
        handleStartBackgroundCopyService(calendarsForCopyService);
        handleBackgroundImportStarted();
      }

    } catch (RemoteException e) {
      indexOfCalendarToPrompt = -1;
      selectedCalendars.clear();
      initializeList();
    }
  }

  private void initButtons() {
    Button actionButton;

    if (setupActivity != null) {
      actionButton = (Button) getActivity().findViewById(R.id.button_next);
      actionButton.setText(R.string.skip);
    }
    else {
      actionButton = (Button) getActivity().findViewById(R.id.button_action);
      actionButton.setText(R.string.cancel);
    }

    actionButton.setOnClickListener(new View.OnClickListener() {

      @Override
      public void onClick(View view) {
        if (selectedCalendars.size() > 0)
          handlePromptForNextCalendarNameAndColors();
        else
          handleBackgroundImportStarted();
      }

    });
  }

  private void initializeList() {
    Log.d(TAG, "initializeList()");

    if (list_is_initializing)
      return;

    selectedCalendars       = new LinkedList<LocalEventCollection>();
    list_is_initializing    = true;
    calendarsForCopyService = new LinkedList<CalendarForCopy>();
    indexOfCalendarToPrompt = -1;

    asyncTask = new RetrieveCalendarsTask().execute();
  }

  @Override
  public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
    Button actionButton;

    if (setupActivity != null)
      actionButton = (Button) getActivity().findViewById(R.id.button_next);
    else
      actionButton = (Button) getActivity().findViewById(R.id.button_action);

    if (selectedCalendars.size() > 0 && setupActivity != null)
      actionButton.setText(R.string.next);
    else if (selectedCalendars.size() > 0 && setupActivity == null)
      actionButton.setText(R.string.button_import);
    else if (setupActivity != null)
      actionButton.setText(R.string.skip);
    else
      actionButton.setText(R.string.cancel);
  }

  private void handleLocalCalendarsRetrieved(List<LocalEventCollection> localCalendars) {
    Log.d(TAG, " handleLocalCalendarsRetrieved()");
    LocalEventCollection[] localCalendarArray = new  LocalEventCollection[localCalendars.size()];
    for (int i = 0; i < localCalendars.size(); i++)
      localCalendarArray[i] = localCalendars.get(i);

    LocalCalendarListAdapter listAdapter =
        new LocalCalendarListAdapter(getActivity().getBaseContext(), localCalendarArray, selectedCalendars, this);

    localCalendarListView = (ListView)getView().findViewById(R.id.list);
    localCalendarListView.setAdapter(listAdapter);
    list_is_initializing = false;
  }

  private void handleStartBackgroundCopyService(final List<CalendarForCopy> copyCalendars) {

    final Context hackContext = getActivity().getApplicationContext();

    new AsyncTask<String, Void, Bundle>() {

      @Override
      protected Bundle doInBackground(String... params) {
        Bundle result      = new Bundle();
        Intent copyService = new Intent(hackContext, CalendarCopyService.class);

        for (CalendarForCopy copyCalendar : copyCalendars) {
          copyService.setAction(CalendarCopyService.ACTION_QUEUE_ACCOUNT_FOR_COPY);
          copyService.putExtra(CalendarCopyService.KEY_FROM_ACCOUNT,   copyCalendar.fromAccount);
          copyService.putExtra(CalendarCopyService.KEY_TO_ACCOUNT,     account.getOsAccount());
          copyService.putExtra(CalendarCopyService.KEY_CALENDAR_ID,    copyCalendar.calendarId);
          copyService.putExtra(CalendarCopyService.KEY_CALENDAR_NAME,  copyCalendar.calendarName);
          copyService.putExtra(CalendarCopyService.KEY_CALENDAR_COLOR, copyCalendar.calendarColor);
          copyService.putExtra(CalendarCopyService.KEY_EVENT_COUNT,    copyCalendar.eventCount);

          hackContext.startService(copyService);
        }

        copyService.setAction(CalendarCopyService.ACTION_START_COPY);
        hackContext.startService(copyService);
        result.putInt(ErrorToaster.KEY_STATUS_CODE, ErrorToaster.CODE_SUCCESS);

        return result;
      }

      @Override
      protected void onPostExecute(Bundle result) {
        Log.d(TAG, "STATUS: " + result.getInt(ErrorToaster.KEY_STATUS_CODE));
        if (result.getInt(ErrorToaster.KEY_STATUS_CODE) != ErrorToaster.CODE_SUCCESS)
          ErrorToaster.handleDisplayToastBundledError(hackContext, result);
      }

    }.execute();
  }

  private class RetrieveCalendarsTask extends AsyncTask<Void, Void, Bundle> {

    private List<LocalEventCollection> localCalendars;

    @Override
    protected void onPreExecute() {
      Log.d(TAG, "RetrieveCalendarsTask()");
      getActivity().setProgressBarIndeterminateVisibility(true);
      getActivity().setProgressBarVisibility(true);
    }

    protected List<LocalEventCollection> getLocalCalendars(List<Account> localAccounts)
      throws RemoteException
    {
      List<LocalEventCollection> collections = new LinkedList<LocalEventCollection>();

      for (Account localAccount : localAccounts) {
        LocalCalendarStore localStore = new LocalCalendarStore(getActivity(), localAccount);
        collections.addAll(localStore.getCollectionsIgnoreSync());
      }

      return collections;
    }

    protected List<Account> getOtherAccounts() {
      List<Account> accounts = new LinkedList<Account>();

      for (Account osAccount : AccountManager.get(getActivity()).getAccounts()) {
        if (!osAccount.name.equals(account.getOsAccount().name) &&
            !osAccount.type.equals(account.getOsAccount().type))
        {
          accounts.add(osAccount);
        }
      }

      return accounts;
    }

    @Override
    protected Bundle doInBackground(Void... params) {
      Bundle        result        = new Bundle();
      List<Account> otherAccounts = getOtherAccounts();

      try {

        localCalendars = getLocalCalendars(otherAccounts);

        result.putInt(ErrorToaster.KEY_STATUS_CODE, ErrorToaster.CODE_SUCCESS);

      } catch (RemoteException e) {
        ErrorToaster.handleBundleError(e, result);
      }

      return result;
    }

    @Override
    protected void onPostExecute(Bundle result) {
      Log.d(TAG, "STATUS: " + result.getInt(ErrorToaster.KEY_STATUS_CODE));
      getActivity().setProgressBarIndeterminateVisibility(false);
      getActivity().setProgressBarVisibility(false);

      if (result.getInt(ErrorToaster.KEY_STATUS_CODE) == ErrorToaster.CODE_SUCCESS)
        handleLocalCalendarsRetrieved(localCalendars);
      else
        ErrorToaster.handleDisplayToastBundledError(getActivity(), result);
    }
  }

  private static class CalendarForCopy {

    public Account fromAccount;
    public long    calendarId;
    public String  calendarName;
    public int     calendarColor;
    public int     eventCount;

    public CalendarForCopy(Account fromAccount,
                           long    calendarId,
                           String  calendarName,
                           int     calendarColor,
                           int     eventCount)
    {
      this.fromAccount   = fromAccount;
      this.calendarId    = calendarId;
      this.calendarName  = calendarName;
      this.calendarColor = calendarColor;
      this.eventCount    = eventCount;
    }

  }

}

{'repo_name': 'signalapp/Flock', 'stars': '362', 'repo_language': 'Java', 'file_name': 'config', 'mime_type': 'text/plain', 'hash': -6923141613704752317, 'source_dataset': 'data'}


import os
import sys

import psutil

from monk.keras_prototype import prototype
from monk.compare_prototype import compare
from monk.pip_unit_tests.keras.common import print_start
from monk.pip_unit_tests.keras.common import print_status

import tensorflow as tf
if(tf.__version__[0] == '2'):
    import tensorflow.compat.v1 as tf
    tf.enable_v2_behavior()

def test_optimizer_rmsprop(system_dict):
    forward = True;
    if(not os.path.isdir("datasets")):
        os.system("! wget --load-cookies /tmp/cookies.txt \"https://docs.google.com/uc?export=download&confirm=$(wget --save-cookies /tmp/cookies.txt --keep-session-cookies --no-check-certificate 'https://docs.google.com/uc?export=download&id=1rG-U1mS8hDU7_wM56a1kc-li_zHLtbq2' -O- | sed -rn 's/.*confirm=([0-9A-Za-z_]+).*/\1\n/p')&id=1rG-U1mS8hDU7_wM56a1kc-li_zHLtbq2\" -O datasets.zip && rm -rf /tmp/cookies.txt")
        os.system("! unzip -qq datasets.zip")

    test = "test_optimizer_rmsprop";
    system_dict["total_tests"] += 1;
    print_start(test, system_dict["total_tests"])
    if(forward):
        try:
            gtf = prototype(verbose=0);
            gtf.Prototype("sample-project-1", "sample-experiment-1");
            gtf.Default(dataset_path="datasets/dataset_cats_dogs_train",
                model_name="resnet50", freeze_base_network=True, num_epochs=2);
            gtf.optimizer_rmsprop(0.01, weight_decay=0.0001, decay_rate=0.9,
                clipnorm=1.0, clipvalue=0.5);
            gtf.Train();
            system_dict["successful_tests"] += 1;
            print_status("Pass");
        except Exception as e:
            system_dict["failed_tests_exceptions"].append(e);
            system_dict["failed_tests_lists"].append(test);
            forward = False;
            print_status("Fail");
    else:
        system_dict["skipped_tests_lists"].append(test);
        print_status("Skipped");

    return system_dict

{'repo_name': 'Tessellate-Imaging/monk_v1', 'stars': '311', 'repo_language': 'Jupyter Notebook', 'file_name': 'requirements_img_proc.txt', 'mime_type': 'text/plain', 'hash': 1437748791774711466, 'source_dataset': 'data'}


using System.Data.Common;

namespace NHibernate.Tool.hbm2ddl
{
	/// <summary>
	/// Contract for delegates responsible for managing connection used by the hbm2ddl tools.
	/// </summary>
	public partial interface IConnectionHelper
	{
		/// <summary>
		///  Prepare the helper for use.
		/// </summary>
		void Prepare();

		/// <summary>
		/// Get a reference to the connection we are using.
		/// </summary>
		DbConnection Connection { get; }

		/// <summary>
		/// Release any resources held by this helper.
		/// </summary>
		void Release();
	}
}

{'repo_name': 'nhibernate/nhibernate-core', 'stars': '1783', 'repo_language': 'C#', 'file_name': 'NhibernateCollection_NamedURL.HxK', 'mime_type': 'text/xml', 'hash': 1380074837439891332, 'source_dataset': 'data'}


<?php

namespace PhpOffice\PhpSpreadsheet\Writer\Pdf;

use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup;
use PhpOffice\PhpSpreadsheet\Writer\Pdf;

class Dompdf extends Pdf
{
    /**
     * Gets the implementation of external PDF library that should be used.
     *
     * @return \Dompdf\Dompdf implementation
     */
    protected function createExternalWriterInstance()
    {
        return new \Dompdf\Dompdf();
    }

    /**
     * Save Spreadsheet to file.
     *
     * @param string $pFilename Name of the file to save as
     *
     * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
     */
    public function save($pFilename)
    {
        $fileHandle = parent::prepareForSave($pFilename);

        //  Default PDF paper size
        $paperSize = 'LETTER'; //    Letter    (8.5 in. by 11 in.)

        //  Check for paper size and page orientation
        if ($this->getSheetIndex() === null) {
            $orientation = ($this->spreadsheet->getSheet(0)->getPageSetup()->getOrientation()
                == PageSetup::ORIENTATION_LANDSCAPE) ? 'L' : 'P';
            $printPaperSize = $this->spreadsheet->getSheet(0)->getPageSetup()->getPaperSize();
        } else {
            $orientation = ($this->spreadsheet->getSheet($this->getSheetIndex())->getPageSetup()->getOrientation()
                == PageSetup::ORIENTATION_LANDSCAPE) ? 'L' : 'P';
            $printPaperSize = $this->spreadsheet->getSheet($this->getSheetIndex())->getPageSetup()->getPaperSize();
        }

        $orientation = ($orientation == 'L') ? 'landscape' : 'portrait';

        //  Override Page Orientation
        if ($this->getOrientation() !== null) {
            $orientation = ($this->getOrientation() == PageSetup::ORIENTATION_DEFAULT)
                ? PageSetup::ORIENTATION_PORTRAIT
                : $this->getOrientation();
        }
        //  Override Paper Size
        if ($this->getPaperSize() !== null) {
            $printPaperSize = $this->getPaperSize();
        }

        if (isset(self::$paperSizes[$printPaperSize])) {
            $paperSize = self::$paperSizes[$printPaperSize];
        }

        //  Create PDF
        $pdf = $this->createExternalWriterInstance();
        $pdf->setPaper(strtolower($paperSize), $orientation);

        $pdf->loadHtml(
            $this->generateHTMLHeader(false) .
            $this->generateSheetData() .
            $this->generateHTMLFooter()
        );
        $pdf->render();

        //  Write to file
        fwrite($fileHandle, $pdf->output());

        parent::restoreStateAfterSave($fileHandle);
    }
}

{'repo_name': 'kiang/pharmacies', 'stars': '162', 'repo_language': 'PHP', 'file_name': 'main.js', 'mime_type': 'text/html', 'hash': 2535612717689055602, 'source_dataset': 'data'}


<link rel="stylesheet" href="{NV_BASE_SITEURL}{NV_ASSETS_DIR}/js/select2/select2.min.css">

    {ERROR}

<form action="{NV_BASE_ADMINURL}index.php?{NV_LANG_VARIABLE}={NV_LANG_DATA}&{NV_NAME_VARIABLE}={MODULE_NAME}&{NV_OP_VARIABLE}={OP}" method="post">

            <col class="w400" />

                    {LANG.closed_site}

                    <select name="closed_site" class="form-control w300">

                        <option value="{MODE_VALUE}"{MODE_SELECTED}>{MODE_NAME}</option>

                    </select>

                    {LANG.site_email}
                    <input type="email" name="site_email" value="{DATA.site_email}" class="form-control" style="width: 450px"/>

                    {LANG.site_phone}
                    <input type="text" name="site_phone" value="{DATA.site_phone}" class="form-control" style="width: 450px"/>

                    {LANG.themeadmin}

                    <select name="admin_theme" class="form-control w300" >

                        <option value="{THEME_NAME}"{THEME_SELECTED}>{THEME_NAME}</option>

                    </select>

                    {LANG.date_pattern}
                    <input type="text" name="date_pattern" value="{DATA.date_pattern}" class="w150 form-control"/>

                    {LANG.time_pattern}
                    <input type="text" name="time_pattern" value="{DATA.time_pattern}" class="w150 form-control"/>

                    {LANG.ssl_https}

                        <select id="ssl_https" name="ssl_https" class="form-control w300" data-val="{DATA.ssl_https}">

                            <option value="{SSL_HTTPS.key}"{SSL_HTTPS.selected}>{SSL_HTTPS.title}</option>

                        </select>

                    {LANG.lang_multi}
                    <input type="checkbox" value="1" name="lang_multi" {CHECKED_LANG_MULTI} data-toggle="controlrw"/>

                    {LANG.site_lang}

                    <select name="site_lang" class="form-control w300">

                        <option value="{LANGOP}" {SELECTED}>{LANGVALUE} </option>

                    </select>

                    {LANG.lang_geo}
                    <input type="checkbox" value="1" name="lang_geo" {CHECKED_LANG_GEO} /> ( {LANG.lang_geo_config} )

                    {LANG.rewrite}
                    <input type="checkbox" value="1" name="rewrite_enable" {CHECKED_REWRITE_ENABLE} data-toggle="controlrw"/>

                    {LANG.rewrite_optional}
                    <input type="checkbox" value="1" name="rewrite_optional" {CHECKED_REWRITE_OPTIONAL} data-toggle="controlrw1"/>

                    {LANG.rewrite_op_mod}

                    <select name="rewrite_op_mod" class="form-control w300">
                        <option value=""> </option>

                        <option value="{MODE_VALUE}"{MODE_SELECTED}>{MODE_NAME}</option>

                    </select>

                    {LANG.site_timezone}

                    <select name="site_timezone" id="site_timezone" class="form-control w300">
                        <option value="">{LANG.timezoneAuto}</option>

                        <option value="{TIMEZONEOP}" {TIMEZONESELECTED}>{TIMEZONELANGVALUE} </option>

                    </select>
                    {CURRENT_TIME}

                    {LANG.gzip_method}
                    <input type="checkbox" value="1" name="gzip_method" {CHECKED_GZIP_METHOD} />

                    {LANG.my_domains}
                    <input type="text" name="my_domains" value="{MY_DOMAINS}" class="form-control" style="width: 450px"/>

                    {LANG.cdn_url}
                    <input type="text" name="cdn_url" value="{DATA.cdn_url}" class="form-control pull-left" style="width: 450px"/>

                    {LANG.error_set_logs}
                    <input type="checkbox" value="1" name="error_set_logs" {CHECKED_ERROR_SET_LOGS} />

                    {LANG.nv_debug}
                    <input type="checkbox" name="nv_debug" value="1"{CFG_DEFINE.nv_debug}/> {LANG.nv_debug_help}

                    {LANG.error_send_email}
                    <input type="email" name="error_send_email" value="{DATA.error_send_email}" class="form-control" style="width: 450px"/>

                    {LANG.searchEngineUniqueID}
                    <input type="text" name="searchEngineUniqueID" value="{DATA.searchEngineUniqueID}" class="form-control" style="width: 450px" maxlength="50" />

                {LANG.notification_config}

            <col class="w500" />

                    {LANG.notification_active}
                    <input type="checkbox" name="notification_active" value="1" {CHECKED_NOTIFI_ACTIVE} />

                    {LANG.notification_autodel}{LANG.notification_autodel_note}
                    <input type="text" name="notification_autodel" value="{DATA.notification_autodel}" class="form-control w100 pull-left" /> {LANG.notification_day}

        <input type="hidden" name="checkss" value="{DATA.checkss}" />
        <input type="submit" name="submit" value="{LANG.submit}" class="btn btn-primary"/>

</form>

{'repo_name': 'nukeviet/nukeviet', 'stars': '111', 'repo_language': 'PHP', 'file_name': '2609.php', 'mime_type': 'text/x-php', 'hash': -2637878145255745407, 'source_dataset': 'data'}


//===--------- JITLinkGeneric.cpp - Generic JIT linker utilities ----------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// Generic JITLinker utility class.
//
//===----------------------------------------------------------------------===//

#include "JITLinkGeneric.h"

#include "llvm/Support/BinaryStreamReader.h"
#include "llvm/Support/MemoryBuffer.h"

#define DEBUG_TYPE "jitlink"

namespace llvm {
namespace jitlink {

JITLinkerBase::~JITLinkerBase() {}

void JITLinkerBase::linkPhase1(std::unique_ptr<JITLinkerBase> Self) {

  // Build the link graph.
  if (auto GraphOrErr = buildGraph(Ctx->getObjectBuffer()))
    G = std::move(*GraphOrErr);
  else
    return Ctx->notifyFailed(GraphOrErr.takeError());
  assert(G && "Graph should have been created by buildGraph above");

  // Prune and optimize the graph.
  if (auto Err = runPasses(Passes.PrePrunePasses))
    return Ctx->notifyFailed(std::move(Err));

  LLVM_DEBUG({
    dbgs() << "Link graph \"" << G->getName() << "\" pre-pruning:\n";
    dumpGraph(dbgs());
  });

  prune(*G);

  LLVM_DEBUG({
    dbgs() << "Link graph \"" << G->getName() << "\" post-pruning:\n";
    dumpGraph(dbgs());
  });

  // Run post-pruning passes.
  if (auto Err = runPasses(Passes.PostPrunePasses))
    return Ctx->notifyFailed(std::move(Err));

  // Sort blocks into segments.
  auto Layout = layOutBlocks();

  // Allocate memory for segments.
  if (auto Err = allocateSegments(Layout))
    return Ctx->notifyFailed(std::move(Err));

  // Notify client that the defined symbols have been assigned addresses.
  Ctx->notifyResolved(*G);

  auto ExternalSymbols = getExternalSymbolNames();

  // We're about to hand off ownership of ourself to the continuation. Grab a
  // pointer to the context so that we can call it to initiate the lookup.
  //
  // FIXME: Once callee expressions are defined to be sequenced before argument
  // expressions (c++17) we can simplify all this to:
  //
  // Ctx->lookup(std::move(UnresolvedExternals),
  //             [Self=std::move(Self)](Expected<AsyncLookupResult> Result) {
  //               Self->linkPhase2(std::move(Self), std::move(Result));
  //             });
  auto *TmpCtx = Ctx.get();
  TmpCtx->lookup(std::move(ExternalSymbols),
                 createLookupContinuation(
                     [S = std::move(Self), L = std::move(Layout)](
                         Expected<AsyncLookupResult> LookupResult) mutable {
                       auto &TmpSelf = *S;
                       TmpSelf.linkPhase2(std::move(S), std::move(LookupResult),
                                          std::move(L));
                     }));
}

void JITLinkerBase::linkPhase2(std::unique_ptr<JITLinkerBase> Self,
                               Expected<AsyncLookupResult> LR,
                               SegmentLayoutMap Layout) {
  // If the lookup failed, bail out.
  if (!LR)
    return deallocateAndBailOut(LR.takeError());

  // Assign addresses to external addressables.
  applyLookupResult(*LR);

  LLVM_DEBUG({
    dbgs() << "Link graph \"" << G->getName() << "\" before copy-and-fixup:\n";
    dumpGraph(dbgs());
  });

  // Copy block content to working memory and fix up.
  if (auto Err = copyAndFixUpBlocks(Layout, *Alloc))
    return deallocateAndBailOut(std::move(Err));

  LLVM_DEBUG({
    dbgs() << "Link graph \"" << G->getName() << "\" after copy-and-fixup:\n";
    dumpGraph(dbgs());
  });

  if (auto Err = runPasses(Passes.PostFixupPasses))
    return deallocateAndBailOut(std::move(Err));

  // FIXME: Use move capture once we have c++14.
  auto *UnownedSelf = Self.release();
  auto Phase3Continuation = [UnownedSelf](Error Err) {
    std::unique_ptr<JITLinkerBase> Self(UnownedSelf);
    UnownedSelf->linkPhase3(std::move(Self), std::move(Err));
  };

  Alloc->finalizeAsync(std::move(Phase3Continuation));
}

void JITLinkerBase::linkPhase3(std::unique_ptr<JITLinkerBase> Self, Error Err) {
  if (Err)
    return deallocateAndBailOut(std::move(Err));
  Ctx->notifyFinalized(std::move(Alloc));
}

Error JITLinkerBase::runPasses(LinkGraphPassList &Passes) {
  for (auto &P : Passes)
    if (auto Err = P(*G))
      return Err;
  return Error::success();
}

JITLinkerBase::SegmentLayoutMap JITLinkerBase::layOutBlocks() {

  SegmentLayoutMap Layout;

  /// Partition blocks based on permissions and content vs. zero-fill.
  for (auto *B : G->blocks()) {
    auto &SegLists = Layout[B->getSection().getProtectionFlags()];
    if (!B->isZeroFill())
      SegLists.ContentBlocks.push_back(B);
    else
      SegLists.ZeroFillBlocks.push_back(B);
  }

  /// Sort blocks within each list.
  for (auto &KV : Layout) {

    auto CompareBlocks = [](const Block *LHS, const Block *RHS) {
      // Sort by section, address and size
      if (LHS->getSection().getOrdinal() != RHS->getSection().getOrdinal())
        return LHS->getSection().getOrdinal() < RHS->getSection().getOrdinal();
      if (LHS->getAddress() != RHS->getAddress())
        return LHS->getAddress() < RHS->getAddress();
      return LHS->getSize() < RHS->getSize();
    };

    auto &SegLists = KV.second;
    llvm::sort(SegLists.ContentBlocks, CompareBlocks);
    llvm::sort(SegLists.ZeroFillBlocks, CompareBlocks);
  }

  LLVM_DEBUG({
    dbgs() << "Segment ordering:\n";
    for (auto &KV : Layout) {
      dbgs() << "  Segment "
             << static_cast<sys::Memory::ProtectionFlags>(KV.first) << ":\n";
      auto &SL = KV.second;
      for (auto &SIEntry :
           {std::make_pair(&SL.ContentBlocks, "content block"),
            std::make_pair(&SL.ZeroFillBlocks, "zero-fill block")}) {
        dbgs() << "    " << SIEntry.second << ":\n";
        for (auto *B : *SIEntry.first)
          dbgs() << "      " << *B << "\n";
      }
    }
  });

  return Layout;
}

Error JITLinkerBase::allocateSegments(const SegmentLayoutMap &Layout) {

  // Compute segment sizes and allocate memory.
  LLVM_DEBUG(dbgs() << "JIT linker requesting: { ");
  JITLinkMemoryManager::SegmentsRequestMap Segments;
  for (auto &KV : Layout) {
    auto &Prot = KV.first;
    auto &SegLists = KV.second;

    uint64_t SegAlign = 1;

    // Calculate segment content size.
    size_t SegContentSize = 0;
    for (auto *B : SegLists.ContentBlocks) {
      SegAlign = std::max(SegAlign, B->getAlignment());
      SegContentSize = alignToBlock(SegContentSize, *B);
      SegContentSize += B->getSize();
    }

    uint64_t SegZeroFillStart = SegContentSize;
    uint64_t SegZeroFillEnd = SegZeroFillStart;

    for (auto *B : SegLists.ZeroFillBlocks) {
      SegAlign = std::max(SegAlign, B->getAlignment());
      SegZeroFillEnd = alignToBlock(SegZeroFillEnd, *B);
      SegZeroFillEnd += B->getSize();
    }

    Segments[Prot] = {SegAlign, SegContentSize,
                      SegZeroFillEnd - SegZeroFillStart};

    LLVM_DEBUG({
      dbgs() << (&KV == &*Layout.begin() ? "" : "; ")
             << static_cast<sys::Memory::ProtectionFlags>(Prot)
             << ": alignment = " << SegAlign
             << ", content size = " << SegContentSize
             << ", zero-fill size = " << (SegZeroFillEnd - SegZeroFillStart);
    });
  }
  LLVM_DEBUG(dbgs() << " }\n");

  if (auto AllocOrErr = Ctx->getMemoryManager().allocate(Segments))
    Alloc = std::move(*AllocOrErr);
  else
    return AllocOrErr.takeError();

  LLVM_DEBUG({
    dbgs() << "JIT linker got working memory:\n";
    for (auto &KV : Layout) {
      auto Prot = static_cast<sys::Memory::ProtectionFlags>(KV.first);
      dbgs() << "  " << Prot << ": "
             << (const void *)Alloc->getWorkingMemory(Prot).data() << "\n";
    }
  });

  // Update block target addresses.
  for (auto &KV : Layout) {
    auto &Prot = KV.first;
    auto &SL = KV.second;

    JITTargetAddress NextBlockAddr =
        Alloc->getTargetMemory(static_cast<sys::Memory::ProtectionFlags>(Prot));

    for (auto *SIList : {&SL.ContentBlocks, &SL.ZeroFillBlocks})
      for (auto *B : *SIList) {
        NextBlockAddr = alignToBlock(NextBlockAddr, *B);
        B->setAddress(NextBlockAddr);
        NextBlockAddr += B->getSize();
      }
  }

  return Error::success();
}

JITLinkContext::LookupMap JITLinkerBase::getExternalSymbolNames() const {
  // Identify unresolved external symbols.
  JITLinkContext::LookupMap UnresolvedExternals;
  for (auto *Sym : G->external_symbols()) {
    assert(Sym->getAddress() == 0 &&
           "External has already been assigned an address");
    assert(Sym->getName() != StringRef() && Sym->getName() != "" &&
           "Externals must be named");
    SymbolLookupFlags LookupFlags =
        Sym->getLinkage() == Linkage::Weak
            ? SymbolLookupFlags::WeaklyReferencedSymbol
            : SymbolLookupFlags::RequiredSymbol;
    UnresolvedExternals[Sym->getName()] = LookupFlags;
  }
  return UnresolvedExternals;
}

void JITLinkerBase::applyLookupResult(AsyncLookupResult Result) {
  for (auto *Sym : G->external_symbols()) {
    assert(Sym->getOffset() == 0 &&
           "External symbol is not at the start of its addressable block");
    assert(Sym->getAddress() == 0 && "Symbol already resolved");
    assert(!Sym->isDefined() && "Symbol being resolved is already defined");
    auto ResultI = Result.find(Sym->getName());
    if (ResultI != Result.end())
      Sym->getAddressable().setAddress(ResultI->second.getAddress());
    else
      assert(Sym->getLinkage() == Linkage::Weak &&
             "Failed to resolve non-weak reference");
  }

  LLVM_DEBUG({
    dbgs() << "Externals after applying lookup result:\n";
    for (auto *Sym : G->external_symbols())
      dbgs() << "  " << Sym->getName() << ": "
             << formatv("{0:x16}", Sym->getAddress()) << "\n";
  });
  assert(llvm::all_of(G->external_symbols(),
                      [](Symbol *Sym) {
                        return Sym->getAddress() != 0 ||
                               Sym->getLinkage() == Linkage::Weak;
                      }) &&
         "All strong external symbols should have been resolved by now");
}

void JITLinkerBase::deallocateAndBailOut(Error Err) {
  assert(Err && "Should not be bailing out on success value");
  assert(Alloc && "can not call deallocateAndBailOut before allocation");
  Ctx->notifyFailed(joinErrors(std::move(Err), Alloc->deallocate()));
}

void JITLinkerBase::dumpGraph(raw_ostream &OS) {
  assert(G && "Graph is not set yet");
  G->dump(dbgs(), [this](Edge::Kind K) { return getEdgeKindName(K); });
}

void prune(LinkGraph &G) {
  std::vector<Symbol *> Worklist;
  DenseSet<Block *> VisitedBlocks;

  // Build the initial worklist from all symbols initially live.
  for (auto *Sym : G.defined_symbols())
    if (Sym->isLive())
      Worklist.push_back(Sym);

  // Propagate live flags to all symbols reachable from the initial live set.
  while (!Worklist.empty()) {
    auto *Sym = Worklist.back();
    Worklist.pop_back();

    auto &B = Sym->getBlock();

    // Skip addressables that we've visited before.
    if (VisitedBlocks.count(&B))
      continue;

    VisitedBlocks.insert(&B);

    for (auto &E : Sym->getBlock().edges()) {
      if (E.getTarget().isDefined() && !E.getTarget().isLive()) {
        E.getTarget().setLive(true);
        Worklist.push_back(&E.getTarget());
      }
    }
  }

  // Collect all the symbols to remove, then remove them.
  {
    LLVM_DEBUG(dbgs() << "Dead-stripping symbols:\n");
    std::vector<Symbol *> SymbolsToRemove;
    for (auto *Sym : G.defined_symbols())
      if (!Sym->isLive())
        SymbolsToRemove.push_back(Sym);
    for (auto *Sym : SymbolsToRemove) {
      LLVM_DEBUG(dbgs() << "  " << *Sym << "...\n");
      G.removeDefinedSymbol(*Sym);
    }
  }

  // Delete any unused blocks.
  {
    LLVM_DEBUG(dbgs() << "Dead-stripping blocks:\n");
    std::vector<Block *> BlocksToRemove;
    for (auto *B : G.blocks())
      if (!VisitedBlocks.count(B))
        BlocksToRemove.push_back(B);
    for (auto *B : BlocksToRemove) {
      LLVM_DEBUG(dbgs() << "  " << *B << "...\n");
      G.removeBlock(*B);
    }
  }
}

} // end namespace jitlink
} // end namespace llvm

{'repo_name': 'epiqc/ScaffCC', 'stars': '118', 'repo_language': 'C++', 'file_name': 'boolean_formula.x2y2.scaffold', 'mime_type': 'text/x-c', 'hash': 5934929470306189178, 'source_dataset': 'data'}


#pragma once

#include <iostream>
#include "Beans/DatabaseBean.h"
#include "GUI/BitmapText.h"

// an item document page bean, directly from the database
struct ItemDocumentPageBean final : DatabaseBean {
	std::string item_id;
	int page_nr;
	std::string title;
	std::string content;
	std::string texture_path;
	TextAlignment content_alignment;
};

{'repo_name': 'tizian/Cendric2', 'stars': '206', 'repo_language': 'C', 'file_name': 'db_tests.sh', 'mime_type': 'text/plain', 'hash': -6477846943609184132, 'source_dataset': 'data'}


{'repo_name': 'GoogleChromeLabs/text-app', 'stars': '451', 'repo_language': 'JavaScript', 'file_name': 'jquery-1.8.3.js', 'mime_type': 'text/plain', 'hash': -2905674415451555889, 'source_dataset': 'data'}


/*
 * This file is subject to the terms and conditions of the GNU General Public
 * License.  See the file "COPYING" in the main directory of this archive
 * for more details.
 *
 * Copyright (C) 1995, 96, 97, 98, 99, 2000, 01, 02 by Ralf Baechle
 * Copyright (C) 1999, 2000 Silicon Graphics, Inc.
 * Copyright (C) 2001 MIPS Technologies, Inc.
 */
#include <linux/errno.h>
#include <asm/asm.h>
#include <asm/asmmacro.h>
#include <asm/irqflags.h>
#include <asm/mipsregs.h>
#include <asm/regdef.h>
#include <asm/stackframe.h>
#include <asm/asm-offsets.h>
#include <asm/sysmips.h>
#include <asm/thread_info.h>
#include <asm/unistd.h>
#include <asm/war.h>

#ifndef CONFIG_BINFMT_ELF32
/* Neither O32 nor N32, so define handle_sys here */
#define handle_sys64 handle_sys
#endif

	.align  5
NESTED(handle_sys64, PT_SIZE, sp)
#if !defined(CONFIG_MIPS32_O32) && !defined(CONFIG_MIPS32_N32)
	/*
	 * When 32-bit compatibility is configured scall_o32.S
	 * already did this.
	 */
	.set	noat
	SAVE_SOME
	TRACE_IRQS_ON_RELOAD
	STI
	.set	at
#endif

	dsubu	t0, v0, __NR_64_Linux	# check syscall number
	sltiu	t0, t0,	__NR_64_Linux_syscalls + 1
#if !defined(CONFIG_MIPS32_O32) && !defined(CONFIG_MIPS32_N32)
	ld	t1, PT_EPC(sp)		# skip syscall on return
	daddiu	t1, 4			# skip to next instruction
	sd	t1, PT_EPC(sp)
#endif
	beqz	t0, illegal_syscall

	dsll	t0, v0, 3		# offset into table
	ld	t2, (sys_call_table - (__NR_64_Linux * 8))(t0)
					# syscall routine

	sd	a3, PT_R26(sp)		# save a3 for syscall restarting

	li	t1, _TIF_SYSCALL_TRACE | _TIF_SYSCALL_AUDIT
	LONG_L	t0, TI_FLAGS($28)	# syscall tracing enabled?
	and	t0, t1, t0
	bnez	t0, syscall_trace_entry

	jalr	t2			# Do The Real Thing (TM)

	li	t0, -EMAXERRNO - 1	# error?
	sltu	t0, t0, v0
	sd	t0, PT_R7(sp)		# set error flag
	beqz	t0, 1f

	ld	t1, PT_R2(sp)		# syscall number
	dnegu	v0			# error
	sd	t1, PT_R0(sp)		# save it for syscall restarting
1:	sd	v0, PT_R2(sp)		# result

n64_syscall_exit:
	local_irq_disable		# make sure need_resched and
					# signals dont change between
					# sampling and return
	LONG_L	a2, TI_FLAGS($28)	# current->work
	li	t0, _TIF_ALLWORK_MASK
	and	t0, a2, t0
	bnez	t0, n64_syscall_exit_work

	j	restore_partial

n64_syscall_exit_work:
	j	syscall_exit_work_partial

/* ------------------------------------------------------------------------ */

syscall_trace_entry:
	SAVE_STATIC
	move	s0, t2
	move	a0, sp
	jal	syscall_trace_enter

	move	t0, s0
	RESTORE_STATIC
	ld	a0, PT_R4(sp)		# Restore argument registers
	ld	a1, PT_R5(sp)
	ld	a2, PT_R6(sp)
	ld	a3, PT_R7(sp)
	ld	a4, PT_R8(sp)
	ld	a5, PT_R9(sp)
	jalr	t0

	li	t0, -EMAXERRNO - 1	# error?
	sltu	t0, t0, v0
	sd	t0, PT_R7(sp)		# set error flag
	beqz	t0, 1f

	ld	t1, PT_R2(sp)		# syscall number
	dnegu	v0			# error
	sd	t1, PT_R0(sp)		# save it for syscall restarting
1:	sd	v0, PT_R2(sp)		# result

	j	syscall_exit

illegal_syscall:
	/* This also isn't a 64-bit syscall, throw an error.  */
	li	v0, ENOSYS			# error
	sd	v0, PT_R2(sp)
	li	t0, 1				# set error flag
	sd	t0, PT_R7(sp)
	j	n64_syscall_exit
	END(handle_sys64)

	.align	3
sys_call_table:
	PTR	sys_read			/* 5000 */
	PTR	sys_write
	PTR	sys_open
	PTR	sys_close
	PTR	sys_newstat
	PTR	sys_newfstat			/* 5005 */
	PTR	sys_newlstat
	PTR	sys_poll
	PTR	sys_lseek
	PTR	sys_mips_mmap
	PTR	sys_mprotect			/* 5010 */
	PTR	sys_munmap
	PTR	sys_brk
	PTR	sys_rt_sigaction
	PTR	sys_rt_sigprocmask
	PTR	sys_ioctl			/* 5015 */
	PTR	sys_pread64
	PTR	sys_pwrite64
	PTR	sys_readv
	PTR	sys_writev
	PTR	sys_access			/* 5020 */
	PTR	sysm_pipe
	PTR	sys_select
	PTR	sys_sched_yield
	PTR	sys_mremap
	PTR	sys_msync			/* 5025 */
	PTR	sys_mincore
	PTR	sys_madvise
	PTR	sys_shmget
	PTR	sys_shmat
	PTR	sys_shmctl			/* 5030 */
	PTR	sys_dup
	PTR	sys_dup2
	PTR	sys_pause
	PTR	sys_nanosleep
	PTR	sys_getitimer			/* 5035 */
	PTR	sys_setitimer
	PTR	sys_alarm
	PTR	sys_getpid
	PTR	sys_sendfile64
	PTR	sys_socket			/* 5040 */
	PTR	sys_connect
	PTR	sys_accept
	PTR	sys_sendto
	PTR	sys_recvfrom
	PTR	sys_sendmsg			/* 5045 */
	PTR	sys_recvmsg
	PTR	sys_shutdown
	PTR	sys_bind
	PTR	sys_listen
	PTR	sys_getsockname			/* 5050 */
	PTR	sys_getpeername
	PTR	sys_socketpair
	PTR	sys_setsockopt
	PTR	sys_getsockopt
	PTR	sys_clone			/* 5055 */
	PTR	sys_fork
	PTR	sys_execve
	PTR	sys_exit
	PTR	sys_wait4
	PTR	sys_kill			/* 5060 */
	PTR	sys_newuname
	PTR	sys_semget
	PTR	sys_semop
	PTR	sys_semctl
	PTR	sys_shmdt			/* 5065 */
	PTR	sys_msgget
	PTR	sys_msgsnd
	PTR	sys_msgrcv
	PTR	sys_msgctl
	PTR	sys_fcntl			/* 5070 */
	PTR	sys_flock
	PTR	sys_fsync
	PTR	sys_fdatasync
	PTR	sys_truncate
	PTR	sys_ftruncate			/* 5075 */
	PTR	sys_getdents
	PTR	sys_getcwd
	PTR	sys_chdir
	PTR	sys_fchdir
	PTR	sys_rename			/* 5080 */
	PTR	sys_mkdir
	PTR	sys_rmdir
	PTR	sys_creat
	PTR	sys_link
	PTR	sys_unlink			/* 5085 */
	PTR	sys_symlink
	PTR	sys_readlink
	PTR	sys_chmod
	PTR	sys_fchmod
	PTR	sys_chown			/* 5090 */
	PTR	sys_fchown
	PTR	sys_lchown
	PTR	sys_umask
	PTR	sys_gettimeofday
	PTR	sys_getrlimit			/* 5095 */
	PTR	sys_getrusage
	PTR	sys_sysinfo
	PTR	sys_times
	PTR	sys_ptrace
	PTR	sys_getuid			/* 5100 */
	PTR	sys_syslog
	PTR	sys_getgid
	PTR	sys_setuid
	PTR	sys_setgid
	PTR	sys_geteuid			/* 5105 */
	PTR	sys_getegid
	PTR	sys_setpgid
	PTR	sys_getppid
	PTR	sys_getpgrp
	PTR	sys_setsid			/* 5110 */
	PTR	sys_setreuid
	PTR	sys_setregid
	PTR	sys_getgroups
	PTR	sys_setgroups
	PTR	sys_setresuid			/* 5115 */
	PTR	sys_getresuid
	PTR	sys_setresgid
	PTR	sys_getresgid
	PTR	sys_getpgid
	PTR	sys_setfsuid			/* 5120 */
	PTR	sys_setfsgid
	PTR	sys_getsid
	PTR	sys_capget
	PTR	sys_capset
	PTR	sys_rt_sigpending		/* 5125 */
	PTR	sys_rt_sigtimedwait
	PTR	sys_rt_sigqueueinfo
	PTR	sys_rt_sigsuspend
	PTR	sys_sigaltstack
	PTR	sys_utime			/* 5130 */
	PTR	sys_mknod
	PTR	sys_personality
	PTR	sys_ustat
	PTR	sys_statfs
	PTR	sys_fstatfs			/* 5135 */
	PTR	sys_sysfs
	PTR	sys_getpriority
	PTR	sys_setpriority
	PTR	sys_sched_setparam
	PTR	sys_sched_getparam		/* 5140 */
	PTR	sys_sched_setscheduler
	PTR	sys_sched_getscheduler
	PTR	sys_sched_get_priority_max
	PTR	sys_sched_get_priority_min
	PTR	sys_sched_rr_get_interval	/* 5145 */
	PTR	sys_mlock
	PTR	sys_munlock
	PTR	sys_mlockall
	PTR	sys_munlockall
	PTR	sys_vhangup			/* 5150 */
	PTR	sys_pivot_root
	PTR	sys_sysctl
	PTR	sys_prctl
	PTR	sys_adjtimex
	PTR	sys_setrlimit			/* 5155 */
	PTR	sys_chroot
	PTR	sys_sync
	PTR	sys_acct
	PTR	sys_settimeofday
	PTR	sys_mount			/* 5160 */
	PTR	sys_umount
	PTR	sys_swapon
	PTR	sys_swapoff
	PTR	sys_reboot
	PTR	sys_sethostname			/* 5165 */
	PTR	sys_setdomainname
	PTR	sys_ni_syscall			/* was create_module */
	PTR	sys_init_module
	PTR	sys_delete_module
	PTR	sys_ni_syscall			/* 5170, was get_kernel_syms */
	PTR	sys_ni_syscall			/* was query_module */
	PTR	sys_quotactl
	PTR	sys_ni_syscall			/* was nfsservctl */
	PTR	sys_ni_syscall			/* res. for getpmsg */
	PTR	sys_ni_syscall			/* 5175  for putpmsg */
	PTR	sys_ni_syscall			/* res. for afs_syscall */
	PTR	sys_ni_syscall			/* res. for security */
	PTR	sys_gettid
	PTR	sys_readahead
	PTR	sys_setxattr			/* 5180 */
	PTR	sys_lsetxattr
	PTR	sys_fsetxattr
	PTR	sys_getxattr
	PTR	sys_lgetxattr
	PTR	sys_fgetxattr			/* 5185 */
	PTR	sys_listxattr
	PTR	sys_llistxattr
	PTR	sys_flistxattr
	PTR	sys_removexattr
	PTR	sys_lremovexattr		/* 5190 */
	PTR	sys_fremovexattr
	PTR	sys_tkill
	PTR	sys_ni_syscall
	PTR	sys_futex
	PTR	sys_sched_setaffinity		/* 5195 */
	PTR	sys_sched_getaffinity
	PTR	sys_cacheflush
	PTR	sys_cachectl
	PTR	sys_sysmips
	PTR	sys_io_setup			/* 5200 */
	PTR	sys_io_destroy
	PTR	sys_io_getevents
	PTR	sys_io_submit
	PTR	sys_io_cancel
	PTR	sys_exit_group			/* 5205 */
	PTR	sys_lookup_dcookie
	PTR	sys_epoll_create
	PTR	sys_epoll_ctl
	PTR	sys_epoll_wait
	PTR	sys_remap_file_pages		/* 5210 */
	PTR	sys_rt_sigreturn
	PTR	sys_set_tid_address
	PTR	sys_restart_syscall
	PTR	sys_semtimedop
	PTR	sys_fadvise64_64		/* 5215 */
	PTR	sys_timer_create
	PTR	sys_timer_settime
	PTR	sys_timer_gettime
	PTR	sys_timer_getoverrun
	PTR	sys_timer_delete		/* 5220 */
	PTR	sys_clock_settime
	PTR	sys_clock_gettime
	PTR	sys_clock_getres
	PTR	sys_clock_nanosleep
	PTR	sys_tgkill			/* 5225 */
	PTR	sys_utimes
	PTR	sys_mbind
	PTR	sys_ni_syscall			/* sys_get_mempolicy */
	PTR	sys_ni_syscall			/* sys_set_mempolicy */
	PTR	sys_mq_open			/* 5230 */
	PTR	sys_mq_unlink
	PTR	sys_mq_timedsend
	PTR	sys_mq_timedreceive
	PTR	sys_mq_notify
	PTR	sys_mq_getsetattr		/* 5235 */
	PTR	sys_ni_syscall			/* sys_vserver */
	PTR	sys_waitid
	PTR	sys_ni_syscall			/* available, was setaltroot */
	PTR	sys_add_key
	PTR	sys_request_key			/* 5240 */
	PTR	sys_keyctl
	PTR	sys_set_thread_area
	PTR	sys_inotify_init
	PTR	sys_inotify_add_watch
	PTR	sys_inotify_rm_watch		/* 5245 */
	PTR	sys_migrate_pages
	PTR	sys_openat
	PTR	sys_mkdirat
	PTR	sys_mknodat
	PTR	sys_fchownat			/* 5250 */
	PTR	sys_futimesat
	PTR	sys_newfstatat
	PTR	sys_unlinkat
	PTR	sys_renameat
	PTR	sys_linkat			/* 5255 */
	PTR	sys_symlinkat
	PTR	sys_readlinkat
	PTR	sys_fchmodat
	PTR	sys_faccessat
	PTR	sys_pselect6			/* 5260 */
	PTR	sys_ppoll
	PTR	sys_unshare
	PTR	sys_splice
	PTR	sys_sync_file_range
	PTR	sys_tee				/* 5265 */
	PTR	sys_vmsplice
	PTR	sys_move_pages
	PTR	sys_set_robust_list
	PTR	sys_get_robust_list
	PTR	sys_kexec_load			/* 5270 */
	PTR	sys_getcpu
	PTR	sys_epoll_pwait
	PTR	sys_ioprio_set
	PTR	sys_ioprio_get
	PTR	sys_utimensat			/* 5275 */
	PTR	sys_signalfd
	PTR	sys_ni_syscall			/* was timerfd */
	PTR	sys_eventfd
	PTR	sys_fallocate
	PTR	sys_timerfd_create		/* 5280 */
	PTR	sys_timerfd_gettime
	PTR	sys_timerfd_settime
	PTR	sys_signalfd4
	PTR	sys_eventfd2
	PTR	sys_epoll_create1		/* 5285 */
	PTR	sys_dup3
	PTR	sys_pipe2
	PTR	sys_inotify_init1
	PTR	sys_preadv
	PTR	sys_pwritev			/* 5290 */
	PTR	sys_rt_tgsigqueueinfo
	PTR	sys_perf_event_open
	PTR	sys_accept4
	PTR	sys_recvmmsg
	PTR	sys_fanotify_init		/* 5295 */
	PTR	sys_fanotify_mark
	PTR	sys_prlimit64
	PTR	sys_name_to_handle_at
	PTR	sys_open_by_handle_at
	PTR	sys_clock_adjtime		/* 5300 */
	PTR	sys_syncfs
	PTR	sys_sendmmsg
	PTR	sys_setns
	PTR	sys_process_vm_readv
	PTR	sys_process_vm_writev		/* 5305 */
	.size	sys_call_table,.-sys_call_table

{'repo_name': 'MotorolaMobilityLLC/kernel-msm', 'stars': '447', 'repo_language': 'C', 'file_name': 'uncompress.h', 'mime_type': 'text/x-c', 'hash': 8206881570046647365, 'source_dataset': 'data'}


;;;; Copied from slamhound 1.5.5
;;;; Copyright © 2011-2012 Phil Hagelberg and contributors
;;;; Distributed under the Eclipse Public License, the same as Clojure.
(ns refactor-nrepl.ns.slam.hound.regrow
  (:require [clojure.set :as set]
            [clojure.string :as string]
            [refactor-nrepl.ns.slam.hound.future :refer [as->* cond->*]]
            [refactor-nrepl.ns.slam.hound.search :as search]
            [nrepl.middleware.interruptible-eval :refer [*msg*]])
  (:import (clojure.lang IMapEntry IRecord)
           (java.util.regex Pattern)))

(def ^:dynamic *cache* (atom {}))
(def ^:dynamic *dirty-ns* (atom #{}))

(defn wrap-clojure-repl [f]
  (fn [& args]
    (when-let [ns (some-> *msg* :ns symbol find-ns)]
      (swap! *dirty-ns* conj ns))
    (apply f args)))

(alter-var-root #'clojure.main/repl wrap-clojure-repl)

(defmacro ^:private caching [key & body]
  `(if *cache*
     (if-let [v# (get @*cache* ~key)]
       v#
       (let [v# (do ~@body)]
         (swap! *cache* assoc ~key v#)
         v#))
     (do ~@body)))

(defn cache-with-dirty-tracking
  "The function to be cached, f, should have two signatures. A zero-operand
  signature which computes the result for all namespaces, and a two-operand
  version which takes the previously computed result and a list of dirty
  namespaces, and returns an updated result."
  [key f]
  (if *cache*
    (if-let [cached (get @*cache* key)]
      (if-let [dirty (seq @*dirty-ns*)]
        (key (swap! *cache* assoc key (f cached dirty)))
        cached)
      (key (swap! *cache* assoc key (f))))
    (f)))

(defn clear-cache! []
  (when *cache*
    (reset! *cache* {})
    (reset! *dirty-ns* #{})))

(defn- all-ns-imports*
  ([]
   (all-ns-imports* {} (all-ns)))
  ([init namespaces]
   (reduce (fn [imports ns]
             (assoc imports ns (ns-imports ns)))
           init namespaces)))

(defn- all-ns-imports []
  (cache-with-dirty-tracking :all-ns-imports all-ns-imports*))

(defn- ns->symbols []
  (caching :ns->symbols
           (let [xs (all-ns)]
             (zipmap xs (mapv (comp set keys ns-publics) xs)))))

(defn- symbols->ns-syms*
  ([]
   (symbols->ns-syms* {} (all-ns)))
  ([init namespaces]
   (reduce
    (fn [m ns] (let [ns-sym (ns-name ns)]
                 (reduce
                  (fn [m k]
                    (assoc m k (conj (or (m k) #{}) ns-sym)))
                  m (keys (ns-publics ns)))))
    init namespaces)))

(defn- symbols->ns-syms []
  (cache-with-dirty-tracking :symbols->ns-syms symbols->ns-syms*))

(defn- walk
  "Adapted from clojure.walk/walk and clojure.walk/prewalk; this version
  preserves metadata on compound forms."
  [f form]
  (-> (cond
        (list? form) (apply list (map f form))
        (instance? IMapEntry form) (vec (map f form))
        (seq? form) (doall (map f form))
        (instance? IRecord form) (reduce (fn [r x] (conj r (f x))) form form)
        (coll? form) (into (empty form) (map f form))
        :else form)
      (as->* form'
        (if-let [m (meta form)]
          (with-meta form' m)
          form'))))

(defn- prewalk [f form]
  (walk (partial prewalk f) (f form)))

(defn- symbols-in-body [body]
  (filter symbol? (remove coll? (rest (tree-seq coll? seq body)))))

(defn- remove-var-form
  "Remove (var symbol) forms from body"
  [expr]
  (if (and (coll? expr) (= (first expr) 'var))
    nil
    expr))

(def ^:private ns-qualifed-syms
  (memoize
   (fn [body]
     (apply merge-with set/union {}
            (for [ss (symbols-in-body body)
                  :let [[_ alias var-name] (re-matches #"(.+)/(.+)" (str ss))]
                  :when alias]
              {(symbol alias) #{(symbol var-name)}})))))

(defn- ns-import-candidates
  "Search (all-ns) for imports that match missing-sym, returning a set of
  class symbols. This is slower than scanning through the list of static
  package names, but will successfully find dynamically created classes such
  as those created by deftype, defrecord, and definterface."
  [missing-sym]
  (reduce (fn [s imports]
            (if-let [^Class cls (get imports missing-sym)]
              (conj s (symbol (.getCanonicalName cls)))
              s))
          #{} (vals (all-ns-imports))))

(defn- alias-candidates [type missing body]
  (set
   (let [syms-with-alias (get (ns-qualifed-syms body) missing)]
     (when (seq syms-with-alias)
       (let [ns->syms (ns->symbols)]
         (for [ns (all-ns)
               :when (set/subset? syms-with-alias (ns->syms ns))]
           (ns-name ns)))))))

(defn candidates
  "Return a set of class or ns symbols that match the given constraints."
  [type missing body old-ns-map]
  (case type
    :import (into (ns-import-candidates missing)
                  (get @search/available-classes-by-last-segment missing))
    :alias (let [cs (alias-candidates type missing body)]
             (if (seq cs)
               cs
               ;; Try the alias search again without dynamically resolved vars
               ;; in case #' was used to resolve private vars in an aliased ns
               (let [body' (prewalk remove-var-form body)]
                 (if (= body' body)
                   cs
                   (alias-candidates type missing body')))))
    :refer (get (symbols->ns-syms) missing)
    :rename (reduce-kv
             (fn [s ns orig->rename]
               (cond->* s
                 (some #{missing} (vals orig->rename)) (conj ns)))
             #{} (:rename old-ns-map))))

{'repo_name': 'clojure-emacs/refactor-nrepl', 'stars': '191', 'repo_language': 'Clojure', 'file_name': 'config.yml', 'mime_type': 'text/plain', 'hash': -5997854240786246171, 'source_dataset': 'data'}


/* SPDX-License-Identifier: Apache-2.0 */
/* Copyright Contributors to the ODPi Egeria project. */
package org.odpi.openmetadata.frameworks.connectors.properties;

import org.odpi.openmetadata.frameworks.connectors.properties.beans.Asset;
import org.odpi.openmetadata.frameworks.connectors.properties.beans.Classification;
import org.odpi.openmetadata.frameworks.connectors.properties.beans.ElementType;
import org.odpi.openmetadata.frameworks.connectors.properties.beans.OwnerType;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * AssetSummary holds asset properties that are used for displaying details of
 * an asset in summary lists or hover text.  It includes the following properties:
 *

 *
type - metadata type information for the asset

 *
guid - globally unique identifier for the asset

 *
url - external link for the asset

 *
qualifiedName - The official (unique) name for the asset. This is often defined by the IT systems
 *     management organization and should be used (when available) on audit logs and error messages.
 *     (Sourced from qualifiedName from Referenceable - model 0010)

 *
displayName - A consumable name for the asset.  Often a shortened form of the asset's qualifiedName
 *     for use on user interfaces and messages.   The asset's displayName should be only be used for audit logs and error
 *     messages if the qualifiedName is not set. (Sourced from displayName attribute name within Asset - model 0010)

 *
shortDescription - short description about the asset.
 *     (Sourced from assetSummary within ConnectionsToAsset - model 0205)

 *
description - full description of the asset.
 *     (Sourced from attribute description within Asset - model 0010)

 *
owner - name of the person or organization that owns the asset.
 *     (Sourced from attribute owner within AssetOwnershipClassification - model 0445)

 *
zoneMembership - list of governance zones assigned to the asset

 *
classifications - list of classifications assigned to the asset

 *

 */
public class AssetSummary extends AssetDescriptor
{
    private static final long     serialVersionUID = 1L;

    /**
     * Default constructor only for subclasses
     */
    protected AssetSummary()
    {
        super();
    }

    /**
     * Bean constructor - initializes AssetSummary using a bean returned by the REST interface.
     *
     * @param assetBean asset properties bean
     */
    public AssetSummary(Asset assetBean)
    {
        super(assetBean);
    }

    /**
     * Copy/clone constructor.  Note, this is a deep copy
     *
     * @param templateAssetSummary template values for asset summary
     */
    public AssetSummary(AssetSummary templateAssetSummary)
    {
        /*
         * Initialize super class
         */
        super(templateAssetSummary);
    }

    /**
     * Return the element type properties for this asset.  These values are set up by the metadata repository
     * and define details to the metadata entity used to represent this element.
     *
     * @return AssetElementType type information.
     */
    public AssetElementType getType()
    {
        ElementType elementType = assetBean.getType();

        if (elementType == null)
        {
            return null;
        }
        else
        {
            return new AssetElementType(elementType);
        }
    }

    /**
     * Return the unique id for the properties object.  Null means no guid is assigned.
     *
     * @return String unique id
     */
    public String getGUID()
    {
        return assetBean.getGUID();
    }

    /**
     * Returns the URL to access the properties object in the metadata repository.
     * If no url is available then null is returned.
     *
     * @return String URL
     */
    public String getURL()
    {
        return assetBean.getURL();
    }

    /**
     * Returns the stored qualified name property for the asset.
     * If no qualified name is provided then null is returned.
     *
     * @return qualifiedName
     */
    public String getQualifiedName()
    {
        return assetBean.getQualifiedName();
    }

    /**
     * Returns the stored display name property for the asset.
     * If no display name is available then null is returned.
     *
     * @return displayName
     */
    public String getDisplayName()
    {
        return assetBean.getDisplayName();
    }

    /**
     * Returns the short description of the asset from relationship with Connection.
     *
     * @return shortDescription String
     */
    public String getShortDescription()
    {
        return assetBean.getShortDescription();
    }

    /**
     * Returns the stored description property for the asset.
     * If no description is provided then null is returned.
     *
     * @return description String
     */
    public String getDescription()
    {
        return assetBean.getDescription();
    }

    /**
     * Returns the name of the owner for this asset.
     *
     * @return owner String
     */
    public String getOwner()
    {
        return assetBean.getOwner();
    }

    /**
     * Return the type of owner stored in the owner property.
     *
     * @return OwnerType enum
     */
    public OwnerType getOwnerType()
    {
        return assetBean.getOwnerType();
    }

    /**
     * Return the names of the zones that this asset is a member of.
     *
     * @return list of zone names
     */
    public List<String> getZoneMembership() { return assetBean.getZoneMembership(); }

    /**
     * Return the list of classifications associated with the asset.
     *
     * @return list of classifications
     */
    public List<AssetClassification> getAssetClassifications()
    {
        List<Classification> classifications = assetBean.getClassifications();

        if (classifications == null)
        {
            return null;
        }
        else
        {
            List<AssetClassification> assetClassifications = new ArrayList<>();

            for (Classification classification : classifications)
            {
                if (classification != null)
                {
                    assetClassifications.add(new AssetClassification(this, classification));
                }
            }

            if (assetClassifications.isEmpty())
            {
                return null;
            }
            else
            {
                return assetClassifications;
            }
        }
    }

    /**
     * Return the properties that characterize where this asset is from.
     *
     * @return map of name value pairs, all strings
     */
    public Map<String, String> getOrigins()
    {
        return assetBean.getOrigin();
    }

    /**
     * Return a short description of the last change to the asset.
     *
     * @return string description
     */
    public String getLatestChange()
    {
        return assetBean.getLatestChange();
    }

    /**
     * Return the set of properties that are specific to the particular type of asset.  The caller is given their
     * own copy of the property object.  The properties are named entityName.attributeName. The values are all strings.
     *
     * @return  asset properties using the name of attributes from the model.
     */
    public Map<String, Object> getExtendedProperties()
    {
        return assetBean.getExtendedProperties();
    }

    /**
     * Return the set of additional properties.
     *
     * @return AdditionalProperties object.
     */
    public AdditionalProperties getAdditionalProperties()
    {
        Map<String, String>   additionalProperties = assetBean.getAdditionalProperties();

        if (additionalProperties == null)
        {
            return null;
        }
        else
        {
            return new AdditionalProperties(this, additionalProperties);
        }
    }

    /**
     * Standard toString method.
     *
     * @return print out of variables in a JSON-style
     */
    @Override
    public String toString()
    {
        return assetBean.toString();
    }

    /**
     * Compare the values of the supplied object with those stored in the current object.
     *
     * @param objectToCompare supplied object
     * @return boolean result of comparison
     */
    @Override
    public boolean equals(Object objectToCompare)
    {
        if (this == objectToCompare)
        {
            return true;
        }
        if (!(objectToCompare instanceof AssetSummary))
        {
            return false;
        }

        AssetSummary that = (AssetSummary) objectToCompare;
        return assetBean.equals(that.getAssetBean());
    }

    /**
     * Create a hash code for this element type.
     *
     * @return int hash code
     */
    @Override
    public int hashCode()
    {
        return assetBean.hashCode();
    }
}

{'repo_name': 'odpi/egeria', 'stars': '221', 'repo_language': 'Java', 'file_name': 'config.yml', 'mime_type': 'text/plain', 'hash': -438761074585032103, 'source_dataset': 'data'}


Reveal.addEventListener( 'ready', function() {

	QUnit.module( 'Markdown' );

	QUnit.test( 'Vertical separator', function( assert ) {
		assert.strictEqual( document.querySelectorAll( '.reveal .slides>section>section' ).length, 4, 'found four slides' );
	});

	QUnit.test( 'Attributes on element header in vertical slides', function( assert ) {
		assert.strictEqual( document.querySelectorAll( '.reveal .slides section>section h2.fragment.fade-out' ).length, 1, 'found one vertical slide with class fragment.fade-out on header' );
		assert.strictEqual( document.querySelectorAll( '.reveal .slides section>section h2.fragment.shrink' ).length, 1, 'found one vertical slide with class fragment.shrink on header' );
	});

	QUnit.test( 'Attributes on element paragraphs in vertical slides', function( assert ) {
		assert.strictEqual( document.querySelectorAll( '.reveal .slides section>section p.fragment.grow' ).length, 2, 'found a vertical slide with two paragraphs with class fragment.grow' );
	});

	QUnit.test( 'Attributes on element list items in vertical slides', function( assert ) {
		assert.strictEqual( document.querySelectorAll( '.reveal .slides section>section li.fragment.grow' ).length, 3, 'found a vertical slide with three list items with class fragment.grow' );
	});

	QUnit.test( 'Attributes on element paragraphs in horizontal slides', function( assert ) {
		assert.strictEqual( document.querySelectorAll( '.reveal .slides section p.fragment.highlight-red' ).length, 4, 'found a horizontal slide with four paragraphs with class fragment.grow' );
	});

	QUnit.test( 'Attributes on element list items in horizontal slides', function( assert ) {
		assert.strictEqual( document.querySelectorAll( '.reveal .slides section li.fragment.highlight-green' ).length, 5, 'found a horizontal slide with five list items with class fragment.roll-in' );
	});

	QUnit.test( 'Attributes on element image in horizontal slides', function( assert ) {
		assert.strictEqual( document.querySelectorAll( '.reveal .slides section img.reveal.stretch' ).length, 1, 'found a horizontal slide with stretched image, class img.reveal.stretch' );
	});

	QUnit.test( 'Attributes on elements in vertical slides with default element attribute separator', function( assert ) {
		assert.strictEqual( document.querySelectorAll( '.reveal .slides section h2.fragment.highlight-red' ).length, 2, 'found two h2 titles with fragment highlight-red in vertical slides with default element attribute separator' );
	});

	QUnit.test( 'Attributes on elements in single slides with default element attribute separator', function( assert ) {
		assert.strictEqual( document.querySelectorAll( '.reveal .slides section p.fragment.highlight-blue' ).length, 3, 'found three elements with fragment highlight-blue in single slide with default element attribute separator' );
	});

} );

Reveal.initialize();

{'repo_name': 'boost-ext/sml', 'stars': '426', 'repo_language': 'C++', 'file_name': 'reveal.js', 'mime_type': 'text/plain', 'hash': 3056163527385855207, 'source_dataset': 'data'}


/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
 * Any copyright is dedicated to the Public Domain.
 * http://creativecommons.org/licenses/publicdomain/
 * Contributor: Blake Kaplan
 */

//-----------------------------------------------------------------------------
var BUGNUMBER = 306794;
var summary = 'Do not assert: parsing foo getter';
var actual = 'No Assertion';
var expect = 'No Assertion';

printBugNumber(BUGNUMBER);
printStatus (summary);

try
{
  eval('getter\n');
}
catch(e)
{
}

reportCompare(expect, actual, summary);

{'repo_name': 'SequoiaDB/SequoiaDB', 'stars': '157', 'repo_language': 'C++', 'file_name': 'rcgen.cpp', 'mime_type': 'text/x-c++', 'hash': 3879136014278103854, 'source_dataset': 'data'}


debug = require('debug')('fsmonitor')
fs    = require 'fs'
Path  = require 'path'

{ EventEmitter } = require 'events'

{ PlaPath } = require './pathutil'

prependUniques = (dest, source) ->
  for item in source
    if dest.indexOf(item) < 0
      dest.unshift item
  dest

appendUniques = (dest, source) ->
  for item in source
    if dest.indexOf(item) < 0
      dest.push item
  dest

class FSFile
  constructor: (@relpath, @stats) ->

  equals: (peer) ->
    if this.stats.isFile
      (this.stats.size == peer.stats.size) and (this.stats.mode == peer.stats.mode) and (+this.stats.mtime == +peer.stats.mtime) and (this.stats.dev == peer.stats.dev) and (this.stats.ino == peer.stats.ino)
    else
      (this.stats.mode == peer.stats.mode)

  toString: ->
    "FSFile(#{@relpath})"

class FSChange
  constructor: ->
    @addedFiles    = []
    @modifiedFiles = []
    @removedFiles  = []

    @addedFolders    = []
    @modifiedFolders = []
    @removedFolders  = []

  isEmpty: ->
    (@addedFiles.length + @modifiedFiles.length + @removedFiles.length + @addedFolders.length + @modifiedFolders.length + @removedFolders.length) == 0

  prepend: (peer) ->
    prependUniques @addedFiles,    peer.addedFiles
    prependUniques @modifiedFiles, peer.modifiedFiles
    prependUniques @removedFiles,  peer.removedFiles

    prependUniques @addedFolders,    peer.addedFolders
    prependUniques @modifiedFolders, peer.modifiedFolders
    prependUniques @removedFolders,  peer.removedFolders

  append: (peer) ->
    appendUniques @addedFiles,    peer.addedFiles
    appendUniques @modifiedFiles, peer.modifiedFiles
    appendUniques @removedFiles,  peer.removedFiles

    appendUniques @addedFolders,    peer.addedFolders
    appendUniques @modifiedFolders, peer.modifiedFolders
    appendUniques @removedFolders,  peer.removedFolders

  toString: ->
    [
      @_listToString '+', @addedFiles,    ''
      @_listToString '!', @modifiedFiles, ''
      @_listToString '-', @removedFiles,  ''
      @_listToString '+', @addedFolders,    '/'
      @_listToString '!', @modifiedFolders, '/'
      @_listToString '-', @removedFolders,  '/'
    ].join('')

  _listToString: (prefix, list, suffix) ->
    result = []
    for relpath in list.slice(0).sort()
      result.push "#{prefix}#{relpath}#{suffix}\n"
    return result.join('')

module.exports =
class FSTree extends EventEmitter

  constructor: (@root, @filter) ->
    if @filter and not ((typeof @filter.matches is 'function') and (typeof @filter.excludes is 'function'))
      throw new Error "Invalid filter provided to FSTree; must define .matches() and .excludes()"
    @filter or= { matches: (-> yes), excludes: (-> no) }

    @_files   = []
    @_folders = []
    @_errors  = []
    await @_walk @root, '', defer()

    @_updateRequested  = no
    @_updateInProgress = no

    debug "Finished building FSTree with #{@_files.length} files and #{@_folders.length} folders at #{@root}"
    @emit 'complete'

  update: (folder, item, recursive) ->
    @_updateRequested = yes
    unless @_updateInProgress
      @_performQueuedUpdate()
    return

  _performQueuedUpdate: ->
    @_updateInProgress = yes
    @_updateRequested  = no
    debug "Updating FSTree at #{@root}"
    debug "Filter = #{@filter}"

    oldFiles = {}
    for file in @_files
      oldFiles[file.relpath] = file

    oldFolders = {}
    for folder in @_folders
      oldFolders[folder.relpath] = folder

    @_files   = []
    @_folders = []
    @_errors  = []
    await @_walk @root, '', defer()

    change = new FSChange()

    # addedFiles, modifiedFiles
    for file in @_files
      relpath = file.relpath
      if oldFiles.hasOwnProperty(relpath)
        old = oldFiles[relpath]
        delete oldFiles[relpath]
        change.modifiedFiles.push(relpath) unless file.equals(old)
        unless file.equals(old)
          debug "Change in file #{relpath}:"
          debug "  .. size #{file.stats.size} != #{old.stats.size}" unless file.stats.size == old.stats.size
          debug "  .. mode #{file.stats.mode} != #{old.stats.mode}" unless file.stats.mode == old.stats.mode
          debug "  .. mtime #{+file.stats.mtime} != #{+old.stats.mtime}" unless +file.stats.mtime == +old.stats.mtime
          debug "  .. dev #{file.stats.dev} != #{old.stats.dev}" unless file.stats.dev == old.stats.dev
          debug "  .. ino #{file.stats.ino} != #{old.stats.ino}" unless file.stats.ino == old.stats.ino
      else
        change.addedFiles.push(relpath)
    # removedFiles
    for own key, file of oldFiles
      change.removedFiles.push file.relpath

    # addedFolders, modifiedFolders
    for folder in @_folders
      relpath = folder.relpath
      if oldFolders.hasOwnProperty(relpath)
        old = oldFolders[relpath]
        delete oldFolders[relpath]
        change.modifiedFolders.push(relpath) unless folder.equals(old)
        unless folder.equals(old)
          debug "Change in folder #{relpath}/:"
          debug "  .. mode #{folder.stats.mode} != #{old.stats.mode}" unless folder.stats.mode == old.stats.mode
      else
        change.addedFolders.push(relpath)
    # removedFolders
    for own key, folder of oldFolders
      change.removedFolders.push folder.relpath

    @emit 'change', change  unless change.isEmpty()

    @_updateInProgress = no
    if @_updateRequested
      @_performQueuedUpdate()

  Object.defineProperty @::, 'allFiles', get: ->
    (file.relpath for file in @_files).sort()

  Object.defineProperty @::, 'allFolders', get: ->
    (file.relpath for file in @_folders).sort()

  findMatchingPaths: (list) ->
    (file.relpath for file in @_files when list.matches(file.relpath)).sort()

  findFilesBySuffix: (suffix, { bestSubtree }, callback) ->
    suffix = PlaPath.normalize(suffix)

    name = Path.basename(suffix)

    bestScore = 0

    allMatches =
      for file in @_files
        path = file.relpath
        # debug "findFilesMatchingSuffixInSubtree considering: path = %j", path

        continue unless Path.basename(path) is name
        score = PlaPath.numberOfMatchingTrailingComponents(path, suffix)
        score += 0.5 if bestSubtree && PlaPath.isSubpath(path, bestSubtree)

        bestScore = score if score > bestScore

        debug "findFilesMatchingSuffixInSubtree match: path = %j, score = %j", path, score

        { path, score }

    bestMatches = (match for match in allMatches when match.score is bestScore)

    bestMatch = if bestMatches.length is 1 then bestMatches[0] else null

    process.nextTick ->
      callback null, { allMatches, bestMatches, bestMatch }

  _addError: (path, err) ->
    @_errors.push { path, err }

  _addFile: (relpath, stats) ->
    stats = { size: stats.size, mode: stats.mode, mtime: stats.mtime, dev: stats.dev, ino: stats.ino, isFile: stats.isFile() }
    @_files.push new FSFile(relpath, stats)

  _addFolder: (relpath, stats) ->
    @_folders.push new FSFile(relpath, stats)

  _walk: (path, relpath, autocb) ->
    await fs.lstat path, defer(err, stats)
    return @_addError(path, err) if err

    if stats.isFile()
      if @filter.matches(relpath, no)
        @_addFile relpath, stats
    else if stats.isDirectory()
      return if @filter.excludes(relpath, yes)
      @_addFolder relpath, stats

      await fs.readdir path, defer(err, files)
      return @_addError(path, err) if err

      for file in files
        await @_walk Path.join(path, file), Path.join(relpath, file), defer()

{'repo_name': 'livereload/LiveReload', 'stars': '1439', 'repo_language': 'Objective-C', 'file_name': 'Tag.swift', 'mime_type': 'text/plain', 'hash': -647024106931816008, 'source_dataset': 'data'}


//
// SystemConfiguration.cpp
//
// Library: Util
// Package: Configuration
// Module:  SystemConfiguration
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier:	BSL-1.0
//

#include "Poco/Util/SystemConfiguration.h"
#include "Poco/Environment.h"
#include "Poco/Path.h"
#include "Poco/DateTime.h"
#include "Poco/DateTimeFormatter.h"
#include "Poco/DateTimeFormat.h"
#include "Poco/NumberFormatter.h"
#if !defined(POCO_VXWORKS)
#include "Poco/Process.h"
#endif
#include "Poco/Exception.h"
#include <cstdio>

using Poco::Environment;
using Poco::Path;

namespace Poco {
namespace Util {

const std::string SystemConfiguration::OSNAME         = "system.osName";
const std::string SystemConfiguration::OSVERSION      = "system.osVersion";
const std::string SystemConfiguration::OSARCHITECTURE = "system.osArchitecture";
const std::string SystemConfiguration::NODENAME       = "system.nodeName";
const std::string SystemConfiguration::NODEID         = "system.nodeId";
const std::string SystemConfiguration::CURRENTDIR     = "system.currentDir";
const std::string SystemConfiguration::HOMEDIR        = "system.homeDir";
const std::string SystemConfiguration::CONFIGHOMEDIR  = "system.configHomeDir";
const std::string SystemConfiguration::CACHEHOMEDIR   = "system.cacheHomeDir";
const std::string SystemConfiguration::DATAHOMEDIR    = "system.dataHomeDir";
const std::string SystemConfiguration::TEMPHOMEDIR    = "system.tempHomeDir";
const std::string SystemConfiguration::TEMPDIR        = "system.tempDir";
const std::string SystemConfiguration::CONFIGDIR      = "system.configDir";
const std::string SystemConfiguration::DATETIME       = "system.dateTime";
#if !defined(POCO_VXWORKS)
const std::string SystemConfiguration::PID            = "system.pid";
#endif
const std::string SystemConfiguration::ENV            = "system.env.";

SystemConfiguration::SystemConfiguration()
{
}

SystemConfiguration::~SystemConfiguration()
{
}

bool SystemConfiguration::getRaw(const std::string& key, std::string& value) const
{
	if (key == OSNAME)
	{
		value = Environment::osName();
	}
	else if (key == OSVERSION)
	{
		value = Environment::osVersion();
	}
	else if (key == OSARCHITECTURE)
	{
		value = Environment::osArchitecture();
	}
	else if (key == NODENAME)
	{
		value = Environment::nodeName();
	}
	else if (key == NODEID)
	{
		try
		{
			Poco::Environment::NodeId id;
			Poco::Environment::nodeId(id);
			char result[13];
			std::sprintf(result, "%02x%02x%02x%02x%02x%02x",
				id[0],
				id[1],
				id[2],
				id[3],
				id[4],
				id[5]);
			value = result;
		}
		catch (...)
		{
			value = "000000000000";
		}
	}
	else if (key == CURRENTDIR)
	{
		value = Path::current();
	}
	else if (key == HOMEDIR)
	{
		value = Path::home();
	}
	else if (key == CONFIGHOMEDIR)
	{
		value = Path::configHome();
	}
	else if (key == CACHEHOMEDIR)
	{
		value = Path::cacheHome();
	}
	else if (key == DATAHOMEDIR)
	{
		value = Path::dataHome();
	}

	else if (key == TEMPHOMEDIR)
	{
		value = Path::tempHome();
	}
	else if (key == TEMPDIR)
	{
		value = Path::temp();
	}
	else if (key == CONFIGDIR)
	{
		value = Path::config();
	}
	else if (key == DATETIME)
	{
		value = Poco::DateTimeFormatter::format(Poco::DateTime(), Poco::DateTimeFormat::ISO8601_FORMAT);
	}
#if !defined(POCO_VXWORKS)
	else if (key == PID)
	{
		value = "0";
		value = Poco::NumberFormatter::format(Poco::Process::id());
	}
#endif
	else if (key.compare(0, ENV.size(), ENV) == 0)
	{
		return getEnv(key.substr(ENV.size()), value);
	}
	else return false;
	return true;
}

void SystemConfiguration::setRaw(const std::string& key, const std::string& value)
{
	throw Poco::InvalidAccessException("Attempt to modify a system property", key);
}

void SystemConfiguration::enumerate(const std::string& key, Keys& range) const
{
	if (key.empty())
	{
		range.push_back("system");
	}
	else if (key == "system")
	{
		range.push_back("osName");
		range.push_back("osVersion");
		range.push_back("osArchitecture");
		range.push_back("nodeName");
		range.push_back("nodeId");
		range.push_back("currentDir");
		range.push_back("homeDir");
		range.push_back("configHomeDir");
		range.push_back("cacheHomeDir");
		range.push_back("dataHomeDir");
		range.push_back("tempHomeDir");
		range.push_back("tempDir");
		range.push_back("configDir");
		range.push_back("dateTime");
#if !defined(POCO_VXWORKS)
		range.push_back("pid");
#endif
		range.push_back("env");
	}
}

void SystemConfiguration::removeRaw(const std::string& key)
{
	throw Poco::NotImplementedException("Removing a key in a SystemConfiguration");
}

bool SystemConfiguration::getEnv(const std::string& name, std::string& value)
{
	if (Environment::has(name))
	{
		value = Environment::get(name);
		return true;
	}
	return false;
}

} } // namespace Poco::Util

{'repo_name': 'toggl-open-source/toggldesktop', 'stars': '1359', 'repo_language': 'C++', 'file_name': 'InfoPlist.strings', 'mime_type': 'text/plain', 'hash': -714327154419455198, 'source_dataset': 'data'}


/*
 * Created by Angel Leon (@gubatron), Alden Torres (aldenml)
 * Copyright (c) 2011-2014, FrostWire(R). All rights reserved.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.limegroup.gnutella.gui;

import com.frostwire.gui.theme.SkinMultilineToolTipUI;

import javax.swing.*;

/**
 * @author gubatron
 * @author aldenml
 */
public final class MultilineToolTip extends JToolTip {
    public MultilineToolTip() {
    }

    public void setTipArray(String[] arr) {
        super.setTipText(join(arr));
    }

    @Override
    public void setTipText(String tipText) {
        // avoid not allowed change
    }

    @Override
    public void updateUI() {
        setUI(new SkinMultilineToolTipUI());
    }

    private String join(String[] arr) {
        StringBuilder sb = new StringBuilder();
        int size = arr.length;
        if (size - 1 > -1) {
            for (int i = 0; i < size - 1; i++) {
                sb.append(arr[i]);
                sb.append(System.lineSeparator());
            }
            sb.append(arr[size - 1]);
        }
        return sb.toString();
    }
}

{'repo_name': 'frostwire/frostwire', 'stars': '234', 'repo_language': 'Java', 'file_name': 'SystemUtilities.hpp', 'mime_type': 'text/x-c', 'hash': 255505026718271339, 'source_dataset': 'data'}


// This file generated by `generator/`. DO NOT EDIT

package models

import (
	"fmt"
	"log"
	"regexp"

	hcl "github.com/hashicorp/hcl/v2"
	"github.com/terraform-linters/tflint/tflint"
)

// AwsCognitoIdentityProviderInvalidProviderNameRule checks the pattern is valid
type AwsCognitoIdentityProviderInvalidProviderNameRule struct {
	resourceType  string
	attributeName string
	max           int
	min           int
	pattern       *regexp.Regexp
}

// NewAwsCognitoIdentityProviderInvalidProviderNameRule returns new rule with default attributes
func NewAwsCognitoIdentityProviderInvalidProviderNameRule() *AwsCognitoIdentityProviderInvalidProviderNameRule {
	return &AwsCognitoIdentityProviderInvalidProviderNameRule{
		resourceType:  "aws_cognito_identity_provider",
		attributeName: "provider_name",
		max:           32,
		min:           1,
		pattern:       regexp.MustCompile(`^[\p{L}\p{M}\p{S}\p{N}\p{P}]+$`),
	}
}

// Name returns the rule name
func (r *AwsCognitoIdentityProviderInvalidProviderNameRule) Name() string {
	return "aws_cognito_identity_provider_invalid_provider_name"
}

// Enabled returns whether the rule is enabled by default
func (r *AwsCognitoIdentityProviderInvalidProviderNameRule) Enabled() bool {
	return true
}

// Severity returns the rule severity
func (r *AwsCognitoIdentityProviderInvalidProviderNameRule) Severity() string {
	return tflint.ERROR
}

// Link returns the rule reference link
func (r *AwsCognitoIdentityProviderInvalidProviderNameRule) Link() string {
	return ""
}

// Check checks the pattern is valid
func (r *AwsCognitoIdentityProviderInvalidProviderNameRule) Check(runner *tflint.Runner) error {
	log.Printf("[TRACE] Check `%s` rule for `%s` runner", r.Name(), runner.TFConfigPath())

	return runner.WalkResourceAttributes(r.resourceType, r.attributeName, func(attribute *hcl.Attribute) error {
		var val string
		err := runner.EvaluateExpr(attribute.Expr, &val)

		return runner.EnsureNoError(err, func() error {
			if len(val) > r.max {
				runner.EmitIssue(
					r,
					"provider_name must be 32 characters or less",
					attribute.Expr.Range(),
				)
			}
			if len(val) < r.min {
				runner.EmitIssue(
					r,
					"provider_name must be 1 characters or higher",
					attribute.Expr.Range(),
				)
			}
			if !r.pattern.MatchString(val) {
				runner.EmitIssue(
					r,
					fmt.Sprintf(`"%s" does not match valid pattern %s`, truncateLongMessage(val), `^[\p{L}\p{M}\p{S}\p{N}\p{P}]+$`),
					attribute.Expr.Range(),
				)
			}
			return nil
		})
	})
}

{'repo_name': 'terraform-linters/tflint', 'stars': '1699', 'repo_language': 'Go', 'file_name': 'test.tf', 'mime_type': 'text/plain', 'hash': 36567568857572415, 'source_dataset': 'data'}


# ルートオブジェクト

**ルートオブジェクト**は現在のアクティブなルートの状態を表現しています。現在の URL をパースした情報と、その URL とマッチした**ルートレコード**を保持しています。

ルートオブジェクトは変更不可です。成功した全てのナビゲーションは結果的に新たなルートオブジェクトになります。

ルートオブジェクトは複数の場所に存在します。

- コンポーネント内での `this.$route`、また、 `$route` watcher コールバック内部

- `router.match(location)` を呼び出した時の返り値

- ナビゲーションガード内での 1 つ目の引数

  ``` js
  router.beforeEach((route, redirect, next) => {
    // ここの route はルートオブジェクト
  })
  ```

- `scrollBehavior` function 内の引数

  ``` js
  const router = new VueRouter({
    scrollBehavior (to, from, savedPosition) {
      // to と from は両方ともルートオブジェクト
    }
  })
  ```

### ルートオブジェクトプロパティ

- **$route.path**

  - 型: `string`

    現在のルートのパスに等しい文字列。常に絶対パスとして解釈されます。e.g. `"/foo/bar"`

- **$route.params**

  - 型: `Object`

    動的セグメントとスターセグメントの key/value ペアを保持するオブジェクト。もしパラメーターがない場合、この値は空オブジェクトになります。

- **$route.query**

  - 型: `Object`

    クエリ文字列の key/value ペアを保持するオブジェクト。例えば `/foo?user=1` というパスの場合、`$route.query.user == 1` となります。もしクエリがない場合は、この値は空オブジェクトになります。

- **$route.hash**

  - 型: `string`

    hash がある時の現在のルートの hash (# 無し) です。もし hash がない場合、この値は空オブジェクトになります。

- **$route.fullPath**

  - 型: `string`

    クエリや hash を含む完全に解決された URL です。

- **$route.matched**

  - 型: `Array<RouteRecord>`

  現在のルートのネストされた全パスセグメントに対しての**ルートレコード** を保持している配列です。ルートレコードは `routes` 設定の配列 (と `children` 配列) 内のオブジェクトのコピーです。

  ``` js
  const router = new VueRouter({
    routes: [
      // 以下のオブジェクトがルートレコード
      { path: '/foo', component: Foo,
        children: [
          // こちらもルートレコード
          { path: 'bar', component: Bar }
        ]
      }
    ]
  })
  ```

  URL が `/foo/bar` である時、 `$route.matched` は親から子の順番で両方の (クローンされた) オブジェクトを含む配列になります。

- **$route.name**

  名前がある場合の現在のルートの名前です。(詳しくは [名前付きルート](../essentials/named-routes.md) をご参照ください)

{'repo_name': 'yisainan/vue', 'stars': '117', 'repo_language': 'JavaScript', 'file_name': 'dev-server.js', 'mime_type': 'text/plain', 'hash': 6784206248485922736, 'source_dataset': 'data'}


import { Microfe, Bootstrap, Route, ConfigInterface } from './lib';

@Microfe({
    deps: ['LayoutApp'],
})
class Main {
    constructor() {
        console.log('Initialised');
    }
}

const Routes: Route[] = [
    { path: '/', redirectTo: '/angular' },
    { path: '/angular', microApp: 'demoAngular', tagName: 'demo-angular' },
    { path: '/react', microApp: 'reactDemo', tagName: 'react-demo' },
    { path: '/static', microApp: 'staticApp', tagName: 'static-app' },
    { path: '*', microApp: 'NotFoundApp', tagName: 'not-found-app' },
];

const Config: ConfigInterface = {
    registryApi: 'http://localhost:3000/registry',
    registryPublic: 'http://localhost:3000',
};

Bootstrap(Routes, Config)(Main);

{'repo_name': 'onerzafer/microfe-client', 'stars': '127', 'repo_language': 'TypeScript', 'file_name': 'Microfe.decorator.ts', 'mime_type': 'text/x-java', 'hash': 5575626930638460510, 'source_dataset': 'data'}


---
versionFrom: 8.0.0
---

# Umbraco Form

The Umbraco Form widget, gives you the ability to add a custom form to your site. It is important to note that a custom form needs to have been made using Umbraco Forms before this widget can be used.

You can create a form by selecting the Forms section in the top menu in your backoffice. Learn more about how to create forms in the [Umbraco Forms](../../../Add-ons/UmbracoForms/Editor/Creating-a-Form) section.

## Sample

![Umbraco Form Frontend](images/Umbraco-forms-front.png)

## Configuration options

You will have multiple options to customize your form, and choose which form should be displayed on your page.

![Umbraco Form Backffce](images/Umbraco-forms-final.png)

### Content

- Pre Heading
- Heading
- Text
- Background Image
- Form (this is where you add the form that you have already created)

### Settings

- Background Color
- Text Color
- Container Width

{'repo_name': 'umbraco/UmbracoDocs', 'stars': '201', 'repo_language': 'None', 'file_name': 'index.md', 'mime_type': 'text/plain', 'hash': -3610698584180220565, 'source_dataset': 'data'}