text:
namespace {

const wchar_t kChromeRegClientsKey[] =
    L"Software\\Google\\Update\\Clients\\"
    L"{8A69D345-D564-463c-AFF1-A69D9E530F96}";
const wchar_t kChromeRegClientStateKey[] =
    L"Software\\Google\\Update\\ClientState\\"
    L"{8A69D345-D564-463c-AFF1-A69D9E530F96}";
const wchar_t kChromeRegLaunchCmd[] = L"InstallerSuccessLaunchCmdLine";
const wchar_t kChromeRegLastLaunchCmd[] = L"LastInstallerSuccessLaunchCmdLine";
const wchar_t kChromeRegVersion[] = L"pv";
const wchar_t kNoChromeOfferUntil[] =
    L"SOFTWARE\\Google\\No Chrome Offer Until";

// Return the company name specified in the file version info resource.
bool GetCompanyName(const wchar_t* filename, wchar_t* buffer, DWORD out_len) {
  wchar_t file_version_info[8192];
  DWORD handle = 0;
  DWORD buffer_size = 0;

  buffer_size = ::GetFileVersionInfoSize(filename, &handle);
  // Cannot stats the file or our buffer size is too small (very unlikely).
  if (buffer_size == 0 || buffer_size > _countof(file_version_info))
    return false;

  buffer_size = _countof(file_version_info);
  memset(file_version_info, 0, buffer_size);
  if (!::GetFileVersionInfo(filename, handle, buffer_size, file_version_info))
    return false;

  DWORD data_len = 0;
  LPVOID data = NULL;
  // Retrieve the language and codepage code if exists.
  buffer_size = 0;
  if (!::VerQueryValue(file_version_info, TEXT("\\VarFileInfo\\Translation"),
      reinterpret_cast<LPVOID *>(&data), reinterpret_cast<UINT *>(&data_len)))
    return false;
  if (data_len != 4)
    return false;

  wchar_t info_name[256];
  DWORD lang = 0;
  // Formulate the string to retrieve the company name of the specific
  // language codepage.
  memcpy(&lang, data, 4);
  ::StringCchPrintf(info_name, _countof(info_name),
      L"\\StringFileInfo\\%02X%02X%02X%02X\\CompanyName",
      (lang & 0xff00)>>8, (lang & 0xff), (lang & 0xff000000)>>24,
      (lang & 0xff0000)>>16);

  data_len = 0;
  if (!::VerQueryValue(file_version_info, info_name,
      reinterpret_cast<LPVOID *>(&data), reinterpret_cast<UINT *>(&data_len)))
    return false;
  if (data_len <= 0 || data_len >= out_len)
    return false;

  memset(buffer, 0, out_len);
  ::StringCchCopyN(buffer, out_len, (const wchar_t*)data, data_len);
  return true;
}

// Return true if we can re-offer Chrome; false, otherwise.
// Each partner can only offer Chrome once every six months.
bool CanReOfferChrome(BOOL set_flag) {
  wchar_t filename[MAX_PATH+1];
  wchar_t company[MAX_PATH];

  // If we cannot retrieve the version info of the executable or company
  // name, we allow the Chrome to be offered because there is no past
  // history to be found.
  if (::GetModuleFileName(NULL, filename, MAX_PATH) == 0)
    return true;
  if (!GetCompanyName(filename, company, sizeof(company)))
    return true;

  bool can_re_offer = true;
  DWORD disposition = 0;
  HKEY key = NULL;
  if (::RegCreateKeyEx(HKEY_LOCAL_MACHINE, kNoChromeOfferUntil,
      0, NULL, REG_OPTION_NON_VOLATILE, KEY_READ | KEY_WRITE,
      NULL, &key, &disposition) == ERROR_SUCCESS) {
    // Get today's date, and format it as YYYYMMDD numeric value.
    SYSTEMTIME now;
    GetLocalTime(&now);
    DWORD today = now.wYear * 10000 + now.wMonth * 100 + now.wDay;

    // Cannot re-offer, if the timer already exists and is not expired yet.
    DWORD value_type = REG_DWORD;
    DWORD value_data = 0;
    DWORD value_length = sizeof(DWORD);
    if (::RegQueryValueEx(key, company, 0, &value_type,
                          reinterpret_cast<LPBYTE>(&value_data),
                          &value_length) == ERROR_SUCCESS &&
        REG_DWORD == value_type &&
        value_data > today) {
      // The time has not expired, we cannot offer Chrome.
      can_re_offer = false;
    } else {
      // Delete the old or invalid value.
      ::RegDeleteValue(key, company);
      if (set_flag) {
        // Set expiration date for offer as six months from today,
        // represented as a YYYYMMDD numeric value.
        SYSTEMTIME timer = now;
        timer.wMonth = timer.wMonth + 6;
        if (timer.wMonth > 12) {
          timer.wMonth = timer.wMonth - 12;
          timer.wYear = timer.wYear + 1;
        }
        DWORD value = timer.wYear * 10000 + timer.wMonth * 100 + timer.wDay;
        ::RegSetValueEx(key, company, 0, REG_DWORD, (LPBYTE)&value,
                        sizeof(DWORD));
      }
    }

    ::RegCloseKey(key);
  }

  return can_re_offer;
}

// Helper function to read a value from registry. Returns true if value
// is read successfully and stored in parameter value. Returns false otherwise.
bool ReadValueFromRegistry(HKEY root_key, const wchar_t *sub_key,
                           const wchar_t *value_name, wchar_t *value,
                           size_t *size) {
  HKEY key;
  if ((::RegOpenKeyEx(root_key, sub_key, NULL,
                      KEY_READ, &key) == ERROR_SUCCESS) &&
      (::RegQueryValueEx(key, value_name, NULL, NULL,
                         reinterpret_cast<LPBYTE>(value),
                         reinterpret_cast<LPDWORD>(size)) == ERROR_SUCCESS)) {
    ::RegCloseKey(key);
    return true;
  }
  return false;
}

bool IsChromeInstalled(HKEY root_key) {
  wchar_t version[64];
  size_t size = _countof(version);
  return ReadValueFromRegistry(root_key, kChromeRegClientsKey,
                               kChromeRegVersion, version, &size);
}

enum WindowsVersion {
  VERSION_BELOW_XP_SP2,
  VERSION_XP_SP2_UP_TO_VISTA, // "but not including"
  VERSION_VISTA_OR_HIGHER,
};
WindowsVersion GetWindowsVersion() {
  OSVERSIONINFOEX version_info = { sizeof version_info };
  GetVersionEx(reinterpret_cast<OSVERSIONINFO*>(&version_info));

  // Windows Vista is version 6.0.
  if (version_info.dwMajorVersion >= 6)
    return VERSION_VISTA_OR_HIGHER;

  // Windows XP is version 5.1.  (5.2 is Windows Server 2003/XP Pro x64.)
  if ((version_info.dwMajorVersion < 5) || (version_info.dwMinorVersion < 1))
    return VERSION_BELOW_XP_SP2;

  // For XP itself, we only support SP2 and above.
  return ((version_info.dwMinorVersion > 1) ||
          (version_info.wServicePackMajor >= 2)) ?
      VERSION_XP_SP2_UP_TO_VISTA : VERSION_BELOW_XP_SP2;
}

// Note this function should not be called on old Windows versions where these
// Windows API are not available. We always invoke this function after checking
// that current OS is Vista or later.
bool VerifyAdminGroup() {
  SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY;
  PSID Group;
  BOOL check = ::AllocateAndInitializeSid(&NtAuthority, 2,
                                          SECURITY_BUILTIN_DOMAIN_RID,
                                          DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0,
                                          0, 0, 0,
                                          &Group);
  if (check) {
    if (!::CheckTokenMembership(NULL, Group, &check))
      check = FALSE;
  }
  ::FreeSid(Group);
  return (check == TRUE);
}

bool VerifyHKLMAccess(const wchar_t* sub_key) {
  HKEY root = HKEY_LOCAL_MACHINE;
  wchar_t str[] = L"test";
  bool result = false;
  DWORD disposition = 0;
  HKEY key = NULL;

  if (::RegCreateKeyEx(root, sub_key, 0, NULL,
                       REG_OPTION_NON_VOLATILE, KEY_READ | KEY_WRITE, NULL,
                       &key, &disposition) == ERROR_SUCCESS) {
    if (::RegSetValueEx(key, str, 0, REG_SZ, (LPBYTE)str,
        (DWORD)lstrlen(str)) == ERROR_SUCCESS) {
      result = true;
      RegDeleteValue(key, str);
    }

    //  If we create the main key, delete the entire key.
    if (disposition == REG_CREATED_NEW_KEY)
      RegDeleteKey(key, NULL);

    RegCloseKey(key);
  }

  return result;
}

bool IsRunningElevated() {
  // This method should be called only for Vista or later.
  if ((GetWindowsVersion() < VERSION_VISTA_OR_HIGHER) ||
      !VerifyAdminGroup())
    return false;

  HANDLE process_token;
  if (!::OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &process_token))
    return false;

  TOKEN_ELEVATION_TYPE elevation_type = TokenElevationTypeDefault;
  DWORD size_returned = 0;
  if (!::GetTokenInformation(process_token, TokenElevationType,
                             &elevation_type, sizeof(elevation_type),
                             &size_returned)) {
    ::CloseHandle(process_token);
    return false;
  }

  ::CloseHandle(process_token);
  return (elevation_type == TokenElevationTypeFull);
}

bool GetUserIdForProcess(size_t pid, wchar_t** user_sid) {
  HANDLE process_handle = ::OpenProcess(PROCESS_QUERY_INFORMATION, TRUE, pid);
  if (process_handle == NULL)
    return false;

  HANDLE process_token;
  bool result = false;
  if (::OpenProcessToken(process_handle, TOKEN_QUERY, &process_token)) {
    DWORD size = 0;
    ::GetTokenInformation(process_token, TokenUser, NULL, 0, &size);
    if (::GetLastError() == ERROR_INSUFFICIENT_BUFFER ||
        ::GetLastError() == ERROR_SUCCESS) {
      DWORD actual_size = 0;
      BYTE* token_user = new BYTE[size];
      if ((::GetTokenInformation(process_token, TokenUser, token_user, size,
                                &actual_size)) &&
          (actual_size <= size)) {
        PSID sid = reinterpret_cast<TOKEN_USER*>(token_user)->User.Sid;
        if (::ConvertSidToStringSid(sid, user_sid))
          result = true;
      }
      delete[] token_user;
    }
    ::CloseHandle(process_token);
  }
  ::CloseHandle(process_handle);
  return result;
}
}  // namespace

#pragma comment(linker, "/EXPORT:GoogleChromeCompatibilityCheck=_GoogleChromeCompatibilityCheck@8,PRIVATE")
DLLEXPORT BOOL __stdcall GoogleChromeCompatibilityCheck(BOOL set_flag,
                                                        DWORD *reasons) {
  DWORD local_reasons = 0;

  WindowsVersion windows_version = GetWindowsVersion();
  // System requirements?
  if (windows_version == VERSION_BELOW_XP_SP2)
    local_reasons |= GCCC_ERROR_OSNOTSUPPORTED;

  if (IsChromeInstalled(HKEY_LOCAL_MACHINE))
    local_reasons |= GCCC_ERROR_SYSTEMLEVELALREADYPRESENT;

  if (IsChromeInstalled(HKEY_CURRENT_USER))
    local_reasons |= GCCC_ERROR_USERLEVELALREADYPRESENT;

  if (!VerifyHKLMAccess(kChromeRegClientsKey)) {
    local_reasons |= GCCC_ERROR_ACCESSDENIED;
  } else if ((windows_version == VERSION_VISTA_OR_HIGHER) &&
             !VerifyAdminGroup()) {
    // For Vista or later check for elevation since even for admin user we could
    // be running in non-elevated mode. We require integrity level High.
    local_reasons |= GCCC_ERROR_INTEGRITYLEVEL;
  }

  // Then only check whether we can re-offer, if everything else is OK.
  if (local_reasons == 0 && !CanReOfferChrome(set_flag))
    local_reasons |= GCCC_ERROR_ALREADYOFFERED;

  // Done. Copy/return results.
  if (reasons != NULL)
    *reasons = local_reasons;

  return (local_reasons == 0);
}

#pragma comment(linker, "/EXPORT:LaunchGoogleChrome=_LaunchGoogleChrome@0,PRIVATE")
DLLEXPORT BOOL __stdcall LaunchGoogleChrome() {
  wchar_t launch_cmd[MAX_PATH];
  size_t size = _countof(launch_cmd);
  if (!ReadValueFromRegistry(HKEY_LOCAL_MACHINE, kChromeRegClientStateKey,
                             kChromeRegLastLaunchCmd, launch_cmd, &size)) {
    size = _countof(launch_cmd);
    if (!ReadValueFromRegistry(HKEY_LOCAL_MACHINE, kChromeRegClientStateKey,
                               kChromeRegLaunchCmd, launch_cmd, &size)) {
      return false;
    }
  }

  HRESULT hr = ::CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
  if (hr != S_OK) {
    if (hr == S_FALSE)
      ::CoUninitialize();
    return false;
  }

  if (::CoInitializeSecurity(NULL, -1, NULL, NULL,
                             RPC_C_AUTHN_LEVEL_PKT_PRIVACY,
                             RPC_C_IMP_LEVEL_IDENTIFY, NULL,
                             EOAC_DYNAMIC_CLOAKING, NULL) != S_OK) {
    ::CoUninitialize();
    return false;
  }

  bool impersonation_success = false;
  if (IsRunningElevated()) {
    wchar_t* curr_proc_sid;
    if (!GetUserIdForProcess(GetCurrentProcessId(), &curr_proc_sid)) {
      ::CoUninitialize();
      return false;
    }

    DWORD pid = 0;
    ::GetWindowThreadProcessId(::GetShellWindow(), &pid);
    if (pid <= 0) {
      ::LocalFree(curr_proc_sid);
      ::CoUninitialize();
      return false;
    }

    wchar_t* exp_proc_sid;
    if (GetUserIdForProcess(pid, &exp_proc_sid)) {
      if (_wcsicmp(curr_proc_sid, exp_proc_sid) == 0) {
        HANDLE process_handle = ::OpenProcess(
            PROCESS_DUP_HANDLE | PROCESS_QUERY_INFORMATION, TRUE, pid);
        if (process_handle != NULL) {
          HANDLE process_token = NULL;
          HANDLE user_token = NULL;
          if (::OpenProcessToken(process_handle, TOKEN_DUPLICATE | TOKEN_QUERY,
                                 &process_token) &&
              ::DuplicateTokenEx(process_token,
                                 TOKEN_IMPERSONATE | TOKEN_QUERY |
                                     TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE,
                                 NULL, SecurityImpersonation,
                                 TokenPrimary, &user_token) &&
              (::ImpersonateLoggedOnUser(user_token) != 0)) {
            impersonation_success = true;
          }
          if (user_token)
            ::CloseHandle(user_token);
          if (process_token)
            ::CloseHandle(process_token);
          ::CloseHandle(process_handle);
        }
      }
      ::LocalFree(exp_proc_sid);
    }

    ::LocalFree(curr_proc_sid);
    if (!impersonation_success) {
      ::CoUninitialize();
      return false;
    }
  }

  bool ret = false;
  CComPtr<IProcessLauncher> ipl;
  if (!FAILED(ipl.CoCreateInstance(__uuidof(ProcessLauncherClass), NULL,
                                   CLSCTX_LOCAL_SERVER))) {
    if (!FAILED(ipl->LaunchCmdLine(launch_cmd)))
      ret = true;
    ipl.Release();
  }

  if (impersonation_success)
    ::RevertToSelf();
  ::CoUninitialize();
  return ret;
}

#pragma comment(linker, "/EXPORT:LaunchGoogleChromeWithDimensions=_LaunchGoogleChromeWithDimensions@16,PRIVATE")
DLLEXPORT BOOL __stdcall LaunchGoogleChromeWithDimensions(int x,
                                                          int y,
                                                          int width,
                                                          int height) {
  if (!LaunchGoogleChrome())
    return false;

  HWND handle = NULL;
  int seconds_elapsed = 0;

  // Chrome may have been launched, but the window may not have appeared
  // yet. Wait for it to appear for 10 seconds, but exit if it takes longer
  // than that.
  while (!handle && seconds_elapsed < 10) {
    handle = FindWindowEx(NULL, handle, L"Chrome_WindowImpl_0", NULL);
    if (!handle) {
      Sleep(1000);
      seconds_elapsed++;
    }
  }

  if (!handle)
    return false;

  // At this point, there are several top-level Chrome windows
  // but we only want the window that has child windows.

  // This loop iterates through all of the top-level Windows named
  // Chrome_WindowImpl_0, and looks for the first one with any children.
  while (handle && !FindWindowEx(handle, NULL, L"Chrome_WindowImpl_0", NULL)) {
    // Get the next top-level Chrome window.
    handle = FindWindowEx(NULL, handle, L"Chrome_WindowImpl_0", NULL);
  }

  return (handle &&
          SetWindowPos(handle, 0, x, y, width, height, SWP_NOZORDER));
}


text:
package filodb.memory

import org.scalatest.BeforeAndAfterAll
import filodb.memory.format.UnsafeUtils.ZeroPointer
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks
import org.scalatest.funspec.AnyFunSpec
import org.scalatest.matchers.should.Matchers

class UTF8StringTest extends AnyFunSpec with Matchers with BeforeAndAfterAll with ScalaCheckPropertyChecks {
  import UTF8StringMedium._

  val nativeMem = new NativeMemoryManager(10 * 1024 * 1024)

  override def afterAll(): Unit = {
    nativeMem.shutdown()   // free all memory
  }

  describe("UTF8StringMedium") {
    it("should compare two strings properly") {
      // Unequal lengths, equal prefix
      compare(native("boobeebob", nativeMem).address, native("boobee", nativeMem).address) should be > 0

      // Equal lengths, different content
      // First comparison fights against int comparisons without proper byte ordering
      native("aaab", nativeMem).compare(native("baaa", nativeMem)) should be < 0
      UTF8StringMedium.equals("bobcat".utf8(nativeMem).address, "bobcat".utf8(nativeMem).address) shouldEqual true

      // Strings longer than 8 chars (in case comparison uses long compare)
      compare("dictionary".utf8(nativeMem).address, "pictionar".utf8(nativeMem).address) should be < 0
      compare("dictionary".utf8(nativeMem).address, "dictionaries".utf8(nativeMem).address) should be > 0

      // Calling equals to some other type should return false
      // Not applicable to non objects
      // UTF8StringMedium("dictionary") should not equal ("dictionary")
    }

    it("should compare on and offheap UTF8Strings") {
      val (base1, off1) = UTF8StringMedium("bobcat")
      val nativeStr1    = "bobcat".utf8(nativeMem)
      UTF8StringMedium.equals(base1, off1, ZeroPointer, nativeStr1.address) shouldEqual true
      UTF8StringMedium.equals(ZeroPointer, nativeStr1.address, base1, off1) shouldEqual true

      val (base2, off2) = UTF8StringMedium("dictionary")
      compare(base2, off2, ZeroPointer, "pictionar".utf8(nativeMem).address) should be < 0
      compare(ZeroPointer, "pictionar".utf8(nativeMem).address, base2, off2) should be > 0
    }

    it("should compare random strings properly") {
      import java.lang.Integer.signum
      forAll { (strs: (String, String)) =>
        val nativeCmp = signum(strs._1.compare(strs._2))
        signum(strs._1.utf8(nativeMem).compare(strs._2.utf8(nativeMem))) shouldEqual nativeCmp
      }
    }

    def getHash32(s: String): Int = {
      val (base, off) = UTF8StringMedium(s)
      UTF8StringMedium.hashCode(base, off)
    }

    def getHash64(s: String): Long = {
      val (base, off) = UTF8StringMedium(s)
      UTF8StringMedium.hashCode64(base, off)
    }

    it("should generate same hashcode for same content") {
      getHash32("bobcat") shouldEqual getHash32("bobcat")
      getHash32("bobcat") should not equal (getHash32("bob"))

      getHash64("bobcat") should equal (getHash64("bobcat"))
      getHash64("bobcat") should not equal (getHash64("bob"))
    }

    val str1 = UTF8StringMedium.native("1234", nativeMem)
    val str2 = UTF8StringMedium.native("一2三4", nativeMem)
    val str3 = UTF8StringMedium.native("一二34", nativeMem)

    it("should startsWith and endsWith correctly") {
      str2.startsWith("一2".utf8(nativeMem)) shouldEqual true
      str2.startsWith("2三".utf8(nativeMem)) shouldEqual false
      str2.startsWith(str1) shouldEqual false

      str2.endsWith(str3) shouldEqual false
      str2.endsWith("4".utf8(nativeMem)) shouldEqual true
    }

    it("should convert to and from Java Strings properly") {
      UTF8StringMedium.native("1234", nativeMem).toString shouldEqual "1234"
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
<?php include "templates/include/header.php" ?>
<?php include "templates/include/admin.php" ?>

Article Categories

 <?php if ( isset( $results['errorMessage'] ) ) { ?>

                        <?php echo $results['errorMessage'] ?>

<?php } ?>
<?php if ( isset( $results['statusMessage'] ) ) { ?>

                        <?php echo $results['statusMessage'] ?>

<?php } ?>

             Category Name
             Description
              Actions

    <?php foreach ( $results['categories'] as $category  ) { ?>

        <?php echo $category->name?>
        <?php echo $category->description?>

        <a class="btn btn-primary btn-xs" href="admin.php?action=editCategory&categoryId=<?php echo $category->id?>">
        <a class="btn btn-danger btn-xs" href="admin.php?action=deleteCategory&categoryId=<?php echo $category->id?>">

    <?php } ?>

                      <?php echo $results['totalRows']?><?php echo ( $results['totalRows'] != 1 ) ? ' categories' : ' category' ?> in total.

  New Category

 <?php
// paging buttons will be here
         include_once 'pagingCategory.php';

?>
<?php include "templates/include/footer.php" ?>


text:
package com.fishercoder;

import com.fishercoder.solutions._2293;
import com.fishercoder.solutions._3;
import org.junit.BeforeClass;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class _2293Test {
    private static _2293.Solution1 solution1;
    private static int expected;
    private static int[] nums;
    private static String s;

    @BeforeClass
    public static void setup() {
        solution1 = new _2293.Solution1();
    }

    @Test
    public void test1() {
        expected = 22;
        nums = new int[]{70, 38, 21, 22};
        assertEquals(expected, solution1.minMaxGame(nums));
    }

}


text:
<?php

class PHP_Shell_Extensions_ExecutionTime implements PHP_Shell_Extension {
    protected $show_exectime = false;

    protected $parse_time;
    protected $exec_time;
    protected $end_time;

    public function register() {
        $opt = PHP_Shell_Options::getInstance();

        $opt->registerOption("exectime", $this, "optSetExecTime");
    }

    public function optSetExecTime($key, $val) {
        switch ($val) {
        case "enable":
        case "1":
        case "on":
            $this->show_exectime = true;
            break;
        case "disable":
        case "0":
        case "off":
            $this->show_exectime = false;
            break;
        default:
            printf(":set %s failed, unknown value. Use :set %s = (on|off)", $key, $key);
            break;
        }
    }

    public function startParseTime() {
        $this->parse_time = microtime(1);
        $this->exec_time = 0.0;
    }
    public function startExecTime() {
        $this->exec_time = microtime(1);
    }
    public function stopTime() {
        $this->end_time = microtime(1);
    }

    public function getParseTime() {
        return ($this->exec_time == 0.0 ? $this->end_time : $this->exec_time) - $this->parse_time;
    }

    public function getExecTime() {
        return ($this->exec_time == 0.0 ? 0.0 : $this->end_time - $this->exec_time);
    }

    public function isShow() {
        return $this->show_exectime;
    }
}


text:
<phpunit bootstrap="./bootstrap.php" colors="true">
    <testsuites>
        <testsuite name="Maestrano Integration Test Suite">
            <directory>./</directory>
        </testsuite>
    </testsuites>
</phpunit>


text:
from __future__ import unicode_literals

import os
import subprocess
import sys

from build import BINARY_DIRS, remove_binaries

miniconda64_envs = os.getenv('MINICONDA64_ENVS')
python_installations = [
    r'%s/py27_64/bin/python' % miniconda64_envs,
    r'%s/py36_64/bin/python' % miniconda64_envs,
    r'%s/py37_64/bin/python' % miniconda64_envs,
    r'%s/py38_64/bin/python' % miniconda64_envs,
    r'%s/py39_64/bin/python' % miniconda64_envs,
    r'%s/py310_64/bin/python' % miniconda64_envs,
    ]
root_dir = os.path.dirname(os.path.dirname(__file__))

def list_binaries():
    for binary_dir in BINARY_DIRS:
        for f in os.listdir(os.path.join(root_dir, binary_dir)):
            if f.endswith('.so'):
                yield f

def extract_version(python_install):
    return python_install.split('/')[-3][2:]

def main():
    from generate_code import generate_dont_trace_files
    from generate_code import generate_cython_module

    # First, make sure that our code is up to date.
    generate_dont_trace_files()
    generate_cython_module()

    for python_install in python_installations:
        assert os.path.exists(python_install)

    remove_binaries(['.so'])

    for f in list_binaries():
        raise AssertionError('Binary not removed: %s' % (f,))

    for i, python_install in enumerate(python_installations):
        new_name = 'pydevd_cython_%s_%s' % (sys.platform, extract_version(python_install))
        args = [
            python_install, os.path.join(root_dir, 'build_tools', 'build.py'), '--no-remove-binaries', '--target-pyd-name=%s' % new_name, '--force-cython']
        if i != 0:
            args.append('--no-regenerate-files')
        version_number = extract_version(python_install)
        if version_number.startswith('36') or version_number.startswith('37') or version_number.startswith('38') \
                or version_number.startswith('39') or version_number.startswith('310'):
            name_frame_eval = 'pydevd_frame_evaluator_%s_%s' % (sys.platform, extract_version(python_install))
            args.append('--target-pyd-frame-eval=%s' % name_frame_eval)
        print('Calling: %s' % (' '.join(args)))
        subprocess.check_call(args)

if __name__ == '__main__':
    main()


text:
'use strict';

const RenderUtil = require('../../renderUtil');
const Mongo  = require('../../../service/Mongo');
const DB     = Mongo.getClient();
const InvitationTask = DB.models.InvitationTask;
const InvitationCard = DB.models.InvitationCard;
const Subscriber = DB.models.Subscriber;

exports.index = function(req, res, next) {
  let renderUtil = new RenderUtil(req, res);
  let InvitationTask = req.app.db.models.InvitationTask;
  let page = parseInt(req.query.page || 1);
  let pageSize = parseInt(req.query.pageSize || 10);
  let start = (page - 1) * pageSize;
  let end = page * pageSize;

  let countQuery = InvitationTask.count();
  let query = InvitationTask.find({}, {cardSetting: 0}).sort({ createdAt: -1 }).skip(start).limit(end - start);

  countQuery.exec(function (err, total) {
    if(err) return next(err);
    query.exec(function (err, docs) {
      if(err) return next(err);

      renderUtil.render({
        path: 'admin/invitationTask',
        subTitle: '邀请任务列表',
        data: {
          totalCount: total,
          page: page,
          pageSize: pageSize,
          pageCount: Math.ceil(total/pageSize),
          result: docs
        }
      });
    });
  });
};

exports.create = function(req, res, next) {
  let renderUtil = new RenderUtil(req, res);
  renderUtil.render({
    path: 'admin/invitationTask/create',
    subTitle: '增加邀请任务',
    data: {}
  });
};

exports.modify = function(req, res, next) {
  let renderUtil = new RenderUtil(req, res);
  const id = req.params.id;

  InvitationTask.findById(id).exec((err, doc) => {
    if(err) return next(err);
    renderUtil.render({
      path: 'admin/invitationTask/modify',
      subTitle: '修改邀请任务',
      data: doc
    }
    );
  });
}

exports.cardList = function(req, res, next) {
  const invitationTaskId = req.params.id;

  let renderUtil = new RenderUtil(req, res);
  let conditions = { invitationTask: invitationTaskId };
  let page = parseInt(req.query.page || 1);
  let pageSize = parseInt(req.query.pageSize || 10);
  let start = (page - 1) * pageSize;
  let end = page * pageSize;

  let countQuery = InvitationCard.count(conditions);
  let query = InvitationCard.find(conditions).skip(start).limit(end - start).populate('subscriber').sort({ invitedCount: -1 });

  countQuery.exec(function (err, total) {
    if(err) return next(err);
    query.exec(function (err, docs) {
      if(err) return next(err);

      renderUtil.render({
        path: 'admin/invitationTask/cardList',
        subTitle: '邀请任务详情',
        data: {
          totalCount: total,
          page: page,
          pageSize: pageSize,
          pageCount: Math.ceil(total/pageSize),
          result: docs
        }
      });
    });
  });
}


text:
package tabletserver

import (
	"fmt"
	"io"
	"net/http"
	"strings"
	"text/template"
	"time"

	log "github.com/golang/glog"
	"github.com/youtube/vitess/go/acl"
)

var (
	querylogzHeader = []byte(`

				Method
				Context
				Effective Caller
				Immediate Caller
				Start
				End
				Duration
				MySQL time
				Conn wait
				Plan
				SQL
				Queries
				Sources
				RowsAffected
				Response Size
				Transaction ID
				Error

	`)
	querylogzFuncMap = template.FuncMap{
		"stampMicro":   func(t time.Time) string { return t.Format(time.StampMicro) },
		"cssWrappable": wrappable,
		"unquote":      func(s string) string { return strings.Trim(s, "\"") },
	}
	querylogzTmpl = template.Must(template.New("example").Funcs(querylogzFuncMap).Parse(`

			{{.Method}}
			{{.ContextHTML}}
			{{.EffectiveCaller}}
			{{.ImmediateCaller}}
			{{.StartTime | stampMicro}}
			{{.EndTime | stampMicro}}
			{{.TotalTime.Seconds}}
			{{.MysqlResponseTime.Seconds}}
			{{.WaitingForConnection.Seconds}}
			{{.PlanType}}
			{{.OriginalSQL | unquote | cssWrappable}}
			{{.NumberOfQueries}}
			{{.FmtQuerySources}}
			{{.RowsAffected}}
			{{.SizeOfResponse}}
			{{.TransactionID}}
			{{.ErrorStr}}

	`))
)

func init() {
	http.HandleFunc("/querylogz", func(w http.ResponseWriter, r *http.Request) {
		ch := StatsLogger.Subscribe("querylogz")
		defer StatsLogger.Unsubscribe(ch)
		querylogzHandler(ch, w, r)
	})
}

// querylogzHandler serves a human readable snapshot of the
// current query log.
func querylogzHandler(ch chan interface{}, w http.ResponseWriter, r *http.Request) {
	if err := acl.CheckAccessHTTP(r, acl.DEBUGGING); err != nil {
		acl.SendError(w, err)
		return
	}
	timeout, limit := parseTimeoutLimitParams(r)
	startHTMLTable(w)
	defer endHTMLTable(w)
	w.Write(querylogzHeader)

	tmr := time.NewTimer(timeout)
	defer tmr.Stop()
	for i := 0; i < limit; i++ {
		select {
		case out := <-ch:
			select {
			case <-tmr.C:
				return
			default:
			}
			stats, ok := out.(*LogStats)
			if !ok {
				err := fmt.Errorf("Unexpected value in %s: %#v (expecting value of type %T)", TxLogger.Name(), out, &LogStats{})
				io.WriteString(w, `<tr class="error">`)
				io.WriteString(w, err.Error())
				io.WriteString(w, "
")
				log.Error(err)
				continue
			}
			var level string
			if stats.TotalTime().Seconds() < 0.01 {
				level = "low"
			} else if stats.TotalTime().Seconds() < 0.1 {
				level = "medium"
			} else {
				level = "high"
			}
			tmplData := struct {
				*LogStats
				ColorLevel string
			}{stats, level}
			if err := querylogzTmpl.Execute(w, tmplData); err != nil {
				log.Errorf("querylogz: couldn't execute template: %v", err)
			}
		case <-tmr.C:
			return
		}
	}
}


text:
/**
 * Report
 *
 * Handle ReportState requests
 *
 * It will signal its completion by calling context.succeed()
 * or context.fail()
 */
'use strict';

var constants   = require('../constants');
var helper      = require('./helper');

/**
 * ReportState Handler
 * @param request
 * @param context
 * @param config
 * @return Nothing. Context.succeed() or fail() will be called.
 */
function handler(request, context, config) {

    var requestedName = request.directive.header.name;
    var token = request.directive.endpoint.scope.token;
    var timestamp = new Date().toISOString();
    var correlation = request.directive.header.correlationToken;
    var endpoint = request.directive.endpoint;

    helper.log('ReportState', request);

    switch (requestedName) {    // This better be ReportState or we shouldn't be here.
        case "ReportState":
            helper.log("Calling device",requestedName);
            config.Device.reportState(request, context, config).then(function(result){

                helper.log("Result from device reportState", result);

                // For now, hard code the entire response. Refactor later after its understood better.
                let contextResult = {
                    "properties": [{
                        "namespace": "Alexa.PowerController",
                        "name": "powerState",
                        "value": (result ? "ON" : "OFF"),
                        "timeOfSample": timestamp,
                        "uncertaintyInMilliseconds": 50
                    }]
                };
                var responseHeader = request.directive.header;
                responseHeader.namespace = "Alexa";
                responseHeader.name = "StateReport";
                responseHeader.messageId = responseHeader.messageId + "-R";
                var response = {
                    "context": contextResult,
                    "event": {
                        "header": responseHeader,
                        "endpoint": endpoint,
                        "payload": {}
                    }
                };
                helper.log("Returning response: ", response);
                context.succeed(response);
            },
            function(error) {
                helper.log("ReportState error",error);
                context.fail("ReportState error: "+error);
            });
            break;

        default:
            helper.log("Report - unsupported operation",requestedName);
            context.fail("Report - Unsupported operation: "+requestedName);
    }
    /*
     Note: No return value or promise.
           Device methods will call context.succeed(result) or context.fail(controllError)
     */
}

/* Export our public functions */
module.exports = {
    handler:handler,
};


text:
zorro-long.github.io
====================

personal blog


text:
package builds

import (
	"bytes"
	"errors"
	"fmt"
	"net/http"
	"net/url"
	"os"
	"os/exec"
	"strings"
	"time"

	g "github.com/onsi/ginkgo"
	o "github.com/onsi/gomega"

	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"

	"github.com/openshift/origin/pkg/build/api"
	exutil "github.com/openshift/origin/test/extended/util"
	"github.com/openshift/origin/test/extended/util/jenkins"
)

const (
	localClientPluginSnapshotImageStream = "jenkins-client-plugin-snapshot-test"
	localClientPluginSnapshotImage       = "openshift/" + localClientPluginSnapshotImageStream + ":latest"
	localSyncPluginSnapshotImageStream   = "jenkins-sync-plugin-snapshot-test"
	localSyncPluginSnapshotImage         = "openshift/" + localSyncPluginSnapshotImageStream + ":latest"
	clientLicenseText                    = "About OpenShift Client Jenkins Plugin"
	syncLicenseText                      = "About OpenShift Sync"
	clientPluginName                     = "openshift-client"
	syncPluginName                       = "openshift-sync"
)

func debugAnyJenkinsFailure(br *exutil.BuildResult, name string, oc *exutil.CLI, dumpMaster bool) {
	if !br.BuildSuccess {
		br.LogDumper = jenkins.DumpLogs
		fmt.Fprintf(g.GinkgoWriter, "\n\n START debugAnyJenkinsFailure\n\n")
		j := jenkins.NewRef(oc)
		jobLog, err := j.GetLastJobConsoleLogs(name)
		if err == nil {
			fmt.Fprintf(g.GinkgoWriter, "\n %s job log:\n%s", name, jobLog)
		} else {
			fmt.Fprintf(g.GinkgoWriter, "\n error getting %s job log: %#v", name, err)
		}
		if dumpMaster {
			exutil.DumpDeploymentLogs("jenkins", oc)
		}
		fmt.Fprintf(g.GinkgoWriter, "\n\n END debugAnyJenkinsFailure\n\n")
	}
}

var _ = g.Describe("[builds][Slow] openshift pipeline build", func() {
	defer g.GinkgoRecover()
	var (
		jenkinsTemplatePath    = exutil.FixturePath("..", "..", "examples", "jenkins", "jenkins-ephemeral-template.json")
		mavenSlavePipelinePath = exutil.FixturePath("..", "..", "examples", "jenkins", "pipeline", "maven-pipeline.yaml")
		//orchestrationPipelinePath = exutil.FixturePath("..", "..", "examples", "jenkins", "pipeline", "mapsapp-pipeline.yaml")
		blueGreenPipelinePath    = exutil.FixturePath("..", "..", "examples", "jenkins", "pipeline", "bluegreen-pipeline.yaml")
		clientPluginPipelinePath = exutil.FixturePath("..", "..", "examples", "jenkins", "pipeline", "openshift-client-plugin-pipeline.yaml")
		envVarsPipelinePath      = exutil.FixturePath("testdata", "samplepipeline-withenvs.yaml")

		oc                       = exutil.NewCLI("jenkins-pipeline", exutil.KubeConfigPath())
		ticker                   *time.Ticker
		j                        *jenkins.JenkinsRef
		dcLogFollow              *exec.Cmd
		dcLogStdOut, dcLogStdErr *bytes.Buffer
		setupJenkins             = func() {
			// Deploy Jenkins
			var licensePrefix, pluginName string
			newAppArgs := []string{"-f", jenkinsTemplatePath}
			newAppArgs, useSnapshotImage := jenkins.SetupSnapshotImage(jenkins.UseLocalClientPluginSnapshotEnvVarName, localClientPluginSnapshotImage, localClientPluginSnapshotImageStream, newAppArgs, oc)
			if !useSnapshotImage {
				newAppArgs, useSnapshotImage = jenkins.SetupSnapshotImage(jenkins.UseLocalSyncPluginSnapshotEnvVarName, localSyncPluginSnapshotImage, localSyncPluginSnapshotImageStream, newAppArgs, oc)
				licensePrefix = syncLicenseText
				pluginName = syncPluginName
			} else {
				licensePrefix = clientLicenseText
				pluginName = clientPluginName
			}

			g.By(fmt.Sprintf("calling oc new-app useSnapshotImage %v with license text %s and newAppArgs %#v", useSnapshotImage, licensePrefix, newAppArgs))
			err := oc.Run("new-app").Args(newAppArgs...).Execute()
			o.Expect(err).NotTo(o.HaveOccurred())

			g.By("waiting for jenkins deployment")
			err = exutil.WaitForADeploymentToComplete(oc.KubeClient().Core().ReplicationControllers(oc.Namespace()), "jenkins", oc)
			o.Expect(err).NotTo(o.HaveOccurred())

			j = jenkins.NewRef(oc)

			g.By("wait for jenkins to come up")
			_, err = j.WaitForContent("", 200, 10*time.Minute, "")

			if err != nil {
				exutil.DumpDeploymentLogs("jenkins", oc)
			}

			o.Expect(err).NotTo(o.HaveOccurred())

			if useSnapshotImage {
				g.By("verifying the test image is being used")
				// for the test image, confirm that a snapshot version of the plugin is running in the jenkins image we'll test against
				_, err = j.WaitForContent(licensePrefix+` ([0-9\.]+)-SNAPSHOT`, 200, 10*time.Minute, "/pluginManager/plugin/"+pluginName+"/thirdPartyLicenses")
				o.Expect(err).NotTo(o.HaveOccurred())
			}

			// Start capturing logs from this deployment config.
			// This command will terminate if the Jenkins instance crashes. This
			// ensures that even if the Jenkins DC restarts, we should capture
			// logs from the crash.
			dcLogFollow, dcLogStdOut, dcLogStdErr, err = oc.Run("logs").Args("-f", "dc/jenkins").Background()
			o.Expect(err).NotTo(o.HaveOccurred())

		}
	)

	g.BeforeEach(func() {
		setupJenkins()

		if os.Getenv(jenkins.DisableJenkinsGCStats) == "" {
			g.By("start jenkins gc tracking")
			ticker = jenkins.StartJenkinsGCTracking(oc, oc.Namespace())
		}

		g.By("waiting for builder service account")
		err := exutil.WaitForBuilderAccount(oc.KubeClient().Core().ServiceAccounts(oc.Namespace()))
		o.Expect(err).NotTo(o.HaveOccurred())
	})

	g.Context("Pipeline with maven slave", func() {
		g.AfterEach(func() {
			if os.Getenv(jenkins.DisableJenkinsGCStats) == "" {
				g.By("stopping jenkins gc tracking")
				ticker.Stop()
			}
		})

		g.It("should build and complete successfully", func() {
			// instantiate the template
			g.By(fmt.Sprintf("calling oc new-app -f %q", mavenSlavePipelinePath))
			err := oc.Run("new-app").Args("-f", mavenSlavePipelinePath).Execute()
			o.Expect(err).NotTo(o.HaveOccurred())

			// start the build
			g.By("starting the pipeline build and waiting for it to complete")
			br, _ := exutil.StartBuildAndWait(oc, "openshift-jee-sample")
			debugAnyJenkinsFailure(br, oc.Namespace()+"-openshift-jee-sample", oc, true)
			br.AssertSuccess()

			// wait for the service to be running
			g.By("expecting the openshift-jee-sample service to be deployed and running")
			_, err = exutil.GetEndpointAddress(oc, "openshift-jee-sample")
			o.Expect(err).NotTo(o.HaveOccurred())
		})
	})

	g.Context("Pipeline using jenkins-client-plugin", func() {
		g.AfterEach(func() {
			if os.Getenv(jenkins.DisableJenkinsGCStats) == "" {
				g.By("stopping jenkins gc tracking")
				ticker.Stop()
			}
		})

		g.It("should build and complete successfully", func() {
			// instantiate the bc
			g.By("create the jenkins pipeline strategy build config that leverages openshift client plugin")
			err := oc.Run("create").Args("-f", clientPluginPipelinePath).Execute()
			o.Expect(err).NotTo(o.HaveOccurred())

			// start the build
			g.By("starting the pipeline build and waiting for it to complete")
			br, _ := exutil.StartBuildAndWait(oc, "sample-pipeline-openshift-client-plugin")
			debugAnyJenkinsFailure(br, oc.Namespace()+"-sample-pipeline-openshift-client-plugin", oc, true)
			br.AssertSuccess()

			g.By("get build console logs and see if succeeded")
			_, err = j.WaitForContent("Finished: SUCCESS", 200, 10*time.Minute, "job/%s-sample-pipeline-openshift-client-plugin/lastBuild/consoleText", oc.Namespace())
			o.Expect(err).NotTo(o.HaveOccurred())
		})
	})

	g.Context("Pipeline with env vars", func() {
		g.AfterEach(func() {
			if os.Getenv(jenkins.DisableJenkinsGCStats) == "" {
				g.By("stopping jenkins gc tracking")
				ticker.Stop()
			}
		})

		g.It("should build and complete successfully", func() {
			// instantiate the bc
			g.By(fmt.Sprintf("calling oc new-app -f %q", envVarsPipelinePath))
			err := oc.Run("new-app").Args("-f", envVarsPipelinePath).Execute()
			o.Expect(err).NotTo(o.HaveOccurred())

			// start the build
			g.By("starting the pipeline build, including env var, and waiting for it to complete")
			br, _ := exutil.StartBuildAndWait(oc, "-e", "FOO2=BAR2", "sample-pipeline-withenvs")
			debugAnyJenkinsFailure(br, oc.Namespace()+"-sample-pipeline-withenvs", oc, true)
			br.AssertSuccess()

			g.By("confirm all the log annotations are there")
			_, err = jenkins.ProcessLogURLAnnotations(oc, br)
			o.Expect(err).NotTo(o.HaveOccurred())

			g.By("get build console logs and see if succeeded")
			_, err = j.WaitForContent("Finished: SUCCESS", 200, 10*time.Minute, "job/%s-sample-pipeline-withenvs/lastBuild/consoleText", oc.Namespace())
			o.Expect(err).NotTo(o.HaveOccurred())

			g.By("get build console logs and see if env is set")
			_, err = j.WaitForContent("FOO2 is BAR2", 200, 10*time.Minute, "job/%s-sample-pipeline-withenvs/lastBuild/consoleText", oc.Namespace())
			o.Expect(err).NotTo(o.HaveOccurred())

			// start the nextbuild
			g.By("starting the pipeline build and waiting for it to complete")
			br, _ = exutil.StartBuildAndWait(oc, "sample-pipeline-withenvs")
			debugAnyJenkinsFailure(br, oc.Namespace()+"-sample-pipeline-withenvs", oc, true)
			br.AssertSuccess()

			g.By("get build console logs and see if succeeded")
			_, err = j.WaitForContent("Finished: SUCCESS", 200, 10*time.Minute, "job/%s-sample-pipeline-withenvs/lastBuild/consoleText", oc.Namespace())
			o.Expect(err).NotTo(o.HaveOccurred())

			g.By("get build console logs and see if env is set")
			_, err = j.WaitForContent("FOO1 is BAR1", 200, 10*time.Minute, "job/%s-sample-pipeline-withenvs/lastBuild/consoleText", oc.Namespace())
			o.Expect(err).NotTo(o.HaveOccurred())

			g.By("get build console logs and see if env is still not set")
			_, err = j.WaitForContent("FOO2 is null", 200, 10*time.Minute, "job/%s-sample-pipeline-withenvs/lastBuild/consoleText", oc.Namespace())
			o.Expect(err).NotTo(o.HaveOccurred())

		})
	})

	/*g.Context("Orchestration pipeline", func() {
		g.AfterEach(func() {
			if os.Getenv(jenkins.DisableJenkinsGCStats) == "" {
				g.By("stopping jenkins gc tracking")
				ticker.Stop()
			}
		})

		g.It("should build and complete successfully", func() {
			// instantiate the template
			g.By(fmt.Sprintf("calling oc new-app -f %q", orchestrationPipelinePath))
			err := oc.Run("new-app").Args("-f", orchestrationPipelinePath).Execute()
			o.Expect(err).NotTo(o.HaveOccurred())

			// start the build
			g.By("starting the pipeline build and waiting for it to complete")
			br, _ := exutil.StartBuildAndWait(oc, "mapsapp-pipeline")
			debugAnyJenkinsFailure(br, oc.Namespace()+"-mapsapp-pipeline", oc, true)
			debugAnyJenkinsFailure(br, oc.Namespace()+"-mlbparks-pipeline", oc, false)
			debugAnyJenkinsFailure(br, oc.Namespace()+"-nationalparks-pipeline", oc, false)
			debugAnyJenkinsFailure(br, oc.Namespace()+"-parksmap-pipeline", oc, false)
			br.AssertSuccess()

			// wait for the service to be running
			g.By("expecting the parksmap-web service to be deployed and running")
			_, err = exutil.GetEndpointAddress(oc, "parksmap")
			o.Expect(err).NotTo(o.HaveOccurred())
		})
	})*/

	g.Context("Blue-green pipeline", func() {
		g.AfterEach(func() {
			if os.Getenv(jenkins.DisableJenkinsGCStats) == "" {
				g.By("stopping jenkins gc tracking")
				ticker.Stop()
			}
		})

		g.It("Blue-green pipeline should build and complete successfully", func() {
			// instantiate the template
			g.By(fmt.Sprintf("calling oc new-app -f %q", blueGreenPipelinePath))
			err := oc.Run("new-app").Args("-f", blueGreenPipelinePath, "-p", "VERBOSE=true").Execute()
			o.Expect(err).NotTo(o.HaveOccurred())

			buildAndSwitch := func(newColour string) {
				// start the build
				g.By("starting the bluegreen pipeline build")
				br, err := exutil.StartBuildResult(oc, "bluegreen-pipeline")
				o.Expect(err).NotTo(o.HaveOccurred())

				errs := make(chan error, 2)
				stop := make(chan struct{})
				go func() {
					defer g.GinkgoRecover()

					g.By("Waiting for the build uri")
					var jenkinsBuildURI string
					for {
						build, err := oc.Client().Builds(oc.Namespace()).Get(br.BuildName, metav1.GetOptions{})
						if err != nil {
							errs <- fmt.Errorf("error getting build: %s", err)
							return
						}
						jenkinsBuildURI = build.Annotations[api.BuildJenkinsBuildURIAnnotation]
						if jenkinsBuildURI != "" {
							break
						}

						select {
						case <-stop:
							return
						default:
							time.Sleep(10 * time.Second)
						}
					}

					url, err := url.Parse(jenkinsBuildURI)
					if err != nil {
						errs <- fmt.Errorf("error parsing build uri: %s", err)
						return
					}
					jenkinsBuildURI = strings.Trim(url.Path, "/") // trim leading https://host/ and trailing /

					g.By("Waiting for the approval prompt")
					for {
						body, status, err := j.GetResource(jenkinsBuildURI + "/consoleText")
						if err == nil && status == http.StatusOK && strings.Contains(body, "Approve?") {
							break
						}
						select {
						case <-stop:
							return
						default:
							time.Sleep(10 * time.Second)
						}
					}

					g.By("Approving the current build")
					_, _, err = j.Post(nil, jenkinsBuildURI+"/input/Approval/proceedEmpty", "")
					if err != nil {
						errs <- fmt.Errorf("error approving the current build: %s", err)
					}
				}()

				go func() {
					defer g.GinkgoRecover()

					for {
						build, err := oc.Client().Builds(oc.Namespace()).Get(br.BuildName, metav1.GetOptions{})
						switch {
						case err != nil:
							errs <- fmt.Errorf("error getting build: %s", err)
							return
						case exutil.CheckBuildFailedFn(build):
							errs <- nil
							return
						case exutil.CheckBuildSuccessFn(build):
							br.BuildSuccess = true
							errs <- nil
							return
						}
						select {
						case <-stop:
							return
						default:
							time.Sleep(5 * time.Second)
						}
					}
				}()

				g.By("waiting for the build to complete")
				select {
				case <-time.After(60 * time.Minute):
					err = errors.New("timeout waiting for build to complete")
				case err = <-errs:
				}
				close(stop)

				if err != nil {
					fmt.Fprintf(g.GinkgoWriter, "error occurred (%s): getting logs before failing\n", err)
				}

				debugAnyJenkinsFailure(br, oc.Namespace()+"-bluegreen-pipeline", oc, true)
				br.AssertSuccess()
				o.Expect(err).NotTo(o.HaveOccurred())

				g.By(fmt.Sprintf("verifying that the main route has been switched to %s", newColour))
				value, err := oc.Run("get").Args("route", "nodejs-mongodb-example", "-o", "jsonpath={ .spec.to.name }").Output()
				o.Expect(err).NotTo(o.HaveOccurred())
				activeRoute := strings.TrimSpace(value)
				g.By(fmt.Sprintf("verifying that the active route is 'nodejs-mongodb-example-%s'", newColour))
				o.Expect(activeRoute).To(o.Equal(fmt.Sprintf("nodejs-mongodb-example-%s", newColour)))
			}

			buildAndSwitch("green")
			buildAndSwitch("blue")
		})
	})
})


text:
<?php

/**
 * PHP Template.
 * Author: Sheetal Patil. Sun Microsystems, Inc.
 *
 */
session_start();
require_once("../etc/config.php");
$connection = DBConnection::getWriteInstance();
$friends = Users_Controller::getInstance();
$person = $_REQUEST['person'];
$friend = $_REQUEST['friend'];
$revokeSql = "delete from PERSON_PERSON where person_username='$friend' and friends_username='$person'";
$connection->beginTransaction();
$connection->exec($revokeSql);
$outgoingRequests = $friends->outgoingRequests($person,$connection);
$connection->commit();
echo "You have revoked your friendship request to ". $friend."\n";
echo $outgoingRequests ;
?>


text:
@interface DTPathUtils : NSObject

@end


text:
"""Support for resolving hosts and options from mongodb+srv:// URIs."""

import ipaddress
import random

try:
    from dns import resolver

    _HAVE_DNSPYTHON = True
except ImportError:
    _HAVE_DNSPYTHON = False

from pymongo.common import CONNECT_TIMEOUT
from pymongo.errors import ConfigurationError

# dnspython can return bytes or str from various parts
# of its API depending on version. We always want str.
def maybe_decode(text):
    if isinstance(text, bytes):
        return text.decode()
    return text

# PYTHON-2667 Lazily call dns.resolver methods for compatibility with eventlet.
def _resolve(*args, **kwargs):
    if hasattr(resolver, "resolve"):
        # dnspython >= 2
        return resolver.resolve(*args, **kwargs)
    # dnspython 1.X
    return resolver.query(*args, **kwargs)

_INVALID_HOST_MSG = (
    "Invalid URI host: %s is not a valid hostname for 'mongodb+srv://'. "
    "Did you mean to use 'mongodb://'?"
)

class _SrvResolver(object):
    def __init__(self, fqdn, connect_timeout, srv_service_name, srv_max_hosts=0):
        self.__fqdn = fqdn
        self.__srv = srv_service_name
        self.__connect_timeout = connect_timeout or CONNECT_TIMEOUT
        self.__srv_max_hosts = srv_max_hosts or 0
        # Validate the fully qualified domain name.
        try:
            ipaddress.ip_address(fqdn)
            raise ConfigurationError(_INVALID_HOST_MSG % ("an IP address",))
        except ValueError:
            pass

        try:
            self.__plist = self.__fqdn.split(".")[1:]
        except Exception:
            raise ConfigurationError(_INVALID_HOST_MSG % (fqdn,))
        self.__slen = len(self.__plist)
        if self.__slen < 2:
            raise ConfigurationError(_INVALID_HOST_MSG % (fqdn,))

    def get_options(self):
        try:
            results = _resolve(self.__fqdn, "TXT", lifetime=self.__connect_timeout)
        except (resolver.NoAnswer, resolver.NXDOMAIN):
            # No TXT records
            return None
        except Exception as exc:
            raise ConfigurationError(str(exc))
        if len(results) > 1:
            raise ConfigurationError("Only one TXT record is supported")
        return (b"&".join([b"".join(res.strings) for res in results])).decode("utf-8")

    def _resolve_uri(self, encapsulate_errors):
        try:
            results = _resolve(
                "_" + self.__srv + "._tcp." + self.__fqdn, "SRV", lifetime=self.__connect_timeout
            )
        except Exception as exc:
            if not encapsulate_errors:
                # Raise the original error.
                raise
            # Else, raise all errors as ConfigurationError.
            raise ConfigurationError(str(exc))
        return results

    def _get_srv_response_and_hosts(self, encapsulate_errors):
        results = self._resolve_uri(encapsulate_errors)

        # Construct address tuples
        nodes = [
            (maybe_decode(res.target.to_text(omit_final_dot=True)), res.port) for res in results
        ]

        # Validate hosts
        for node in nodes:
            try:
                nlist = node[0].split(".")[1:][-self.__slen :]
            except Exception:
                raise ConfigurationError("Invalid SRV host: %s" % (node[0],))
            if self.__plist != nlist:
                raise ConfigurationError("Invalid SRV host: %s" % (node[0],))
        if self.__srv_max_hosts:
            nodes = random.sample(nodes, min(self.__srv_max_hosts, len(nodes)))
        return results, nodes

    def get_hosts(self):
        _, nodes = self._get_srv_response_and_hosts(True)
        return nodes

    def get_hosts_and_min_ttl(self):
        results, nodes = self._get_srv_response_and_hosts(False)
        return nodes, results.rrset.ttl


text:
const path = require('path')
const fs = require('fs')

module.exports = ({
  baseDir,
  rootDirectory,
  defaultOpts,
  defaultExtensions = [],
  cliModuleName = 'jsreport-cli',
  deps
}) => {
  const {
    extend,
    mkdirp,
    rimraf,
    execa
  } = deps

  return {
    getTempDir: getTempDir.bind(undefined, baseDir),
    cleanTempDir: cleanTempDir.bind(undefined, baseDir),
    createTempDir: createTempDir.bind(undefined, baseDir),
    setup: setup.bind(undefined, baseDir),
    init: init.bind(undefined, baseDir),
    exec: exec.bind(undefined, baseDir)
  }

  function getTempDir (baseDir, dir) {
    return path.join(baseDir, dir)
  }

  function cleanTempDir (baseDir, dir) {
    const fullDir = getTempDir(baseDir, dir)
    let dirs

    try {
      dirs = fs.readdirSync(fullDir)
    } catch (e) {}

    if (!dirs) {
      return
    }

    dirs.forEach((d) => {
      rimraf.sync(path.join(fullDir, d))
    })
  }

  function createTempDir (baseDir, dir) {
    const fullDir = getTempDir(baseDir, dir)
    mkdirp.sync(fullDir)
    return fullDir
  }

  async function setup (baseDir, dir, extensions = [], cliRunnerExtension, opts) {
    cleanTempDir(baseDir, dir)

    const tempDir = createTempDir(baseDir, dir)

    const tempDataDir = createTempDir(baseDir, `${dir}/data`)

    let optionsToUse = extend(true, {
      rootDirectory,
      migrateEntitySetsToFolders: false,
      store: {
        provider: 'memory'
      },
      extensions: {
        'fs-store': {
          dataDirectory: tempDataDir
        }
      }
    }, defaultOpts)

    if (opts) {
      optionsToUse = extend(true, {}, optionsToUse, opts)
    }

    fs.writeFileSync(
      path.join(tempDir, './package.json'),
      JSON.stringify({
        name: dir,
        dependencies: {
          'jsreport-core': '*'
        },
        jsreport: {
          entryPoint: 'server.js'
        }
      }, null, 2)
    )

    fs.writeFileSync(
      path.join(tempDir, './instance.js'),
      `
        process.env.cli_instance_lookup_fallback = process.env.cli_instance_lookup_fallback != null ? process.env.cli_instance_lookup_fallback : 'enabled'

        const defaultOpts = ${optionsToUse != null ? JSON.stringify(optionsToUse) : 'undefined'}

        module.exports = (initOpts) => {
          return (
            require('jsreport-core')(initOpts != null ? initOpts : defaultOpts)
              .use(require(\`${escapePath(cliModuleName)}\`)())
              ${defaultExtensions && defaultExtensions.length > 0 ? defaultExtensions.map((e) => `.use(require(\`${escapePath(e)}\`)())`).join('') : ''}
              ${extensions && extensions.length > 0 ? extensions.map((e) => `.use(require(\`${escapePath(e)}\`)())`).join('') : ''}
          )
        }

        module.exports.defaultOpts = defaultOpts
      `
    )

    fs.writeFileSync(
      path.join(tempDir, './server.js'),
      `
        const createJsreport = require('./instance')

        if (process.env.JSREPORT_CLI) {
          module.exports = createJsreport()
        } else {
          createJsreport().init().catch(function (e) {
            console.error("error on jsreport init")
            console.error(e.stack)
            process.exit(1)
          })
        }
      `
    )

    fs.writeFileSync(
      path.join(tempDir, './cliRunner.js'),
      `
      const createJsreport = require('./instance')

      const commander = require(\`${escapePath(cliModuleName)}\`).commander(undefined, {
        instance: process.env.noDefaultInstance != null ? undefined : createJsreport()
      })

      ${cliRunnerExtension != null ? cliRunnerExtension : ''}

      commander.start(process.argv.slice(2))
      `
    )
  }

  async function init (baseDir, dir, opts) {
    const fullDir = getTempDir(baseDir, dir)

    const createJsreport = require(path.join(fullDir, 'instance.js'))

    const jsreport = createJsreport(
      extend(true, {}, createJsreport.defaultOpts, opts)
    )

    await jsreport.init()

    return jsreport
  }

  function exec (baseDir, dir, cmd = '', opts) {
    const defaultCWD = getTempDir(baseDir, dir)
    const cliRunner = path.join(defaultCWD, 'cliRunner.js')

    const file = process.execPath
    const fullCmd = `${process.env.debugCLI ? '--inspect-brk ' : ''}${cliRunner} ${cmd}`

    // this should be replaced when execa.command (v2) is released
    const args = (
      fullCmd
        .trim()
        .split(/ +/g)
        .reduce((tokens, token, index) => {
          if (index === 0) {
            return [token]
          }

          const previousToken = tokens[tokens.length - 1]

          if (previousToken.endsWith('\\')) {
            return [...tokens.slice(0, -1), `${previousToken.slice(0, -1)} ${token}`]
          }

          return [...tokens, token]
        }, [])
    )

    return execa(file, args, {
      env: Object.assign({ DEBUG: 'jsreport' }, opts != null ? opts.env : undefined),
      cwd: opts && opts.cwd != null ? opts.cwd : defaultCWD,
      windowsHide: true
    })
  }
}

function escapePath (pathStr) {
  return pathStr.replace(/\\/g, '\\\\')
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<rootTag>
  <Award>
    <AwardTitle>High-Performance Computing Education at the University of the Pacific</AwardTitle>
    <AwardEffectiveDate>10/01/2012</AwardEffectiveDate>
    <AwardExpirationDate>09/30/2014</AwardExpirationDate>
    <AwardAmount>34626</AwardAmount>
    <AwardInstrument>
      <Value>Standard Grant</Value>
    </AwardInstrument>
    <Organization>
      05020000
      <Directorate>
        <LongName>Direct For Computer & Info Scie & Enginr</LongName>
      </Directorate>
      <Division>
        <LongName>Div Of Information & Intelligent Systems</LongName>
      </Division>
    </Organization>
    <ProgramOfficer>
      <SignBlockName>Sylvia J. Spengler</SignBlockName>
    </ProgramOfficer>
    <AbstractNarration>This award is to support travel to Super Computing to participate in student challenge activities, hardware acquisition, curriculum development, and training support for the University of the Pacific all-female team to SC13. The LittleFe cluster computers requested as part of this proposal are widely known and used in the HPC education community, thanks to an active outreach effort at past SC conferences and other venues. Curriculum developed at Pacific for the LittleFe clusters can be easily used by other institutions, greatly facilitating the spread of new educational innovations. The travel support requested for the all-female student team will enable future participation in the student cluster competition. This activity enables teaching of key HPC skills (such as cluster architecture, system administrative, and scientific computing) in a competitive learning environment.</AbstractNarration>
    <MinAmdLetterDate>09/11/2012</MinAmdLetterDate>
    <MaxAmdLetterDate>09/11/2012</MaxAmdLetterDate>
    <ARRAAmount/>
    <AwardID>1250653</AwardID>
    <Investigator>
      <FirstName>James</FirstName>
      <LastName>Hetrick</LastName>
      <EmailAddress>jhetrick@pacific.edu</EmailAddress>
      <StartDate>09/11/2012</StartDate>
      <EndDate/>
      <RoleCode>Co-Principal Investigator</RoleCode>
    </Investigator>
    <Investigator>
      <FirstName>Jinzhu</FirstName>
      <LastName>Gao</LastName>
      <EmailAddress>jgao@pacific.edu</EmailAddress>
      <StartDate>09/11/2012</StartDate>
      <EndDate/>
      <RoleCode>Co-Principal Investigator</RoleCode>
    </Investigator>
    <Investigator>
      <FirstName>Jeffrey</FirstName>
      <LastName>Shafer</LastName>
      <EmailAddress>jshafer@pacific.edu</EmailAddress>
      <StartDate>09/11/2012</StartDate>
      <EndDate/>
      <RoleCode>Principal Investigator</RoleCode>
    </Investigator>
    <Institution>
      <Name>University of the Pacific</Name>
      <CityName>Stockton</CityName>
      <ZipCode>952110110</ZipCode>
      <PhoneNumber>2099467706</PhoneNumber>
      <StreetAddress>3601 Pacific Avenue</StreetAddress>
      <CountryName>United States</CountryName>
      <StateName>California</StateName>
      <StateCode>CA</StateCode>
    </Institution>
  </Award>
</rootTag>


text:
void init_led();

// Turn the green led on or off.
void set_green_led(unsigned char on);

// Turn the red led on or off.
void set_red_led(unsigned char on);

// Turn the red and green led's on or off.
// The amber led cannot be controlled by software.
void set_all_leds(unsigned char on);

#define LED_ON 1
#define LED_OFF 0

#endif  // INC_LED_H_


text:
<?php
    include_once('../functions.php');
    global $userInfo;

    try {
        $db_con = connectDBi();
    } catch (Exception $e) {
        if ($e->getMessage() == "100") {
            $error = mysql_error();
            die("Error connecting to the database");
        } else if ($e->getMessage() == "101") {
            $error = mysql_error();
            die("Error selecting the database");
        }
    }

    $tokenHash = hash('sha512', $_SESSION['sfToken']);

    $dbStr = "INSERT INTO `User` (`SFUserID`, `Username`, `FullName`, `Email`, `TokenHash`) VALUES " .
             "('" . $userInfo->userId . "', '" . $userInfo->userName . "', '" . $userInfo->userFullName . "', '" . $userInfo->userEmail . "', '" . $tokenHash . "') " .
             "ON DUPLICATE KEY UPDATE `Username` = '" . $userInfo->userName . "', `FullName` = '" . $userInfo->userFullName . "', `Email` = '" . $userInfo->userEmail . "', `TokenHash` = '" . $tokenHash . "'";
    $result = $db_con->query($dbStr);
?>


text:
import java.rmi.*;

public interface Interface extends Remote {
    // la methode que le serveur expose au client
    public double fibonacci(int n) throws RemoteException;
}


text:
<?php

/**
 * BulkmakedraftCmsController
 *
 * @package     CrowdFusion
 */
class BulkmakedraftCmsController extends AbstractBulkActionController
{
    protected $RegulatedNodeService;

    public function setRegulatedNodeService(RegulatedNodeService $RegulatedNodeService)
    {
        $this->RegulatedNodeService = $RegulatedNodeService;
    }

    public function execute() {

        $this->_beginBulkaction();

        $noderefs = $this->_getNodeRefs();

        foreach($noderefs as $noderef) {

            try {

                $node = $this->RegulatedNodeService->getByNodeRef($noderef);

                if(!empty($node)) {

                    $node->Status = "draft";

                    $this->RegulatedNodeService->edit($node);
                }

                $this->_updateBulkaction($noderef->getElement()->Slug,$noderef->Slug);
            } catch(Exception $e) {
                $this->_failureBulkaction($e->getMessage(),$noderef->getElement()->Slug,$noderef->Slug);
            }
        }

        return $this->_endBulkaction();
    }

}


text:
* {outline: none}
body, h1, h2, h3, p, td, th
{
    font-family: "Helvetica Neue",Helvetica,Arial,sans-serif;
    color: #333;
    font-weight: normal;
}
h1 {font-size: 36px}
h3 {font-size: 24px; margin-bottom: 12px}
a {color: #337ab7; text-decoration: none}
p {margin: 0 0 10px; font-size: 14px; line-height: 1.4}
input, button, select
{
    background: #fff;
    border-radius: 4px;
    border: 1px solid #ccc;
    padding: 8px;
    font-size: 14px;
    color: #333;
}
input[type="date"] {padding: 6px;}
select {padding: 7px 12px;}
button, select {cursor: pointer}
button:hover {background: #eee}
input:focus {border-color: #46b8da}

.hidden, .togglable {display: none}
table {border-collapse: collapse; border: 1px solid #ddd; border-radius: 2px; width: 100%}
td, th {padding: 8px; border: 1px solid #ddd; font-size: 14px; line-height: 1.4}
th {font-weight: bold; padding: 12px 8px;}
hr {border-bottom: 0; border-top: 1px solid #ccc; margin: 12px 0}
fieldset {border: 1px solid #ddd; border-radius: 2px; margin: 0}
li.procedure {list-style: none; padding: 25px 15px; border-bottom: 1px solid #e0e0e0}
li.collection {list-style: none; display: block}
.procedure .name {font-weight: bold}
.parameters {margin: 10px 0 16px;}
.api-form button {margin-top: 10px}
.api-result {margin: 20px 0 0}
.red, .required td {color: rgb(255, 95, 0)}
.login-form {margin: 10px 0 30px 40px}
.btn-clear {float: right; margin-right: 20px; background: #46b8da; color: #fff; border: 1px solid #46b8da}
.btn-clear:hover {background: #32abda}
.pagination, .pagination td {border: 0}
textarea {color: #333; line-height: 1.4;}

header {text-align: center; margin: 35px 0 30px}
pre
{
    display: inline-block;
    max-width: calc(100% - 20px);
    background: #f5f5f5;
    padding: 9px;
    border: 1px solid #ccc;
    color: #333;
    overflow: auto;
    border-radius: 2px;
}
.pagination input {width: 80px}
#console {display: none; padding:20px 0 0 5px; position: fixed; right:0}
#console textarea {width: 100%; height: calc(100vh - 95px); font-family: monospace}
#console form {min-height: 32px}
footer {margin: 24px 0 16px}

@media screen and (min-width: 1024px)
{
    body {display: flex}
    #docz {width:calc(50vw - 30px)}
    #console {width:50vw; display: block}
}


text:
mDNS Service
============

Overview
--------

mDNS is a multicast UDP service that is used to provide local network service and host discovery.

mDNS is installed by default on most operating systems or is available as separate package. On ``Mac OS`` it is installed by default and is called ``Bonjour``. Apple releases an installer for ``Windows`` that can be found `on Apple's support page <https://support.apple.com/downloads/bonjour%2520for%2520windows>`_. On ``Linux``, mDNS is provided by `avahi <https://github.com/lathiat/avahi>`_ and is usually installed by default.

mDNS Properties
^^^^^^^^^^^^^^^

    * ``hostname``: the hostname that the device will respond to. If not set, the ``hostname`` will be read from the interface. Example: ``my-esp32`` will resolve to ``my-esp32.local``
    * ``default_instance``: friendly name for your device, like ``Jhon's ESP32 Thing``. If not set, ``hostname`` will be used.

Example method to start mDNS for the STA interface and set ``hostname`` and ``default_instance``:

  ::

    mdns_server_t * mdns = NULL;

    void start_mdns_service()
    {
        //initialize mDNS service on STA interface
        esp_err_t err = mdns_init(TCPIP_ADAPTER_IF_STA, &mdns);
        if (err) {
            printf("MDNS Init failed: %d\n", err);
            return;
        }

        //set hostname
        mdns_set_hostname(mdns, "my-esp32");
        //set default instance
        mdns_set_instance(mdns, "Jhon's ESP32 Thing");
    }

mDNS Services
^^^^^^^^^^^^^

mDNS can advertise information about network services that your device offers. Each service is defined by a few properties.

    * ``service``: (required) service type, prepended with underscore. Some common types can be found `here <http://www.dns-sd.org/serviceTypes.html>`_.
    * ``proto``: (required) protocol that the service runs on, prepended with underscore. Example: ``_tcp`` or ``_udp``
    * ``port``: (required) network port that the service runs on
    * ``instance``: friendly name for your service, like ``Jhon's ESP32 Web Server``. If not defined, ``default_instance`` will be used.
    * ``txt``: ``var=val`` array of strings, used to define properties for your service

Example method to add a few services and different properties:

  ::

    void add_mdns_services()
    {
        //add our services
        mdns_service_add(mdns, "_http", "_tcp", 80);
        mdns_service_add(mdns, "_arduino", "_tcp", 3232);
        mdns_service_add(mdns, "_myservice", "_udp", 1234);

        //NOTE: services must be added before their properties can be set
        //use custom instance for the web server
        mdns_service_instance_set(mdns, "_http", "_tcp", "Jhon's ESP32 Web Server");

        const char * arduTxtData[4] = {
                "board=esp32",
                "tcp_check=no",
                "ssh_upload=no",
                "auth_upload=no"
        };
        //set txt data for service (will free and replace current data)
        mdns_service_txt_set(mdns, "_arduino", "_tcp", 4, arduTxtData);

        //change service port
        mdns_service_port_set(mdns, "_myservice", "_udp", 4321);
    }

mDNS Query
^^^^^^^^^^

mDNS provides methods for browsing for services and resolving host's IP/IPv6 addresses.
    Results are returned as a linked list of ``mdns_result_t`` objects. If the result is from host query,
    it will contain only ``addr`` and ``addrv6`` if found. Service queries will populate all fields
    in a result that were found.

Example method to resolve host IPs:

  ::

    void resolve_mdns_host(const char * hostname)
    {
        printf("mDNS Host Lookup: %s.local\n", hostname);
        //run search for 1000 ms
        if (mdns_query(mdns, hostname, NULL, 1000)) {
            //results were found
            const mdns_result_t * results = mdns_result_get(mdns, 0);
            //itterate through all results
            size_t i = 1;
            while(results) {
                //print result information
                printf("  %u: IP:" IPSTR ", IPv6:" IPV6STR "\n", i++
                    IP2STR(&results->addr), IPV62STR(results->addrv6));
                //load next result. Will be NULL if this was the last one
                results = results->next;
            }
            //free the results from memory
            mdns_result_free(mdns);
        } else {
            //host was not found
            printf("  Host Not Found\n");
        }
    }

Example method to resolve local services:

  ::

    void find_mdns_service(const char * service, const char * proto)
    {
        printf("mDNS Service Lookup: %s.%s\n", service, proto);
        //run search for 1000 ms
        if (mdns_query(mdns, service, proto, 1000)) {
            //results were found
            const mdns_result_t * results = mdns_result_get(mdns, 0);
            //itterate through all results
            size_t i = 1;
            while(results) {
                //print result information
                printf("  %u: hostname:%s, instance:\"%s\", IP:" IPSTR ", IPv6:" IPV6STR ", port:%u, txt:%s\n", i++,
                    (results->host)?results->host:"NULL", (results->instance)?results->instance:"NULL",
                    IP2STR(&results->addr), IPV62STR(results->addrv6),
                    results->port, (results->txt)?results->txt:"\r");
                //load next result. Will be NULL if this was the last one
                results = results->next;
            }
            //free the results from memory
            mdns_result_free(mdns);
        } else {
            //service was not found
            printf("  Service Not Found\n");
        }
    }

Example of using the methods above:

  ::

    void my_app_some_method(){
        //search for esp32-mdns.local
        resolve_mdns_host("esp32-mdns");

        //search for HTTP servers
        find_mdns_service("_http", "_tcp");
        //or file servers
        find_mdns_service("_smb", "_tcp"); //windows sharing
        find_mdns_service("_afpovertcp", "_tcp"); //apple sharing
        find_mdns_service("_nfs", "_tcp"); //NFS server
        find_mdns_service("_ftp", "_tcp"); //FTP server
        //or networked printer
        find_mdns_service("_printer", "_tcp");
        find_mdns_service("_ipp", "_tcp");
    }

Application Example
-------------------

mDNS server/scanner example: :example:`protocols/mdns`.

API Reference
-------------

Header Files
^^^^^^^^^^^^

  * :component_file:`mdns/include/mdns.h`

Macros
^^^^^^

Type Definitions
^^^^^^^^^^^^^^^^

.. doxygentypedef:: mdns_server_t
.. doxygentypedef:: mdns_result_t

Enumerations
^^^^^^^^^^^^

Structures
^^^^^^^^^^

.. doxygenstruct:: mdns_result_s
    :members:

Functions
^^^^^^^^^

.. doxygenfunction:: mdns_init
.. doxygenfunction:: mdns_free
.. doxygenfunction:: mdns_set_hostname
.. doxygenfunction:: mdns_set_instance
.. doxygenfunction:: mdns_service_add
.. doxygenfunction:: mdns_service_remove
.. doxygenfunction:: mdns_service_instance_set
.. doxygenfunction:: mdns_service_txt_set
.. doxygenfunction:: mdns_service_port_set
.. doxygenfunction:: mdns_service_remove_all
.. doxygenfunction:: mdns_query
.. doxygenfunction:: mdns_query_end
.. doxygenfunction:: mdns_result_get_count
.. doxygenfunction:: mdns_result_get
.. doxygenfunction:: mdns_result_free


text:
  {{ label }}

    <button id="{{ id }}" name="{{ id }}" class='btn {{ buttontype }}'>{{ buttonlabel }}</button>


text:
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc.  All rights reserved.
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

package com.github.os72.protobuf241;

import protobuf_unittest.UnittestOptimizeFor.TestOptimizedForSize;
import protobuf_unittest.UnittestProto;
import protobuf_unittest.UnittestProto.ForeignMessage;
import protobuf_unittest.UnittestProto.TestAllExtensions;
import protobuf_unittest.UnittestProto.TestAllTypes;
import protobuf_unittest.UnittestProto.TestPackedTypes;
import protobuf_unittest.UnittestProto.TestRequired;
import protobuf_unittest.UnittestProto.TestRequiredForeign;
import protobuf_unittest.UnittestProto.TestUnpackedTypes;

import junit.framework.TestCase;

import java.util.Map;

/**
 * Unit test for {@link AbstractMessage}.
 *
 * @author kenton@google.com Kenton Varda
 */
public class AbstractMessageTest extends TestCase {
  /**
   * Extends AbstractMessage and wraps some other message object.  The methods
   * of the Message interface which aren't explicitly implemented by
   * AbstractMessage are forwarded to the wrapped object.  This allows us to
   * test that AbstractMessage's implementations work even if the wrapped
   * object does not use them.
   */
  private static class AbstractMessageWrapper extends AbstractMessage {
    private final Message wrappedMessage;

    public AbstractMessageWrapper(Message wrappedMessage) {
      this.wrappedMessage = wrappedMessage;
    }

    public Descriptors.Descriptor getDescriptorForType() {
      return wrappedMessage.getDescriptorForType();
    }
    public AbstractMessageWrapper getDefaultInstanceForType() {
      return new AbstractMessageWrapper(
        wrappedMessage.getDefaultInstanceForType());
    }
    public Map<Descriptors.FieldDescriptor, Object> getAllFields() {
      return wrappedMessage.getAllFields();
    }
    public boolean hasField(Descriptors.FieldDescriptor field) {
      return wrappedMessage.hasField(field);
    }
    public Object getField(Descriptors.FieldDescriptor field) {
      return wrappedMessage.getField(field);
    }
    public int getRepeatedFieldCount(Descriptors.FieldDescriptor field) {
      return wrappedMessage.getRepeatedFieldCount(field);
    }
    public Object getRepeatedField(
        Descriptors.FieldDescriptor field, int index) {
      return wrappedMessage.getRepeatedField(field, index);
    }
    public UnknownFieldSet getUnknownFields() {
      return wrappedMessage.getUnknownFields();
    }
    public Builder newBuilderForType() {
      return new Builder(wrappedMessage.newBuilderForType());
    }
    public Builder toBuilder() {
      return new Builder(wrappedMessage.toBuilder());
    }

    static class Builder extends AbstractMessage.Builder<Builder> {
      private final Message.Builder wrappedBuilder;

      public Builder(Message.Builder wrappedBuilder) {
        this.wrappedBuilder = wrappedBuilder;
      }

      public AbstractMessageWrapper build() {
        return new AbstractMessageWrapper(wrappedBuilder.build());
      }
      public AbstractMessageWrapper buildPartial() {
        return new AbstractMessageWrapper(wrappedBuilder.buildPartial());
      }
      public Builder clone() {
        return new Builder(wrappedBuilder.clone());
      }
      public boolean isInitialized() {
        return clone().buildPartial().isInitialized();
      }
      public Descriptors.Descriptor getDescriptorForType() {
        return wrappedBuilder.getDescriptorForType();
      }
      public AbstractMessageWrapper getDefaultInstanceForType() {
        return new AbstractMessageWrapper(
          wrappedBuilder.getDefaultInstanceForType());
      }
      public Map<Descriptors.FieldDescriptor, Object> getAllFields() {
        return wrappedBuilder.getAllFields();
      }
      public Builder newBuilderForField(Descriptors.FieldDescriptor field) {
        return new Builder(wrappedBuilder.newBuilderForField(field));
      }
      public boolean hasField(Descriptors.FieldDescriptor field) {
        return wrappedBuilder.hasField(field);
      }
      public Object getField(Descriptors.FieldDescriptor field) {
        return wrappedBuilder.getField(field);
      }
      public Builder setField(Descriptors.FieldDescriptor field, Object value) {
        wrappedBuilder.setField(field, value);
        return this;
      }
      public Builder clearField(Descriptors.FieldDescriptor field) {
        wrappedBuilder.clearField(field);
        return this;
      }
      public int getRepeatedFieldCount(Descriptors.FieldDescriptor field) {
        return wrappedBuilder.getRepeatedFieldCount(field);
      }
      public Object getRepeatedField(
          Descriptors.FieldDescriptor field, int index) {
        return wrappedBuilder.getRepeatedField(field, index);
      }
      public Builder setRepeatedField(Descriptors.FieldDescriptor field,
                                      int index, Object value) {
        wrappedBuilder.setRepeatedField(field, index, value);
        return this;
      }
      public Builder addRepeatedField(
          Descriptors.FieldDescriptor field, Object value) {
        wrappedBuilder.addRepeatedField(field, value);
        return this;
      }
      public UnknownFieldSet getUnknownFields() {
        return wrappedBuilder.getUnknownFields();
      }
      public Builder setUnknownFields(UnknownFieldSet unknownFields) {
        wrappedBuilder.setUnknownFields(unknownFields);
        return this;
      }
    }
  }

  // =================================================================

  TestUtil.ReflectionTester reflectionTester =
    new TestUtil.ReflectionTester(TestAllTypes.getDescriptor(), null);

  TestUtil.ReflectionTester extensionsReflectionTester =
    new TestUtil.ReflectionTester(TestAllExtensions.getDescriptor(),
                                  TestUtil.getExtensionRegistry());

  public void testClear() throws Exception {
    AbstractMessageWrapper message =
      new AbstractMessageWrapper.Builder(
          TestAllTypes.newBuilder(TestUtil.getAllSet()))
        .clear().build();
    TestUtil.assertClear((TestAllTypes) message.wrappedMessage);
  }

  public void testCopy() throws Exception {
    AbstractMessageWrapper message =
      new AbstractMessageWrapper.Builder(TestAllTypes.newBuilder())
        .mergeFrom(TestUtil.getAllSet()).build();
    TestUtil.assertAllFieldsSet((TestAllTypes) message.wrappedMessage);
  }

  public void testSerializedSize() throws Exception {
    TestAllTypes message = TestUtil.getAllSet();
    Message abstractMessage = new AbstractMessageWrapper(TestUtil.getAllSet());

    assertEquals(message.getSerializedSize(),
                 abstractMessage.getSerializedSize());
  }

  public void testSerialization() throws Exception {
    Message abstractMessage = new AbstractMessageWrapper(TestUtil.getAllSet());

    TestUtil.assertAllFieldsSet(
      TestAllTypes.parseFrom(abstractMessage.toByteString()));

    assertEquals(TestUtil.getAllSet().toByteString(),
                 abstractMessage.toByteString());
  }

  public void testParsing() throws Exception {
    AbstractMessageWrapper.Builder builder =
      new AbstractMessageWrapper.Builder(TestAllTypes.newBuilder());
    AbstractMessageWrapper message =
      builder.mergeFrom(TestUtil.getAllSet().toByteString()).build();
    TestUtil.assertAllFieldsSet((TestAllTypes) message.wrappedMessage);
  }

  public void testPackedSerialization() throws Exception {
    Message abstractMessage =
        new AbstractMessageWrapper(TestUtil.getPackedSet());

    TestUtil.assertPackedFieldsSet(
      TestPackedTypes.parseFrom(abstractMessage.toByteString()));

    assertEquals(TestUtil.getPackedSet().toByteString(),
                 abstractMessage.toByteString());
  }

  public void testPackedParsing() throws Exception {
    AbstractMessageWrapper.Builder builder =
      new AbstractMessageWrapper.Builder(TestPackedTypes.newBuilder());
    AbstractMessageWrapper message =
      builder.mergeFrom(TestUtil.getPackedSet().toByteString()).build();
    TestUtil.assertPackedFieldsSet((TestPackedTypes) message.wrappedMessage);
  }

  public void testUnpackedSerialization() throws Exception {
    Message abstractMessage =
      new AbstractMessageWrapper(TestUtil.getUnpackedSet());

    TestUtil.assertUnpackedFieldsSet(
      TestUnpackedTypes.parseFrom(abstractMessage.toByteString()));

    assertEquals(TestUtil.getUnpackedSet().toByteString(),
                 abstractMessage.toByteString());
  }

  public void testParsePackedToUnpacked() throws Exception {
    AbstractMessageWrapper.Builder builder =
      new AbstractMessageWrapper.Builder(TestUnpackedTypes.newBuilder());
    AbstractMessageWrapper message =
      builder.mergeFrom(TestUtil.getPackedSet().toByteString()).build();
    TestUtil.assertUnpackedFieldsSet(
      (TestUnpackedTypes) message.wrappedMessage);
  }

  public void testParseUnpackedToPacked() throws Exception {
    AbstractMessageWrapper.Builder builder =
      new AbstractMessageWrapper.Builder(TestPackedTypes.newBuilder());
    AbstractMessageWrapper message =
      builder.mergeFrom(TestUtil.getUnpackedSet().toByteString()).build();
    TestUtil.assertPackedFieldsSet((TestPackedTypes) message.wrappedMessage);
  }

  public void testUnpackedParsing() throws Exception {
    AbstractMessageWrapper.Builder builder =
      new AbstractMessageWrapper.Builder(TestUnpackedTypes.newBuilder());
    AbstractMessageWrapper message =
      builder.mergeFrom(TestUtil.getUnpackedSet().toByteString()).build();
    TestUtil.assertUnpackedFieldsSet(
      (TestUnpackedTypes) message.wrappedMessage);
  }

  public void testOptimizedForSize() throws Exception {
    // We're mostly only checking that this class was compiled successfully.
    TestOptimizedForSize message =
      TestOptimizedForSize.newBuilder().setI(1).build();
    message = TestOptimizedForSize.parseFrom(message.toByteString());
    assertEquals(2, message.getSerializedSize());
  }

  // -----------------------------------------------------------------
  // Tests for isInitialized().

  private static final TestRequired TEST_REQUIRED_UNINITIALIZED =
    TestRequired.getDefaultInstance();
  private static final TestRequired TEST_REQUIRED_INITIALIZED =
    TestRequired.newBuilder().setA(1).setB(2).setC(3).build();

  public void testIsInitialized() throws Exception {
    TestRequired.Builder builder = TestRequired.newBuilder();
    AbstractMessageWrapper.Builder abstractBuilder =
      new AbstractMessageWrapper.Builder(builder);

    assertFalse(abstractBuilder.isInitialized());
    builder.setA(1);
    assertFalse(abstractBuilder.isInitialized());
    builder.setB(1);
    assertFalse(abstractBuilder.isInitialized());
    builder.setC(1);
    assertTrue(abstractBuilder.isInitialized());
  }

  public void testForeignIsInitialized() throws Exception {
    TestRequiredForeign.Builder builder = TestRequiredForeign.newBuilder();
    AbstractMessageWrapper.Builder abstractBuilder =
      new AbstractMessageWrapper.Builder(builder);

    assertTrue(abstractBuilder.isInitialized());

    builder.setOptionalMessage(TEST_REQUIRED_UNINITIALIZED);
    assertFalse(abstractBuilder.isInitialized());

    builder.setOptionalMessage(TEST_REQUIRED_INITIALIZED);
    assertTrue(abstractBuilder.isInitialized());

    builder.addRepeatedMessage(TEST_REQUIRED_UNINITIALIZED);
    assertFalse(abstractBuilder.isInitialized());

    builder.setRepeatedMessage(0, TEST_REQUIRED_INITIALIZED);
    assertTrue(abstractBuilder.isInitialized());
  }

  // -----------------------------------------------------------------
  // Tests for mergeFrom

  static final TestAllTypes MERGE_SOURCE =
    TestAllTypes.newBuilder()
      .setOptionalInt32(1)
      .setOptionalString("foo")
      .setOptionalForeignMessage(ForeignMessage.getDefaultInstance())
      .addRepeatedString("bar")
      .build();

  static final TestAllTypes MERGE_DEST =
    TestAllTypes.newBuilder()
      .setOptionalInt64(2)
      .setOptionalString("baz")
      .setOptionalForeignMessage(ForeignMessage.newBuilder().setC(3).build())
      .addRepeatedString("qux")
      .build();

  static final String MERGE_RESULT_TEXT =
      "optional_int32: 1\n" +
      "optional_int64: 2\n" +
      "optional_string: \"foo\"\n" +
      "optional_foreign_message {\n" +
      "  c: 3\n" +
      "}\n" +
      "repeated_string: \"qux\"\n" +
      "repeated_string: \"bar\"\n";

  public void testMergeFrom() throws Exception {
    AbstractMessageWrapper result =
      new AbstractMessageWrapper.Builder(
        TestAllTypes.newBuilder(MERGE_DEST))
      .mergeFrom(MERGE_SOURCE).build();

    assertEquals(MERGE_RESULT_TEXT, result.toString());
  }

  // -----------------------------------------------------------------
  // Tests for equals and hashCode

  public void testEqualsAndHashCode() throws Exception {
    TestAllTypes a = TestUtil.getAllSet();
    TestAllTypes b = TestAllTypes.newBuilder().build();
    TestAllTypes c = TestAllTypes.newBuilder(b).addRepeatedString("x").build();
    TestAllTypes d = TestAllTypes.newBuilder(c).addRepeatedString("y").build();
    TestAllExtensions e = TestUtil.getAllExtensionsSet();
    TestAllExtensions f = TestAllExtensions.newBuilder(e)
        .addExtension(UnittestProto.repeatedInt32Extension, 999).build();

    checkEqualsIsConsistent(a);
    checkEqualsIsConsistent(b);
    checkEqualsIsConsistent(c);
    checkEqualsIsConsistent(d);
    checkEqualsIsConsistent(e);
    checkEqualsIsConsistent(f);

    checkNotEqual(a, b);
    checkNotEqual(a, c);
    checkNotEqual(a, d);
    checkNotEqual(a, e);
    checkNotEqual(a, f);

    checkNotEqual(b, c);
    checkNotEqual(b, d);
    checkNotEqual(b, e);
    checkNotEqual(b, f);

    checkNotEqual(c, d);
    checkNotEqual(c, e);
    checkNotEqual(c, f);

    checkNotEqual(d, e);
    checkNotEqual(d, f);

    checkNotEqual(e, f);

    // Deserializing into the TestEmptyMessage such that every field
    // is an {@link UnknownFieldSet.Field}.
    UnittestProto.TestEmptyMessage eUnknownFields =
        UnittestProto.TestEmptyMessage.parseFrom(e.toByteArray());
    UnittestProto.TestEmptyMessage fUnknownFields =
        UnittestProto.TestEmptyMessage.parseFrom(f.toByteArray());
    checkNotEqual(eUnknownFields, fUnknownFields);
    checkEqualsIsConsistent(eUnknownFields);
    checkEqualsIsConsistent(fUnknownFields);

    // Subsequent reconstitutions should be identical
    UnittestProto.TestEmptyMessage eUnknownFields2 =
        UnittestProto.TestEmptyMessage.parseFrom(e.toByteArray());
    checkEqualsIsConsistent(eUnknownFields, eUnknownFields2);
  }

  /**
   * Asserts that the given proto has symetric equals and hashCode methods.
   */
  private void checkEqualsIsConsistent(Message message) {
    // Object should be equal to itself.
    assertEquals(message, message);

    // Object should be equal to a dynamic copy of itself.
    DynamicMessage dynamic = DynamicMessage.newBuilder(message).build();
    checkEqualsIsConsistent(message, dynamic);
  }

  /**
   * Asserts that the given protos are equal and have the same hash code.
   */
  private void checkEqualsIsConsistent(Message message1, Message message2) {
    assertEquals(message1, message2);
    assertEquals(message2, message1);
    assertEquals(message2.hashCode(), message1.hashCode());
  }

  /**
   * Asserts that the given protos are not equal and have different hash codes.
   *
   * @warning It's valid for non-equal objects to have the same hash code, so
   *   this test is stricter than it needs to be. However, this should happen
   *   relatively rarely.
   */
  private void checkNotEqual(Message m1, Message m2) {
    String equalsError = String.format("%s should not be equal to %s", m1, m2);
    assertFalse(equalsError, m1.equals(m2));
    assertFalse(equalsError, m2.equals(m1));

    assertFalse(
        String.format("%s should have a different hash code from %s", m1, m2),
        m1.hashCode() == m2.hashCode());
  }
}


text:
<?php

namespace Joli\Jane\OpenApi\Tests\Expected\Resource;

use Joli\Jane\OpenApi\Runtime\Client\QueryParam;
use Joli\Jane\OpenApi\Runtime\Client\Resource;

class TestResource extends Resource
{
    /**
     * @param string $testString
     * @param array  $parameters List of parameters
     * @param string $fetch      Fetch mode (object or response)
     *
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function testSimpleBodyParameter($testString, $parameters = [], $fetch = self::FETCH_OBJECT)
    {
        $queryParam = new QueryParam();
        $url        = '/test-simple';
        $url        = $url . ('?' . $queryParam->buildQueryString($parameters));
        $headers    = array_merge(['Host' => 'localhost'], $queryParam->buildHeaders($parameters));
        $body       = $testString;
        $request    = $this->messageFactory->createRequest('POST', $url, $headers, $body);
        $promise    = $this->httpClient->sendAsyncRequest($request);
        if (self::FETCH_PROMISE === $fetch) {
            return $promise;
        }
        $response = $promise->wait();

        return $response;
    }

    /**
     * @param \Joli\Jane\OpenApi\Tests\Expected\Model\Schema $testObject
     * @param array                                          $parameters List of parameters
     * @param string                                         $fetch      Fetch mode (object or response)
     *
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function testObjectBodyParameter(\Joli\Jane\OpenApi\Tests\Expected\Model\Schema $testObject, $parameters = [], $fetch = self::FETCH_OBJECT)
    {
        $queryParam = new QueryParam();
        $url        = '/test-object';
        $url        = $url . ('?' . $queryParam->buildQueryString($parameters));
        $headers    = array_merge(['Host' => 'localhost'], $queryParam->buildHeaders($parameters));
        $body       = $this->serializer->serialize($testObject, 'json');
        $request    = $this->messageFactory->createRequest('POST', $url, $headers, $body);
        $promise    = $this->httpClient->sendAsyncRequest($request);
        if (self::FETCH_PROMISE === $fetch) {
            return $promise;
        }
        $response = $promise->wait();

        return $response;
    }

    /**
     * @param array  $testObjectList
     * @param array  $parameters     List of parameters
     * @param string $fetch          Fetch mode (object or response)
     *
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function testObjectListBodyParameter(array $testObjectList, $parameters = [], $fetch = self::FETCH_OBJECT)
    {
        $queryParam = new QueryParam();
        $url        = '/test-object-list';
        $url        = $url . ('?' . $queryParam->buildQueryString($parameters));
        $headers    = array_merge(['Host' => 'localhost'], $queryParam->buildHeaders($parameters));
        $body       = $testObjectList;
        $request    = $this->messageFactory->createRequest('POST', $url, $headers, $body);
        $promise    = $this->httpClient->sendAsyncRequest($request);
        if (self::FETCH_PROMISE === $fetch) {
            return $promise;
        }
        $response = $promise->wait();

        return $response;
    }
}