text:
namespace Xilium.CefGlue
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Runtime.InteropServices;
    using Xilium.CefGlue.Interop;

    /// <summary>
    /// Class representing a V8 context handle. V8 handles can only be accessed from
    /// the thread on which they are created. Valid threads for creating a V8 handle
    /// include the render process main thread (TID_RENDERER) and WebWorker threads.
    /// A task runner for posting tasks on the associated thread can be retrieved via
    /// the CefV8Context::GetTaskRunner() method.
    /// </summary>
    public sealed unsafe partial class CefV8Context
    {
        /// <summary>
        /// Returns the current (top) context object in the V8 context stack.
        /// </summary>
        public static cef_v8context_t* GetCurrentContext()
        {
            throw new NotImplementedException(); // TODO: CefV8Context.GetCurrentContext
        }

        /// <summary>
        /// Returns the entered (bottom) context object in the V8 context stack.
        /// </summary>
        public static cef_v8context_t* GetEnteredContext()
        {
            throw new NotImplementedException(); // TODO: CefV8Context.GetEnteredContext
        }

        /// <summary>
        /// Returns true if V8 is currently inside a context.
        /// </summary>
        public static int InContext()
        {
            throw new NotImplementedException(); // TODO: CefV8Context.InContext
        }

        /// <summary>
        /// Returns the task runner associated with this context. V8 handles can only
        /// be accessed from the thread on which they are created. This method can be
        /// called on any render process thread.
        /// </summary>
        public cef_task_runner_t* GetTaskRunner()
        {
            throw new NotImplementedException(); // TODO: CefV8Context.GetTaskRunner
        }

        /// <summary>
        /// Returns true if the underlying handle is valid and it can be accessed on
        /// the current thread. Do not call any other methods if this method returns
        /// false.
        /// </summary>
        public int IsValid()
        {
            throw new NotImplementedException(); // TODO: CefV8Context.IsValid
        }

        /// <summary>
        /// Returns the browser for this context. This method will return an empty
        /// reference for WebWorker contexts.
        /// </summary>
        public cef_browser_t* GetBrowser()
        {
            throw new NotImplementedException(); // TODO: CefV8Context.GetBrowser
        }

        /// <summary>
        /// Returns the frame for this context. This method will return an empty
        /// reference for WebWorker contexts.
        /// </summary>
        public cef_frame_t* GetFrame()
        {
            throw new NotImplementedException(); // TODO: CefV8Context.GetFrame
        }

        /// <summary>
        /// Returns the global object for this context. The context must be entered
        /// before calling this method.
        /// </summary>
        public cef_v8value_t* GetGlobal()
        {
            throw new NotImplementedException(); // TODO: CefV8Context.GetGlobal
        }

        /// <summary>
        /// Enter this context. A context must be explicitly entered before creating a
        /// V8 Object, Array, Function or Date asynchronously. Exit() must be called
        /// the same number of times as Enter() before releasing this context. V8
        /// objects belong to the context in which they are created. Returns true if
        /// the scope was entered successfully.
        /// </summary>
        public int Enter()
        {
            throw new NotImplementedException(); // TODO: CefV8Context.Enter
        }

        /// <summary>
        /// Exit this context. Call this method only after calling Enter(). Returns
        /// true if the scope was exited successfully.
        /// </summary>
        public int Exit()
        {
            throw new NotImplementedException(); // TODO: CefV8Context.Exit
        }

        /// <summary>
        /// Returns true if this object is pointing to the same handle as |that|
        /// object.
        /// </summary>
        public int IsSame(cef_v8context_t* that)
        {
            throw new NotImplementedException(); // TODO: CefV8Context.IsSame
        }

        /// <summary>
        /// Execute a string of JavaScript code in this V8 context. The |script_url|
        /// parameter is the URL where the script in question can be found, if any.
        /// The |start_line| parameter is the base line number to use for error
        /// reporting. On success |retval| will be set to the return value, if any, and
        /// the function will return true. On failure |exception| will be set to the
        /// exception, if any, and the function will return false.
        /// </summary>
        public int Eval(cef_string_t* code, cef_string_t* script_url, int start_line, cef_v8value_t** retval, cef_v8exception_t** exception)
        {
            throw new NotImplementedException(); // TODO: CefV8Context.Eval
        }

    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Sentiment.Analysis.Interfaces
{
    public class Score
    {
        public double PositiveScore { get; set; }
        public double NegativeScore { get; set; }
        public string AnalyzedBy { get; set; }
        public DateTime TimeStamp { get; set; }
    }

    interface ISentimentAnalyze
    {
        Score DoSentimentAnalysis(string contents);
        Score DoSentimentAnalysis(Uri url);
    }
}

redpajama_set_name: RedPajamaGithub


text:
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.ipnb.editor.panels.code;

import com.intellij.ide.DataManager;
import com.intellij.openapi.actionSystem.CustomShortcutSet;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.DefaultActionGroup;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.editor.event.EditorMouseEvent;
import com.intellij.openapi.editor.event.EditorMouseListener;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.ui.popup.ListPopup;
import com.intellij.openapi.wm.IdeFocusManager;
import com.intellij.reference.SoftReference;
import com.intellij.ui.Gray;
import com.intellij.ui.awt.RelativePoint;
import com.intellij.ui.components.panels.HorizontalLayout;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.plugins.ipnb.editor.IpnbEditorUtil;
import org.jetbrains.plugins.ipnb.editor.IpnbFileEditor;
import org.jetbrains.plugins.ipnb.editor.actions.*;
import org.jetbrains.plugins.ipnb.editor.panels.IpnbEditorPanel;
import org.jetbrains.plugins.ipnb.editor.panels.IpnbFilePanel;
import org.jetbrains.plugins.ipnb.editor.panels.IpnbPanel;
import org.jetbrains.plugins.ipnb.format.cells.IpnbCodeCell;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

/**
 * @author traff
 */
public class IpnbCodeSourcePanel extends IpnbPanel<JComponent, IpnbCodeCell> implements IpnbEditorPanel {
  private Editor myEditor;
  @NotNull private final Project myProject;
  @NotNull private final SoftReference<IpnbCodePanel> myParent;

  public IpnbCodeSourcePanel(@NotNull final Project project, @NotNull final IpnbCodePanel parent, @NotNull final IpnbCodeCell cell) {
    super(cell, new HorizontalLayout(5));
    myProject = project;
    myParent = new SoftReference<>(parent);
    final JComponent panel = createViewPanel();
    add(panel);
    addRightClickMenu();
  }

  public void addMouseListener(@NotNull final EditorMouseListener listener) {
    myEditor.addEditorMouseListener(listener);
  }

  @NotNull
  public IpnbCodePanel getIpnbCodePanel() {
    return SoftReference.dereference(myParent);
  }

  @Override
  @NotNull
  public Editor getEditor() {
    return myEditor;
  }

  public void dispose() {
    removeAll();
    EditorFactory.getInstance().releaseEditor(myEditor);
    myEditor = null;
  }

  @Override
  protected JComponent createViewPanel() {
    final JPanel panel = new JPanel(new BorderLayout());
    panel.setBackground(UIUtil.isUnderDarcula() ? IpnbEditorUtil.getBackground() : Gray._247);

    myEditor = IpnbEditorUtil.createPythonCodeEditor(myProject, this);
    final IpnbCodePanel codePanel = getIpnbCodePanel();
    final JComponent component = myEditor.getComponent();
    final JComponent contentComponent = myEditor.getContentComponent();

    new IpnbRunCellAction(codePanel.getFileEditor()).registerCustomShortcutSet(new CustomShortcutSet(KeyStroke.getKeyStroke("shift ENTER")), contentComponent);
    new IpnbRunCellInplaceAction(codePanel.getFileEditor()).registerCustomShortcutSet(new CustomShortcutSet(KeyStroke.getKeyStroke("ctrl ENTER")), contentComponent);

    contentComponent.addKeyListener(new KeyAdapter() {
      @Override
      public void keyPressed(KeyEvent e) {
        final int keyCode = e.getKeyCode();
        final Container parent = codePanel.getParent();
        if (keyCode == KeyEvent.VK_ESCAPE && parent instanceof IpnbFilePanel) {
          getIpnbCodePanel().setEditing(false);
          IdeFocusManager.getGlobalInstance().requestFocus(getIpnbCodePanel().getFileEditor().getIpnbFilePanel(), true);
        }
      }

      private void updateVisibleArea(boolean up) {
        final IpnbFileEditor fileEditor = codePanel.getFileEditor();
        final IpnbFilePanel ipnbPanel = fileEditor.getIpnbFilePanel();
        final Rectangle rect = ipnbPanel.getVisibleRect();

        final Rectangle cellBounds = IpnbCodeSourcePanel.this.getIpnbCodePanel().getBounds();
        final JScrollPane scrollPane = fileEditor.getScrollPane();

        final int y = cellBounds.y + myEditor.visualPositionToXY(myEditor.getCaretModel().getVisualPosition()).y;
        int delta = myEditor.getLineHeight() * 2;
        if (y <= rect.getY() && up) {
          scrollPane.getVerticalScrollBar().setValue(y);
        }
        if (y + delta > rect.getY() + rect.getHeight() && !up) {
          scrollPane.getVerticalScrollBar().setValue(y - rect.height + delta);
        }
      }

      @Override
      public void keyReleased(KeyEvent e) {
        final int keyCode = e.getKeyCode();
        final Container parent = codePanel.getParent();

        final int height = myEditor.getLineHeight() * Math.max(myEditor.getDocument().getLineCount(), 1) + 10;
        contentComponent.setPreferredSize(new Dimension(parent.getWidth() - 300, height));
        panel.setPreferredSize(new Dimension(parent.getWidth() - 300, height));

        if (parent instanceof IpnbFilePanel) {
          IpnbFilePanel ipnbFilePanel = (IpnbFilePanel)parent;
          if (keyCode == KeyEvent.VK_ENTER && InputEvent.CTRL_MASK == e.getModifiers()) {
            IpnbRunCellBaseAction.runCell(ipnbFilePanel, false);
          }
          else if (keyCode == KeyEvent.VK_ENTER && InputEvent.SHIFT_DOWN_MASK == e.getModifiersEx()) {
            IpnbRunCellBaseAction.runCell(ipnbFilePanel, true);
          }
          else if (keyCode == KeyEvent.VK_UP || keyCode == KeyEvent.VK_DOWN || keyCode == KeyEvent.VK_PAGE_DOWN ||
                   keyCode == KeyEvent.VK_PAGE_UP) {
            updateVisibleArea(keyCode == KeyEvent.VK_UP || keyCode == KeyEvent.VK_PAGE_UP);
          }
        }
      }
    });

    contentComponent.addMouseListener(new MouseAdapter() {
      @Override
      public void mousePressed(MouseEvent e) {
        if (InputEvent.CTRL_DOWN_MASK == e.getModifiersEx()) return;
        final Container ipnbFilePanel = codePanel.getParent();
        if (ipnbFilePanel instanceof IpnbFilePanel) {
          ((IpnbFilePanel)ipnbFilePanel).setSelectedCell(codePanel, true);
          codePanel.switchToEditing();
        }
        UIUtil.requestFocus(contentComponent);
      }
    });

    panel.add(component);
    contentComponent.addHierarchyListener(new HierarchyListener() {
      @Override
      public void hierarchyChanged(HierarchyEvent e) {
        final Container parent = codePanel.getParent();
        if (parent != null && myEditor != null) {
          final int height = myEditor.getLineHeight() * Math.max(myEditor.getDocument().getLineCount(), 1) + 10;
          contentComponent.setPreferredSize(new Dimension(parent.getWidth() - 300, height));
          panel.setPreferredSize(new Dimension(parent.getWidth() - 300, height));
        }
      }
    });
    contentComponent.addHierarchyBoundsListener(new HierarchyBoundsAdapter() {
      @Override
      public void ancestorResized(HierarchyEvent e) {
        final Container parent = codePanel.getParent();
        final Component component = e.getChanged();
        if (parent != null && component instanceof IpnbFilePanel && myEditor != null) {
          final int height = myEditor.getLineHeight() * Math.max(myEditor.getDocument().getLineCount(), 1) + 10;
          contentComponent.setPreferredSize(new Dimension(parent.getWidth() - 300, height));
          panel.setPreferredSize(new Dimension(parent.getWidth() - 300, height));
          panel.revalidate();
          panel.repaint();
        }
      }
    });
    return panel;
  }

  @Override
  protected void addRightClickMenu() {
    addMouseListener(new EditorMouseListener() {
      @Override
      public void mousePressed(@NotNull EditorMouseEvent e) {
        final MouseEvent mouseEvent = e.getMouseEvent();
        if (SwingUtilities.isRightMouseButton(mouseEvent) && mouseEvent.getClickCount() == 1) {
          final ListPopup menu = createPopupMenu(new DefaultActionGroup(new IpnbMergeCellAboveAction(), new IpnbMergeCellBelowAction(),
                                                                        new IpnbSplitCellAction(),
                                                                        new IpnbToggleLineNumbersAction(myParent.get())));
          menu.show(RelativePoint.fromScreen(e.getMouseEvent().getLocationOnScreen()));
        }
      }
    });
  }

  @Override
  public ListPopup createPopupMenu(@NotNull DefaultActionGroup group) {
    final DataContext context = DataManager.getInstance().getDataContext(this);
    return JBPopupFactory.getInstance().createActionGroupPopup(null, group, context, JBPopupFactory.ActionSelectionAid.MNEMONICS,
                                                               false);
  }
}


text:
Create and manager groups of users from ImageSite getting the latest (12 till now) posted photos from each user.

## Environment file

Create a `.env` file on the project root folder:

```sh
API_TOKEN=MY_TELEGRAM_API
ADMIN_ID=YOUR_ID
```

## Run

`docker-compose build && docker-compose up`

## Code example without bot:

### Install dependencies

`pip install -r requeriments.txt`

### Application

**MongoDB Server**

To store the data into a separated container:

`docker volume create --name mongodata`

Runing:

`docker run -d -p 27017:27017 --name mongod -v mongodata:/data mongo mongod`

`python example.py`


text:
[![Tests](https://github.com/ioos/ciso/actions/workflows/tests.yml/badge.svg)](https://github.com/ioos/ciso/actions/workflows/tests.yml)
[![Wheels](https://github.com/ioos/ciso/actions/workflows/cibuildwheel.yml/badge.svg)](https://github.com/ioos/ciso/actions/workflows/cibuildwheel.yml)

Fast cythonized code for iso-slices of ocean models properties.


text:
Injection flaws occur when untrusted data is sent to an interpreter as part of
a command or query. The attacker's hostile data can trick the interpreter into
executing unintended commands or accessing data without proper authorization.

- Exploitability: EASY
- Prevalence: COMMON
- Detectability: AVERAGE
- Technical Impact: SEVERE


text:
layout: post
title: Introduciendo Polyglot
lang: es
---

Después de meses de trabajo y el refinamiento, me siento orgulloso de presentar **Polyglot**: un plugin para i18n [Jekyll](http://jekyllrb.com) sitios que *necesidad* para atender su contenido a varios idiomas y audiencias.

### Características

Si bien hay otros plugins multi-idioma para Jekyll, Polyglot es especial. Polyglot se encarga de las tonterías típicas normalmente de izquierda a los desarrolladores para gestionar (como discusiones urls y la garantía de mapas de sitio consistentes) mientras que proporciona herramientas eficaces y sencillas desarrolladores Jekyll puede utilizar en SEO y agregación de contenidos vía rápida.

## Url Relativizado

En el pasado, un sitio estático multilenguaje blog o tenían que mantener un registro de lo delicado lenguaje cada enlace relativa sitio estaba sirviendo. Era demasiado fácil para un desarrollador para tropezar, y los visitantes de lengua extranjera de forma rápida se perdiera en el contenido sin traducir.

Polyglot relativiza automáticamente las direcciones url para cada idioma que desea su sitio a construir para. Esto permite que los visitantes del sitio para quedarse aislado en un idioma mientras navega por su sitio web.

## Soporte de Retorno

Cuando *usted no se han* traducido o contenido multilingüe, Jekyll todavía construir con el contenido que tienen. Cuando *usted ha* traducido o contenido multilingüe, Jekyll construirá usando ese contenido. Simple como eso.

Sitemaps mantenerse coherente en todos los idiomas, y se traducen estancias en el sitio que fue construido para.

## Rich Traducción de Contenidos

Idioma de los contenidos Rich es normalmente difícil de implementar. Cadenas cortas o lenguaje banderas dependientes suelen ser difícil para un sitio web Jekyll para mantener constante.

*Excepto cuando es tan fácil*. En su config.yml, simplemente almacenar sus cadenas como:
{% highlight yaml %}
hello:
  en: Hello!
  es: ¡hola!
  fr: Bonjour!
  de: Guten Tag!
{% endhighlight %}
y en su liquid, simplemente llame a:
{% highlight html %}
{% raw %}
{{ site.hello[site.active_lang]}}
{% endraw %}
{% endhighlight %}
produce:
<p class="message">
{{ site.hello[site.active_lang]}}
</p>

## Rápido, Asíncrono, Cero-Overhead Builds

  Polyglot va a construir su sitio web en varios idiomas tan rápido como se va a construir su sitio web idioma predeterminado. Polyglot se ejecuta con una sobrecarga mínima de *simultáneamente* edificio todos los idiomas de su sitio web como proceso independiente. Esto significa que su sitio web el tiempo de construcción no va a ser una función de la cantidad de idiomas que necesita para apoyar.

### Descargar

  Polyglot está disponible como una ruby gem, o como un plugin Jekyll. Se puede instalar con:
  {% highlight bash %}
  gem install 'jekyll-polyglot'
  {% endhighlight %}


text:
/*
 |--------------------------------------------------------------------------
 | Browser-sync config file
 |--------------------------------------------------------------------------
 |
 | For up-to-date information about the options:
 |   http://www.browsersync.io/docs/options/
 |
 | There are more options than you see here, these are just the ones that are
 | set internally. See the website for more info.
 |
 |
 */
const ConfigData = require('config')
const path = require('path')
const setupOptions = require('./config/func/setupBrowserSyncOptions')

let options = setupOptions()

// 設定の拡張
options.ui = {
  port: 3001,
  weinre: {
    port: 8080
  }
}

options.server = path.resolve(ConfigData.output_dir)
module.exports = options


text:
package com.treode.store

import scala.util.Random

import com.treode.async.Async
import com.treode.async.stubs.StubScheduler
import com.treode.async.io.stubs.StubFile
import com.treode.async.stubs.{AsyncCaptor, AsyncChecks, StubScheduler}
import com.treode.async.stubs.implicits._
import com.treode.cluster.{Cluster, HostId}
import com.treode.cluster.stubs.{StubCluster, StubHost, StubNetwork}
import com.treode.disk.stubs.{StubDisk, StubDiskDrive}
import com.treode.store.catalog.Catalogs
import org.scalatest.FlatSpec

import Async.when
import StoreTestTools._

class LibrarianSpec extends FlatSpec with AsyncChecks {

  private class StubLibrarianHost (
      val localId: HostId
  ) (implicit
      random: Random,
      scheduler: StubScheduler,
      network: StubNetwork
  ) extends StubHost {

    val config = StoreTestConfig()
    import config._

    implicit val cluster = new StubCluster (localId)
    implicit val library = new Library
    implicit val recovery = StubDisk.recover()
    implicit val _catalogs = Catalogs.recover()

    val diskDrive = new StubDiskDrive

    val _launch =
      for {
        launch <- recovery.reattach (diskDrive)
        catalogs <- _catalogs.launch (launch, cluster)
      } yield {
        launch.launch()
        (launch.disk, catalogs)
      }

    val captor = _launch.capture()
    scheduler.run()
    while (!captor.wasInvoked)
      Thread.sleep (10)
    implicit val (disk, catalogs) = captor.assertPassed()

    val rebalancer = AsyncCaptor [Unit]

    def rebalance (atlas: Atlas): Async [Unit] = {
      val active = atlas.cohorts (0) contains localId
      val moving = atlas.cohorts exists (_.moving)
      when (active && moving) (rebalancer.start())
    }

    val librarian = Librarian (rebalance _)

    cluster.startup()

    def issue (cohorts: Cohort*) {
      val version = library.atlas.version + 1
      val atlas = Atlas (cohorts.toArray, version)
      library.atlas = atlas
      library.residents = atlas.residents (localId)
      catalogs.issue (Atlas.catalog) (version, atlas) .expectPass()
    }

    def expectAtlas (atlas: Atlas) {
      assertResult (atlas) (library.atlas)
      assertResult (librarian.issued) (atlas.version)
      assert (librarian.receipts forall (_._2 == atlas.version))
    }}

  def expectAtlas (version: Int, cohorts: Cohort*) (hosts: Seq [StubLibrarianHost]) {
    val atlas = Atlas (cohorts.toArray, version)
    for (host <- hosts)
      host.expectAtlas (atlas)
  }

  "It" should "work" in {

    implicit val (random, scheduler, network) = newKit()

    val hs = Seq.fill (10) (new StubLibrarianHost (random.nextLong))
    val Seq (h0, h1, h2, h3) = hs take 4

    for (h1 <- hs; h2 <- hs)
      h1.hail (h2.localId)
    h0.issue (issuing (h0, h1, h2) (h0, h1, h3))
    scheduler.run (count = 2000, timers = true)
    expectAtlas (2, moving (h0, h1, h2) (h0, h1, h3)) (hs)
    h0.rebalancer.pass (())
    scheduler.run (count = 2000, timers = true)
    expectAtlas (2, moving (h0, h1, h2) (h0, h1, h3)) (hs)
    h1.rebalancer.pass (())
    scheduler.run (count = 2000, timers = true)
    expectAtlas (3, settled (h0, h1, h3)) (hs)
  }}


text:
package com.cyanogenmod.filemanager.ui.dialogs;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.util.Log;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.cyanogenmod.filemanager.FileManagerApplication;
import com.cyanogenmod.filemanager.R;
import com.cyanogenmod.filemanager.commands.AsyncResultListener;
import com.cyanogenmod.filemanager.commands.FolderUsageExecutable;
import com.cyanogenmod.filemanager.console.ConsoleBuilder;
import com.cyanogenmod.filemanager.model.AID;
import com.cyanogenmod.filemanager.model.FileSystemObject;
import com.cyanogenmod.filemanager.model.FolderUsage;
import com.cyanogenmod.filemanager.model.Group;
import com.cyanogenmod.filemanager.model.GroupPermission;
import com.cyanogenmod.filemanager.model.OthersPermission;
import com.cyanogenmod.filemanager.model.Permission;
import com.cyanogenmod.filemanager.model.Permissions;
import com.cyanogenmod.filemanager.model.Symlink;
import com.cyanogenmod.filemanager.model.User;
import com.cyanogenmod.filemanager.model.UserPermission;
import com.cyanogenmod.filemanager.preferences.AccessMode;
import com.cyanogenmod.filemanager.preferences.FileManagerSettings;
import com.cyanogenmod.filemanager.preferences.Preferences;
import com.cyanogenmod.filemanager.ui.ThemeManager;
import com.cyanogenmod.filemanager.ui.ThemeManager.Theme;
import com.cyanogenmod.filemanager.util.AIDHelper;
import com.cyanogenmod.filemanager.util.CommandHelper;
import com.cyanogenmod.filemanager.util.DialogHelper;
import com.cyanogenmod.filemanager.util.ExceptionUtil;
import com.cyanogenmod.filemanager.util.FileHelper;
import com.cyanogenmod.filemanager.util.MimeTypeHelper;
import com.cyanogenmod.filemanager.util.MimeTypeHelper.MimeTypeCategory;
import com.cyanogenmod.filemanager.util.ResourcesHelper;
import com.cyanogenmod.filemanager.util.StorageHelper;

import java.io.File;
import java.io.IOException;

/**
 * A class that wraps a dialog for showing information about a {@link FileSystemObject}
 */
public class FsoPropertiesDialog
    implements OnClickListener, OnCheckedChangeListener, OnItemSelectedListener,
    DialogInterface.OnCancelListener, DialogInterface.OnDismissListener, AsyncResultListener {

    private static final String TAG = "FsoPropertiesDialog"; //$NON-NLS-1$

    private static final String OWNER_TYPE = "owner"; //$NON-NLS-1$
    private static final String GROUP_TYPE = "group"; //$NON-NLS-1$
    private static final String OTHERS_TYPE = "others"; //$NON-NLS-1$

    private static final String AID_FORMAT = "%05d - %s"; //$NON-NLS-1$
    private static final String AID_SEPARATOR = " - "; //$NON-NLS-1$

    /**
     * @hide
     */
    final FileSystemObject mFso;
    /**
     * @hide
     */
    boolean mHasChanged;

    /**
     * @hide
     */
    final Context mContext;
    private final AlertDialog mDialog;
    private final View mContentView;
    private View mInfoViewTab;
    private View mPermissionsViewTab;
    private View mInfoView;
    private View mPermissionsView;
    /**
     * @hide
     */
    CheckBox mChkNoMedia;
    /**
     * @hide
     */
    Spinner mSpnOwner;
    /**
     * @hide
     */
    Spinner mSpnGroup;
    /**
     * @hide
     */
    private CheckBox[] mChkUserPermission;
    private CheckBox[] mChkGroupPermission;
    private CheckBox[] mChkOthersPermission;
    private TextView mInfoMsgView;
    /**
     * @hide
     */
    TextView mTvSize;
    /**
     * @hide
     */
    TextView mTvContains;

    /**
     * @hide
     */
    boolean mIgnoreCheckEvents;
    private boolean mHasPrivileged;
    private final boolean mIsAdvancedMode;

    private final boolean mComputeFolderStatistics;
    private FolderUsageExecutable mFolderUsageExecutable;
    private FolderUsage mFolderUsage;
    /**
     * @hide
     */
    boolean mDrawingFolderUsage;

    private DialogInterface.OnDismissListener mOnDismissListener;

    /**
     * Constructor of FsoPropertiesDialog.
     *
     * @param context The current context
     * @param fso The file system object reference
     */
    public FsoPropertiesDialog(Context context, FileSystemObject fso) {
        super();

        //Save the context
        this.mContext = context;

        //Save data
        this.mFso = fso;
        this.mHasChanged = false;
        this.mIgnoreCheckEvents = true;
        this.mHasPrivileged = false;
        this.mIsAdvancedMode =
                FileManagerApplication.getAccessMode().compareTo(AccessMode.SAFE) != 0;

        //Inflate the content
        LayoutInflater li =
                (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        this.mContentView = li.inflate(R.layout.fso_properties_dialog, null);

        // Apply current theme
        applyTheme();

        //Create the dialog
        this.mDialog = DialogHelper.createDialog(
                                        context,
                                        0,
                                        R.string.fso_properties_dialog_title,
                                        this.mContentView);
        this.mDialog.setButton(
                DialogInterface.BUTTON_NEGATIVE,
                this.mContext.getString(android.R.string.ok),
                (DialogInterface.OnClickListener)null);
        this.mDialog.setOnCancelListener(this);
        this.mDialog.setOnDismissListener(this);

        // Retrieve the user settings about computing folder statistics
        this.mComputeFolderStatistics =
                Preferences.getSharedPreferences().
                    getBoolean(
                        FileManagerSettings.SETTINGS_COMPUTE_FOLDER_STATISTICS.getId(),
                        ((Boolean)FileManagerSettings.SETTINGS_COMPUTE_FOLDER_STATISTICS.
                                getDefaultValue()).booleanValue());

        //Fill the dialog
        fillData(this.mContentView);
    }

    /**
     * Set a listener to be invoked when the dialog is dismissed.
     *
     * @param onDismissListener The {@link "OnDismissListener"} to use.
     */
    public void setOnDismissListener(DialogInterface.OnDismissListener onDismissListener) {
        this.mOnDismissListener = onDismissListener;
    }

    /**
     * Method that shows the dialog.
     */
    public void show() {
        DialogHelper.delegateDialogShow(this.mContext, this.mDialog);
    }

    /**
     * Method that return the associated {@link FileSystemObject} reference
     *
     * @return FileSystemObject The fso
     */
    public FileSystemObject getFso() {
        return this.mFso;
    }

    /**
     * Method that returns if the properties of the file was changed
     *
     * @return boolean If the properties of the file was changed
     */
    public boolean isHasChanged() {
        return this.mHasChanged;
    }

    /**
     * Method that fill the dialog with the data of the mount point.
     *
     * @param contentView The content view
     */
    private void fillData(View contentView) {
        //Get the tab views
        this.mInfoViewTab = contentView.findViewById(R.id.fso_properties_dialog_tab_info);
        this.mPermissionsViewTab =
                contentView.findViewById(R.id.fso_properties_dialog_tab_permissions);
        this.mInfoView = contentView.findViewById(R.id.fso_tab_info);
        this.mPermissionsView = contentView.findViewById(R.id.fso_tab_permissions);

        //Register the listeners
        this.mInfoViewTab.setOnClickListener(this);
        this.mPermissionsViewTab.setOnClickListener(this);

        //Gets text views
        TextView tvName = (TextView)contentView.findViewById(R.id.fso_properties_name);
        TextView tvParent = (TextView)contentView.findViewById(R.id.fso_properties_parent);
        TextView tvType = (TextView)contentView.findViewById(R.id.fso_properties_type);
        View vCategoryRow = contentView.findViewById(R.id.fso_properties_category_row);
        TextView tvCategory = (TextView)contentView.findViewById(R.id.fso_properties_category);
        View vLinkRow = contentView.findViewById(R.id.fso_properties_link_row);
        TextView tvLink = (TextView)contentView.findViewById(R.id.fso_properties_link);
        this.mTvSize = (TextView)contentView.findViewById(R.id.fso_properties_size);
        View vContatinsRow = contentView.findViewById(R.id.fso_properties_contains_row);
        this.mTvContains = (TextView)contentView.findViewById(R.id.fso_properties_contains);
        TextView tvLastAccessedTime =
                (TextView)contentView.findViewById(R.id.fso_properties_last_accessed);
        TextView tvLastModifiedTime =
                (TextView)contentView.findViewById(R.id.fso_properties_last_modified);
        TextView tvLastChangedTime =
                (TextView)contentView.findViewById(R.id.fso_properties_last_changed);
        this.mChkNoMedia = (CheckBox)contentView.findViewById(R.id.fso_include_in_media_scan);
        this.mSpnOwner = (Spinner)contentView.findViewById(R.id.fso_properties_owner);
        this.mSpnGroup = (Spinner)contentView.findViewById(R.id.fso_properties_group);
        this.mInfoMsgView = (TextView)contentView.findViewById(R.id.fso_info_msg);

        //Fill the text views
        //- Info
        tvName.setText(this.mFso.getName());
        if (FileHelper.isRootDirectory(this.mFso)) {
            tvParent.setText("-"); //$NON-NLS-1$
        } else {
            tvParent.setText(this.mFso.getParent());
        }
        tvType.setText(MimeTypeHelper.getMimeTypeDescription(this.mContext, this.mFso));
        if (this.mFso instanceof Symlink) {
            Symlink link = (Symlink)this.mFso;
            if (link.getLinkRef() != null) {
                tvLink.setText(link.getLinkRef().getFullPath());
            } else {
                tvLink.setText("-"); //$NON-NLS-1$
            }
        }
        MimeTypeCategory category = MimeTypeHelper.getCategory(this.mContext, this.mFso);
        if (category.compareTo(MimeTypeCategory.NONE) == 0) {
            vCategoryRow.setVisibility(View.GONE);
        } else {
            tvCategory.setText(
                    MimeTypeHelper.getCategoryDescription(
                            this.mContext, category));
        }
        vLinkRow.setVisibility(this.mFso instanceof Symlink ? View.VISIBLE : View.GONE);
        String size = FileHelper.getHumanReadableSize(this.mFso);
        if (size.length() == 0) {
            size = "-"; //$NON-NLS-1$
        }
        this.mTvSize.setText(size);
        this.mTvContains.setText("-");  //$NON-NLS-1$
        tvLastAccessedTime.setText(
                FileHelper.formatFileTime(this.mContext, this.mFso.getLastAccessedTime()));
        tvLastModifiedTime.setText(
                FileHelper.formatFileTime(this.mContext, this.mFso.getLastModifiedTime()));
        tvLastChangedTime.setText(
                FileHelper.formatFileTime(this.mContext, this.mFso.getLastChangedTime()));

        //- Permissions
        String loadingMsg = this.mContext.getString(R.string.loading_message);
        setSpinnerMsg(this.mContext, FsoPropertiesDialog.this.mSpnOwner, loadingMsg);
        setSpinnerMsg(this.mContext, FsoPropertiesDialog.this.mSpnGroup, loadingMsg);
        updatePermissions();

        // Load owners and groups AIDs in background
        loadAIDs();

        // Load owners and groups AIDs in background
        if (FileHelper.isDirectory(this.mFso)) {
            vContatinsRow.setVisibility(View.VISIBLE);
            if (this.mComputeFolderStatistics) {
                computeFolderUsage();
            }
        }

        // Check if permissions operations are allowed
        try {
            this.mHasPrivileged = ConsoleBuilder.getConsole(this.mContext).isPrivileged();
        } catch (Throwable ex) {/**NON BLOCK**/}
        this.mSpnOwner.setEnabled(this.mHasPrivileged);
        this.mSpnGroup.setEnabled(this.mHasPrivileged);
        // Not allowed for symlinks
        if (!(this.mFso instanceof Symlink)) {
            setCheckBoxesPermissionsEnable(this.mChkUserPermission, this.mHasPrivileged);
            setCheckBoxesPermissionsEnable(this.mChkGroupPermission, this.mHasPrivileged);
            setCheckBoxesPermissionsEnable(this.mChkOthersPermission, this.mHasPrivileged);
        } else {
            setCheckBoxesPermissionsEnable(this.mChkUserPermission, false);
            setCheckBoxesPermissionsEnable(this.mChkGroupPermission, false);
            setCheckBoxesPermissionsEnable(this.mChkOthersPermission, false);
        }
        if (!this.mHasPrivileged && this.mIsAdvancedMode) {
            this.mInfoMsgView.setVisibility(View.VISIBLE);
            this.mInfoMsgView.setOnClickListener(this);
        }

        // Add the listener after set the value to avoid raising triggers
        this.mSpnOwner.setOnItemSelectedListener(this);
        this.mSpnGroup.setOnItemSelectedListener(this);
        setPermissionCheckBoxesListener(this.mChkUserPermission);
        setPermissionCheckBoxesListener(this.mChkGroupPermission);
        setPermissionCheckBoxesListener(this.mChkOthersPermission);

        // Check if we should show "Skip media scan" toggle
        if (!FileHelper.isDirectory(this.mFso) ||
            !StorageHelper.isPathInStorageVolume(this.mFso.getFullPath())) {
            LinearLayout fsoSkipMediaScanView =
                    (LinearLayout)contentView.findViewById(R.id.fso_skip_media_scan_view);
            fsoSkipMediaScanView.setVisibility(View.GONE);
        } else {
            //attach the click events
            this.mChkNoMedia.setChecked(isNoMediaFilePresent());
            this.mChkNoMedia.setOnCheckedChangeListener(this);
        }

        //Change the tab
        onClick(this.mInfoViewTab);
        this.mIgnoreCheckEvents = false;
    }

    /**
     * Method that loads the AIDs in background
     */
    private void loadAIDs() {
        // Load owners and groups AIDs in background
        AsyncTask<Void, Void, SparseArray<AID>> aidsTask =
                        new AsyncTask<Void, Void, SparseArray<AID>>() {
            @Override
            protected SparseArray<AID> doInBackground(Void...params) {
                return AIDHelper.getAIDs(FsoPropertiesDialog.this.mContext, true);
            }

            @Override
            protected void onPostExecute(SparseArray<AID> aids) {
                if (!isCancelled()) {
                    // Ensure that at least one AID was loaded
                    if (aids == null) {
                        String errorMsg =
                                FsoPropertiesDialog.this.mContext.getString(R.string.error_message);
                        setSpinnerMsg(
                                FsoPropertiesDialog.this.mContext,
                                FsoPropertiesDialog.this.mSpnOwner, errorMsg);
                        setSpinnerMsg(
                                FsoPropertiesDialog.this.mContext,
                                FsoPropertiesDialog.this.mSpnGroup, errorMsg);
                        return;
                    }

                    // Position of the owner and group
                    int owner = FsoPropertiesDialog.this.mFso.getUser().getId();
                    int group = FsoPropertiesDialog.this.mFso.getGroup().getId();
                    int ownerPosition = 0;
                    int groupPosition = 0;

                    // Convert the SparseArray in an array of string of "uid - name"
                    int len = aids.size();
                    final String[] data = new String[len];
                    for (int i = 0; i < len; i++) {
                        AID aid = aids.valueAt(i);
                        data[i] = String.format(AID_FORMAT,
                                        Integer.valueOf(aid.getId()), aid.getName());
                        if (owner == aid.getId()) ownerPosition = i;
                        if (group == aid.getId()) groupPosition = i;
                    }

                    // Change the adapter of the spinners
                    setSpinnerData(
                            FsoPropertiesDialog.this.mContext,
                            FsoPropertiesDialog.this.mSpnOwner, data, ownerPosition);
                    setSpinnerData(
                            FsoPropertiesDialog.this.mContext,
                            FsoPropertiesDialog.this.mSpnGroup, data, groupPosition);
                }
            }
        };
        aidsTask.execute();
    }

    /**
     * Method that computes the disk usage of the folder in background
     */
    private void computeFolderUsage() {
        try {
            if (this.mFso instanceof Symlink && ((Symlink) this.mFso).getLinkRef() != null) {
                this.mFolderUsageExecutable =
                    CommandHelper.getFolderUsage(
                            this.mContext,
                            ((Symlink) this.mFso).getLinkRef().getFullPath(), this, null);
            } else {
                this.mFolderUsageExecutable =
                    CommandHelper.getFolderUsage(
                        this.mContext, this.mFso.getFullPath(), this, null);
            }
        } catch (Exception cause) {
            //Capture the exception
            ExceptionUtil.translateException(this.mContext, cause, true, false);
            this.mTvSize.setText(R.string.error_message);
            this.mTvContains.setText(R.string.error_message);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void onDismiss(DialogInterface dialog) {
        cancelFolderUsageCommand();
        if (this.mOnDismissListener != null) {
            this.mOnDismissListener.onDismiss(dialog);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void onCancel(DialogInterface dialog) {
        cancelFolderUsageCommand();
        if (this.mOnDismissListener != null) {
            this.mOnDismissListener.onDismiss(dialog);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.fso_properties_dialog_tab_info:
                if (!this.mInfoViewTab.isSelected()) {
                    this.mInfoViewTab.setSelected(true);
                    ((TextView)this.mInfoViewTab).setTextAppearance(
                            this.mContext, R.style.primary_text_appearance);
                    this.mPermissionsViewTab.setSelected(false);
                    ((TextView)this.mPermissionsViewTab).setTextAppearance(
                            this.mContext, R.style.secondary_text_appearance);
                    this.mInfoView.setVisibility(View.VISIBLE);
                    this.mPermissionsView.setVisibility(View.GONE);

                    // Apply the them
                    applyTabTheme();
                }
                break;

            case R.id.fso_properties_dialog_tab_permissions:
                if (!this.mPermissionsViewTab.isSelected()) {
                    this.mInfoViewTab.setSelected(false);
                    ((TextView)this.mInfoViewTab).setTextAppearance(
                            this.mContext, R.style.secondary_text_appearance);
                    this.mPermissionsViewTab.setSelected(true);
                    ((TextView)this.mPermissionsViewTab).setTextAppearance(
                            this.mContext, R.style.primary_text_appearance);
                    this.mInfoView.setVisibility(View.GONE);
                    this.mPermissionsView.setVisibility(View.VISIBLE);

                    // Apply the them
                    applyTabTheme();

                    // Adjust the size of the spinners
                    adjustSpinnerSize(this.mSpnOwner);
                    adjustSpinnerSize(this.mSpnGroup);
                }
                this.mInfoMsgView.setVisibility(
                        this.mHasPrivileged || !this.mIsAdvancedMode ? View.GONE : View.VISIBLE);
                break;

            case R.id.fso_info_msg:
                //Change the console
                boolean superuser = ConsoleBuilder.changeToPrivilegedConsole(this.mContext);
                if (superuser) {
                    this.mInfoMsgView.setOnClickListener(null);
                    this.mInfoMsgView.setVisibility(View.GONE);
                    this.mInfoMsgView.setBackground(null);

                    // Enable controls
                    this.mSpnOwner.setEnabled(true);
                    this.mSpnGroup.setEnabled(true);
                    setCheckBoxesPermissionsEnable(this.mChkUserPermission, true);
                    setCheckBoxesPermissionsEnable(this.mChkGroupPermission, true);
                    setCheckBoxesPermissionsEnable(this.mChkOthersPermission, true);
                    // Not allowed for symlinks
                    if (!(this.mFso instanceof Symlink)) {
                        setCheckBoxesPermissionsEnable(this.mChkUserPermission, true);
                        setCheckBoxesPermissionsEnable(this.mChkGroupPermission, true);
                        setCheckBoxesPermissionsEnable(this.mChkOthersPermission, true);
                    }
                    this.mHasPrivileged = true;
                }
                break;

            default:
                break;
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        switch (buttonView.getId()) {
            case R.id.fso_include_in_media_scan:
                onNoMediaCheckedChanged(buttonView, isChecked);
                break;

            default:
                onPermissionsCheckedChanged(buttonView, isChecked);
                break;
        }
    }

    /**
     * Method that manage a check changed event
     *
     * @param buttonView The checkbox
     * @param isChecked If the checkbox is checked
     */
    private void onNoMediaCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (this.mIgnoreCheckEvents) {
            this.mIgnoreCheckEvents = false;
            return;
        }
        // Checked means "skip media scan"
        final File nomedia = FileHelper.getNoMediaFile(this.mFso);
        if (isChecked) {
            preventMediaScan(nomedia);
        } else {
            allowMediaScan(nomedia);
        }
    }

    /**
     * Method that manage a check changed event
     *
     * @param buttonView The checkbox
     * @param isChecked If the checkbox is checked
     */
    private void onPermissionsCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (this.mIgnoreCheckEvents) return;
        try {
            // Cancel the folder usage command
            cancelFolderUsageCommand();

            // Retrieve the permissions and send to operating system
            Permissions permissions = getPermissions();
            if (!CommandHelper.changePermissions(
                    this.mContext, this.mFso.getFullPath(), permissions, null)) {
                // Show the warning message
                setMsg(this.mContext.getString(
                        R.string.fso_properties_failed_to_change_permission_msg));

                // Update the permissions with the previous information
                updatePermissions();
                return;
            }

            // Some filesystem, like sdcards, doesn't allow to change the permissions.
            // But the system doesn't return the fail. Read again the fso and compare to
            // ensure that the permission was changed
            try {
                FileSystemObject systemFso  =
                        CommandHelper.getFileInfo(
                                this.mContext, this.mFso.getFullPath(), false, null);
                if (systemFso == null || systemFso.getPermissions().compareTo(permissions) != 0) {
                    // Show the warning message
                    setMsg(FsoPropertiesDialog.this.mContext.getString(
                            R.string.fso_properties_failed_to_change_permission_msg));

                    // Update the permissions with the previous information
                    updatePermissions();
                    return;
                }
            } catch (Exception e) {
                // Show the warning message
                setMsg(FsoPropertiesDialog.this.mContext.getString(
                        R.string.fso_properties_failed_to_change_permission_msg));

                // Update the permissions with the previous information
                updatePermissions();
                return;
            }

            // The permission was changed. Refresh the information
            this.mFso.setPermissions(permissions);
            this.mHasChanged = true;
            setMsg(null);

        } catch (Exception ex) {
            // Capture the exception and show warning message
            ExceptionUtil.translateException(
                    this.mContext, ex, true, true, new ExceptionUtil.OnRelaunchCommandResult() {
                @Override
                public void onSuccess() {
                    // Hide the message
                    setMsg(null);
                }

                @Override
                public void onCancelled() {
                    // Update the permissions with the previous information
                    updatePermissions();
                    setMsg(null);
                }

                @Override
                public void onFailed(Throwable cause) {
                    // Show the warning message
                    setMsg(FsoPropertiesDialog.this.mContext.getString(
                            R.string.fso_properties_failed_to_change_permission_msg));

                    // Update the permissions with the previous information
                    updatePermissions();
                }
            });
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        User user = null;
        Group group = null;
        String msg = null;

        try {
            // Apply theme
            Theme theme = ThemeManager.getCurrentTheme(this.mContext);
            theme.setTextColor(
                    this.mContext, ((TextView) parent.getChildAt(0)), "text_color"); //$NON-NLS-1$

            String row = parent.getItemAtPosition(position).toString();
            int uid = Integer.parseInt(row.substring(0, row.indexOf(AID_SEPARATOR)));
            String name = row.substring(row.indexOf(AID_SEPARATOR) + 3);

            // Check which spinner was changed
            switch (parent.getId()) {
                case R.id.fso_properties_owner:
                    //Owner
                    user = new User(uid, name);
                    group = this.mFso.getGroup();
                    msg = this.mContext.getString(
                            R.string.fso_properties_failed_to_change_owner_msg);
                    break;
                case R.id.fso_properties_group:
                    //Group
                    user = this.mFso.getUser();
                    group = new Group(uid, name);
                    msg = this.mContext.getString(
                            R.string.fso_properties_failed_to_change_group_msg);
                    break;

                default:
                    break;
            }
        } catch (Exception ex) {
            // Capture the exception
            ExceptionUtil.translateException(this.mContext, ex);

            // Exit from dialog. The dialog may have inconsistency
            this.mDialog.dismiss();
            return;
        }

        // Has changed?
        if (this.mFso.getUser().compareTo(user) == 0 &&
             this.mFso.getGroup().compareTo(group) == 0) {
            return;
        }

        // Cancel the folder usage command
        cancelFolderUsageCommand();

        // Change the owner and group of the fso
        try {
            if (!CommandHelper.changeOwner(
                    this.mContext, this.mFso.getFullPath(), user, group, null)) {
                // Show the warning message
                setMsg(msg);

                // Update the information of owner and group
                updateSpinnerFromAid(this.mSpnOwner, this.mFso.getUser());
                updateSpinnerFromAid(this.mSpnGroup, this.mFso.getGroup());
                return;
            }

            //Change the fso reference
            this.mFso.setUser(user);
            this.mFso.setGroup(group);
            this.mHasChanged = true;
            setMsg(null);

        } catch (Exception ex) {
            // Capture the exception and show warning message
            final String txtMsg = msg;
            ExceptionUtil.translateException(
                    this.mContext, ex, true, true, new ExceptionUtil.OnRelaunchCommandResult() {
                @Override
                public void onSuccess() {
                    // Hide the message
                    setMsg(null);
                }

                @Override
                public void onCancelled() {
                    // Update the information of owner and group
                    updateSpinnerFromAid(
                            FsoPropertiesDialog.this.mSpnOwner,
                            FsoPropertiesDialog.this.mFso.getUser());
                    updateSpinnerFromAid(
                            FsoPropertiesDialog.this.mSpnGroup,
                            FsoPropertiesDialog.this.mFso.getGroup());
                    setMsg(null);
                }

                @Override
                public void onFailed(Throwable cause) {
                    setMsg(txtMsg);

                    // Update the information of owner and group
                    updateSpinnerFromAid(
                            FsoPropertiesDialog.this.mSpnOwner,
                            FsoPropertiesDialog.this.mFso.getUser());
                    updateSpinnerFromAid(
                            FsoPropertiesDialog.this.mSpnGroup,
                            FsoPropertiesDialog.this.mFso.getGroup());
                    return;
                }
            });

        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void onNothingSelected(AdapterView<?> parent) {/**NON BLOCK**/}

    /**
     * Method that shows a simple message on the spinner (loading, error, ...)
     *
     * @param ctx The current context
     * @param spinner The spinner
     * @param msg The message
     * @hide
     */
    static void setSpinnerMsg(Context ctx, Spinner spinner, String msg) {
        ArrayAdapter<String> loadingAdapter =
                new ArrayAdapter<String>(
                        ctx, R.layout.spinner_item, new String[]{msg});
        loadingAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(loadingAdapter);
        spinner.setEnabled(false);
    }

    /**
     * Method that fills the spinner with the data
     *
     * @param ctx The current context
     * @param spinner The spinner
     * @param data The data
     * @param selection The object to select
     * @hide
     */
    void setSpinnerData(
            Context ctx, Spinner spinner, String[] data, int selection) {
        ArrayAdapter<String> adapter =
                new ArrayAdapter<String>(
                        ctx, R.layout.spinner_item, data);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        spinner.setSelection(selection);
        spinner.setEnabled(this.mHasPrivileged);
    }

    /**
     * Method that update a spinner from an {@link AID} reference
     *
     * @param spinner The spinner to update
     * @param aid The {@link AID} reference
     */
    @SuppressWarnings({"unchecked", "boxing"})
    public static void updateSpinnerFromAid(Spinner spinner, AID aid) {
        ArrayAdapter<String> adapter = (ArrayAdapter<String>)spinner.getAdapter();
        int position = adapter.getPosition(String.format(AID_FORMAT, aid.getId(), aid.getName()));
        if (position != -1) {
            spinner.setSelection(position);
        }
    }

    /**
     * Method that refresh the information of permissions
     * @hide
     */
    void updatePermissions() {
        // Update the permissions with the previous information
        FsoPropertiesDialog.this.mIgnoreCheckEvents = true;
        try {
            Permissions permissions = this.mFso.getPermissions();
            this.mChkUserPermission =
                    loadCheckBoxUserPermission(
                            this.mContext, this.mContentView, permissions.getUser());
            this.mChkGroupPermission =
                    loadCheckBoxGroupPermission(
                            this.mContext, this.mContentView, permissions.getGroup());
            this.mChkOthersPermission =
                    loadCheckBoxOthersPermission(
                            this.mContext, this.mContentView, permissions.getOthers());
        } finally {
            FsoPropertiesDialog.this.mIgnoreCheckEvents = false;
        }
    }

    /**
     * Method that load the checkboxes for a user permission
     *
     * @param ctx The current context
     * @param rootView The root view
     * @return UserPermission The user permission
     */
    private static CheckBox[] loadCheckBoxUserPermission (
            Context ctx, View rootView, UserPermission permission) {
        CheckBox[] chkPermissions = loadPermissionCheckBoxes(ctx, rootView, OWNER_TYPE);
        chkPermissions[0].setChecked(permission.isSetUID());
        setCheckBoxesPermissions(chkPermissions, permission);
        return chkPermissions;
    }

    /**
     * Method that load the checkboxes for a group permission
     *
     * @param ctx The current context
     * @param rootView The root view
     * @return UserPermission The user permission
     */
    private static CheckBox[] loadCheckBoxGroupPermission (
            Context ctx, View rootView, GroupPermission permission) {
        CheckBox[] chkPermissions = loadPermissionCheckBoxes(ctx, rootView, GROUP_TYPE);
        chkPermissions[0].setChecked(permission.isSetGID());
        setCheckBoxesPermissions(chkPermissions, permission);
        return chkPermissions;
    }

    /**
     * Method that load the checkboxes for a group permission
     *
     * @param ctx The current context
     * @param rootView The root view
     * @return UserPermission The user permission
     */
    private static CheckBox[] loadCheckBoxOthersPermission (
            Context ctx, View rootView, OthersPermission permission) {
        CheckBox[] chkPermissions = loadPermissionCheckBoxes(ctx, rootView, OTHERS_TYPE);
        chkPermissions[0].setChecked(permission.isStickybit());
        setCheckBoxesPermissions(chkPermissions, permission);
        return chkPermissions;
    }

    /**
     * Method that check/uncheck the common permission for a permission checkboxes
     *
     * @param chkPermissions The checkboxes
     * @param permission The permission
     */
    private static void setCheckBoxesPermissions (
            CheckBox[] chkPermissions, Permission permission) {
        chkPermissions[1].setChecked(permission.isRead());
        chkPermissions[2].setChecked(permission.isWrite());
        chkPermissions[3].setChecked(permission.isExecute());
    }

    /**
     * Method that check/uncheck the common permission for a permission checkboxes
     *
     * @param chkPermissions The checkboxes
     * @param enabled If the checkbox should be enabled
     */
    private static void setCheckBoxesPermissionsEnable (
            CheckBox[] chkPermissions, boolean enabled) {
        int cc = chkPermissions.length;
        for (int i = 0; i < cc; i++) {
            chkPermissions[i].setEnabled(enabled);
        }
    }

    /**
     * Method that load the checkboxes associated with a type of permission
     *
     * @param ctx The current context
     * @param rootView The root view
     * @param type The type of permission [owner, group, others]
     * @return CheckBox[] The checkboxes associated
     */
    private static CheckBox[] loadPermissionCheckBoxes(Context ctx, View rootView, String type) {
        Resources res = ctx.getResources();
        CheckBox[] chkPermissions = new CheckBox[4];
        chkPermissions[0] = (CheckBox)rootView.findViewById(
                ResourcesHelper.getIdentifier(
                        res, "id",  //$NON-NLS-1$
                        String.format("fso_permissions_%s_special", type))); //$NON-NLS-1$
        chkPermissions[1] = (CheckBox)rootView.findViewById(
                ResourcesHelper.getIdentifier(
                        res, "id",  //$NON-NLS-1$
                        String.format("fso_permissions_%s_read", type))); //$NON-NLS-1$
        chkPermissions[2] = (CheckBox)rootView.findViewById(
                ResourcesHelper.getIdentifier(
                        res, "id",  //$NON-NLS-1$
                        String.format("fso_permissions_%s_write", type))); //$NON-NLS-1$
        chkPermissions[3] = (CheckBox)rootView.findViewById(
                ResourcesHelper.getIdentifier(
                        res, "id",  //$NON-NLS-1$
                        String.format("fso_permissions_%s_execute", type))); //$NON-NLS-1$
        return chkPermissions;
    }

    /**
     * Method that sets the listener for the permission checkboxes
     *
     * @param chkPermissions The checkboxes
     */
    private void setPermissionCheckBoxesListener(CheckBox[] chkPermissions) {
        int cc = chkPermissions.length;
        for (int i = 0; i < cc; i++) {
            chkPermissions[i].setOnCheckedChangeListener(this);
        }
    }

    /**
     * Method that retrieves the current permissions selected by the user
     *
     * @return Permissions The permissions selected by the user
     */
    private Permissions getPermissions() {
        UserPermission userPermission =
                new UserPermission(
                        this.mChkUserPermission[1].isChecked(),
                        this.mChkUserPermission[2].isChecked(),
                        this.mChkUserPermission[3].isChecked(),
                        this.mChkUserPermission[0].isChecked());
        GroupPermission groupPermission =
                new GroupPermission(
                        this.mChkGroupPermission[1].isChecked(),
                        this.mChkGroupPermission[2].isChecked(),
                        this.mChkGroupPermission[3].isChecked(),
                        this.mChkGroupPermission[0].isChecked());
        OthersPermission othersPermission =
                new OthersPermission(
                        this.mChkOthersPermission[1].isChecked(),
                        this.mChkOthersPermission[2].isChecked(),
                        this.mChkOthersPermission[3].isChecked(),
                        this.mChkOthersPermission[0].isChecked());
        Permissions permissions =
                new Permissions(userPermission, groupPermission, othersPermission);
        return permissions;
    }

    /**
     * Method that set a message in the dialog. If the message is {@link null} then
     * the view is hidden
     *
     * @param msg The message to show. {@link null} to hide the dialog
     * @hide
     */
    void setMsg(String msg) {
        this.mInfoMsgView.setText(msg);
        this.mInfoMsgView.setVisibility(
                !this.mIsAdvancedMode || (this.mHasPrivileged && msg == null) ?
                        View.GONE :
                        View.VISIBLE);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void onAsyncStart() {
        this.mDrawingFolderUsage = false;
        this.mFolderUsage = new FolderUsage(this.mFso.getFullPath());
        printFolderUsage(true, false);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void onAsyncEnd(final boolean cancelled) {
        try {
            // Clone the reference
            FsoPropertiesDialog.this.mFolderUsage =
                    (FolderUsage)this.mFolderUsageExecutable.getFolderUsage().clone();
            printFolderUsage(true, cancelled);
        } catch (Exception ex) {/**NON BLOCK**/}
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void onPartialResult(final Object partialResults) {
        try {
            // Do not saturate ui thread
            if (this.mDrawingFolderUsage) {
                return;
            }

            // Clone the reference
            FsoPropertiesDialog.this.mFolderUsage =
                    (FolderUsage)(((FolderUsage)partialResults).clone());
            printFolderUsage(true, false);
        } catch (Exception ex) {/**NON BLOCK**/}
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void onAsyncExitCode(int exitCode) {/**NON BLOCK**/}

    /**
     * {@inheritDoc}
     */
    @Override
    public void onException(Exception cause) {
        //Capture the exception
        ExceptionUtil.translateException(this.mContext, cause);
    }

    /**
     * Method that cancels the folder usage command execution
     */
    private void cancelFolderUsageCommand() {
        if (this.mComputeFolderStatistics) {
            // Cancel the folder usage command
            try {
                if (this.mFolderUsageExecutable != null &&
                    this.mFolderUsageExecutable.isCancellable() &&
                    !this.mFolderUsageExecutable.isCancelled()) {
                    this.mFolderUsageExecutable.cancel();
                }
            } catch (Exception ex) {
                Log.e(TAG, "Failed to cancel the folder usage command", ex); //$NON-NLS-1$
            }
        }
    }

    /**
     * Method that redraws the information about folder usage
     *
     * @param computing If the process if computing the data
     * @param cancelled If the process was cancelled
     */
    private void printFolderUsage(final boolean computing, final boolean cancelled) {
        // Mark that a drawing is in progress
        this.mDrawingFolderUsage = true;

        final Resources res = this.mContext.getResources();
        if (cancelled) {
            try {
                FsoPropertiesDialog.this.mTvSize.setText(R.string.cancelled_message);
                FsoPropertiesDialog.this.mTvContains.setText(R.string.cancelled_message);
            } catch (Throwable e) {/**NON BLOCK**/}

            // End of drawing
            this.mDrawingFolderUsage = false;
        } else {
            // Calculate size prior to use ui thread
            final String size = FileHelper.getHumanReadableSize(this.mFolderUsage.getTotalSize());

            // Compute folders and files string
            String folders = res.getQuantityString(
                                        R.plurals.n_folders,
                                        this.mFolderUsage.getNumberOfFolders(),
                                        Integer.valueOf(this.mFolderUsage.getNumberOfFolders()));
            String files = res.getQuantityString(
                                        R.plurals.n_files,
                                        this.mFolderUsage.getNumberOfFiles(),
                                        Integer.valueOf(this.mFolderUsage.getNumberOfFiles()));
            final String contains = res.getString(
                                        R.string.fso_properties_dialog_folder_items,
                                        folders, files);

            // Update the dialog
            ((Activity)this.mContext).runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (computing) {
                        FsoPropertiesDialog.this.mTvSize.setText(
                                res.getString(R.string.computing_message, size));
                        FsoPropertiesDialog.this.mTvContains.setText(
                                res.getString(R.string.computing_message_ln, contains));
                    } else {
                        FsoPropertiesDialog.this.mTvSize.setText(size);
                        FsoPropertiesDialog.this.mTvContains.setText(contains);
                    }

                    // End of drawing
                    FsoPropertiesDialog.this.mDrawingFolderUsage = false;
                }
            });
        }
    }

    /**
     * Method that adjust the size of the spinner to fit the window
     *
     * @param spinner The spinner
     */
    private void adjustSpinnerSize(final Spinner spinner) {
        final View v = this.mContentView.findViewById(R.id.fso_properties_dialog_tabhost);
        spinner.post(new Runnable() {
            @Override
            public void run() {
                // Align with the last checkbox of the column
                int vW = v.getMeasuredWidth();
                int[] cbSpn = new int[2];
                spinner.getLocationInWindow(cbSpn);

                // Set the width
                spinner.getLayoutParams().width = vW - cbSpn[0];
            }
        });
    }

    /**
     * Method that applies the current theme to the activity
     */
    private void applyTheme() {
        Theme theme = ThemeManager.getCurrentTheme(this.mContext);
        theme.setBackgroundDrawable(
                this.mContext, this.mContentView, "background_drawable"); //$NON-NLS-1$
        applyTabTheme();
        View v = this.mContentView.findViewById(R.id.fso_properties_dialog_tab_divider1);
        theme.setBackgroundColor(this.mContext, v, "horizontal_divider_color"); //$NON-NLS-1$
        v = this.mContentView.findViewById(R.id.fso_properties_dialog_tab_divider2);
        theme.setBackgroundColor(this.mContext, v, "vertical_divider_color"); //$NON-NLS-1$
        v = this.mContentView.findViewById(R.id.fso_properties_dialog_tab_divider3);
        theme.setBackgroundColor(this.mContext, v, "vertical_divider_color"); //$NON-NLS-1$

        v = this.mContentView.findViewById(R.id.fso_properties_name_label);
        theme.setTextColor(this.mContext, (TextView)v, "text_color"); //$NON-NLS-1$
        v = this.mContentView.findViewById(R.id.fso_properties_name);
        theme.setTextColor(this.mContext, (TextView)v, "text_color"); //$NON-NLS-1$
        v = this.mContentView.findViewById(R.id.fso_properties_parent_label);
        theme.setTextColor(this.mContext, (TextView)v, "text_color"); //$NON-NLS-1$
        v = this.mContentView.findViewById(R.id.fso_properties_parent);
        theme.setTextColor(this.mContext, (TextView)v, "text_color"); //$NON-NLS-1$
        v = this.mContentView.findViewById(R.id.fso_properties_type_label);
        theme.setTextColor(this.mContext, (TextView)v, "text_color"); //$NON-NLS-1$
        v = this.mContentView.findViewById(R.id.fso_properties_type);
        theme.setTextColor(this.mContext, (TextView)v, "text_color"); //$NON-NLS-1$
        v = this.mContentView.findViewById(R.id.fso_properties_category_label);
        theme.setTextColor(this.mContext, (TextView)v, "text_color"); //$NON-NLS-1$
        v = this.mContentView.findViewById(R.id.fso_properties_category);
        theme.setTextColor(this.mContext, (TextView)v, "text_color"); //$NON-NLS-1$
        v = this.mContentView.findViewById(R.id.fso_properties_link_label);
        theme.setTextColor(this.mContext, (TextView)v, "text_color"); //$NON-NLS-1$
        v = this.mContentView.findViewById(R.id.fso_properties_link);
        theme.setTextColor(this.mContext, (TextView)v, "text_color"); //$NON-NLS-1$
        v = this.mContentView.findViewById(R.id.fso_properties_size_label);
        theme.setTextColor(this.mContext, (TextView)v, "text_color"); //$NON-NLS-1$
        v = this.mContentView.findViewById(R.id.fso_properties_size);
        theme.setTextColor(this.mContext, (TextView)v, "text_color"); //$NON-NLS-1$
        v = this.mContentView.findViewById(R.id.fso_properties_contains_label);
        theme.setTextColor(this.mContext, (TextView)v, "text_color"); //$NON-NLS-1$
        v = this.mContentView.findViewById(R.id.fso_properties_contains);
        theme.setTextColor(this.mContext, (TextView)v, "text_color"); //$NON-NLS-1$
        v = this.mContentView.findViewById(R.id.fso_properties_last_accessed_label);
        theme.setTextColor(this.mContext, (TextView)v, "text_color"); //$NON-NLS-1$
        v = this.mContentView.findViewById(R.id.fso_properties_last_accessed);
        theme.setTextColor(this.mContext, (TextView)v, "text_color"); //$NON-NLS-1$
        v = this.mContentView.findViewById(R.id.fso_properties_last_modified_label);
        theme.setTextColor(this.mContext, (TextView)v, "text_color"); //$NON-NLS-1$
        v = this.mContentView.findViewById(R.id.fso_properties_last_modified);
        theme.setTextColor(this.mContext, (TextView)v, "text_color"); //$NON-NLS-1$
        v = this.mContentView.findViewById(R.id.fso_properties_last_changed_label);
        theme.setTextColor(this.mContext, (TextView)v, "text_color"); //$NON-NLS-1$
        v = this.mContentView.findViewById(R.id.fso_properties_last_changed);
        theme.setTextColor(this.mContext, (TextView)v, "text_color"); //$NON-NLS-1$
        v = this.mContentView.findViewById(R.id.fso_include_in_media_scan_label);
        theme.setTextColor(this.mContext, (TextView)v, "text_color"); //$NON-NLS-1$

        v = this.mContentView.findViewById(R.id.fso_properties_owner_label);
        theme.setTextColor(this.mContext, (TextView)v, "text_color"); //$NON-NLS-1$
        v = this.mContentView.findViewById(R.id.fso_properties_group_label);
        theme.setTextColor(this.mContext, (TextView)v, "text_color"); //$NON-NLS-1$
        v = this.mContentView.findViewById(R.id.fso_properties_permissions_special_label);
        theme.setTextColor(this.mContext, (TextView)v, "text_color"); //$NON-NLS-1$
        v = this.mContentView.findViewById(R.id.fso_properties_permissions_read_label);
        theme.setTextColor(this.mContext, (TextView)v, "text_color"); //$NON-NLS-1$
        v = this.mContentView.findViewById(R.id.fso_properties_permissions_write_label);
        theme.setTextColor(this.mContext, (TextView)v, "text_color"); //$NON-NLS-1$
        v = this.mContentView.findViewById(R.id.fso_properties_permissions_execute_label);
        theme.setTextColor(this.mContext, (TextView)v, "text_color"); //$NON-NLS-1$
        v = this.mContentView.findViewById(R.id.fso_properties_permissions_owner_label);
        theme.setTextColor(this.mContext, (TextView)v, "text_color"); //$NON-NLS-1$
        v = this.mContentView.findViewById(R.id.fso_properties_permissions_group_label);
        theme.setTextColor(this.mContext, (TextView)v, "text_color"); //$NON-NLS-1$
        v = this.mContentView.findViewById(R.id.fso_properties_permissions_others_label);
        theme.setTextColor(this.mContext, (TextView)v, "text_color"); //$NON-NLS-1$
        v = this.mContentView.findViewById(R.id.fso_info_msg);
        theme.setTextColor(this.mContext, (TextView)v, "text_color"); //$NON-NLS-1$
        ((TextView)v).setCompoundDrawablesWithIntrinsicBounds(
                theme.getDrawable(this.mContext, "filesystem_warning_drawable"), //$NON-NLS-1$
                null, null, null);
    }

    /**
     * Method that applies the current theme to the tab host
     */
    private void applyTabTheme() {
        // Apply the theme
        Theme theme = ThemeManager.getCurrentTheme(this.mContext);
        View v = this.mContentView.findViewById(R.id.fso_properties_dialog_tab_info);
        theme.setTextColor(this.mContext, (TextView)v, "text_color"); //$NON-NLS-1$
        v = this.mContentView.findViewById(R.id.fso_properties_dialog_tab_permissions);
        theme.setTextColor(this.mContext, (TextView)v, "text_color"); //$NON-NLS-1$
    }

    /**
     * Method that prevents media scan in the directory (creates a new .nomedia file)
     *
     * @param nomedia The .nomedia file
     */
    private void preventMediaScan(final File nomedia) {
        // Create .nomedia file. The file should not exist here
        try {
            if (!nomedia.createNewFile()) {
                // failed to create .nomedia file
                DialogHelper.showToast(
                    this.mContext,
                    this.mContext.getString(
                            R.string.fso_failed_to_prevent_media_scan),
                    Toast.LENGTH_SHORT);
                this.mIgnoreCheckEvents = true;
                this.mChkNoMedia.setChecked(false);
                return;
            }

            // Refresh the listview
            this.mHasChanged = true;

        } catch (IOException ex) {
            // failed to create .nomedia file
            ExceptionUtil.translateException(this.mContext, ex, true, false, null);
            DialogHelper.showToast(
                this.mContext,
                this.mContext.getString(
                        R.string.fso_failed_to_prevent_media_scan),
                Toast.LENGTH_SHORT);
            this.mIgnoreCheckEvents = true;
            this.mChkNoMedia.setChecked(false);
        }
    }

    /**
     * Method that allows media scan in the directory (removes the .nomedia file)
     *
     * @param nomedia The .nomedia file
     */
    private void allowMediaScan(final File nomedia) {
        // Delete .nomedia file. The file should exist here

        // .nomedia is a directory? Then ask the user prior to remove completely the folder
        if (nomedia.isDirectory()) {
            // confirm removing the dir
            AlertDialog alert = DialogHelper.createYesNoDialog(
                this.mContext,
                R.string.fso_delete_nomedia_dir_title,
                R.string.fso_delete_nomedia_dir_body,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (which == DialogInterface.BUTTON_POSITIVE) {
                            boolean ret = FileHelper.deleteFolder(nomedia);
                            if (!ret) {
                                DialogHelper.showToast(
                                    FsoPropertiesDialog.this.mContext,
                                    FsoPropertiesDialog.this.mContext.getString(
                                            R.string.fso_failed_to_allow_media_scan),
                                    Toast.LENGTH_SHORT);
                                FsoPropertiesDialog.this.mIgnoreCheckEvents = true;
                                FsoPropertiesDialog.this.mChkNoMedia.setChecked(true);
                                return;
                            }

                            // Refresh the listview
                            FsoPropertiesDialog.this.mHasChanged = true;

                        } else {
                            FsoPropertiesDialog.this.mIgnoreCheckEvents = true;
                            FsoPropertiesDialog.this.mChkNoMedia.setChecked(true);
                        }
                    }
                });
            DialogHelper.delegateDialogShow(this.mContext, alert);

        // .nomedia file is not empty?  Then ask the user prior to remove the file
        } else if (nomedia.length() != 0) {
            // confirm removing non empty file
            AlertDialog alert = DialogHelper.createYesNoDialog(
                this.mContext,
                R.string.fso_delete_nomedia_non_empty_title,
                R.string.fso_delete_nomedia_non_empty_body,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (which == DialogInterface.BUTTON_POSITIVE) {
                            if (!nomedia.delete()) {
                                DialogHelper.showToast(
                                    FsoPropertiesDialog.this.mContext,
                                    FsoPropertiesDialog.this.mContext.getString(
                                            R.string.fso_failed_to_allow_media_scan),
                                    Toast.LENGTH_SHORT);
                                FsoPropertiesDialog.this.mIgnoreCheckEvents = true;
                                FsoPropertiesDialog.this.mChkNoMedia.setChecked(true);
                                return;
                            }

                            // Refresh the listview
                            FsoPropertiesDialog.this.mHasChanged = true;

                        } else {
                            FsoPropertiesDialog.this.mIgnoreCheckEvents = true;
                            FsoPropertiesDialog.this.mChkNoMedia.setChecked(true);
                        }
                    }
                });
            DialogHelper.delegateDialogShow(this.mContext, alert);

        // Normal .nomedia file
        } else {
            if (!nomedia.delete()) {
                //failed to delete .nomedia file
                DialogHelper.showToast(
                    this.mContext,
                    this.mContext.getString(
                            R.string.fso_failed_to_allow_media_scan),
                    Toast.LENGTH_SHORT);
                FsoPropertiesDialog.this.mIgnoreCheckEvents = true;
                FsoPropertiesDialog.this.mChkNoMedia.setChecked(true);
                return;
            }

            // Refresh the listview
            FsoPropertiesDialog.this.mHasChanged = true;
        }
    }

    /**
     * Method that checks if the .nomedia file is present
     *
     * @return boolean If the .nomedia file is present
     */
    private boolean isNoMediaFilePresent() {
        final File nomedia = FileHelper.getNoMediaFile(this.mFso);
        return nomedia.exists();
    }

}


text:
package agent;

/** A complete representation of a situation in the agent environment.
    Since this is very domain specific, few methods are given.
    However, there should be methods for updating and retrieving various
    aspects of the state. This corresponds to the set E. */
public abstract class State {

   /** Display information about the state. This may be as simple as
      text-based output, or could update a graphical display. */
   public abstract void display();

}


text:
package com.intirix.openmm.server.ui.html.pages;

import org.simpleframework.xml.Default;

import com.intirix.openmm.server.api.beans.Show;
import com.intirix.openmm.server.ui.html.PageData;

@Default
public class ShowsListBean extends PageData
{

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	private Show[] shows;

	public Show[] getShows()
	{
		return shows;
	}

	public void setShows( Show[] shows )
	{
		this.shows = shows;
	}

}


text:
'use strict';

Object.defineProperty(exports, '__esModule', {
  value: true
});

var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();

var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }

function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var _livia = require('livia');

var IntegerType = (function (_Types$Number) {
  _inherits(IntegerType, _Types$Number);

  function IntegerType() {
    _classCallCheck(this, IntegerType);

    _get(Object.getPrototypeOf(IntegerType.prototype), 'constructor', this).apply(this, arguments);
  }

  _createClass(IntegerType, null, [{
    key: 'toString',
    value: function toString() {
      return 'Integer';
    }
  }, {
    key: 'getDbType',
    value: function getDbType() {
      return 'INTEGER';
    }
  }]);

  return IntegerType;
})(_livia.Types.Number);

exports['default'] = IntegerType;
module.exports = exports['default'];


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

		<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
		<title>HBase 0.98.6-hadoop2 Reference Package org.apache.hadoop.hbase.tmpl.regionserver</title>
		<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="style" />

        	org.apache.hadoop.hbase.tmpl.regionserver

Classes

            	BlockCacheTmpl

            	BlockCacheTmplImpl

            	BlockCacheViewTmpl

            	BlockCacheViewTmplImpl

            	ImplData

            	Intf

            	RSStatusTmpl

            	RSStatusTmplImpl

            	RegionListTmpl

            	RegionListTmplImpl

            	ServerMetricsTmpl

            	ServerMetricsTmplImpl


text:
package com.acadiasoft.im.simmple;

import com.acadiasoft.im.base.fx.FxRate;
import com.acadiasoft.im.base.fx.NoConversionFxRate;
import com.acadiasoft.im.simm.config.SimmCalculationType;
import com.acadiasoft.im.simm.engine.Simm;
import com.acadiasoft.im.simmple.config.ImRole;
import com.acadiasoft.im.simmple.engine.Simmple;
import com.acadiasoft.im.simmple.model.DefaultCrif;
import com.acadiasoft.im.simmple.model.utils.SimmpleResult;
import org.junit.Assert;
import org.junit.Test;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Collections;

/**
 *
 * @author alec.stewart
 */
public class CalculationCurrencyTest {

  private final FxRate fx = new NoConversionFxRate();

  @Test
  public void testCalculationCurrencyBasic() {
    DefaultCrif one = new DefaultCrif("1a", "2018-02-01", "2019-02-01", null, null, "SIMM-P", "RatesFX", "Risk_FX", "USD", "", "", "", "1000.00", "USD", "1000.00", "CFTC", "CFTC");
    DefaultCrif two = new DefaultCrif("1b", "2018-02-01", "2019-02-01", null, null, "SIMM-P", "RatesFX", "Risk_FX", "EUR", "", "", "", "5000.00", "USD", "5000.00", "CFTC", "CFTC");
    BigDecimal simmLibAmount = Simm.calculateStandard(Collections.singletonList(one), "GBP").negate();
    SimmpleResult simmpleAmount = Simmple.calculateSimmWorstOf(Arrays.asList(one, two), "EUR", fx, FxRate.USD, ImRole.PLEDGOR, SimmCalculationType.STANDARD);
    Assert.assertEquals(simmLibAmount, simmpleAmount.getImTree().getMargin());
  }

}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>Reflection Blog 2</title>
    <link href="../styles/main.css" rel="stylesheet"  type="text/css">

Technical Blog

Lesson 1

What is a responsive site and why is responsive important?

A responisve site adapts to the device a person is using for a better user experience.

What mobile first design is and why it's important?

Mobile first is basically the act of creating your design starting with the smallest device so when you get to the bigger devices you can spread your wings so to speak.

What frameworks are and their pros and cons?

You basically have two frameworks.  You have frontend and backend.  The frontend deals with the look based on languages such as HTML, CSS, JS, etc.  The backend is the server side and logic behind the website.  Pros and cons of these frameworks varies from it speeds up the mock-up process, but on the other hand mixes content.  Code is usually clean and tidy, but there can be unused code.

What a wireframe is and why we use it?

A wireframe is a mockup of or example of what you website layout will look like.  There are several reasons to do this, but I see the main one is to have a goal written down for the project you are about to start.  It defines your initial thoughts so you can work on that creation versus trying many code versions first.

    Home


text:
subreddit = 'shittyaskscience'
t_channel = '@ShitScience'

def send_post(submission, r2t):
    return r2t.send_simple(submission)


text:
========================================
 Discount for total amount of pos order
========================================

Installation
============

* `Install <https://odoo-development.readthedocs.io/en/latest/odoo/usage/install-module.html>`__ this module in a usual way


text:
package org.jetbrains.plugins.scala.lang.completion.postfix.templates

import com.intellij.psi.PsiElement
import org.jetbrains.plugins.scala.lang.completion.postfix.templates.selector.SelectorType._
import org.jetbrains.plugins.scala.lang.completion.postfix.templates.selector.{SelectorConditions, AncestorSelector}

/**
 * @author Roman.Shein
 * @since 14.09.2015.
 */
class ScalaDoWhilePostfixTemplate extends ScalaStringBasedPostfixTemplate("dowhile", "do {} while (expr)",
  new AncestorSelector(SelectorConditions.BOOLEAN_EXPR, Topmost)) {

  override def getTemplateString(element: PsiElement): String = "do {\n$END$\n} while ($expr$)"
}


text:
pushd etl/practicefusion
#pig -useHCatalog ./ndc_to_rxnorm.pig && \
#pig -useHCatalog ./denormalize.pig && \
#pig ./group_values.pig && \
#pig -useHCatalog ./enrich_rxnorm.pig && \
#pig -useHCatalog ./enrich_generalize.pig && \
#pig -param min_drug=10 -param input=grouped -param output=sentences_ndc to_sentences.pig && \
#pig -param min_drug=20 -param input=rxnorm_normalized -param output=sentences_rxnorm to_sentences.pig && \
pig -param min_drug=10 -param input=nlp_normalized -param output=sentences_nlp to_sentences.pig
popd


text:
package de.pascaldierich.domain.interactors.storage.newsfeed;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import com.google.firebase.crash.FirebaseCrash;

import de.pascaldierich.domain.executor.Executor;
import de.pascaldierich.domain.executor.MainThread;
import de.pascaldierich.domain.interactors.storage.Storage;
import de.pascaldierich.domain.interactors.storage.StorageInteractor;
import de.pascaldierich.domain.repository.ApiConnector;
import de.pascaldierich.model.ModelException;
import de.pascaldierich.model.domainmodels.Post;

/**
 * Interactor to save a new Post in 'NewsFeed'
 */
public class Set extends Storage implements StorageInteractor {
    private StorageInteractor.SetCallback mCallback;
    private Post mItem;

    /**
     * Constructor
     *

     *
     * @param executor,   Executor:
     * @param mainThread, MainThread:
     * @param callback,   AddNewInteractor.Callback: usually represented by 'this'
     * @param context,    WeakReference<Context>: Context to access DB
     * @param item,       Post: new Post to store
     */
    public Set(@NonNull Executor executor, @NonNull MainThread mainThread,
               @NonNull Context context,
               @NonNull StorageInteractor.SetCallback callback,
               @Nullable Post item) {
        super(executor, mainThread, context);

        mCallback = callback;
        mItem = item;
    }

    /**
     * Set a new Post
     *

     *
     * @param item, Post: new Post to store
     */
    public void setItem(@NonNull Post item) {
        mItem = item;
    }

    /**
     * run Interactor
     */
    @Override
    public void run() {
        try {
            if (mItem == null) {
                mMainThread.post(new Runnable() {
                    @Override
                    public void run() {
                        FirebaseCrash.log("setNewsFeed: Item is null. \n" +
                                "postFailure in " + Set.class.getSimpleName());

                        mCallback.onFailure(-1);
                    }
                });
            }

            final long postId = ApiConnector.getApi().get().setNewsFeed(mContext, mItem);

            mMainThread.post(new Runnable() {
                @Override
                public void run() {
                    mCallback.onSuccess(postId, true);
                }
            });
        } catch (final ModelException modelE) {
            mMainThread.post(new Runnable() {
                @Override
                public void run() {
                    FirebaseCrash.log("setNewsFeed: " + modelE.getErrorCode() + ". \n" +
                            "ModelException in " + Set.class.getSimpleName());

                    mCallback.onFailure(modelE.getErrorCode());
                }
            });
        }
    }
}


text:
<!doctype html>

		<title>Zabuun - Learn Egyptian Arabic for English speakers</title>
		<meta name="description" content="">
		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/head.php';?>

		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/ie8.php';?>
		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/header.php';?>

			<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/side.php';?>

Essays > Ray Charles: The Man and His Music

						Expand All | Collapse All

Ray Charles: The Man and His Music

Ray Charles was one of the most inspirational, and successful singers in the history of music in the United States. Charles combined several musical influences to create his own, unique style that served him well during his career. His influences included genres such as gospel, blues, jazz, pop, Rock 'n' Roll, and country music. Although he was born sighted, he developed a severe case of glaucoma at the age of five, and was completely blind by the age of seven, but that did not hold him back

		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/footer.php';?>
		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/scripts.php';?>