text:
package com.orientechnologies.orient.core.db.record;

import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNotNull;

import java.util.HashSet;
import java.util.Set;

import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.record.impl.ODocument;

public class ORecordLazySetPeristentTest {

  private ODatabaseDocument db;

  @BeforeTest
  public void init() throws Exception {
    String url = "memory:" + ORecordLazySetPeristentTest.class.getSimpleName();
    db = new ODatabaseDocumentTx(url);
    db = db.create();
  }

  @Test
  public void test1() {
    ORID orid1;
    ORID orid2;

    db.begin();
    {
      ODocument doc1 = new ODocument();
      doc1.field("linkset", new HashSet<ODocument>());
      Set<ODocument> linkset = doc1.field("linkset");
      ODocument doc2 = new ODocument();
      orid2 = doc2.save().getIdentity();
      linkset.add(doc2);
      orid1 = doc1.save().getIdentity();
      assertNotNull(orid1);
    }
    db.commit();

    db.begin();
    {
      ODocument doc1 = db.load(orid1);
      assertNotNull(doc1);
      Set<ODocument> linkset = doc1.field("linkset");
      assertNotNull(linkset);
      assertEquals(1, linkset.size());

      ODocument doc2 = db.load(orid2);
      assertNotNull(doc2);

      assertEquals(orid2, linkset.iterator().next().getIdentity());
      assertEquals(orid2, doc2.getIdentity());

      linkset.remove(doc2);
      assertEquals(0, linkset.size()); // AssertionError: expected:<0> but was:<1>
    }
    db.commit();
  }

  @Test
  public void test2() {
    ORID orid1;
    ORID orid2;

    db.begin();
    {
      ODocument doc1 = new ODocument();
      doc1.field("linkset", new HashSet<OIdentifiable>());
      Set<OIdentifiable> linkset = doc1.field("linkset");
      ODocument doc2 = new ODocument();
      orid2 = doc2.save().getIdentity();
      linkset.add(doc2);
      orid1 = doc1.save().getIdentity();
      assertNotNull(orid1);
    }
    db.commit();

    db.begin();
    {
      ODocument doc1 = db.load(orid1);
      assertNotNull(doc1);
      Set<OIdentifiable> linkset = doc1.field("linkset");

      assertNotNull(linkset);
      assertEquals(1, linkset.size());

      ODocument doc2 = db.load(orid2);
      assertNotNull(doc2);

      assertEquals(orid2, linkset.iterator().next().getIdentity());
      assertEquals(orid2, doc2.getIdentity());

      linkset.remove(doc2);
      assertEquals(0, linkset.size()); // AssertionError: expected:<0> but was:<1>
    }
    db.commit();
  }

  @AfterTest
  public void close() {
    if (db != null) {
      db.drop();
    }
  }

}


text:
<?php
$dzsap_config = array(
    'type' => 'normal',
    'url_portalphp' => 'portal.php',
    'mysql_server' => 'localhost',
    'mysql_user' => 'root',
    'mysql_password' => 'root',
    'mysql_table' => 'zoomsounds',
    'enable_likes' => 'on',
    'enable_views' => 'on',
    'enable_rates' => 'on',
    'str_likes_part1' => '
Like
',
    'str_views' => '
{{get_plays}} plays
',
    'str_likes_part2' => '
{{get_likes}} likes
',
    'str_rates' => '
{{get_rates}} rates
',
    'soundcloud_api_key' => '',
    'skinwave_comments_enable' => 'on',
            'dzsap_tab_share_content' => '

Tweet

Embed

{{embedcode}}

',

);

redpajama_set_name: RedPajamaGithub


text:
#import "AAPLSearchShowResultsInSourceViewController.h"

@interface AAPLSearchShowResultsInSourceViewController ()

@property (nonatomic, strong) UISearchController *searchController;

@end

@implementation AAPLSearchShowResultsInSourceViewController

#pragma mark - View Life Cycle

- (void)viewDidLoad {
    [super viewDidLoad];

    // Create the search controller, but we'll make sure that this AAPLSearchShowResultsInSourceViewController
    // performs the results updating.
    self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
    self.searchController.searchResultsUpdater = self;
    self.searchController.dimsBackgroundDuringPresentation = NO;

    // Make sure the that the search bar is visible within the navigation bar.
    [self.searchController.searchBar sizeToFit];

    // Include the search controller's search bar within the table's header view.
    self.tableView.tableHeaderView = self.searchController.searchBar;

    self.definesPresentationContext = YES;
}

@end


text:
namespace file_util {

namespace {

const DWORD kFileShareAll =
    FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;

}  // namespace

bool AbsolutePath(FilePath* path) {
  base::ThreadRestrictions::AssertIOAllowed();
  wchar_t file_path_buf[MAX_PATH];
  if (!_wfullpath(file_path_buf, path->value().c_str(), MAX_PATH))
    return false;
  *path = FilePath(file_path_buf);
  return true;
}

int CountFilesCreatedAfter(const FilePath& path,
                           const base::Time& comparison_time) {
  base::ThreadRestrictions::AssertIOAllowed();

  int file_count = 0;
  FILETIME comparison_filetime(comparison_time.ToFileTime());

  WIN32_FIND_DATA find_file_data;
  // All files in given dir
  std::wstring filename_spec = path.Append(L"*").value();
  HANDLE find_handle = FindFirstFile(filename_spec.c_str(), &find_file_data);
  if (find_handle != INVALID_HANDLE_VALUE) {
    do {
      // Don't count current or parent directories.
      if ((wcscmp(find_file_data.cFileName, L"..") == 0) ||
          (wcscmp(find_file_data.cFileName, L".") == 0))
        continue;

      long result = CompareFileTime(&find_file_data.ftCreationTime,  // NOLINT
                                    &comparison_filetime);
      // File was created after or on comparison time
      if ((result == 1) || (result == 0))
        ++file_count;
    } while (FindNextFile(find_handle,  &find_file_data));
    FindClose(find_handle);
  }

  return file_count;
}

bool Delete(const FilePath& path, bool recursive) {
  base::ThreadRestrictions::AssertIOAllowed();

  if (path.value().length() >= MAX_PATH)
    return false;

  if (!recursive) {
    // If not recursing, then first check to see if |path| is a directory.
    // If it is, then remove it with RemoveDirectory.
    base::PlatformFileInfo file_info;
    if (GetFileInfo(path, &file_info) && file_info.is_directory)
      return RemoveDirectory(path.value().c_str()) != 0;

    // Otherwise, it's a file, wildcard or non-existant. Try DeleteFile first
    // because it should be faster. If DeleteFile fails, then we fall through
    // to SHFileOperation, which will do the right thing.
    if (DeleteFile(path.value().c_str()) != 0)
      return true;
  }

  // SHFILEOPSTRUCT wants the path to be terminated with two NULLs,
  // so we have to use wcscpy because wcscpy_s writes non-NULLs
  // into the rest of the buffer.
  wchar_t double_terminated_path[MAX_PATH + 1] = {0};
#pragma warning(suppress:4996)  // don't complain about wcscpy deprecation
  if (g_bug108724_debug)
    LOG(WARNING) << "copying ";
  wcscpy(double_terminated_path, path.value().c_str());

  SHFILEOPSTRUCT file_operation = {0};
  file_operation.wFunc = FO_DELETE;
  file_operation.pFrom = double_terminated_path;
  file_operation.fFlags = FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION;
  if (!recursive)
    file_operation.fFlags |= FOF_NORECURSION | FOF_FILESONLY;
  if (g_bug108724_debug)
    LOG(WARNING) << "Performing shell operation";
  int err = SHFileOperation(&file_operation);
  if (g_bug108724_debug)
    LOG(WARNING) << "Done: " << err;

  // Since we're passing flags to the operation telling it to be silent,
  // it's possible for the operation to be aborted/cancelled without err
  // being set (although MSDN doesn't give any scenarios for how this can
  // happen).  See MSDN for SHFileOperation and SHFILEOPTSTRUCT.
  if (file_operation.fAnyOperationsAborted)
    return false;

  // Some versions of Windows return ERROR_FILE_NOT_FOUND (0x2) when deleting
  // an empty directory and some return 0x402 when they should be returning
  // ERROR_FILE_NOT_FOUND. MSDN says Vista and up won't return 0x402.
  return (err == 0 || err == ERROR_FILE_NOT_FOUND || err == 0x402);
}

bool DeleteAfterReboot(const FilePath& path) {
  base::ThreadRestrictions::AssertIOAllowed();

  if (path.value().length() >= MAX_PATH)
    return false;

  return MoveFileEx(path.value().c_str(), NULL,
                    MOVEFILE_DELAY_UNTIL_REBOOT |
                        MOVEFILE_REPLACE_EXISTING) != FALSE;
}

bool Move(const FilePath& from_path, const FilePath& to_path) {
  base::ThreadRestrictions::AssertIOAllowed();

  // NOTE: I suspect we could support longer paths, but that would involve
  // analyzing all our usage of files.
  if (from_path.value().length() >= MAX_PATH ||
      to_path.value().length() >= MAX_PATH) {
    return false;
  }
  if (MoveFileEx(from_path.value().c_str(), to_path.value().c_str(),
                 MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING) != 0)
    return true;

  // Keep the last error value from MoveFileEx around in case the below
  // fails.
  bool ret = false;
  DWORD last_error = ::GetLastError();

  if (DirectoryExists(from_path)) {
    // MoveFileEx fails if moving directory across volumes. We will simulate
    // the move by using Copy and Delete. Ideally we could check whether
    // from_path and to_path are indeed in different volumes.
    ret = CopyAndDeleteDirectory(from_path, to_path);
  }

  if (!ret) {
    // Leave a clue about what went wrong so that it can be (at least) picked
    // up by a PLOG entry.
    ::SetLastError(last_error);
  }

  return ret;
}

bool ReplaceFile(const FilePath& from_path, const FilePath& to_path) {
  base::ThreadRestrictions::AssertIOAllowed();
  // Try a simple move first.  It will only succeed when |to_path| doesn't
  // already exist.
  if (::MoveFile(from_path.value().c_str(), to_path.value().c_str()))
    return true;
  // Try the full-blown replace if the move fails, as ReplaceFile will only
  // succeed when |to_path| does exist. When writing to a network share, we may
  // not be able to change the ACLs. Ignore ACL errors then
  // (REPLACEFILE_IGNORE_MERGE_ERRORS).
  if (::ReplaceFile(to_path.value().c_str(), from_path.value().c_str(), NULL,
                    REPLACEFILE_IGNORE_MERGE_ERRORS, NULL, NULL)) {
    return true;
  }
  return false;
}

bool CopyFile(const FilePath& from_path, const FilePath& to_path) {
  base::ThreadRestrictions::AssertIOAllowed();

  // NOTE: I suspect we could support longer paths, but that would involve
  // analyzing all our usage of files.
  if (from_path.value().length() >= MAX_PATH ||
      to_path.value().length() >= MAX_PATH) {
    return false;
  }
  return (::CopyFile(from_path.value().c_str(), to_path.value().c_str(),
                     false) != 0);
}

bool ShellCopy(const FilePath& from_path, const FilePath& to_path,
               bool recursive) {
  base::ThreadRestrictions::AssertIOAllowed();

  // NOTE: I suspect we could support longer paths, but that would involve
  // analyzing all our usage of files.
  if (from_path.value().length() >= MAX_PATH ||
      to_path.value().length() >= MAX_PATH) {
    return false;
  }

  // SHFILEOPSTRUCT wants the path to be terminated with two NULLs,
  // so we have to use wcscpy because wcscpy_s writes non-NULLs
  // into the rest of the buffer.
  wchar_t double_terminated_path_from[MAX_PATH + 1] = {0};
  wchar_t double_terminated_path_to[MAX_PATH + 1] = {0};
#pragma warning(suppress:4996)  // don't complain about wcscpy deprecation
  wcscpy(double_terminated_path_from, from_path.value().c_str());
#pragma warning(suppress:4996)  // don't complain about wcscpy deprecation
  wcscpy(double_terminated_path_to, to_path.value().c_str());

  SHFILEOPSTRUCT file_operation = {0};
  file_operation.wFunc = FO_COPY;
  file_operation.pFrom = double_terminated_path_from;
  file_operation.pTo = double_terminated_path_to;
  file_operation.fFlags = FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION |
                          FOF_NOCONFIRMMKDIR;
  if (!recursive)
    file_operation.fFlags |= FOF_NORECURSION | FOF_FILESONLY;

  return (SHFileOperation(&file_operation) == 0);
}

bool CopyDirectory(const FilePath& from_path, const FilePath& to_path,
                   bool recursive) {
  base::ThreadRestrictions::AssertIOAllowed();

  if (recursive)
    return ShellCopy(from_path, to_path, true);

  // The following code assumes that from path is a directory.
  DCHECK(DirectoryExists(from_path));

  // Instead of creating a new directory, we copy the old one to include the
  // security information of the folder as part of the copy.
  if (!PathExists(to_path)) {
    // Except that Vista fails to do that, and instead do a recursive copy if
    // the target directory doesn't exist.
    if (base::win::GetVersion() >= base::win::VERSION_VISTA)
      CreateDirectory(to_path);
    else
      ShellCopy(from_path, to_path, false);
  }

  FilePath directory = from_path.Append(L"*.*");
  return ShellCopy(directory, to_path, false);
}

bool CopyAndDeleteDirectory(const FilePath& from_path,
                            const FilePath& to_path) {
  base::ThreadRestrictions::AssertIOAllowed();
  if (CopyDirectory(from_path, to_path, true)) {
    if (Delete(from_path, true)) {
      return true;
    }
    // Like Move, this function is not transactional, so we just
    // leave the copied bits behind if deleting from_path fails.
    // If to_path exists previously then we have already overwritten
    // it by now, we don't get better off by deleting the new bits.
  }
  return false;
}

bool PathExists(const FilePath& path) {
  base::ThreadRestrictions::AssertIOAllowed();
  return (GetFileAttributes(path.value().c_str()) != INVALID_FILE_ATTRIBUTES);
}

bool PathIsWritable(const FilePath& path) {
  base::ThreadRestrictions::AssertIOAllowed();
  HANDLE dir =
      CreateFile(path.value().c_str(), FILE_ADD_FILE, kFileShareAll,
                 NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);

  if (dir == INVALID_HANDLE_VALUE)
    return false;

  CloseHandle(dir);
  return true;
}

bool DirectoryExists(const FilePath& path) {
  base::ThreadRestrictions::AssertIOAllowed();
  DWORD fileattr = GetFileAttributes(path.value().c_str());
  if (fileattr != INVALID_FILE_ATTRIBUTES)
    return (fileattr & FILE_ATTRIBUTE_DIRECTORY) != 0;
  return false;
}

bool GetFileCreationLocalTimeFromHandle(HANDLE file_handle,
                                        LPSYSTEMTIME creation_time) {
  base::ThreadRestrictions::AssertIOAllowed();
  if (!file_handle)
    return false;

  FILETIME utc_filetime;
  if (!GetFileTime(file_handle, &utc_filetime, NULL, NULL))
    return false;

  FILETIME local_filetime;
  if (!FileTimeToLocalFileTime(&utc_filetime, &local_filetime))
    return false;

  return !!FileTimeToSystemTime(&local_filetime, creation_time);
}

bool GetFileCreationLocalTime(const std::wstring& filename,
                              LPSYSTEMTIME creation_time) {
  base::ThreadRestrictions::AssertIOAllowed();
  base::win::ScopedHandle file_handle(
      CreateFile(filename.c_str(), GENERIC_READ, kFileShareAll, NULL,
                 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL));
  return GetFileCreationLocalTimeFromHandle(file_handle.Get(), creation_time);
}

bool ResolveShortcut(FilePath* path) {
  base::ThreadRestrictions::AssertIOAllowed();

  HRESULT result;
  base::win::ScopedComPtr<IShellLink> i_shell_link;
  bool is_resolved = false;

  // Get pointer to the IShellLink interface
  result = i_shell_link.CreateInstance(CLSID_ShellLink, NULL,
                                       CLSCTX_INPROC_SERVER);
  if (SUCCEEDED(result)) {
    base::win::ScopedComPtr<IPersistFile> persist;
    // Query IShellLink for the IPersistFile interface
    result = persist.QueryFrom(i_shell_link);
    if (SUCCEEDED(result)) {
      WCHAR temp_path[MAX_PATH];
      // Load the shell link
      result = persist->Load(path->value().c_str(), STGM_READ);
      if (SUCCEEDED(result)) {
        // Try to find the target of a shortcut
        result = i_shell_link->Resolve(0, SLR_NO_UI);
        if (SUCCEEDED(result)) {
          result = i_shell_link->GetPath(temp_path, MAX_PATH,
                                  NULL, SLGP_UNCPRIORITY);
          *path = FilePath(temp_path);
          is_resolved = true;
        }
      }
    }
  }

  return is_resolved;
}

bool CreateShortcutLink(const wchar_t *source, const wchar_t *destination,
                        const wchar_t *working_dir, const wchar_t *arguments,
                        const wchar_t *description, const wchar_t *icon,
                        int icon_index, const wchar_t* app_id) {
  base::ThreadRestrictions::AssertIOAllowed();

  // Length of description must be less than MAX_PATH.
  DCHECK(lstrlen(description) < MAX_PATH);

  base::win::ScopedComPtr<IShellLink> i_shell_link;
  base::win::ScopedComPtr<IPersistFile> i_persist_file;

  // Get pointer to the IShellLink interface
  HRESULT result = i_shell_link.CreateInstance(CLSID_ShellLink, NULL,
                                               CLSCTX_INPROC_SERVER);
  if (FAILED(result))
    return false;

  // Query IShellLink for the IPersistFile interface
  result = i_persist_file.QueryFrom(i_shell_link);
  if (FAILED(result))
    return false;

  if (FAILED(i_shell_link->SetPath(source)))
    return false;

  if (working_dir && FAILED(i_shell_link->SetWorkingDirectory(working_dir)))
    return false;

  if (arguments && FAILED(i_shell_link->SetArguments(arguments)))
    return false;

  if (description && FAILED(i_shell_link->SetDescription(description)))
    return false;

  if (icon && FAILED(i_shell_link->SetIconLocation(icon, icon_index)))
    return false;

  if (app_id && (base::win::GetVersion() >= base::win::VERSION_WIN7)) {
    base::win::ScopedComPtr<IPropertyStore> property_store;
    if (FAILED(property_store.QueryFrom(i_shell_link)))
      return false;

    if (!base::win::SetAppIdForPropertyStore(property_store, app_id))
      return false;
  }

  result = i_persist_file->Save(destination, TRUE);
  return SUCCEEDED(result);
}

bool UpdateShortcutLink(const wchar_t *source, const wchar_t *destination,
                        const wchar_t *working_dir, const wchar_t *arguments,
                        const wchar_t *description, const wchar_t *icon,
                        int icon_index, const wchar_t* app_id) {
  base::ThreadRestrictions::AssertIOAllowed();

  // Length of arguments and description must be less than MAX_PATH.
  DCHECK(lstrlen(arguments) < MAX_PATH);
  DCHECK(lstrlen(description) < MAX_PATH);

  // Get pointer to the IPersistFile interface and load existing link
  base::win::ScopedComPtr<IShellLink> i_shell_link;
  if (FAILED(i_shell_link.CreateInstance(CLSID_ShellLink, NULL,
                                         CLSCTX_INPROC_SERVER)))
    return false;

  base::win::ScopedComPtr<IPersistFile> i_persist_file;
  if (FAILED(i_persist_file.QueryFrom(i_shell_link)))
    return false;

  if (FAILED(i_persist_file->Load(destination, STGM_READWRITE)))
    return false;

  if (source && FAILED(i_shell_link->SetPath(source)))
    return false;

  if (working_dir && FAILED(i_shell_link->SetWorkingDirectory(working_dir)))
    return false;

  if (arguments && FAILED(i_shell_link->SetArguments(arguments)))
    return false;

  if (description && FAILED(i_shell_link->SetDescription(description)))
    return false;

  if (icon && FAILED(i_shell_link->SetIconLocation(icon, icon_index)))
    return false;

  if (app_id && base::win::GetVersion() >= base::win::VERSION_WIN7) {
    base::win::ScopedComPtr<IPropertyStore> property_store;
    if (FAILED(property_store.QueryFrom(i_shell_link)))
      return false;

    if (!base::win::SetAppIdForPropertyStore(property_store, app_id))
      return false;
  }

  HRESULT result = i_persist_file->Save(destination, TRUE);

  i_persist_file.Release();
  i_shell_link.Release();

  // If we successfully updated the icon, notify the shell that we have done so.
  if (SUCCEEDED(result)) {
    SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST | SHCNF_FLUSHNOWAIT,
                   NULL, NULL);
  }

  return SUCCEEDED(result);
}

bool TaskbarPinShortcutLink(const wchar_t* shortcut) {
  base::ThreadRestrictions::AssertIOAllowed();

  // "Pin to taskbar" is only supported after Win7.
  if (base::win::GetVersion() < base::win::VERSION_WIN7)
    return false;

  int result = reinterpret_cast<int>(ShellExecute(NULL, L"taskbarpin", shortcut,
      NULL, NULL, 0));
  return result > 32;
}

bool TaskbarUnpinShortcutLink(const wchar_t* shortcut) {
  base::ThreadRestrictions::AssertIOAllowed();

  // "Unpin from taskbar" is only supported after Win7.
  if (base::win::GetVersion() < base::win::VERSION_WIN7)
    return false;

  int result = reinterpret_cast<int>(ShellExecute(NULL, L"taskbarunpin",
      shortcut, NULL, NULL, 0));
  return result > 32;
}

bool GetTempDir(FilePath* path) {
  base::ThreadRestrictions::AssertIOAllowed();

  wchar_t temp_path[MAX_PATH + 1];
  DWORD path_len = ::GetTempPath(MAX_PATH, temp_path);
  if (path_len >= MAX_PATH || path_len <= 0)
    return false;
  // TODO(evanm): the old behavior of this function was to always strip the
  // trailing slash.  We duplicate this here, but it shouldn't be necessary
  // when everyone is using the appropriate FilePath APIs.
  *path = FilePath(temp_path).StripTrailingSeparators();
  return true;
}

bool GetShmemTempDir(FilePath* path, bool executable) {
  return GetTempDir(path);
}

bool CreateTemporaryFile(FilePath* path) {
  base::ThreadRestrictions::AssertIOAllowed();

  FilePath temp_file;

  if (!GetTempDir(path))
    return false;

  if (CreateTemporaryFileInDir(*path, &temp_file)) {
    *path = temp_file;
    return true;
  }

  return false;
}

FILE* CreateAndOpenTemporaryShmemFile(FilePath* path, bool executable) {
  base::ThreadRestrictions::AssertIOAllowed();
  return CreateAndOpenTemporaryFile(path);
}

// On POSIX we have semantics to create and open a temporary file
// atomically.
// TODO(jrg): is there equivalent call to use on Windows instead of
// going 2-step?
FILE* CreateAndOpenTemporaryFileInDir(const FilePath& dir, FilePath* path) {
  base::ThreadRestrictions::AssertIOAllowed();
  if (!CreateTemporaryFileInDir(dir, path)) {
    return NULL;
  }
  // Open file in binary mode, to avoid problems with fwrite. On Windows
  // it replaces \n's with \r\n's, which may surprise you.
  // Reference: http://msdn.microsoft.com/en-us/library/h9t88zwz(VS.71).aspx
  return OpenFile(*path, "wb+");
}

bool CreateTemporaryFileInDir(const FilePath& dir,
                              FilePath* temp_file) {
  base::ThreadRestrictions::AssertIOAllowed();

  wchar_t temp_name[MAX_PATH + 1];

  if (!GetTempFileName(dir.value().c_str(), L"", 0, temp_name)) {
    DPLOG(WARNING) << "Failed to get temporary file name in " << dir.value();
    return false;
  }

  DWORD path_len = GetLongPathName(temp_name, temp_name, MAX_PATH);
  if (path_len > MAX_PATH + 1 || path_len == 0) {
    DPLOG(WARNING) << "Failed to get long path name for " << temp_name;
    return false;
  }

  std::wstring temp_file_str;
  temp_file_str.assign(temp_name, path_len);
  *temp_file = FilePath(temp_file_str);
  return true;
}

bool CreateTemporaryDirInDir(const FilePath& base_dir,
                             const FilePath::StringType& prefix,
                             FilePath* new_dir) {
  base::ThreadRestrictions::AssertIOAllowed();

  FilePath path_to_create;
  srand(static_cast<uint32>(time(NULL)));

  for (int count = 0; count < 50; ++count) {
    // Try create a new temporary directory with random generated name. If
    // the one exists, keep trying another path name until we reach some limit.
    string16 new_dir_name;
    new_dir_name.assign(prefix);
    new_dir_name.append(base::IntToString16(rand() % kint16max));

    path_to_create = base_dir.Append(new_dir_name);
    if (::CreateDirectory(path_to_create.value().c_str(), NULL)) {
      *new_dir = path_to_create;
      return true;
    }
  }

  return false;
}

bool CreateNewTempDirectory(const FilePath::StringType& prefix,
                            FilePath* new_temp_path) {
  base::ThreadRestrictions::AssertIOAllowed();

  FilePath system_temp_dir;
  if (!GetTempDir(&system_temp_dir))
    return false;

  return CreateTemporaryDirInDir(system_temp_dir, prefix, new_temp_path);
}

bool CreateDirectory(const FilePath& full_path) {
  base::ThreadRestrictions::AssertIOAllowed();

  // If the path exists, we've succeeded if it's a directory, failed otherwise.
  const wchar_t* full_path_str = full_path.value().c_str();
  DWORD fileattr = ::GetFileAttributes(full_path_str);
  if (fileattr != INVALID_FILE_ATTRIBUTES) {
    if ((fileattr & FILE_ATTRIBUTE_DIRECTORY) != 0) {
      DVLOG(1) << "CreateDirectory(" << full_path_str << "), "
               << "directory already exists.";
      return true;
    }
    DLOG(WARNING) << "CreateDirectory(" << full_path_str << "), "
                  << "conflicts with existing file.";
    return false;
  }

  // Invariant:  Path does not exist as file or directory.

  // Attempt to create the parent recursively.  This will immediately return
  // true if it already exists, otherwise will create all required parent
  // directories starting with the highest-level missing parent.
  FilePath parent_path(full_path.DirName());
  if (parent_path.value() == full_path.value()) {
    return false;
  }
  if (!CreateDirectory(parent_path)) {
    DLOG(WARNING) << "Failed to create one of the parent directories.";
    return false;
  }

  if (!::CreateDirectory(full_path_str, NULL)) {
    DWORD error_code = ::GetLastError();
    if (error_code == ERROR_ALREADY_EXISTS && DirectoryExists(full_path)) {
      // This error code ERROR_ALREADY_EXISTS doesn't indicate whether we
      // were racing with someone creating the same directory, or a file
      // with the same path.  If DirectoryExists() returns true, we lost the
      // race to create the same directory.
      return true;
    } else {
      DLOG(WARNING) << "Failed to create directory " << full_path_str
                    << ", last error is " << error_code << ".";
      return false;
    }
  } else {
    return true;
  }
}

// TODO(rkc): Work out if we want to handle NTFS junctions here or not, handle
// them if we do decide to.
bool IsLink(const FilePath& file_path) {
  return false;
}

bool GetFileInfo(const FilePath& file_path, base::PlatformFileInfo* results) {
  base::ThreadRestrictions::AssertIOAllowed();

  WIN32_FILE_ATTRIBUTE_DATA attr;
  if (!GetFileAttributesEx(file_path.value().c_str(),
                           GetFileExInfoStandard, &attr)) {
    return false;
  }

  ULARGE_INTEGER size;
  size.HighPart = attr.nFileSizeHigh;
  size.LowPart = attr.nFileSizeLow;
  results->size = size.QuadPart;

  results->is_directory =
      (attr.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
  results->last_modified = base::Time::FromFileTime(attr.ftLastWriteTime);
  results->last_accessed = base::Time::FromFileTime(attr.ftLastAccessTime);
  results->creation_time = base::Time::FromFileTime(attr.ftCreationTime);

  return true;
}

FILE* OpenFile(const FilePath& filename, const char* mode) {
  base::ThreadRestrictions::AssertIOAllowed();
  std::wstring w_mode = ASCIIToWide(std::string(mode));
  return _wfsopen(filename.value().c_str(), w_mode.c_str(), _SH_DENYNO);
}

FILE* OpenFile(const std::string& filename, const char* mode) {
  base::ThreadRestrictions::AssertIOAllowed();
  return _fsopen(filename.c_str(), mode, _SH_DENYNO);
}

int ReadFile(const FilePath& filename, char* data, int size) {
  base::ThreadRestrictions::AssertIOAllowed();
  base::win::ScopedHandle file(CreateFile(filename.value().c_str(),
                                          GENERIC_READ,
                                          FILE_SHARE_READ | FILE_SHARE_WRITE,
                                          NULL,
                                          OPEN_EXISTING,
                                          FILE_FLAG_SEQUENTIAL_SCAN,
                                          NULL));
  if (!file)
    return -1;

  DWORD read;
  if (::ReadFile(file, data, size, &read, NULL) &&
      static_cast<int>(read) == size)
    return read;
  return -1;
}

int WriteFile(const FilePath& filename, const char* data, int size) {
  base::ThreadRestrictions::AssertIOAllowed();
  base::win::ScopedHandle file(CreateFile(filename.value().c_str(),
                                          GENERIC_WRITE,
                                          0,
                                          NULL,
                                          CREATE_ALWAYS,
                                          0,
                                          NULL));
  if (!file) {
    DLOG(WARNING) << "CreateFile failed for path " << filename.value()
                  << " error code=" << GetLastError();
    return -1;
  }

  DWORD written;
  BOOL result = ::WriteFile(file, data, size, &written, NULL);
  if (result && static_cast<int>(written) == size)
    return written;

  if (!result) {
    // WriteFile failed.
    DLOG(WARNING) << "writing file " << filename.value()
                  << " failed, error code=" << GetLastError();
  } else {
    // Didn't write all the bytes.
    DLOG(WARNING) << "wrote" << written << " bytes to "
                  << filename.value() << " expected " << size;
  }
  return -1;
}

// Gets the current working directory for the process.
bool GetCurrentDirectory(FilePath* dir) {
  base::ThreadRestrictions::AssertIOAllowed();

  wchar_t system_buffer[MAX_PATH];
  system_buffer[0] = 0;
  DWORD len = ::GetCurrentDirectory(MAX_PATH, system_buffer);
  if (len == 0 || len > MAX_PATH)
    return false;
  // TODO(evanm): the old behavior of this function was to always strip the
  // trailing slash.  We duplicate this here, but it shouldn't be necessary
  // when everyone is using the appropriate FilePath APIs.
  std::wstring dir_str(system_buffer);
  *dir = FilePath(dir_str).StripTrailingSeparators();
  return true;
}

// Sets the current working directory for the process.
bool SetCurrentDirectory(const FilePath& directory) {
  base::ThreadRestrictions::AssertIOAllowed();
  BOOL ret = ::SetCurrentDirectory(directory.value().c_str());
  return ret != 0;
}

///////////////////////////////////////////////
// FileEnumerator

FileEnumerator::FileEnumerator(const FilePath& root_path,
                               bool recursive,
                               FileType file_type)
    : recursive_(recursive),
      file_type_(file_type),
      has_find_data_(false),
      find_handle_(INVALID_HANDLE_VALUE) {
  // INCLUDE_DOT_DOT must not be specified if recursive.
  DCHECK(!(recursive && (INCLUDE_DOT_DOT & file_type_)));
  memset(&find_data_, 0, sizeof(find_data_));
  pending_paths_.push(root_path);
}

FileEnumerator::FileEnumerator(const FilePath& root_path,
                               bool recursive,
                               FileType file_type,
                               const FilePath::StringType& pattern)
    : recursive_(recursive),
      file_type_(file_type),
      has_find_data_(false),
      pattern_(pattern),
      find_handle_(INVALID_HANDLE_VALUE) {
  // INCLUDE_DOT_DOT must not be specified if recursive.
  DCHECK(!(recursive && (INCLUDE_DOT_DOT & file_type_)));
  memset(&find_data_, 0, sizeof(find_data_));
  pending_paths_.push(root_path);
}

FileEnumerator::~FileEnumerator() {
  if (find_handle_ != INVALID_HANDLE_VALUE)
    FindClose(find_handle_);
}

void FileEnumerator::GetFindInfo(FindInfo* info) {
  DCHECK(info);

  if (!has_find_data_)
    return;

  memcpy(info, &find_data_, sizeof(*info));
}

// static
bool FileEnumerator::IsDirectory(const FindInfo& info) {
  return (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
}

// static
bool FileEnumerator::IsLink(const FindInfo& info) {
  return false;
}

// static
FilePath FileEnumerator::GetFilename(const FindInfo& find_info) {
  return FilePath(find_info.cFileName);
}

// static
int64 FileEnumerator::GetFilesize(const FindInfo& find_info) {
  ULARGE_INTEGER size;
  size.HighPart = find_info.nFileSizeHigh;
  size.LowPart = find_info.nFileSizeLow;
  DCHECK_LE(size.QuadPart, std::numeric_limits<int64>::max());
  return static_cast<int64>(size.QuadPart);
}

// static
base::Time FileEnumerator::GetLastModifiedTime(const FindInfo& find_info) {
  return base::Time::FromFileTime(find_info.ftLastWriteTime);
}

FilePath FileEnumerator::Next() {
  base::ThreadRestrictions::AssertIOAllowed();

  while (has_find_data_ || !pending_paths_.empty()) {
    if (!has_find_data_) {
      // The last find FindFirstFile operation is done, prepare a new one.
      root_path_ = pending_paths_.top();
      pending_paths_.pop();

      // Start a new find operation.
      FilePath src = root_path_;

      if (pattern_.empty())
        src = src.Append(L"*");  // No pattern = match everything.
      else
        src = src.Append(pattern_);

      find_handle_ = FindFirstFile(src.value().c_str(), &find_data_);
      has_find_data_ = true;
    } else {
      // Search for the next file/directory.
      if (!FindNextFile(find_handle_, &find_data_)) {
        FindClose(find_handle_);
        find_handle_ = INVALID_HANDLE_VALUE;
      }
    }

    if (INVALID_HANDLE_VALUE == find_handle_) {
      has_find_data_ = false;

      // This is reached when we have finished a directory and are advancing to
      // the next one in the queue. We applied the pattern (if any) to the files
      // in the root search directory, but for those directories which were
      // matched, we want to enumerate all files inside them. This will happen
      // when the handle is empty.
      pattern_ = FilePath::StringType();

      continue;
    }

    FilePath cur_file(find_data_.cFileName);
    if (ShouldSkip(cur_file))
      continue;

    // Construct the absolute filename.
    cur_file = root_path_.Append(find_data_.cFileName);

    if (find_data_.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
      if (recursive_) {
        // If |cur_file| is a directory, and we are doing recursive searching,
        // add it to pending_paths_ so we scan it after we finish scanning this
        // directory.
        pending_paths_.push(cur_file);
      }
      if (file_type_ & FileEnumerator::DIRECTORIES)
        return cur_file;
    } else if (file_type_ & FileEnumerator::FILES) {
      return cur_file;
    }
  }

  return FilePath();
}

///////////////////////////////////////////////
// MemoryMappedFile

MemoryMappedFile::MemoryMappedFile()
    : file_(INVALID_HANDLE_VALUE),
      file_mapping_(INVALID_HANDLE_VALUE),
      data_(NULL),
      length_(INVALID_FILE_SIZE) {
}

bool MemoryMappedFile::InitializeAsImageSection(const FilePath& file_name) {
  if (IsValid())
    return false;
  file_ = base::CreatePlatformFile(
      file_name, base::PLATFORM_FILE_OPEN | base::PLATFORM_FILE_READ,
      NULL, NULL);

  if (file_ == base::kInvalidPlatformFileValue) {
    DLOG(ERROR) << "Couldn't open " << file_name.value();
    return false;
  }

  if (!MapFileToMemoryInternalEx(SEC_IMAGE)) {
    CloseHandles();
    return false;
  }

  return true;
}

bool MemoryMappedFile::MapFileToMemoryInternal() {
  return MapFileToMemoryInternalEx(0);
}

bool MemoryMappedFile::MapFileToMemoryInternalEx(int flags) {
  base::ThreadRestrictions::AssertIOAllowed();

  if (file_ == INVALID_HANDLE_VALUE)
    return false;

  length_ = ::GetFileSize(file_, NULL);
  if (length_ == INVALID_FILE_SIZE)
    return false;

  file_mapping_ = ::CreateFileMapping(file_, NULL, PAGE_READONLY | flags,
                                      0, 0, NULL);
  if (!file_mapping_) {
    // According to msdn, system error codes are only reserved up to 15999.
    // http://msdn.microsoft.com/en-us/library/ms681381(v=VS.85).aspx.
    UMA_HISTOGRAM_ENUMERATION("MemoryMappedFile.CreateFileMapping",
                              logging::GetLastSystemErrorCode(), 16000);
    return false;
  }

  data_ = static_cast<uint8*>(
      ::MapViewOfFile(file_mapping_, FILE_MAP_READ, 0, 0, 0));
  if (!data_) {
    UMA_HISTOGRAM_ENUMERATION("MemoryMappedFile.MapViewOfFile",
                              logging::GetLastSystemErrorCode(), 16000);
  }
  return data_ != NULL;
}

void MemoryMappedFile::CloseHandles() {
  if (data_)
    ::UnmapViewOfFile(data_);
  if (file_mapping_ != INVALID_HANDLE_VALUE)
    ::CloseHandle(file_mapping_);
  if (file_ != INVALID_HANDLE_VALUE)
    ::CloseHandle(file_);

  data_ = NULL;
  file_mapping_ = file_ = INVALID_HANDLE_VALUE;
  length_ = INVALID_FILE_SIZE;
}

bool HasFileBeenModifiedSince(const FileEnumerator::FindInfo& find_info,
                              const base::Time& cutoff_time) {
  base::ThreadRestrictions::AssertIOAllowed();
  FILETIME file_time = cutoff_time.ToFileTime();
  long result = CompareFileTime(&find_info.ftLastWriteTime,  // NOLINT
                                &file_time);
  return result == 1 || result == 0;
}

bool NormalizeFilePath(const FilePath& path, FilePath* real_path) {
  base::ThreadRestrictions::AssertIOAllowed();
  FilePath mapped_file;
  if (!NormalizeToNativeFilePath(path, &mapped_file))
    return false;
  // NormalizeToNativeFilePath() will return a path that starts with
  // "\Device\Harddisk...".  Helper DevicePathToDriveLetterPath()
  // will find a drive letter which maps to the path's device, so
  // that we return a path starting with a drive letter.
  return DevicePathToDriveLetterPath(mapped_file, real_path);
}

bool DevicePathToDriveLetterPath(const FilePath& nt_device_path,
                                 FilePath* out_drive_letter_path) {
  base::ThreadRestrictions::AssertIOAllowed();

  // Get the mapping of drive letters to device paths.
  const int kDriveMappingSize = 1024;
  wchar_t drive_mapping[kDriveMappingSize] = {'\0'};
  if (!::GetLogicalDriveStrings(kDriveMappingSize - 1, drive_mapping)) {
    DLOG(ERROR) << "Failed to get drive mapping.";
    return false;
  }

  // The drive mapping is a sequence of null terminated strings.
  // The last string is empty.
  wchar_t* drive_map_ptr = drive_mapping;
  wchar_t device_path_as_string[MAX_PATH];
  wchar_t drive[] = L" :";

  // For each string in the drive mapping, get the junction that links
  // to it.  If that junction is a prefix of |device_path|, then we
  // know that |drive| is the real path prefix.
  while (*drive_map_ptr) {
    drive[0] = drive_map_ptr[0];  // Copy the drive letter.

    if (QueryDosDevice(drive, device_path_as_string, MAX_PATH)) {
      FilePath device_path(device_path_as_string);
      if (device_path == nt_device_path ||
          device_path.IsParent(nt_device_path)) {
        *out_drive_letter_path = FilePath(drive +
            nt_device_path.value().substr(wcslen(device_path_as_string)));
        return true;
      }
    }
    // Move to the next drive letter string, which starts one
    // increment after the '\0' that terminates the current string.
    while (*drive_map_ptr++);
  }

  // No drive matched.  The path does not start with a device junction
  // that is mounted as a drive letter.  This means there is no drive
  // letter path to the volume that holds |device_path|, so fail.
  return false;
}

bool NormalizeToNativeFilePath(const FilePath& path, FilePath* nt_path) {
  base::ThreadRestrictions::AssertIOAllowed();
  // In Vista, GetFinalPathNameByHandle() would give us the real path
  // from a file handle.  If we ever deprecate XP, consider changing the
  // code below to a call to GetFinalPathNameByHandle().  The method this
  // function uses is explained in the following msdn article:
  // http://msdn.microsoft.com/en-us/library/aa366789(VS.85).aspx
  base::win::ScopedHandle file_handle(
      ::CreateFile(path.value().c_str(),
                   GENERIC_READ,
                   kFileShareAll,
                   NULL,
                   OPEN_EXISTING,
                   FILE_ATTRIBUTE_NORMAL,
                   NULL));
  if (!file_handle)
    return false;

  // Create a file mapping object.  Can't easily use MemoryMappedFile, because
  // we only map the first byte, and need direct access to the handle. You can
  // not map an empty file, this call fails in that case.
  base::win::ScopedHandle file_map_handle(
      ::CreateFileMapping(file_handle.Get(),
                          NULL,
                          PAGE_READONLY,
                          0,
                          1,  // Just one byte.  No need to look at the data.
                          NULL));
  if (!file_map_handle)
    return false;

  // Use a view of the file to get the path to the file.
  void* file_view = MapViewOfFile(file_map_handle.Get(),
                                  FILE_MAP_READ, 0, 0, 1);
  if (!file_view)
    return false;

  // The expansion of |path| into a full path may make it longer.
  // GetMappedFileName() will fail if the result is longer than MAX_PATH.
  // Pad a bit to be safe.  If kMaxPathLength is ever changed to be less
  // than MAX_PATH, it would be nessisary to test that GetMappedFileName()
  // not return kMaxPathLength.  This would mean that only part of the
  // path fit in |mapped_file_path|.
  const int kMaxPathLength = MAX_PATH + 10;
  wchar_t mapped_file_path[kMaxPathLength];
  bool success = false;
  HANDLE cp = GetCurrentProcess();
  if (::GetMappedFileNameW(cp, file_view, mapped_file_path, kMaxPathLength)) {
    *nt_path = FilePath(mapped_file_path);
    success = true;
  }
  ::UnmapViewOfFile(file_view);
  return success;
}

}  // namespace file_util


text:
"""Tests for tf.layers.base."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import copy

from tensorflow.python.eager import context
from tensorflow.python.eager import def_function
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.framework import test_util
from tensorflow.python.keras.engine import base_layer as keras_base_layer
from tensorflow.python.keras.engine import input_spec
from tensorflow.python.layers import base as base_layers
from tensorflow.python.layers import core as core_layers
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import init_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import partitioned_variables
from tensorflow.python.ops import random_ops
from tensorflow.python.ops import state_ops
from tensorflow.python.ops import variable_scope
from tensorflow.python.platform import test

class BaseLayerTest(test.TestCase):

  @test_util.run_in_graph_and_eager_modes
  def testLayerProperties(self):
    layer = base_layers.Layer(name='my_layer')
    self.assertEqual(layer.variables, [])
    self.assertEqual(layer.trainable_variables, [])
    self.assertEqual(layer.non_trainable_variables, [])
    if not context.executing_eagerly():
      # updates, losses only supported in GRAPH mode
      self.assertEqual(layer.updates, [])
      self.assertEqual(layer.losses, [])
    self.assertEqual(layer.built, False)
    layer = base_layers.Layer(name='my_layer', trainable=False)
    self.assertEqual(layer.trainable, False)

  @test_util.run_in_graph_and_eager_modes
  def testInt64Layer(self):
    layer = base_layers.Layer(name='my_layer', dtype='int64')
    layer.add_variable('my_var', [2, 2])
    self.assertEqual(layer.name, 'my_layer')

  @test_util.run_in_graph_and_eager_modes
  def testKerasStyleAddWeight(self):
    keras_layer = keras_base_layer.Layer(name='keras_layer')
    with ops.name_scope('foo'):
      keras_variable = keras_layer.add_variable(
          'my_var', [2, 2], initializer=init_ops.zeros_initializer())
    self.assertEqual(keras_variable.name, 'foo/my_var:0')

    with ops.name_scope('baz'):
      old_style_layer = base_layers.Layer(name='my_layer')
      # Test basic variable creation.
      variable = old_style_layer.add_variable(
          'my_var', [2, 2], initializer=init_ops.zeros_initializer())
    self.assertEqual(variable.name, 'my_layer/my_var:0')

    with base_layers.keras_style_scope():
      layer = base_layers.Layer(name='my_layer')
    # Test basic variable creation.
    with ops.name_scope('bar'):
      variable = layer.add_variable(
          'my_var', [2, 2], initializer=init_ops.zeros_initializer())
    self.assertEqual(variable.name, 'bar/my_var:0')

  @test_util.run_in_graph_and_eager_modes
  def testAddWeight(self):
    layer = base_layers.Layer(name='my_layer')

    # Test basic variable creation.
    variable = layer.add_variable(
        'my_var', [2, 2], initializer=init_ops.zeros_initializer())
    self.assertEqual(variable.name, 'my_layer/my_var:0')
    self.assertEqual(layer.variables, [variable])
    self.assertEqual(layer.trainable_variables, [variable])
    self.assertEqual(layer.non_trainable_variables, [])
    if not context.executing_eagerly():
      self.assertEqual(
          layer.variables,
          ops.get_collection(ops.GraphKeys.TRAINABLE_VARIABLES))

    # Test non-trainable variable creation.
    # layer.add_variable should work even outside `build` and `call`.
    variable_2 = layer.add_variable(
        'non_trainable_var', [2, 2],
        initializer=init_ops.zeros_initializer(),
        trainable=False)
    self.assertEqual(layer.variables, [variable, variable_2])
    self.assertEqual(layer.trainable_variables, [variable])
    self.assertEqual(layer.non_trainable_variables, [variable_2])

    if not context.executing_eagerly():
      self.assertEqual(
          len(ops.get_collection(ops.GraphKeys.TRAINABLE_VARIABLES)), 1)

    regularizer = lambda x: math_ops.reduce_sum(x) * 1e-3
    _ = layer.add_variable(
        'reg_var', [2, 2],
        initializer=init_ops.zeros_initializer(),
        regularizer=regularizer)
    self.assertEqual(len(layer.losses), 1)

    added_variable = [False]

    # Test that sync `ON_READ` variables are defaulted to be non-trainable.
    variable_3 = layer.add_variable(
        'sync_on_read_var', [2, 2],
        initializer=init_ops.zeros_initializer(),
        synchronization=variable_scope.VariableSynchronization.ON_READ,
        aggregation=variable_scope.VariableAggregation.SUM)
    self.assertEqual(layer.non_trainable_variables, [variable_2, variable_3])

    @def_function.function
    def function_adds_weight():
      if not added_variable[0]:
        layer.add_variable(
            'reg_var_from_function', [2, 2],
            initializer=init_ops.zeros_initializer(),
            regularizer=regularizer)
        added_variable[0] = True

    function_adds_weight()
    self.assertEqual(len(layer.losses), 2)

  def testInvalidTrainableSynchronizationCombination(self):
    layer = base_layers.Layer(name='my_layer')

    with self.assertRaisesRegexp(
        ValueError, 'Synchronization value can be set to '
        'VariableSynchronization.ON_READ only for non-trainable variables. '
        'You have specified trainable=True and '
        'synchronization=VariableSynchronization.ON_READ.'):
      _ = layer.add_variable(
          'v', [2, 2],
          initializer=init_ops.zeros_initializer(),
          synchronization=variable_scope.VariableSynchronization.ON_READ,
          trainable=True)

  @test_util.run_deprecated_v1
  def testReusePartitionedVaraiblesAndRegularizers(self):
    regularizer = lambda x: math_ops.reduce_sum(x) * 1e-3
    partitioner = partitioned_variables.fixed_size_partitioner(3)
    for reuse in [False, True]:
      with variable_scope.variable_scope(variable_scope.get_variable_scope(),
                                         partitioner=partitioner,
                                         reuse=reuse):
        layer = base_layers.Layer(name='my_layer')
        _ = layer.add_variable(
            'reg_part_var', [4, 4],
            initializer=init_ops.zeros_initializer(),
            regularizer=regularizer)
    self.assertEqual(
        len(ops.get_collection(ops.GraphKeys.REGULARIZATION_LOSSES)), 3)

  @test_util.run_in_graph_and_eager_modes
  def testCall(self):

    class MyLayer(base_layers.Layer):

      def call(self, inputs):
        return math_ops.square(inputs)

    layer = MyLayer(name='my_layer')
    inputs = random_ops.random_uniform((5,), seed=1)
    outputs = layer.apply(inputs)
    self.assertEqual(layer.built, True)
    if not context.executing_eagerly():
      # op is only supported in GRAPH mode
      self.assertEqual(outputs.op.name, 'my_layer/Square')

  @test_util.run_in_graph_and_eager_modes
  def testDeepCopy(self):

    class MyLayer(base_layers.Layer):

      def call(self, inputs):
        return math_ops.square(inputs)

    layer = MyLayer(name='my_layer')
    layer._private_tensor = random_ops.random_uniform(())
    inputs = random_ops.random_uniform((5,), seed=1)
    outputs = layer.apply(inputs)
    self.assertEqual(layer.built, True)
    if not context.executing_eagerly():
      # op only supported in GRAPH mode.
      self.assertEqual(outputs.op.name, 'my_layer/Square')

    layer_copy = copy.deepcopy(layer)
    self.assertEqual(layer_copy.name, layer.name)
    self.assertEqual(layer_copy._scope.name, layer._scope.name)
    self.assertEqual(layer_copy._private_tensor, layer._private_tensor)

  @test_util.run_in_graph_and_eager_modes
  def testScopeNaming(self):

    class PrivateLayer(base_layers.Layer):

      def call(self, inputs):
        return inputs

    inputs = random_ops.random_uniform((5,))
    default_layer = PrivateLayer()
    _ = default_layer.apply(inputs)
    self.assertEqual(default_layer._scope.name, 'private_layer')
    default_layer1 = PrivateLayer()
    default_layer1.apply(inputs)
    self.assertEqual(default_layer1._scope.name, 'private_layer_1')
    my_layer = PrivateLayer(name='my_layer')
    my_layer.apply(inputs)
    self.assertEqual(my_layer._scope.name, 'my_layer')
    my_layer1 = PrivateLayer(name='my_layer')
    my_layer1.apply(inputs)
    self.assertEqual(my_layer1._scope.name, 'my_layer_1')
    my_layer2 = PrivateLayer(name='my_layer')
    my_layer2.apply(inputs)
    self.assertEqual(my_layer2._scope.name, 'my_layer_2')
    # Name scope shouldn't affect names.
    with ops.name_scope('some_name_scope'):
      default_layer2 = PrivateLayer()
      default_layer2.apply(inputs)
      self.assertEqual(default_layer2._scope.name, 'private_layer_2')
      my_layer3 = PrivateLayer(name='my_layer')
      my_layer3.apply(inputs)
      self.assertEqual(my_layer3._scope.name, 'my_layer_3')
      other_layer = PrivateLayer(name='other_layer')
      other_layer.apply(inputs)
      self.assertEqual(other_layer._scope.name, 'other_layer')
    # Variable scope gets added to scope names.
    with variable_scope.variable_scope('var_scope'):
      default_layer_scoped = PrivateLayer()
      default_layer_scoped.apply(inputs)
      self.assertEqual(default_layer_scoped._scope.name,
                       'var_scope/private_layer')
      my_layer_scoped = PrivateLayer(name='my_layer')
      my_layer_scoped.apply(inputs)
      self.assertEqual(my_layer_scoped._scope.name, 'var_scope/my_layer')
      my_layer_scoped1 = PrivateLayer(name='my_layer')
      my_layer_scoped1.apply(inputs)
      self.assertEqual(my_layer_scoped1._scope.name, 'var_scope/my_layer_1')

  @test_util.run_in_graph_and_eager_modes
  def testInputSpecNdimCheck(self):

    class CustomerLayer(base_layers.Layer):

      def __init__(self):
        super(CustomerLayer, self).__init__()
        self.input_spec = input_spec.InputSpec(ndim=2)

      def call(self, inputs):
        return inputs

    if not context.executing_eagerly():
      layer = CustomerLayer()
      with self.assertRaisesRegexp(ValueError, r'requires a defined rank'):
        layer.apply(array_ops.placeholder('int32'))

    layer = CustomerLayer()
    with self.assertRaisesRegexp(ValueError, r'expected ndim=2'):
      layer.apply(constant_op.constant([1]))

    # Note that we re-create the layer since in Eager mode, input spec checks
    # only happen on first call.
    # Works
    layer = CustomerLayer()
    layer.apply(constant_op.constant([[1], [2]]))

  @test_util.run_in_graph_and_eager_modes
  def testInputSpecMinNdimCheck(self):

    class CustomerLayer(base_layers.Layer):

      def __init__(self):
        super(CustomerLayer, self).__init__()
        self.input_spec = input_spec.InputSpec(min_ndim=2)

      def call(self, inputs):
        return inputs

    if not context.executing_eagerly():
      layer = CustomerLayer()
      with self.assertRaisesRegexp(ValueError, r'requires a defined rank'):
        layer.apply(array_ops.placeholder('int32'))

    layer = CustomerLayer()
    with self.assertRaisesRegexp(ValueError, r'expected min_ndim=2'):
      layer.apply(constant_op.constant([1]))

    # Works
    layer = CustomerLayer()
    layer.apply(constant_op.constant([[1], [2]]))

    layer = CustomerLayer()
    layer.apply(constant_op.constant([[[1], [2]]]))

  @test_util.run_in_graph_and_eager_modes
  def testInputSpecMaxNdimCheck(self):

    class CustomerLayer(base_layers.Layer):

      def __init__(self):
        super(CustomerLayer, self).__init__()
        self.input_spec = input_spec.InputSpec(max_ndim=2)

      def call(self, inputs):
        return inputs

    if not context.executing_eagerly():
      layer = CustomerLayer()
      with self.assertRaisesRegexp(ValueError, r'requires a defined rank'):
        layer.apply(array_ops.placeholder('int32'))

    layer = CustomerLayer()
    with self.assertRaisesRegexp(ValueError, r'expected max_ndim=2'):
      layer.apply(constant_op.constant([[[1], [2]]]))

    # Works
    layer = CustomerLayer()
    layer.apply(constant_op.constant([1]))

    layer = CustomerLayer()
    layer.apply(constant_op.constant([[1], [2]]))

  @test_util.run_in_graph_and_eager_modes
  def testInputSpecDtypeCheck(self):

    class CustomerLayer(base_layers.Layer):

      def __init__(self):
        super(CustomerLayer, self).__init__()
        self.input_spec = input_spec.InputSpec(dtype='float32')

      def call(self, inputs):
        return inputs

    layer = CustomerLayer()
    with self.assertRaisesRegexp(ValueError, r'expected dtype=float32'):
      layer.apply(constant_op.constant(1, dtype=dtypes.int32))

    # Works
    layer = CustomerLayer()
    layer.apply(constant_op.constant(1.0, dtype=dtypes.float32))

  @test_util.run_in_graph_and_eager_modes
  def testInputSpecAxesCheck(self):

    class CustomerLayer(base_layers.Layer):

      def __init__(self):
        super(CustomerLayer, self).__init__()
        self.input_spec = input_spec.InputSpec(axes={-1: 2})

      def call(self, inputs):
        return inputs

    layer = CustomerLayer()
    with self.assertRaisesRegexp(ValueError, r'expected axis'):
      layer.apply(constant_op.constant([1, 2, 3]))

    # Works
    layer = CustomerLayer()
    layer.apply(constant_op.constant([1, 2]))
    layer = CustomerLayer()
    layer.apply(constant_op.constant([[1, 2], [3, 4], [5, 6]]))

  @test_util.run_in_graph_and_eager_modes
  def testInputSpecShapeCheck(self):

    class CustomerLayer(base_layers.Layer):

      def __init__(self):
        super(CustomerLayer, self).__init__()
        self.input_spec = input_spec.InputSpec(shape=(None, 3))

      def call(self, inputs):
        return inputs

    layer = CustomerLayer()
    with self.assertRaisesRegexp(ValueError, r'expected shape'):
      layer.apply(constant_op.constant([[1, 2]]))

    # Works
    layer = CustomerLayer()
    layer.apply(constant_op.constant([[1, 2, 3], [4, 5, 6]]))

  @test_util.run_in_graph_and_eager_modes
  def testNoInputSpec(self):

    class CustomerLayer(base_layers.Layer):

      def __init__(self):
        super(CustomerLayer, self).__init__()
        self.input_spec = None

      def call(self, inputs):
        return inputs

    layer = CustomerLayer()

    layer.apply(constant_op.constant(1))

    # Works
    if not context.executing_eagerly():
      layer.apply(array_ops.placeholder('int32'))
      layer.apply(array_ops.placeholder('int32', shape=(2, 3)))

  @test_util.run_in_graph_and_eager_modes
  def test_count_params(self):
    dense = core_layers.Dense(16)
    dense.build((None, 4))
    self.assertEqual(dense.count_params(), 16 * 4 + 16)

    dense = core_layers.Dense(16)
    with self.assertRaises(ValueError):
      dense.count_params()

  @test_util.run_in_graph_and_eager_modes
  def testDictInputOutput(self):

    class DictLayer(base_layers.Layer):

      def call(self, inputs):
        return {'l' + key: inputs[key] for key in inputs}

    layer = DictLayer()
    if context.executing_eagerly():
      i1 = constant_op.constant(3)
      i2 = constant_op.constant(4.0)
      result = layer.apply({'abel': i1, 'ogits': i2})
      self.assertTrue(isinstance(result, dict))
      self.assertEqual(set(['label', 'logits']), set(result.keys()))
      self.assertEqual(3, result['label'].numpy())
      self.assertEqual(4.0, result['logits'].numpy())
    else:
      i1 = array_ops.placeholder('int32')
      i2 = array_ops.placeholder('float32')
      result = layer.apply({'abel': i1, 'ogits': i2})
      self.assertTrue(isinstance(result, dict))
      self.assertEqual(set(['label', 'logits']), set(result.keys()))

  @test_util.run_deprecated_v1
  def testActivityRegularizer(self):
    regularizer = math_ops.reduce_sum
    layer = base_layers.Layer(activity_regularizer=regularizer)
    x = array_ops.placeholder('int32')
    layer.apply(x)
    self.assertEqual(len(layer.get_losses_for(x)), 1)

  def testNameScopeIsConsistentWithVariableScope(self):
    # Github issue 13429.

    class MyLayer(base_layers.Layer):

      def build(self, input_shape):
        self.my_var = self.add_variable('my_var', (), dtypes.float32)
        self.built = True

      def call(self, inputs):
        return math_ops.multiply(inputs, self.my_var, name='my_op')

    def _gen_layer(x, name=None):
      layer = MyLayer(name=name)
      out = layer.apply(x)
      return layer, out

    # unnamed layer
    with ops.Graph().as_default():
      x = array_ops.placeholder(dtypes.float32, (), 'x')
      layer, op = _gen_layer(x)
      layer1, op1 = _gen_layer(op)
      layer2, op2 = _gen_layer(op1)

      self.assertEqual(layer.my_var.name, 'my_layer/my_var:0')
      self.assertEqual(op.name, 'my_layer/my_op:0')
      self.assertEqual(layer1.my_var.name, 'my_layer_1/my_var:0')
      self.assertEqual(op1.name, 'my_layer_1/my_op:0')
      self.assertEqual(layer2.my_var.name, 'my_layer_2/my_var:0')
      self.assertEqual(op2.name, 'my_layer_2/my_op:0')
    # name starts from zero
    with ops.Graph().as_default():
      x = array_ops.placeholder(dtypes.float32, (), 'x')
      layer, op = _gen_layer(x, name='name')
      layer1, op1 = _gen_layer(op, name='name_1')
      layer2, op2 = _gen_layer(op1, name='name_2')

      self.assertEqual(layer.my_var.name, 'name/my_var:0')
      self.assertEqual(op.name, 'name/my_op:0')
      self.assertEqual(layer1.my_var.name, 'name_1/my_var:0')
      self.assertEqual(op1.name, 'name_1/my_op:0')
      self.assertEqual(layer2.my_var.name, 'name_2/my_var:0')
      self.assertEqual(op2.name, 'name_2/my_op:0')
    # name starts from one
    with ops.Graph().as_default():
      x = array_ops.placeholder(dtypes.float32, (), 'x')
      layer, op = _gen_layer(x, name='name_1')
      layer1, op1 = _gen_layer(op, name='name_2')
      layer2, op2 = _gen_layer(op1, name='name_3')

      self.assertEqual(layer.my_var.name, 'name_1/my_var:0')
      self.assertEqual(op.name, 'name_1/my_op:0')
      self.assertEqual(layer1.my_var.name, 'name_2/my_var:0')
      self.assertEqual(op1.name, 'name_2/my_op:0')
      self.assertEqual(layer2.my_var.name, 'name_3/my_var:0')
      self.assertEqual(op2.name, 'name_3/my_op:0')

  def testVariablesAreLiftedFromFunctionBuildingGraphs(self):
    class MyLayer(base_layers.Layer):

      def build(self, input_shape):
        self.my_var = self.add_variable('my_var', (), dtypes.float32)
        self.built = True

      def call(self, inputs):
        return inputs

    outer_graph = ops.get_default_graph()
    function_building_graph = ops.Graph()
    function_building_graph._building_function = True
    with outer_graph.as_default():
      with function_building_graph.as_default():
        layer = MyLayer()
        # Create a variable by invoking build through __call__ and assert that
        # it is both tracked and lifted into the outer graph.
        inputs = array_ops.placeholder(dtypes.float32, (), 'inputs')
        layer.apply(inputs)
        self.assertEqual(len(layer.variables), 1)
        self.assertEqual(len(layer.trainable_variables), 1)
        self.assertEqual(layer.variables[0].graph, outer_graph)

  @test_util.run_deprecated_v1
  def testGetUpdateFor(self):

    class MyLayer(base_layers.Layer):

      def build(self, input_shape):
        self.a = self.add_variable('a',
                                   (),
                                   dtypes.float32,
                                   trainable=False)
        self.b = self.add_variable('b',
                                   (),
                                   dtypes.float32,
                                   trainable=False)
        self.add_update(state_ops.assign_add(self.a, 1., name='b_update'))
        self.built = True

      def call(self, inputs):
        self.add_update(state_ops.assign_add(self.a, inputs, name='a_update'),
                        inputs=True)
        return inputs + 1

    layer = MyLayer()
    inputs = array_ops.placeholder(dtypes.float32, (), 'inputs')
    intermediate_inputs = inputs + 1
    outputs = layer.apply(intermediate_inputs)

    self.assertEqual(len(layer.updates), 2)
    self.assertEqual(len(layer.get_updates_for(None)), 1)
    self.assertEqual(len(layer.get_updates_for([inputs])), 1)
    self.assertEqual(len(layer.get_updates_for([intermediate_inputs])), 1)
    self.assertEqual(len(layer.get_updates_for([outputs])), 0)

    # Call same layer on new input, creating one more conditional update
    inputs = array_ops.placeholder(dtypes.float32, (), 'inputs')
    intermediate_inputs = inputs + 1
    outputs = layer.apply(intermediate_inputs)

    self.assertEqual(len(layer.updates), 3)
    self.assertEqual(len(layer.get_updates_for(None)), 1)
    # Check that we are successfully filtering out irrelevant updates
    self.assertEqual(len(layer.get_updates_for([inputs])), 1)
    self.assertEqual(len(layer.get_updates_for([intermediate_inputs])), 1)
    self.assertEqual(len(layer.get_updates_for([outputs])), 0)

  @test_util.run_deprecated_v1
  def testGetLossesFor(self):

    class MyLayer(base_layers.Layer):

      def build(self, input_shape):
        self.a = self.add_variable('a',
                                   (),
                                   dtypes.float32,
                                   trainable=False)
        self.b = self.add_variable('b',
                                   (),
                                   dtypes.float32,
                                   trainable=False)
        self.add_loss(self.a)
        self.built = True

      def call(self, inputs):
        self.add_loss(inputs, inputs=True)
        return inputs + 1

    layer = MyLayer()
    inputs = array_ops.placeholder(dtypes.float32, (), 'inputs')
    intermediate_inputs = inputs + 1
    outputs = layer.apply(intermediate_inputs)

    self.assertEqual(len(layer.losses), 2)
    self.assertEqual(len(layer.get_losses_for(None)), 1)
    self.assertEqual(len(layer.get_losses_for([inputs])), 1)
    self.assertEqual(len(layer.get_losses_for([intermediate_inputs])), 1)
    self.assertEqual(len(layer.get_losses_for([outputs])), 0)

    # Call same layer on new input, creating one more conditional loss
    inputs = array_ops.placeholder(dtypes.float32, (), 'inputs')
    intermediate_inputs = inputs + 1
    outputs = layer.apply(intermediate_inputs)

    self.assertEqual(len(layer.losses), 3)
    self.assertEqual(len(layer.get_losses_for(None)), 1)
    # Check that we are successfully filtering out irrelevant losses
    self.assertEqual(len(layer.get_losses_for([inputs])), 1)
    self.assertEqual(len(layer.get_losses_for([intermediate_inputs])), 1)
    self.assertEqual(len(layer.get_losses_for([outputs])), 0)

if __name__ == '__main__':
  test.main()


text:
This plugin deals with users contact methods.

Basically when sould be edit a user in the administration, there's a "contact information" block.

The way how to add your own fields there, and to go a bit further, how to show (or not) these new fields on the registration page is shown on this repository.


text:
import org.junit.*;
import java.util.*;
import play.test.*;
//import models.*;

public class App1BasicTest extends UnitTest {

    @Test
    public void aVeryImportantThingToTest() {
        assertEquals(2, 1 + 1);
    }

}


text:
import sys
import unittest
from dynd import nd, ndt
import ctypes

class TestCTypesDTypeInterop(unittest.TestCase):
    def test_type_from_ctype_typeobject(self):
        self.assertEqual(ndt.int8, ndt.type(ctypes.c_int8))
        self.assertEqual(ndt.int16, ndt.type(ctypes.c_int16))
        self.assertEqual(ndt.int32, ndt.type(ctypes.c_int32))
        self.assertEqual(ndt.int64, ndt.type(ctypes.c_int64))
        self.assertEqual(ndt.uint8, ndt.type(ctypes.c_uint8))
        self.assertEqual(ndt.uint16, ndt.type(ctypes.c_uint16))
        self.assertEqual(ndt.uint32, ndt.type(ctypes.c_uint32))
        self.assertEqual(ndt.uint64, ndt.type(ctypes.c_uint64))
        self.assertEqual(ndt.uint32, ndt.type(ctypes.c_uint32))
        self.assertEqual(ndt.uint64, ndt.type(ctypes.c_uint64))
        self.assertEqual(ndt.float32, ndt.type(ctypes.c_float))
        self.assertEqual(ndt.float64, ndt.type(ctypes.c_double))

    def test_type_from_annotated_ctype_typeobject(self):
        self.assertEqual(ndt.bool, ndt.type(ndt.ctypes.c_dynd_bool))
        self.assertEqual(ndt.complex_float32, ndt.type(ndt.ctypes.c_complex_float32))
        self.assertEqual(ndt.complex_float64, ndt.type(ndt.ctypes.c_complex_float64))
        self.assertEqual(ndt.complex_float32, ndt.type(ndt.ctypes.c_complex64))
        self.assertEqual(ndt.complex_float64, ndt.type(ndt.ctypes.c_complex128))

    def test_type_from_ctype_cstruct(self):
        class POINT(ctypes.Structure):
            _fields_ = [('x', ctypes.c_int32), ('y', ctypes.c_int32)]
        self.assertEqual(ndt.make_cstruct(
                                [ndt.int32, ndt.int32],['x', 'y']),
                        ndt.type(POINT))
        class DATA(ctypes.Structure):
            _fields_ = [
                        ('pos', POINT),
                        ('flags', ctypes.c_int8),
                        ('size', ctypes.c_float),
                        ('vel', POINT)
                       ]
        self.assertEqual(ndt.make_cstruct([POINT, ndt.int8, ndt.float32, POINT],
                                ['pos', 'flags', 'size', 'vel']),
                        ndt.type(DATA))

    def test_type_from_ctypes_carray(self):
        self.assertEqual(ndt.make_cfixed_dim(10, ndt.int32),
                ndt.type(ctypes.c_int32 * 10))
        self.assertEqual(ndt.make_cfixed_dim((10, 3), ndt.int32),
                ndt.type((ctypes.c_int32 * 3) * 10))
        self.assertEqual(ndt.make_cfixed_dim((10, 3, 4), ndt.int32),
                ndt.type(((ctypes.c_int32 * 4) * 3) * 10))

        class POINT(ctypes.Structure):
            _fields_ = [('x', ctypes.c_int32), ('y', ctypes.c_int32)]
        self.assertEqual(ndt.make_cfixed_dim(10, ndt.type(POINT)),
                ndt.type(POINT * 10))

if __name__ == '__main__':
    unittest.main()


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE194_Unexpected_Sign_Extension__fgets_memcpy_62b.cpp
Label Definition File: CWE194_Unexpected_Sign_Extension.label.xml
Template File: sources-sink-62b.tmpl.cpp
*/
/*
 * @description
 * CWE: 194 Unexpected Sign Extension
 * BadSource: fgets Read data from the console using fgets()
 * GoodSource: Positive integer
 * Sinks: memcpy
 *    BadSink : Copy strings using memcpy() with the length of data
 * Flow Variant: 62 Data flow: data flows using a C++ reference from one function to another in different source files
 *
 * */

#include "std_testcase.h"

/* Must be at least 8 for atoi() to work properly */
#define CHAR_ARRAY_SIZE 8

namespace CWE194_Unexpected_Sign_Extension__fgets_memcpy_62
{

#ifndef OMITBAD

void badSource(short &data)
{
    {
        char inputBuffer[CHAR_ARRAY_SIZE] = "";
        /* FLAW: Use a value input from the console using fgets() */
        if (fgets(inputBuffer, CHAR_ARRAY_SIZE, stdin) != NULL)
        {
            /* Convert to short */
            data = (short)atoi(inputBuffer);
        }
        else
        {
            printLine("fgets() failed.");
        }
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B() uses the GoodSource with the BadSink */
void goodG2BSource(short &data)
{
    /* FIX: Use a positive integer less than &InitialDataSize&*/
    data = 100-1;
}

#endif /* OMITGOOD */

} /* close namespace */


text:
addMessageCallback( 'MsgConnectionError', handleConnectionErrorMessage );

function handleConnectionErrorMessage(%msgType, %msgString, %msgError)
{
   // On connect the server transmits a message to display if there
   // are any problems with the connection.  Most connection errors
   // are game version differences, so hopefully the server message
   // will tell us where to get the latest version of the game.
   $ServerConnectionErrorMessage = %msgError;
}

//----------------------------------------------------------------------------
// GameConnection client callbacks
//----------------------------------------------------------------------------

function GameConnection::initialControlSet(%this)
{
   echo ("*** Initial Control Object");

   // The first control object has been set by the server
   // and we are now ready to go.

   // first check if the editor is active
   if (!isToolBuild() || !Editor::checkActiveLoadDone())
   {
      if (Canvas.getContent() != PlayGui.getId())
         Canvas.setContent(PlayGui);
   }
}

function GameConnection::onControlObjectChange(%this)
{
   echo ("*** Control Object Changed");

   // Reset the current FOV to match the new object
   // and turn off any current zoom.
   resetCurrentFOV();
   turnOffZoom();
}

// Called on the new connection object after connect() succeeds.
function GameConnection::onConnectionAccepted(%this)
{
   // Startup the physX world on the client before any
   // datablocks and objects are ghosted over.
   physicsInitWorld( "client" );
}

function GameConnection::onConnectionError(%this, %msg)
{
   // General connection error, usually raised by ghosted objects
   // initialization problems, such as missing files.  We'll display
   // the server's connection error message.
   disconnectedCleanup();
   MessageBoxOK( "DISCONNECT", $ServerConnectionErrorMessage @ " (" @ %msg @ ")" );
}

//-----------------------------------------------------------------------------
// Disconnect
//-----------------------------------------------------------------------------

function disconnect()
{
   // We need to stop the client side simulation
   // else physics resources will not cleanup properly.
   physicsStopSimulation( "client" );

   // Delete the connection if it's still there.
   if (isObject(ServerConnection))
      ServerConnection.delete();

   disconnectedCleanup();

   // Call destroyServer in case we're hosting
   destroyServer();
}

function disconnectedCleanup()
{
   // End mission, if it's running.

   if( $Client::missionRunning )
      clientEndMission();

   // Disable mission lighting if it's going, this is here
   // in case we're disconnected while the mission is loading.

   $lightingMission = false;
   $sceneLighting::terminateLighting = true;

   // Back to the launch screen
   if (isObject( MainMenuGui ))
      Canvas.setContent( MainMenuGui );

   // Before we destroy the client physics world
   // make sure all ServerConnection objects are deleted.
   if(isObject(ServerConnection))
   {
      ServerConnection.deleteAllObjects();
   }

   // We can now delete the client physics simulation.
   physicsDestroyWorld( "client" );
}


text:
<!doctype html>
<meta charset="utf-8">

<title>Armoire Automated Tests Page</title>
<link rel="stylesheet" href="http://code.jquery.com/qunit/qunit-1.17.1.css">


text:
package com.aol.cyclops.functionaljava.comprehenders;

import java.util.function.Function;

import com.aol.cyclops.lambda.api.Comprehender;

import fj.data.IO;
import fj.data.IOFunctions;
import fj.data.Option;
import fj.data.State;

public class IOComprehender implements Comprehender<IO>{

	@Override
	public Object resolveForCrossTypeFlatMap(Comprehender comp, IO apply) {
		return comp.empty();
	}

	@Override
	public Object map(IO t, Function fn) {

		return IOFunctions.map(t,r->fn.apply(r));
	}

	@Override
	public Object flatMap(IO t, Function fn) {
		return IOFunctions.flatMap(t, r->(IO)fn.apply(r));
	}

	@Override
	public IO of(Object o) {
		return IOFunctions.unit(o);
	}

	@Override
	public IO empty() {
		return IOFunctions.unit(Option.none());
	}

	@Override
	public Class getTargetClass() {
		return IO.class;
	}

}


text:
{-# OPTIONS_GHC -fno-warn-orphans  #-}
{-# LANGUAGE TemplateHaskell       #-}
{-# LANGUAGE MultiParamTypeClasses #-}
module Database.HDBC.Schema.MySQL
    (
      driverMySQL
    )
    where

import           Prelude                            hiding (length)
import           Language.Haskell.TH                (TypeQ)
import qualified Data.List                          as List
import           Data.Map                           (fromList)

import           Database.HDBC                      (IConnection, SqlValue)
import           Database.HDBC.Record.Query         (runQuery')
import           Database.HDBC.Record.Persistable   ()
import           Database.HDBC.Schema.Driver        ( TypeMap
                                                    , Driver
                                                    , getFieldsWithMap
                                                    , getPrimaryKey
                                                    , emptyDriver
                                                    )
import           Database.Record.TH                 (makeRecordPersistableWithSqlTypeDefaultFromDefined)
import           Database.Relational.Schema.MySQL   ( normalizeColumn
                                                    , notNull
                                                    , getType
                                                    , columnsQuerySQL
                                                    , primaryKeyQuerySQL
                                                    )

import           Database.Relational.Schema.MySQLInfo.Columns (Columns)
import qualified Database.Relational.Schema.MySQLInfo.Columns as Columns

$(makeRecordPersistableWithSqlTypeDefaultFromDefined [t| SqlValue |] ''Columns)

logPrefix :: String -> String
logPrefix = ("MySQL: " ++)

putLog :: String -> IO ()
putLog = putStrLn . logPrefix

compileErrorIO :: String -> IO a
compileErrorIO = fail . logPrefix

getPrimaryKey' :: IConnection conn
               => conn
               -> String
               -> String
               -> IO [String]
getPrimaryKey' conn scm tbl = do
    primCols <- runQuery' conn primaryKeyQuerySQL (scm, tbl)
    let primaryKeyCols = normalizeColumn `fmap` primCols
    putLog $ "getPrimaryKey: primary key = " ++ show primaryKeyCols
    return primaryKeyCols

getFields' :: IConnection conn
           => TypeMap
           -> conn
           -> String
           -> String
           -> IO ([(String, TypeQ)], [Int])
getFields' tmap conn scm tbl = do
    cols <- runQuery' conn columnsQuerySQL (scm, tbl)
    case cols of
        [] -> compileErrorIO
                $ "getFields: No columns found: schema = " ++ scm
                ++ ", table = " ++ tbl
        _  -> return ()
    let notNullIdxs = map fst . filter (notNull . snd) . zip [0..] $ cols
    putLog
      $  "getFields: num of columns = " ++ show (List.length cols)
      ++ ", not null columns = " ++ show notNullIdxs
    types <- mapM getType' cols
    return (types, notNullIdxs)
    where
        getType' col =
            case getType (fromList tmap) col of
                Nothing -> compileErrorIO
                             $ "Type mapping is not defined against MySQL type: "
                             ++ Columns.dataType col
                Just p  -> return p

-- | Driver implementation
driverMySQL :: IConnection conn => Driver conn
driverMySQL =
    emptyDriver { getFieldsWithMap = getFields' }
                { getPrimaryKey    = getPrimaryKey' }


text:
package org.netbeans.modules.liberty.main.zzz;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import javax.swing.event.ChangeListener;
import org.netbeans.api.server.properties.InstanceProperties;
import org.netbeans.api.server.properties.InstancePropertiesManager;
import org.openide.util.ChangeSupport;

/**
 * Manager of all Liberty server instances registered in the IDE (usually just one).
 */
public class LibertyInstanceManager {

    private static final String LIBERTY_IP_NAMESPACE = "liberty.websphere"; // NOI18N

//    static final String PREFIX = "org.netbeans.modules.websphere.liberty"; // NOI18N
    static final String USERNAME = "username"; // NOI18N
    static final String PASSWORD = "password"; // NOI18N
    private static final String NAME = "name"; // NOI18N
//    private static final String ADMIN_URL = "admin-url"; // NOI18N
    private static final String DATA_CENTER = "data-center"; // NOI18N
    private static final String IDENTITY_DOMAIN = "identity-domain"; // NOI18N
    private static final String JAVA_SERVICE_NAME = "java-service-name"; // NOI18N
    private static final String DATABASE_SERVICE_NAME = "db-service-name"; // NOI18N
    private static final String ON_PREMISE_SERVICE_INSTANCE_ID = "on-premise"; // NOI18N

    private static LibertyInstanceManager instance;
    private List<LibertyInstance> instances = new ArrayList<LibertyInstance>();
    private ChangeSupport listeners;

    private static final String TEST_SERVER_NAME = "WebSphere Liberty";

    private static final Logger LOG = Logger.getLogger(LibertyInstanceManager.class.getSimpleName());

    public static synchronized LibertyInstanceManager getDefault() {
        if (instance == null) {
            instance = new LibertyInstanceManager();
        }
        return instance;
    }

    private LibertyInstanceManager() {
        listeners = new ChangeSupport(this);
        init();
    }

    private void init() {
       instances.addAll(load());
       notifyChange();
    }

    private void notifyChange() {
       listeners.fireChange();
    }

    public List<LibertyInstance> getInstances() {
        return instances;
    }

    public void add(LibertyInstance ai) {
        store(ai);
        instances.add(ai);
        notifyChange();
    }

    private void store(LibertyInstance ai) {
        InstanceProperties props = InstancePropertiesManager.getInstance().createProperties(LIBERTY_IP_NAMESPACE);
        saveUsernameAndPassword(ai);
//        props.putString(ADMIN_URL, ai.getAdminURL());
//        props.putString(DATA_CENTER, ai.getDataCenter());
//        props.putString(IDENTITY_DOMAIN, ai.getIdentityDomain());
//        props.putString(JAVA_SERVICE_NAME, ai.getJavaServiceName());
//        props.putString(DATABASE_SERVICE_NAME, ai.getDatabaseServiceName());
        props.putString(NAME, ai.getInstanceName());
//        if (ai.getOnPremiseServerInstanceId() != null) {
//            props.putString(ON_PREMISE_SERVICE_INSTANCE_ID, ai.getOnPremiseServerInstanceId());
//        }
    }

    public void update(LibertyInstance ai) {
        for(InstanceProperties props : InstancePropertiesManager.getInstance().getProperties(LIBERTY_IP_NAMESPACE)) {
            String name = props.getString(NAME, null); // NOI18N
            if (name.equals(ai.getInstanceName())) {
//                props.putString(ADMIN_URL, ai.getAdminURL());
//                props.putString(DATA_CENTER, ai.getDataCenter());
//                props.putString(IDENTITY_DOMAIN, ai.getIdentityDomain());
//                props.putString(JAVA_SERVICE_NAME, ai.getJavaServiceName());
//                props.putString(DATABASE_SERVICE_NAME, ai.getDatabaseServiceName());
//                if (ai.getOnPremiseServerInstanceId() == null) {
//                    props.removeKey(ON_PREMISE_SERVICE_INSTANCE_ID);
//                } else {
//                    props.putString(ON_PREMISE_SERVICE_INSTANCE_ID, ai.getOnPremiseServerInstanceId());
//                }
                saveUsernameAndPassword(ai);
                notifyChange();
                break;
            }
        }
    }

    public boolean exist(String adminURL, String identityDomain, String javaServiceName, String user) {
//        for (LibertyInstance oi : getInstances()) {
////            if (adminURL.equals(oi.getAdminURL())
////                    && identityDomain.equals(oi.getIdentityDomain())
////                    && javaServiceName.equals(oi.getJavaServiceName())
////                    && user.equals(oi.getUser())) {
////                return true;
////            }
//        }
        return true;
    }

    private static void saveUsernameAndPassword(LibertyInstance ai) {
//        Keyring.save(PREFIX+USERNAME+"."+ai.getName(), ai.getUser().toCharArray(), "Liberty Username"); // NOI18N
//        Keyring.save(PREFIX+PASSWORD+"."+ai.getName(), ai.getPassword().toCharArray(), "Liberty Password"); // NOI18N
    }

    private static List<LibertyInstance> load() {
        List<LibertyInstance> result = new ArrayList<LibertyInstance>();
        for(InstanceProperties props : InstancePropertiesManager.getInstance().getProperties(LIBERTY_IP_NAMESPACE)) {
            String name = props.getString(NAME, null); // NOI18N
            assert name != null : "Instance without name";
//            String adminURL = props.getString(ADMIN_URL, ""); // NOI18N
//
//            String identityDomain = props.getString(IDENTITY_DOMAIN, "undefined"); // NOI18N
//            String javaServiceName = props.getString(JAVA_SERVICE_NAME, "undefined"); // NOI18N
//            String databaseServiceName = props.getString(DATABASE_SERVICE_NAME, ""); // NOI18N
//            String onPremise = props.getString(ON_PREMISE_SERVICE_INSTANCE_ID, null); // NOI18N
//            String dataCenter = props.getString(DATA_CENTER, "us1"); // NOI18N
//            String sdkFolder = CloudSDKHelper.getSDKFolder();
//        LibertyInstance serverInfo = new LibertyInstance(
//                new File(TEST_RUNTIME_LOC + "\\usr"),
//                null,
//                TEST_SERVER_NAME,
//                TEST_RUNTIME_LOC,
//                new File(System.getProperty("java.home")),
//                7777,
//                true);
//          result.add(serverInfo);
        }
        return result;
    }

    public void addChangeListener(ChangeListener l) {
        listeners.addChangeListener(l);
    }

    public void removeChangeListener(ChangeListener l) {
        listeners.removeChangeListener(l);
    }

    void remove(LibertyInstance ai) {
        for (InstanceProperties props : InstancePropertiesManager.getInstance().getProperties(LIBERTY_IP_NAMESPACE)) {
            if (ai.getInstanceName().equals(props.getString(NAME, null))) { // NOI18N
                props.remove();
                break;
            }
        }
        instances.remove(ai);
//        ai.deregisterJ2EEServerInstances();
        notifyChange();
    }

}


text:
MongoDB\Driver\Exception\Exception extends Throwable
--SKIPIF--
<?php if (!interface_exists('Throwable')) { die('skip Throwable is not available'); } ?>
--FILE--
<?php
var_dump(in_array('Throwable', class_implements('MongoDB\Driver\Exception\Exception')));
?>
===DONE===
<?php exit(0); ?>
--EXPECT--
bool(true)
===DONE===


text:
$def with (token_url)
$var ContentType: text/plain; charset=UTF-8
$var Subject: Password reset

Dear User,

On your request, we have generated a link to reset your password.

You can do this by visiting the following page, otherwise just ignore this email and nothing will happen.

$token_url

This link will be valid for a limited time.
Please do not reply to this email as this is an automatically generated message.

Thanks.


text: Capstone Project


text:
#include "Log.h"
#include <time.h>
#include <iostream>
#include <iomanip>
#include <algorithm>

#if WONDERLAND_ACTIVE_PLATFORM == WONDERLAND_PLATFORM_WINDOWS
#	define LOGV(TAG, MSG)	{}
#	define LOGD(TAG, MSG)	{ std::cerr << message << std::endl; }
#	define LOGI(TAG, MSG)	{}
#	define LOGW(TAG, MSG)	{}
#	define LOGE(TAG, MSG)	{}
#elif WONDERLAND_ACTIVE_PLATFORM == WONDERLAND_PLATFORM_ANDROID
#	include <android/log.h>
#	define LOGV(TAG, MSG) __android_log_print(ANDROID_LOG_VERBOSE, TAG, "%s", MSG)
#	define LOGD(TAG, MSG) __android_log_print(ANDROID_LOG_DEBUG  , TAG, "%s", MSG)
#	define LOGI(TAG, MSG) __android_log_print(ANDROID_LOG_INFO   , TAG, "%s", MSG)
#	define LOGW(TAG, MSG) __android_log_print(ANDROID_LOG_WARN   , TAG, "%s", MSG)
#	define LOGE(TAG, MSG) __android_log_print(ANDROID_LOG_ERROR  , TAG, "%s", MSG)
#elif WONDERLAND_ACTIVE_PLATFORM == WONDERLAND_PLATFORM_IOS || WONDERLAND_PLATFORM_MAC
#   include <iostream>
#	define LOGV(TAG, MSG)	{}
#	define LOGD(TAG, MSG)	{ std::cout << TAG << " : " << MSG << std::endl; }
#	define LOGI(TAG, MSG)	{}
#	define LOGW(TAG, MSG)	{}
#	define LOGE(TAG, MSG)	{}
#endif // WONDERLAND_ACTIVE_PLATFORM == ...

template <> Log* Singleton< Log >::instance = 0;

//-----------------------------------------------------------------------
Log::Log()
{
}
//-----------------------------------------------------------------------
void Log::Create( const std::string& name, bool debuggerOuput, bool suppressFile )
{
	mLogLevel	= LL_NORMAL;
	mDebugOut	= debuggerOuput,
	mSuppressFile	= suppressFile;
	mTimeStamp	= true;
	mLogName	= name;

	if (!mSuppressFile)
	{
		mfpLog.open(name.c_str());
	}
}
//-----------------------------------------------------------------------
void Log::Destroy()
{
	if (!mSuppressFile)
	{
		mfpLog.close();
	}
}
//-----------------------------------------------------------------------
Log::~Log()
{
}
//-----------------------------------------------------------------------
void Log::LogDebug( const std::string& message, LogMessageLevel lml, bool maskDebug )
{
	if ((mLogLevel + lml) >= OGRE_LOG_THRESHOLD)
	{
		for( mtLogListener::iterator i = mListeners.begin(); i != mListeners.end(); ++i )
			(*i)->MessageLogged( message, lml, maskDebug, mLogName );

		if (mDebugOut && !maskDebug)
            LOGD(mLogName.c_str(), message.c_str());

#if WONDERLAND_ACTIVE_PLATFORM == WONDERLAND_PLATFORM_WINDOWS || WONDERLAND_ACTIVE_PLATFORM == WONDERLAND_PLATFORM_ANDROID
		// Write time into log
		if (!mSuppressFile)
		{
			if (mTimeStamp)
			{
				struct tm pTime;
				time_t ctTime; time(&ctTime);

				time_t tStore;
				errno_t err = localtime_s( &pTime, &tStore);
				mfpLog << std::setw(2) << std::setfill('0') << pTime.tm_hour
					<< ":" << std::setw(2) << std::setfill('0') << pTime.tm_min
					<< ":" << std::setw(2) << std::setfill('0') << pTime.tm_sec
					<< ": ";
			}
			mfpLog << message << std::endl;

			// Flush stcmdream to ensure it is written (incase of a crash, we need log to be up to date)
			mfpLog.flush();
		}
#endif
	}
}

//-----------------------------------------------------------------------
void Log::SetTimeStampEnabled(bool timeStamp)
{

	mTimeStamp = timeStamp;
}

//-----------------------------------------------------------------------
void Log::SetDebugOutputEnabled(bool debugOutput)
{

	mDebugOut = debugOutput;
}

//-----------------------------------------------------------------------
void Log::SetLogDetail(LoggingLevel ll)
{

	mLogLevel = ll;
}

//-----------------------------------------------------------------------
void Log::AddListener(LogListener* listener)
{

	mListeners.push_back(listener);
}

//-----------------------------------------------------------------------
void Log::RemoveListener(LogListener* listener)
{

	mListeners.erase(std::find(mListeners.begin(), mListeners.end(), listener));
}
//---------------------------------------------------------------------
Log::Stream Log::GetStream(LogMessageLevel lml, bool maskDebug)
{
	return Stream(this, lml, maskDebug);

}


text:
package org.olat.lms.ims.cp.objects;

import java.util.Iterator;
import java.util.Vector;

import org.dom4j.tree.DefaultElement;
import org.olat.lms.ims.cp.CPCore;
import org.olat.system.exception.OLATRuntimeException;

/**
 * Description:

 * This class represents a organization-element of a IMS-manifest-file
 *

 * Initial Date: 26.06.2008

 *
 * @author Sergio Trentini
 */
public class CPOrganization extends DefaultElement implements CPNode {

    private String title;
    private String identifier;
    private final String structure;
    private CPMetadata metadata;
    private int position;
    private CPOrganizations parent;
    private final Vector<CPItem> items;
    private final Vector<String> errors;

    /**
     * this constructor is used when the cp is built (parsing XML manifest file)
     *
     * @param me
     */
    CPOrganization(final DefaultElement me) {
        super(me.getName());
        items = new Vector<CPItem>();
        errors = new Vector<String>();
        setAttributes(me.attributes());
        setContent(me.content());

        this.identifier = me.attributeValue(CPCore.IDENTIFIER);
        this.structure = me.attributeValue(CPCore.STRUCTURE, "hierarchical");
        // this.title = me.

    }

    /**
	 */
    @Override
    public void buildChildren() {
        final Iterator<DefaultElement> children = this.elementIterator();
        // iterate through children
        while (children.hasNext()) {
            final DefaultElement child = children.next();
            if (child.getName().equals(CPCore.ITEM)) {
                final CPItem item = new CPItem(child, this);
                item.setParentElement(this);
                item.buildChildren();
                item.setPosition(items.size());
                items.add(item);
            } else if (child.getName().equals(CPCore.TITLE)) {
                title = child.getText();
            } else if (child.getName().equals(CPCore.METADATA)) {
                metadata = new CPMetadata(child);
                metadata.setParentElement(this);
            } else {
                errors.add("Invalid IMS-Manifest ( unallowed element under <organization> )");
            }
        }

        this.clearContent();
        validateElement();
    }

    /**
	 */
    @Override
    public boolean validateElement() {
        // nothing to validate
        return true;
    }

    /**
	 */
    @Override
    public void buildDocument(final DefaultElement parent) {

        final DefaultElement orgaElement = new DefaultElement(CPCore.ORGANIZATION);

        orgaElement.addAttribute(CPCore.IDENTIFIER, identifier);
        orgaElement.addAttribute(CPCore.STRUCTURE, structure);

        final DefaultElement titleElement = new DefaultElement(CPCore.TITLE);
        titleElement.setText(title);
        orgaElement.add(titleElement);

        if (metadata != null) {
            metadata.buildDocument(orgaElement);
        }
        for (final Iterator<CPItem> itItem = items.iterator(); itItem.hasNext();) {
            final CPItem item = itItem.next();
            item.buildDocument(orgaElement);
        }
        parent.add(orgaElement);

    }

    // *** CP manipulation ***

    /**
     * adds a new CPItem to the end of the items-vector
     */
    public void addItem(final CPItem newItem) {
        newItem.setParentElement(this);
        items.add(newItem);
    }

    public void addItemAt(final CPItem newItem, final int index) {
        newItem.setParentElement(this);
        if (index > -1 && index <= items.size()) {
            items.add(index, newItem);
            newItem.setPosition(index);
        } else {
            items.add(newItem);
        }
    }

    /**
     * removes this <organization> element from the manifest
     *
     * @param resourceFlag
     *            indicates whether linked resources should be deleted as well (true-->delete resources too)
     */
    public void removeFromManifest(final boolean resourceFlag) {
        for (final Iterator<CPItem> itItem = items.iterator(); itItem.hasNext();) {
            final CPItem item = itItem.next();
            parent.getParentElement().getCP().removeElement(item.getIdentifier(), resourceFlag);
        }
    }

    /**
     * removes a child <item> from this elements children-collection
     *
     * @param id
     *            the identifier of the child to remove
     */
    public void removeChild(final String id) {
        boolean removed = false;
        for (final Iterator<CPItem> itItem = items.iterator(); itItem.hasNext();) {
            final CPItem item = itItem.next();
            if (item.getIdentifier().equals(id)) {
                items.remove(item);
                removed = true;
                break;
            }
        }
        if (!removed) {
            throw new OLATRuntimeException(CPOrganizations.class, "error while removing child: child-element with identifier \"" + id + "\" not found!", new Exception());
        }

    }

    // *** getters ***

    /**
     * Returns the Item with the specified identifier Returns null if Item is not found
     *
     * @param identifier
     *            id
     * @return CPItem or null
     */
    public CPItem getItemByID(final String id) {
        final Iterator<CPItem> it = items.iterator();
        CPItem item;
        while (it.hasNext()) {
            item = it.next();
            if (item.getIdentifier().equals(id)) {
                return item;
            }
        }
        // TODO: should it throw an exception, if no element with the given
        // identifier is found ???
        return null;
    }

    public Vector<CPItem> getItems() {
        return items;
    }

    public Iterator<CPItem> getItemIterator() {
        return items.iterator();
    }

    public String getIdentifier() {
        return identifier;
    }

    public void setIdentifier(final String identifier) {
        this.identifier = identifier;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(final String title) {
        this.title = title;
    }

    String getStructure() {
        return structure;
    }

    /**
	 */
    @Override
    public DefaultElement getElementByIdentifier(final String id) {
        if (identifier.equals(id)) {
            return this;
        }

        DefaultElement e;
        for (final Iterator<CPItem> it = items.iterator(); it.hasNext();) {
            final CPItem item = it.next();
            e = item.getElementByIdentifier(id);
            if (e != null) {
                return e;
            }
        }
        return null;
    }

    @Override
    public int getPosition() {
        return position;
    }

    /**
     * returns a vector that holds all items in this organization-element (recursively, all ! )
     *
     * @return vector
     */
    public Vector<CPItem> getAllItems() {
        final Vector<CPItem> allItems = new Vector<CPItem>();
        for (final Iterator<CPItem> itItem = items.iterator(); itItem.hasNext();) {
            final CPItem item = itItem.next();
            allItems.add(item);
            allItems.addAll(item.getAllItems());
        }
        // System.out.println("item count: "+allItems.size());
        return allItems;
    }

    /**
     * Returns the first Item. If this organization has no child-items, null is returned.
     *
     * @return
     */
    public CPItem getFirstItem() {
        if (items.size() > 0) {
            return items.firstElement();
        }
        return null;
    }

    /**
     * returns the parent element
     *
     * @return
     */
    CPOrganizations getParentElement() {
        return parent;
    }

    /**
     * @return
     */
    String getLastError() {
        for (final CPItem item : getAllItems()) {
            final String err = item.getLastError();
            if (err != null) {
                return err;
            }
        }
        return null;
    }

    // *** SETTERS ***

    @Override
    public void setPosition(final int pos) {
        position = pos;
    }

    public void setParentElement(final CPOrganizations parent) {
        this.parent = parent;
    }

    public void setMetadata(final CPMetadata md) {
        metadata = md;
    }

}


text:
.class Landroid/webkit/HTML5VideoFullScreen$FullScreenMediaController;
.super Landroid/widget/MediaController;
.source "HTML5VideoFullScreen.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/webkit/HTML5VideoFullScreen;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x8
    name = "FullScreenMediaController"
.end annotation

# instance fields
.field mVideoView:Landroid/view/View;

# direct methods
.method public constructor <init>(Landroid/content/Context;Landroid/view/View;)V
    .locals 0
    .parameter "context"
    .parameter "video"

    .prologue
    .line 343
    invoke-direct {p0, p1}, Landroid/widget/MediaController;-><init>(Landroid/content/Context;)V

    .line 344
    iput-object p2, p0, Landroid/webkit/HTML5VideoFullScreen$FullScreenMediaController;->mVideoView:Landroid/view/View;

    .line 345
    return-void
.end method

# virtual methods
.method public hide()V
    .locals 2

    .prologue
    .line 357
    iget-object v0, p0, Landroid/webkit/HTML5VideoFullScreen$FullScreenMediaController;->mVideoView:Landroid/view/View;

    if-eqz v0, :cond_0

    .line 358
    iget-object v0, p0, Landroid/webkit/HTML5VideoFullScreen$FullScreenMediaController;->mVideoView:Landroid/view/View;

    const/4 v1, 0x3

    invoke-virtual {v0, v1}, Landroid/view/View;->setSystemUiVisibility(I)V

    .line 361
    :cond_0
    invoke-super {p0}, Landroid/widget/MediaController;->hide()V

    .line 362
    return-void
.end method

.method public show()V
    .locals 2

    .prologue
    .line 349
    invoke-super {p0}, Landroid/widget/MediaController;->show()V

    .line 350
    iget-object v0, p0, Landroid/webkit/HTML5VideoFullScreen$FullScreenMediaController;->mVideoView:Landroid/view/View;

    if-eqz v0, :cond_0

    .line 351
    iget-object v0, p0, Landroid/webkit/HTML5VideoFullScreen$FullScreenMediaController;->mVideoView:Landroid/view/View;

    const/4 v1, 0x0

    invoke-virtual {v0, v1}, Landroid/view/View;->setSystemUiVisibility(I)V

    .line 353
    :cond_0
    return-void
.end method