问:
Using OnClick Events to Change Scenes
I'm new to events and delegates and I'm having trouble making the functional connection between things, specifically the events manager and how events get connected to specific buttons in my program. So far I've created a few delegates and then I have a class that should subscribe to those delegates but I don't get how this system actually gets connected to buttons on different scenes. I just need someone to help me make the connection so that I can see how everything functions. Thank you.

Here is my event manager class

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Event_Manager : MonoBehaviour
{
    public static Event_Manager evt = null; // create singleton

    public delegate void GoToStartingSceneDelegate();
    public static GoToStartingSceneDelegate onGoToStartingSceneDelegate;

    public delegate void GoToSelectionSceneDelegate();
    public static GoToSelectionSceneDelegate onGoToSelectionSceneDelegate;

    public delegate void GoToColoringSceneDelegate();
    public static GoToColoringSceneDelegate onGoToColoringSceneDelegate;

    public delegate void GoToCaveSceneDelegate();
    public static GoToCaveSceneDelegate onGoToCaveSceneDelegate;

    private void Awake()
    {
        if (evt == null)
            evt = this;
        else if (evt != null)
            Destroy(gameObject);

        DontDestroyOnLoad(gameObject);
    }

    public static void OnStartGameButtonClick()
    {
        Debug.Log("Start Game");
        if (onGoToStartingSceneDelegate != null)
            onGoToStartingSceneDelegate();
    }

    public static void OnStartOverButtonClick()
    {
        Debug.Log("Start Over");
        if (onGoToSelectionSceneDelegate != null)
            onGoToSelectionSceneDelegate();
    }

    public static void OnSendAnimalButtonClick()
    {
        Debug.Log("Send Animal");
        if (onGoToCaveSceneDelegate != null)
            onGoToCaveSceneDelegate();
    }

    public static void OnPlayAgainButtonClick()
    {
        Debug.Log("Play Again");
        if (onGoToStartingSceneDelegate != null)
            onGoToStartingSceneDelegate();
    }
}
</code>```

and this is the class that I'm wanting to subscribe to those events

```<code>using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using System.Collections;
using UnityEngine.UI.ProceduralImage;

    public class LoadSceneButtonController : MonoBehaviour
    {
        [SerializeField] public Object startingScene;
        [SerializeField] public Object selectionScene;
        [SerializeField] public Object coloringScene;
        [SerializeField] public Object caveScene;

        GameObject transitionManager;

        public GameObject touchToPlayButton;
        public GameObject sendAnimalToForestButton;
        public GameObject startOverButton;

    private void OnEnable()
    {
        Event_Manager.onGoToStartingSceneDelegate += GoToStartingScene;
        Event_Manager.onGoToSelectionSceneDelegate += GoToSelectionScene;
        Event_Manager.onGoToColoringSceneDelegate += GoToColoringScene;
        Event_Manager.onGoToCaveSceneDelegate += GoToCaveScene;
    }

    private void OnDisable()
    {
        Event_Manager.onGoToStartingSceneDelegate -= GoToStartingScene;
        Event_Manager.onGoToSelectionSceneDelegate -= GoToSelectionScene;
        Event_Manager.onGoToColoringSceneDelegate -= GoToColoringScene;
        Event_Manager.onGoToCaveSceneDelegate -= GoToCaveScene;
    }

    void GoToStartingScene()
    {
        SceneManager.LoadScene(startingScene.name.ToString());
    }

    void GoToSelectionScene()
    {
        SceneManager.LoadScene(selectionScene.name.ToString());
    }

    void GoToColoringScene()
    {
        SceneManager.LoadScene(coloringScene.name.ToString());
    }

    void GoToCaveScene()
    {
        SceneManager.LoadScene(caveScene.name.ToString());
    }
</code>```

答:
Your code is not working but the problem has nothing to do with your events or delegates.

The problem is how you declared your scene variables. Do not use UnityEngine.Object for that. If you do, you can only cast it to SceneAsset which is from the UnityEditor namespace. This means that your code will only work in the Editor with the AssetDatabase class.

Use UnityEngine.SceneManagement instead of UnityEngine.Object. You are currently passing Object.name to the SceneManager.LoadScene function and Object.name refers to the name of the Object not a  scene name.

Replace all:

```<code>[SerializeField] public Object startingScene;
[SerializeField] public Object selectionScene;
[SerializeField] public Object coloringScene;
[SerializeField] public Object caveScene;
</code>```

with

```<code>public Scene startingScene;
public Scene selectionScene;
public Scene coloringScene;
public Scene caveScene;
</code>```

Here is a simple Unity tutorial for events and delegates. I don't think you need that since that part of your code looks fine.

As for connecting it to your buttons, it is very easy. Just subscribe to the onClick.AddListener button event and notify the Event_Manager event when there is a click.

```<code>public Button startingButton;
public Button selectionButton;
public Button coloringButton;
public Button CaveButton;

void OnEnable()
{
    //Register Button Events
    startingButton.onClick.AddListener(() => buttonCallBack(startingButton));
    selectionButton.onClick.AddListener(() => buttonCallBack(selectionButton));
    coloringButton.onClick.AddListener(() => buttonCallBack(coloringButton));
    CaveButton.onClick.AddListener(() => buttonCallBack(CaveButton));
}

private void buttonCallBack(Button buttonPressed)
{
    if (buttonPressed == startingButton)
    {
        Debug.Log("Clicked: " + startingButton.name);
        Event_Manager.OnStartGameButtonClick();
    }

    if (buttonPressed == selectionButton)
    {
        Debug.Log("Clicked: " + selectionButton.name);
        Event_Manager.OnStartOverButtonClick();
    }

    if (buttonPressed == coloringButton)
    {
        Debug.Log("Clicked: " + coloringButton.name);
        Event_Manager.OnSendAnimalButtonClick();
    }

    if (buttonPressed == CaveButton)
    {
        Debug.Log("Clicked: " + CaveButton.name);
        Event_Manager.OnSendAnimalButtonClick();
    }
}
</code>```

Title: Using OnClick Events to Change Scenes

Body:
I'm new to events and delegates and I'm having trouble making the functional connection between things, specifically the events manager and how events get connected to specific buttons in my program. So far I've created a few delegates and then I have a class that should subscribe to those delegates but I don't get how this system actually gets connected to buttons on different scenes. I just need someone to help me make the connection so that I can see how everything functions. Thank you.

Here is my event manager class

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Event_Manager : MonoBehaviour
{
    public static Event_Manager evt = null; // create singleton

    public delegate void GoToStartingSceneDelegate();
    public static GoToStartingSceneDelegate onGoToStartingSceneDelegate;

    public delegate void GoToSelectionSceneDelegate();
    public static GoToSelectionSceneDelegate onGoToSelectionSceneDelegate;

    public delegate void GoToColoringSceneDelegate();
    public static GoToColoringSceneDelegate onGoToColoringSceneDelegate;

    public delegate void GoToCaveSceneDelegate();
    public static GoToCaveSceneDelegate onGoToCaveSceneDelegate;

    private void Awake()
    {
        if (evt == null)
            evt = this;
        else if (evt != null)
            Destroy(gameObject);

        DontDestroyOnLoad(gameObject);
    }

    public static void OnStartGameButtonClick()
    {
        Debug.Log("Start Game");
        if (onGoToStartingSceneDelegate != null)
            onGoToStartingSceneDelegate();
    }

    public static void OnStartOverButtonClick()
    {
        Debug.Log("Start Over");
        if (onGoToSelectionSceneDelegate != null)
            onGoToSelectionSceneDelegate();
    }

    public static void OnSendAnimalButtonClick()
    {
        Debug.Log("Send Animal");
        if (onGoToCaveSceneDelegate != null)
            onGoToCaveSceneDelegate();
    }

    public static void OnPlayAgainButtonClick()
    {
        Debug.Log("Play Again");
        if (onGoToStartingSceneDelegate != null)
            onGoToStartingSceneDelegate();
    }
}

and this is the class that I'm wanting to subscribe to those events

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using System.Collections;
using UnityEngine.UI.ProceduralImage;

    public class LoadSceneButtonController : MonoBehaviour
    {
        [SerializeField] public Object startingScene;
        [SerializeField] public Object selectionScene;
        [SerializeField] public Object coloringScene;
        [SerializeField] public Object caveScene;

        GameObject transitionManager;

        public GameObject touchToPlayButton;
        public GameObject sendAnimalToForestButton;
        public GameObject startOverButton;

    private void OnEnable()
    {
        Event_Manager.onGoToStartingSceneDelegate += GoToStartingScene;
        Event_Manager.onGoToSelectionSceneDelegate += GoToSelectionScene;
        Event_Manager.onGoToColoringSceneDelegate += GoToColoringScene;
        Event_Manager.onGoToCaveSceneDelegate += GoToCaveScene;
    }

    private void OnDisable()
    {
        Event_Manager.onGoToStartingSceneDelegate -= GoToStartingScene;
        Event_Manager.onGoToSelectionSceneDelegate -= GoToSelectionScene;
        Event_Manager.onGoToColoringSceneDelegate -= GoToColoringScene;
        Event_Manager.onGoToCaveSceneDelegate -= GoToCaveScene;
    }

    void GoToStartingScene()
    {
        SceneManager.LoadScene(startingScene.name.ToString());
    }

    void GoToSelectionScene()
    {
        SceneManager.LoadScene(selectionScene.name.ToString());
    }

    void GoToColoringScene()
    {
        SceneManager.LoadScene(coloringScene.name.ToString());
    }

    void GoToCaveScene()
    {
        SceneManager.LoadScene(caveScene.name.ToString());
    }

Body:
Your code is not working but the problem has nothing to do with your events or delegates.

The problem is how you declared your scene variables. Do not use UnityEngine.Object for that. If you do, you can only cast it to SceneAsset which is from the UnityEditor namespace. This means that your code will only work in the Editor with the AssetDatabase class.

Use UnityEngine.SceneManagement instead of UnityEngine.Object. You are currently passing Object.name to the SceneManager.LoadScene function and Object.name refers to the name of the Object not a  scene name.

Replace all:

[SerializeField] public Object startingScene;
[SerializeField] public Object selectionScene;
[SerializeField] public Object coloringScene;
[SerializeField] public Object caveScene;

with

public Scene startingScene;
public Scene selectionScene;
public Scene coloringScene;
public Scene caveScene;

Here is a simple Unity tutorial for events and delegates. I don't think you need that since that part of your code looks fine.

As for connecting it to your buttons, it is very easy. Just subscribe to the onClick.AddListener button event and notify the Event_Manager event when there is a click.

public Button startingButton;
public Button selectionButton;
public Button coloringButton;
public Button CaveButton;

void OnEnable()
{
    //Register Button Events
    startingButton.onClick.AddListener(() => buttonCallBack(startingButton));
    selectionButton.onClick.AddListener(() => buttonCallBack(selectionButton));
    coloringButton.onClick.AddListener(() => buttonCallBack(coloringButton));
    CaveButton.onClick.AddListener(() => buttonCallBack(CaveButton));
}

private void buttonCallBack(Button buttonPressed)
{
    if (buttonPressed == startingButton)
    {
        Debug.Log("Clicked: " + startingButton.name);
        Event_Manager.OnStartGameButtonClick();
    }

    if (buttonPressed == selectionButton)
    {
        Debug.Log("Clicked: " + selectionButton.name);
        Event_Manager.OnStartOverButtonClick();
    }

    if (buttonPressed == coloringButton)
    {
        Debug.Log("Clicked: " + coloringButton.name);
        Event_Manager.OnSendAnimalButtonClick();
    }

    if (buttonPressed == CaveButton)
    {
        Debug.Log("Clicked: " + CaveButton.name);
        Event_Manager.OnSendAnimalButtonClick();
    }
}


来源: stackexchange

问:
Stripping HTML from C# program that integrates a website into Jira
I am working on a website that is integrated in Jira. The web page has a "description" section. When I write a description on the web page this looks okay, but when it gets imported into Jira , the ticket has html tags in the description:

```<code>ex: < p > this is the description < p >
</code>```

instead of simply 'this is the description'

Here is the description call in the C# code:

```<code>var ticket = new Ticket()
{
    Id = 0,
    IsActive = true,
    TicketDescription =
        string.IsNullOrEmpty(issue.Description)
            ? string.Empty
            : issue.Description.Replace(Environment.NewLine, "<br />"),
    AssignedToId = assignedToUser.SecurityUserId,
    TicketTypeId = type == 0 ? 1 : type,
};
</code>```

what would I need to add to TicketDescription so the html is always stripped ?

答:
You can create a string extension which will strip all tags:

```<code>public static string RemoveHtmlTags(string input)
{
   return Regex.Replace(input, "<.*?>", String.Empty);
}
</code>```

then you can use it like:

```<code>TicketDescription =
        string.IsNullOrEmpty(issue.Description)
            ? string.Empty
            : issue.Description.RemoveHtmlTags()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am working on a website that is integrated in Jira. The web page has a "description" section. When I write a description on the web page this looks okay, but when it gets imported into Jira , the ticket has html tags in the description:

ex:
 this is the description

instead of simply 'this is the description'

Here is the description call in the C# code:

var ticket = new Ticket()
{
    Id = 0,
    IsActive = true,
    TicketDescription =
        string.IsNullOrEmpty(issue.Description)
            ? string.Empty
            : issue.Description.Replace(Environment.NewLine, "
"),
    AssignedToId = assignedToUser.SecurityUserId,
    TicketTypeId = type == 0 ? 1 : type,
};

what would I need to add to TicketDescription so the html is always stripped ?

Body:
You can create a string extension which will strip all tags:

public static string RemoveHtmlTags(string input)
{
   return Regex.Replace(input, "<.*?>", String.Empty);
}

then you can use it like:

TicketDescription =
        string.IsNullOrEmpty(issue.Description)
            ? string.Empty
            : issue.Description.RemoveHtmlTags()


问:
How can I open the terminal in Visual Studio?
How can I open the terminal for executing shell commands in Visual Studio (Community Edition)?</p>

答:
I am not sure if this will help, but I usually pull the command prompt up by going into "Synchronization" tab in Team Explorer and clicking on "Actions".

When the command prompt opens, it is in the directory of the project.

ContentLicense: CC BY-SA 4.0


问:
Change language of entire React Native App
I have a react native application in which the default language is English. I have a profile page in which the user can change the language from English to another language. And when the user saves the language change, the language including the title, drawer navigation names all should be changed to the user chosen language. How we can implement this functionality in react native?</p>

答:
You can use this package: https://github.com/AlexanderZaytsev/react-native-i18n

Once installed all you have to do is to define your locale files, for example:

```<code>// src/i18n/locales/en.js
export default {
  greeting: 'Hi!'
};

// src/i18n/locales/es.js
export default {
  greeting: 'Hola!'
};

// src/i18n/locales/jp.js
export default {
  greeting: 'Konichiwa!'
};
</code>```

Then import those files and setup the configuration for i18n support like this:

```<code>// src/i18n/index.js
import I18n from 'react-native-i18n';
import en from './locales/en';
import es from './locales/es';
import jp from './locales/jp';

I18n.fallbacks = true;

I18n.translations = {
  en,
  es,
  jp,
};

export default I18n;
</code>```

And finally use it in your components like this:

```<code>import I18n from 'src/i18n';

class Demo extends React.Component {
  render () {
    return (
      <Text>{I18n.t('greeting')}</Text>
    )
  }
}
</code>```

By default it will use the device's locale, but if you want to overwrite that. For example when the user has device with a Spanish locale, but want to use Japanese, you can do something like this:

```<code>I18n.locale = 'jp';
</code>```

Whenever you call I18n.t('greeting') it will render Konichiwa!. From now on, you will always need to use I18n.t to render any text in your app.

The main issue with this library is the fact that you don't know which keys are still in use once your app grows, managing all your translations is super challenging, I'd recommend you to use a tool like LinguiJS for that: https://bleext.com/post/translating-your-product-into-multiple-languages

Body:
You can use this package: https://github.com/AlexanderZaytsev/react-native-i18n

Once installed all you have to do is to define your locale files, for example:

// src/i18n/locales/en.js
export default {
  greeting: 'Hi!'
};

// src/i18n/locales/es.js
export default {
  greeting: 'Hola!'
};

// src/i18n/locales/jp.js
export default {
  greeting: 'Konichiwa!'
};

Then import those files and setup the configuration for i18n support like this:

// src/i18n/index.js
import I18n from 'react-native-i18n';
import en from './locales/en';
import es from './locales/es';
import jp from './locales/jp';

I18n.fallbacks = true;

I18n.translations = {
  en,
  es,
  jp,
};

export default I18n;

And finally use it in your components like this:

import I18n from 'src/i18n';

class Demo extends React.Component {
  render () {
    return (
      <Text>{I18n.t('greeting')}</Text>
    )
  }
}

By default it will use the device's locale, but if you want to overwrite that. For example when the user has device with a Spanish locale, but want to use Japanese, you can do something like this:

I18n.locale = 'jp';

Whenever you call I18n.t('greeting') it will render Konichiwa!. From now on, you will always need to use I18n.t to render any text in your app.

The main issue with this library is the fact that you don't know which keys are still in use once your app grows, managing all your translations is super challenging, I'd recommend you to use a tool like LinguiJS for that: https://bleext.com/post/translating-your-product-into-multiple-languages


问:
WPF Datagrid: MVVM friendly way to bind SelectedCells to my ViewModel
I'm using the WPF datagrid, and have SelectionUnit="Cell" and SelectionMode="Extended". I'm also trying to adhere to the MVVM principals as much as I can.

I need my ViewModel to keep track of the current SelectedCells.

Life would be easy if I could just Bind its SelectedCells property to my ViewModel. Oddly enough, SelectedCells is only raised once - when we first select any cell in the grid.

MS explains it here: http://social.msdn.microsoft.com/Forums/en/wpf/thread/737117f4-6d20-4232-88cf-e52cc44d4431

Can anyone think of an MVVM-friendly approach to get around it?

Thanks!

答:
Do you need the SelectedCells constantly data-binded, or just when the user hits the OK/Accept button? If you only need it at the end of whatever process the user is in you can bind the SelectedCells to the CommandParameter property of a Button, for example. The SelectedCells is an IList, and you know enough to just do a cast to whatever object type the selection actually is. The other option is messier, you can use an attached property, keeping the event-handling out of your Views. This attached property would handle either a ListBox or in your case a DataGrid (MultiSelector).

```<code>public class Attach
{
    public static IList GetSelectedItems(DependencyObject obj)
    {
        return (IList)obj.GetValue(SelectedItemsProperty);
    }

    public static void SetSelectedItems(DependencyObject obj, IList value)
    {
        obj.SetValue(SelectedItemsProperty, value);
    }

    /// <summary>
    /// Attach this property to expose the read-only SelectedItems property of a MultiSelector for data binding.
    /// </summary>
    public static readonly DependencyProperty SelectedItemsProperty =
        DependencyProperty.RegisterAttached("SelectedItems", typeof(IList), typeof(Attach), new UIPropertyMetadata(new List<object>() as IList, OnSelectedItemsChanged));

    static SelectionChangedEventHandler GetSelectionChangedHandler(DependencyObject obj)
    {
        return (SelectionChangedEventHandler)obj.GetValue(SelectionChangedHandlerProperty);
    }
    static void SetSelectionChangedHandler(DependencyObject obj, SelectionChangedEventHandler value)
    {
        obj.SetValue(SelectionChangedHandlerProperty, value);
    }
    static readonly DependencyProperty SelectionChangedHandlerProperty =
        DependencyProperty.RegisterAttached("SelectionChangedHandler", typeof(SelectionChangedEventHandler), typeof(Attach), new UIPropertyMetadata(null));

    //d is MultiSelector (d as ListBox not supported)
    static void OnSelectedItemsChanged(DependencyObject d, DependencyPropertyChangedEventArgs args)
    {
        if (GetSelectionChangedHandler(d) != null)
            return;

        if (d is MultiSelector)//DataGrid
        {
            MultiSelector multiselector = d as MultiSelector;
            SelectionChangedEventHandler selectionchanged = null;
            foreach (var selected in GetSelectedItems(d) as IList)
                multiselector.SelectedItems.Add(selected);

            selectionchanged = (sender, e) =>
            {
                SetSelectedItems(d, multiselector.SelectedItems);
            };
            SetSelectionChangedHandler(d, selectionchanged);
            multiselector.SelectionChanged += GetSelectionChangedHandler(d);
        }
        else if (d is ListBox)
        {
            ListBox listbox = d as ListBox;
            SelectionChangedEventHandler selectionchanged = null;

            selectionchanged = (sender, e) =>
            {
                SetSelectedItems(d, listbox.SelectedItems);
            };
            SetSelectionChangedHandler(d, selectionchanged);
            listbox.SelectionChanged += GetSelectionChangedHandler(d);
        }}}
</code>```

Usage in XAML:

```<code><DataGrid ItemsSource="{Binding Path=SourceList}"
              myControls:Attach.SelectedItems="{Binding Path=myMvvmSelectedItems, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
              SelectionMode="Extended" />
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Do you need the SelectedCells constantly data-binded, or just when the user hits the OK/Accept button? If you only need it at the end of whatever process the user is in you can bind the SelectedCells to the CommandParameter property of a Button, for example. The SelectedCells is an IList, and you know enough to just do a cast to whatever object type the selection actually is. The other option is messier, you can use an attached property, keeping the event-handling out of your Views. This attached property would handle either a ListBox or in your case a DataGrid (MultiSelector).

public class Attach
{
    public static IList GetSelectedItems(DependencyObject obj)
    {
        return (IList)obj.GetValue(SelectedItemsProperty);
    }

    public static void SetSelectedItems(DependencyObject obj, IList value)
    {
        obj.SetValue(SelectedItemsProperty, value);
    }

    /// <summary>
    /// Attach this property to expose the read-only SelectedItems property of a MultiSelector for data binding.
    /// </summary>
    public static readonly DependencyProperty SelectedItemsProperty =
        DependencyProperty.RegisterAttached("SelectedItems", typeof(IList), typeof(Attach), new UIPropertyMetadata(new List<object>() as IList, OnSelectedItemsChanged));

    static SelectionChangedEventHandler GetSelectionChangedHandler(DependencyObject obj)
    {
        return (SelectionChangedEventHandler)obj.GetValue(SelectionChangedHandlerProperty);
    }
    static void SetSelectionChangedHandler(DependencyObject obj, SelectionChangedEventHandler value)
    {
        obj.SetValue(SelectionChangedHandlerProperty, value);
    }
    static readonly DependencyProperty SelectionChangedHandlerProperty =
        DependencyProperty.RegisterAttached("SelectionChangedHandler", typeof(SelectionChangedEventHandler), typeof(Attach), new UIPropertyMetadata(null));

    //d is MultiSelector (d as ListBox not supported)
    static void OnSelectedItemsChanged(DependencyObject d, DependencyPropertyChangedEventArgs args)
    {
        if (GetSelectionChangedHandler(d) != null)
            return;

        if (d is MultiSelector)//DataGrid
        {
            MultiSelector multiselector = d as MultiSelector;
            SelectionChangedEventHandler selectionchanged = null;
            foreach (var selected in GetSelectedItems(d) as IList)
                multiselector.SelectedItems.Add(selected);

            selectionchanged = (sender, e) =>
            {
                SetSelectedItems(d, multiselector.SelectedItems);
            };
            SetSelectionChangedHandler(d, selectionchanged);
            multiselector.SelectionChanged += GetSelectionChangedHandler(d);
        }
        else if (d is ListBox)
        {
            ListBox listbox = d as ListBox;
            SelectionChangedEventHandler selectionchanged = null;

            selectionchanged = (sender, e) =>
            {
                SetSelectedItems(d, listbox.SelectedItems);
            };
            SetSelectionChangedHandler(d, selectionchanged);
            listbox.SelectionChanged += GetSelectionChangedHandler(d);
        }}}

Usage in XAML:

<DataGrid ItemsSource="{Binding Path=SourceList}"
              myControls:Attach.SelectedItems="{Binding Path=myMvvmSelectedItems, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
              SelectionMode="Extended" />


Title: Overflowing of HTML table

Body:
tr {
width: 100%;
display: inline-table;
table-layout: fixed;
}

table{
 height:300px;
 display: -moz-groupbox;
}
tbody{
  overflow-y: scroll;
  height: 400px;
  min-width: 1034px;
  position: absolute;
}

Col 1	Col 2	Col 3

.1.	.1.	.1.

..	..	..

..	.sdfdsfqf.	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

..	..	..

I am trying to make a fixed header HTML table.
Scrollable table with fixed header in bootstrap  I referred this question. But I have some sort of problems. The tbody's width is larger than the thead. When I resize the page it becomes larger.

While resizing

Without resizing

Body:
I have edited the snippet now.

tr {
width: 100%;
display: inline-table;
table-layout: fixed;
}

thead {
float: left
}
table{
 height:300px;
 display: -moz-groupbox;
}
tbody{
  overflow-y: scroll;
  height: 400px;
  min-width: 100%;

}

<table class="table table-striped tabl-responsive">
<thead><tr><th>Col 1</th><th>Col 2</th><th>Col 3</th></tr></thead>
<tbody>
  <tr><td>.1.</td><td>.1.</td><td>.1.</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>.sdfdsfqf.</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
  </tbody>
</table>


问:
How to Push Sqlite File into Android Device?
I am pulling Sql file using below commands and then how to push the file into device?</p>

```<code>$ adb -d shell
$ run-as your.package.name
$ cat /data/data/your.package.name/databases/yourdatabasename  >/sdcard/yourdatabasename
</code>```

答:
This is a sample of my win batch file i've created for myself for pushing sqlite db to android device or emulator (root access is not required). You can put this file on your windows desktop to directory containing db file you want to push to android device. I hope the source are self-explained but i am ready to answer the questions. Also i will be grateful for comments, ideas etc.

This script was checked on API 27 Intel X86 emulator and ASUS_Z00ED android 6.0.1 without root access.

```<code>------------------ pull_waitlist_db.bat-------------------------------------
set PATH=%PATH%;C:\Users\pc\AppData\Local\Android\Sdk\platform-tools\
set dbpath=/data/data/com.example.android.waitlist/databases/waitlist.db
set package=com.example.android.waitlist
set remotename=waitlist.db

adb shell "run-as %package% chmod 666 %dbpath%"
adb exec-out run-as %package% cat %dbpath% > %remotename%
adb shell "run-as %package% chmod 600 %dbpath%"

cmd /k
</code>```

Body:
I am pulling Sql file using below commands and then how to push the file into device?

$ adb -d shell
$ run-as your.package.name
$ cat /data/data/your.package.name/databases/yourdatabasename  >/sdcard/yourdatabasename

Body:
This is a sample of my win batch file i've created for myself for pushing sqlite db to android device or emulator (root access is not required). You can put this file on your windows desktop to directory containing db file you want to push to android device. I hope the source are self-explained but i am ready to answer the questions. Also i will be grateful for comments, ideas etc.

This script was checked on API 27 Intel X86 emulator and ASUS_Z00ED android 6.0.1 without root access.

------------------ pull_waitlist_db.bat-------------------------------------
set PATH=%PATH%;C:\Users\pc\AppData\Local\Android\Sdk\platform-tools\
set dbpath=/data/data/com.example.android.waitlist/databases/waitlist.db
set package=com.example.android.waitlist
set remotename=waitlist.db

adb shell "run-as %package% chmod 666 %dbpath%"
adb exec-out run-as %package% cat %dbpath% > %remotename%
adb shell "run-as %package% chmod 600 %dbpath%"

cmd /k


问:
How to grep and execute command for every multiline match
Is there the possibility to process a multiline grep-output by one command each?

I've got something like

```<code><fulldata>
<value>1</value>
<value>2</value>
</fulldata>
<fulldata>
<value>2</value>
<value>3</value>
</fulldata>
</code>```

and want to get means, standard deviation and do some other things with data-element on its own.

In this case, I want to execute

```<code>function printStatistics {
        mean1=$(awk -F ';' '{print $1}' $1 | awk '{sum += $1; square += $1^2} END {print sum / NR}')
        deviation1=$(awk -F ';' '{print $1}' $1 | awk '{sum += $1; square += $1^2} END {print sqrt(square / NR - (sum/NR)^2)}')
        size=$(cat $1 | wc -l)
        echo $mean1 $deviation1 $size
}
</code>```

with the expected result (for the sample data), idealy separated by newline:

```<code>1,5 0,7 2
2,5 0,7 2
</code>```

Running

```<code>cat add.xml | grep "<fulldata" -A 2001 | while read line ; do echo "Line: $line" ; done
</code>```

like suggested in How to grep and execute a command (for every match) does result in one entry for each line; but I want one entry for each entry (in order to execute awk stuff on it later).

Is this possible with grep, or is this a use case where another language would be more appropriate?

答:
awk to the rescue!

```<code>$ awk -v RS='\n?</?fulldata>\n' -F'\n' '
        !(NR%2){gsub("</?value>","");
                s=ss=0;
                for(i=1;i<=NF;i++) {s+=$i; ss+=$i^2}
                printf "%.1f %.1f %d\n", s/NF, sqrt((ss-s^2/NF)/(NF-1)), NF} ' file

1.5 0.7 2
2.5 0.7 2
</code>```

for the sample standard deviation as computed you need to guard for single observation (NF==1) case.

Body:
Is there the possibility to process a multiline grep-output by one command each?

I've got something like

<fulldata>
<value>1</value>
<value>2</value>
</fulldata>
<fulldata>
<value>2</value>
<value>3</value>
</fulldata>

and want to get means, standard deviation and do some other things with data-element on its own.

In this case, I want to execute

function printStatistics {
        mean1=$(awk -F ';' '{print $1}' $1 | awk '{sum += $1; square += $1^2} END {print sum / NR}')
        deviation1=$(awk -F ';' '{print $1}' $1 | awk '{sum += $1; square += $1^2} END {print sqrt(square / NR - (sum/NR)^2)}')
        size=$(cat $1 | wc -l)
        echo $mean1 $deviation1 $size
}

with the expected result (for the sample data), idealy separated by newline:

1,5 0,7 2
2,5 0,7 2

Running

cat add.xml | grep "<fulldata" -A 2001 | while read line ; do echo "Line: $line" ; done

like suggested in How to grep and execute a command (for every match) does result in one entry for each line; but I want one entry for each entry (in order to execute awk stuff on it later).

Is this possible with grep, or is this a use case where another language would be more appropriate?

Body:
awk to the rescue!

$ awk -v RS='\n?</?fulldata>\n' -F'\n' '
        !(NR%2){gsub("</?value>","");
                s=ss=0;
                for(i=1;i<=NF;i++) {s+=$i; ss+=$i^2}
                printf "%.1f %.1f %d\n", s/NF, sqrt((ss-s^2/NF)/(NF-1)), NF} ' file

1.5 0.7 2
2.5 0.7 2

for the sample standard deviation as computed you need to guard for single observation (NF==1) case.


问:
New line without carriage return in assembly language
I am doing a program on dosbox assembly where i print 0 to 9 diagonally. Here is my current code

```<code>code segment
assume cs:code, ds:code
org 100h

start:
mov ah, 02h
mov dl, 30h
mov ch, 30h
int 21h

again:
inc dl  ;output next number
mov bl, dl
mov dl, 0ah ;new line
int 21h
mov dl, 20h ;space
int 21h
mov dl, bl
int 21h

inc ch  ;increment counter
cmp ch, 39h ;if counter is at 9 end program
je terminate
loop again

terminate:
mov ax, 4c00h
int 21h
code ends
end start
</code>```

The problem is when i add a new line, the cursor goes back to the beginning of the next line, so printing diagonally is impossible. Is there a way that I can print a new line, but the cursor stays on the current position? I've read somewhere that 'Line Feed' can solve my problem, but it has been changed to 'New Line', where after adding a new line, the cursor automatically goes back to the starting position ala automatic 'Carriage Return'

EDIT: Thanks everyone for checking out this question. We aren't allowed to use those other functions aside from loop, jmp, and cmp. My friend figured out how to do it, but I still don't understand maybe 2/3 of their code, mainly on the again2 and jump loops. Code: https://pastebin.com/Vji29VL3.

答:
An alternative to BIOS functions would be to write directly to video.

```<code>      mov     al, 30H
      mov     cx, B800H
      mov     es, cx
      xor     di, di               ; Change if you don't want to start at top/left.
      mov     cx, 161              ; STOSB has already incremented by one.

Loop:
      stosb
      add     di, cx
      inc     al
      cmp     al, 9
      jbe     Loop
</code>```

Of course this makes a few assumption, particularly that you're writing to page 0 and attribute is set to something that will actually display. If you prefer you could also establish an attribute in AH, then use STOSW and only add 160 to DI each time.

Body:
I am doing a program on dosbox assembly where i print 0 to 9 diagonally. Here is my current code

code segment
assume cs:code, ds:code
org 100h

start:
mov ah, 02h
mov dl, 30h
mov ch, 30h
int 21h

again:
inc dl  ;output next number
mov bl, dl
mov dl, 0ah ;new line
int 21h
mov dl, 20h ;space
int 21h
mov dl, bl
int 21h

inc ch  ;increment counter
cmp ch, 39h ;if counter is at 9 end program
je terminate
loop again

terminate:
mov ax, 4c00h
int 21h
code ends
end start

The problem is when i add a new line, the cursor goes back to the beginning of the next line, so printing diagonally is impossible. Is there a way that I can print a new line, but the cursor stays on the current position? I've read somewhere that 'Line Feed' can solve my problem, but it has been changed to 'New Line', where after adding a new line, the cursor automatically goes back to the starting position ala automatic 'Carriage Return'

EDIT: Thanks everyone for checking out this question. We aren't allowed to use those other functions aside from loop, jmp, and cmp. My friend figured out how to do it, but I still don't understand maybe 2/3 of their code, mainly on the again2 and jump loops. Code: https://pastebin.com/Vji29VL3.

Body:
An alternative to BIOS functions would be to write directly to video.

      mov     al, 30H
      mov     cx, B800H
      mov     es, cx
      xor     di, di               ; Change if you don't want to start at top/left.
      mov     cx, 161              ; STOSB has already incremented by one.

Loop:
      stosb
      add     di, cx
      inc     al
      cmp     al, 9
      jbe     Loop

Of course this makes a few assumption, particularly that you're writing to page 0 and attribute is set to something that will actually display. If you prefer you could also establish an attribute in AH, then use STOSW and only add 160 to DI each time.


问:
How to stop swipe in ScrollView?
look this video of current scrolling behavior. i want, as soon as finger is lifted from screen, to disable scrolling.

Edit: the video shows a user scrolling through a list. When the finger is lifted from the screen, you see the scrolling continues up or down for a short time.

答:
What I believe you want is basically to stop the scroll when momentum beings. For that, you can use the onMomentumScrollBegin callback on your ScrollView and call .scrollToEnd({animated: false}) on it.

Here's how that would look:

```<code><ScrollView
  ref={(ref) => this.scrollView = ref}
  scrollEnabled={this.state.scroll}
  onMomentumScrollBegin={
    () => this.scrollView.scrollToEnd({animated: false})
  }
 >
   ...CONTENT HERE...
 </ScrollView>
</code>```

Title: How to stop swipe in ScrollView?

Body:
What I believe you want is basically to stop the scroll when momentum beings. For that, you can use the onMomentumScrollBegin callback on your ScrollView and call .scrollToEnd({animated: false}) on it.

Here's how that would look:

<ScrollView
  ref={(ref) => this.scrollView = ref}
  scrollEnabled={this.state.scroll}
  onMomentumScrollBegin={
    () => this.scrollView.scrollToEnd({animated: false})
  }
 >
   ...CONTENT HERE...
 </ScrollView>


问:
Apk incresed in size after adding FFmpegMediaMetadataRetriever
I added the dependency (com.github.wseemann:FFmpegMediaMetadataRetriever:1.0.3)  to my application ( build.gradle ) in my Android Studio, The apk jumped from 2 MB to 16 MB .I just used the sample code nothing more ,is there a way to have a less size than this?</p>

```<code>        FFmpegMediaMetadataRetriever mmr = new FFmpegMediaMetadataRetriever();
        mmr.setDataSource("http://testsite.com/test/upload/Twale_FLO.mp3");
        mmr.extractMetadata(FFmpegMediaMetadataRetriever.METADATA_KEY_ALBUM);
        mmr.extractMetadata(FFmpegMediaMetadataRetriever.METADATA_KEY_ARTIST);
        long duration =Long.parseLong(mmr.extractMetadata(FFmpegMediaMetadataRetriever.METADATA_KEY_DURATION));
        duration=duration/1000;
        long minute=duration/(60);
        long second=duration-(minute*60);
        mmr.release();
        your_text_view.setText(minute+":"+second);
</code>```

答:
The only way to decrease Apk size after including FFmpegMediaMetadataRetriever is the support ABI spits.

FFmpegMediaMetadataRetriever uses native code that is different for every CPU used. If you don't slit, all native codes will be merged inside your APK: a total of 25Mb or more!

So by adding these lines to your build.gradle, you will enable APK splitting:

```<code>lintOptions {
        checkReleaseBuilds false
        abortOnError false
    }

    splits {

        // Configures multiple APKs based on ABI.
        abi {

            // Enables building multiple APKs per ABI.
            enable true

            // By default all ABIs are included, so use reset() and include to specify that we only
            // want APKs for x86, armeabi-v7a, and mips.

            // Resets the list of ABIs that Gradle should create APKs for to none.
            reset()

            // Specifies a list of ABIs that Gradle should create APKs for.
            include "x86", "armeabi-v7a", "mips", "arm64-v8a", "x86_64", "armeabi"

            // Specifies that we do not want to also generate a universal APK that includes all ABIs.
            universalApk true
        }
    }
</code>```

So, after apk build (or generate signed APK), your build would have 6 apks, one for each cpu. Upload them all to google play so your user would only download the necessary files. A armeabi-v7a APK will only be around 6Mb!

Body:
I added the dependency (com.github.wseemann:FFmpegMediaMetadataRetriever:1.0.3)  to my application ( build.gradle ) in my Android Studio, The apk jumped from 2 MB to 16 MB .I just used the sample code nothing more ,is there a way to have a less size than this?

        FFmpegMediaMetadataRetriever mmr = new FFmpegMediaMetadataRetriever();
        mmr.setDataSource("http://testsite.com/test/upload/Twale_FLO.mp3");
        mmr.extractMetadata(FFmpegMediaMetadataRetriever.METADATA_KEY_ALBUM);
        mmr.extractMetadata(FFmpegMediaMetadataRetriever.METADATA_KEY_ARTIST);
        long duration =Long.parseLong(mmr.extractMetadata(FFmpegMediaMetadataRetriever.METADATA_KEY_DURATION));
        duration=duration/1000;
        long minute=duration/(60);
        long second=duration-(minute*60);
        mmr.release();
        your_text_view.setText(minute+":"+second);

Body:
The only way to decrease Apk size after including FFmpegMediaMetadataRetriever is the support ABI spits.

FFmpegMediaMetadataRetriever uses native code that is different for every CPU used. If you don't slit, all native codes will be merged inside your APK: a total of 25Mb or more!

So by adding these lines to your build.gradle, you will enable APK splitting:

lintOptions {
        checkReleaseBuilds false
        abortOnError false
    }

    splits {

        // Configures multiple APKs based on ABI.
        abi {

            // Enables building multiple APKs per ABI.
            enable true

            // By default all ABIs are included, so use reset() and include to specify that we only
            // want APKs for x86, armeabi-v7a, and mips.

            // Resets the list of ABIs that Gradle should create APKs for to none.
            reset()

            // Specifies a list of ABIs that Gradle should create APKs for.
            include "x86", "armeabi-v7a", "mips", "arm64-v8a", "x86_64", "armeabi"

            // Specifies that we do not want to also generate a universal APK that includes all ABIs.
            universalApk true
        }
    }

So, after apk build (or generate signed APK), your build would have 6 apks, one for each cpu. Upload them all to google play so your user would only download the necessary files. A armeabi-v7a APK will only be around 6Mb!


问:
Back button isn't getting displayed upon pushing a controller into the stack
I created iOS application from Navigation-based application template.

This snippet is from RootViewController.m:

```<code>- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  DotoViewController *detailViewController = [[DotoViewController alloc]
                             initWithNibName:@"DotoViewController" bundle:nil];
  NSManagedObject *selectedObject = [[self fetchedResultsController]
                             objectAtIndexPath:indexPath];

  detailViewController.dotoObj = selectedObject;
  [self.navigationController pushViewController:detailViewController animated:YES];
  [detailViewController release];
}
</code>```

DotoViewController is a subclass of UIViewController and has an accompanying NIB file.

Upong clicking on a row, DotoViewController is getting displayed but without the back button to RootViewController on the left side.

What I'm missing?

答: Perhaps your root view controller has an empty title? The view controller's title is used as the title for the back button, so if you have an empty string there, this can cause the back button to disappear. If it's nil, it should display the standard "Back" though.</p>

Body:
I created iOS application from Navigation-based application template.

This snippet is from RootViewController.m:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  DotoViewController *detailViewController = [[DotoViewController alloc]
                             initWithNibName:@"DotoViewController" bundle:nil];
  NSManagedObject *selectedObject = [[self fetchedResultsController]
                             objectAtIndexPath:indexPath];

  detailViewController.dotoObj = selectedObject;
  [self.navigationController pushViewController:detailViewController animated:YES];
  [detailViewController release];
}

DotoViewController is a subclass of UIViewController and has an accompanying NIB file.

Upong clicking on a row, DotoViewController is getting displayed but without the back button to RootViewController on the left side.

What I'm missing?


问:
Safe (bounds-checked) array lookup in Swift, through optional bindings?
If I have an array in Swift, and try to access an index that is out of bounds, there is an unsurprising runtime error:

```<code>var str = ["Apple", "Banana", "Coconut"]

str[0] // "Apple"
str[3] // EXC_BAD_INSTRUCTION
</code>```

However, I would have thought with all the optional chaining and safety that Swift brings, it would be trivial to do something like:

```<code>let theIndex = 3
if let nonexistent = str[theIndex] { // Bounds check + Lookup
    print(nonexistent)
    ...do other things with nonexistent...
}
</code>```

Instead of:

```<code>let theIndex = 3
if (theIndex < str.count) {         // Bounds check
    let nonexistent = str[theIndex] // Lookup
    print(nonexistent)
    ...do other things with nonexistent...
}
</code>```

But this is not the case - I have to use the ol' if statement to check and ensure the index is less than str.count.

I tried adding my own subscript() implementation, but I'm not sure how to pass the call to the original implementation, or to access the items (index-based) without using subscript notation:

```<code>extension Array {
    subscript(var index: Int) -> AnyObject? {
        if index >= self.count {
            NSLog("Womp!")
            return nil
        }
        return ... // What?
    }
}
</code>```

答:
Swift 4

An extension for those who prefer a more traditional syntax:

```<code>extension Array {
    func item(at index: Int) -> Element? {
        return indices.contains(index) ? self[index] : nil
    }
}
</code>```

Body:
If I have an array in Swift, and try to access an index that is out of bounds, there is an unsurprising runtime error:

var str = ["Apple", "Banana", "Coconut"]

str[0] // "Apple"
str[3] // EXC_BAD_INSTRUCTION

However, I would have thought with all the optional chaining and safety that Swift brings, it would be trivial to do something like:

let theIndex = 3
if let nonexistent = str[theIndex] { // Bounds check + Lookup
    print(nonexistent)
    ...do other things with nonexistent...
}

Instead of:

let theIndex = 3
if (theIndex < str.count) {         // Bounds check
    let nonexistent = str[theIndex] // Lookup
    print(nonexistent)
    ...do other things with nonexistent...
}

But this is not the case - I have to use the ol' if statement to check and ensure the index is less than str.count.

I tried adding my own subscript() implementation, but I'm not sure how to pass the call to the original implementation, or to access the items (index-based) without using subscript notation:

extension Array {
    subscript(var index: Int) -> AnyObject? {
        if index >= self.count {
            NSLog("Womp!")
            return nil
        }
        return ... // What?
    }
}

Body:
Swift 4

An extension for those who prefer a more traditional syntax:

extension Array {
    func item(at index: Int) -> Element? {
        return indices.contains(index) ? self[index] : nil
    }
}


问:
convert_tz returns null
I know this sounds stupid, but when I use

```<code>SELECT CONVERT_TZ('2004-01-01 12:00:00','UTC','Asia/Jakarta') AS time
</code>```

it outputs NULL. I'm using MySQL Workbench in Ubuntu 12.04 64 bit, and it works in my other laptop/os (also using MySQL Workbench).

答:
These are the steps to make it work if you're in windows and using MySQL 5.7.

Right click on My Computer/Computer/This PC or whatever the name in your OS and choose Properties.

Choose "Advanced system settings" from the left panel.

Choose "Environmental Variables", enter the complete path name of your MySQL bin directory (generally it will be in, C:\Program Files\MySQL\MySQL Server 5.7\bin).

Open cmd prompt, enter into mysql using mysql -u root -p password.

Enter use mysql to select the MySQL DB.

Download the file "timezone_YYYYc_posix_sql.zip" (In the place of YYYY, substitute the maximum year available in that page like 2017 or 2018) from https://dev.mysql.com/downloads/timezones.html.

Extract it and open the file in text editor.

Copy the contents and execute in the cmd prompt.

On successful completion, you should be able to use CONVERT_TZ and other timezone functions.

Title: convert_tz returns null

Body:
I know this sounds stupid, but when I use

SELECT CONVERT_TZ('2004-01-01 12:00:00','UTC','Asia/Jakarta') AS time

it outputs NULL. I'm using MySQL Workbench in Ubuntu 12.04 64 bit, and it works in my other laptop/os (also using MySQL Workbench).


问:
How to match and remove any line containing a specific string?
I have a huge directory list of URLs from my Web site. Example:

```<code>/folder/folder2/folder3/page.htm
/folder/folder2/folder3/page2.htm
/folder/folder2/folder3/page3.htm
/folder/folder2/folder3/page4.htm
</code>```

I want to clean this list of all items that have /folder2 in the path. I need a regular expression to perform a find and replace for everything that uses /folder2/ and delete those lines from my list. So find/replace it with blank.

Does anyone know what the proper regular expression for this would be? I should specify I am using Dreamweaver as my editor, which may use different regular expressions.

答:
This expression will match the entire line such that the string "/folder2" occurs in it:

```<code>^.+?\/folder2/.+$
</code>```

HTH.

Body:
I have a huge directory list of URLs from my Web site. Example:

/folder/folder2/folder3/page.htm
/folder/folder2/folder3/page2.htm
/folder/folder2/folder3/page3.htm
/folder/folder2/folder3/page4.htm

I want to clean this list of all items that have /folder2 in the path. I need a regular expression to perform a find and replace for everything that uses /folder2/ and delete those lines from my list. So find/replace it with blank.

Does anyone know what the proper regular expression for this would be? I should specify I am using Dreamweaver as my editor, which may use different regular expressions.

Body:
This expression will match the entire line such that the string "/folder2" occurs in it:

^.+?\/folder2/.+$

HTH.


问:
Why do vectors implement Associative?
I was surprised to discover that clojure vectors implement the Associative interface.

```<code>(associative? [1 2 3]) ; => true
</code>```

I assume this interface provides optimized indexing by keys. Following this assumption, the interface seems appropriate for map data structures, but odd for vectors, which don't follow a key-value heuristic in my mind.

Is my mental model for Associative or vector's implementation incorrect? What purpose does this design choice serve?

答:
Clojure vectors associate an index with a value. This means you can do things like this:

```<code>(assoc [0 1] 0 2)

(reduce-kv (fn [m idx v]
             (assoc m idx v)) {} [0 1 2])
</code>```

And both are efficient.

Title: Why do vectors implement Associative?

Body:
I was surprised to discover that clojure vectors implement the Associative interface.

(associative? [1 2 3]) ; => true

I assume this interface provides optimized indexing by keys. Following this assumption, the interface seems appropriate for map data structures, but odd for vectors, which don't follow a key-value heuristic in my mind.

Is my mental model for Associative or vector's implementation incorrect? What purpose does this design choice serve?

Body:
Clojure vectors associate an index with a value. This means you can do things like this:

(assoc [0 1] 0 2)

(reduce-kv (fn [m idx v]
             (assoc m idx v)) {} [0 1 2])

And both are efficient.


问:
git problem : fatal: Unable to write new index file
I have an existing project that has been managed under git. I recently had to do a ground-up rebuild of the computer (OS X Snow Leopard), and returning to the project, git can track the changes in the project, but I can't save anything to git. I get the error in the title when I try :

```<code>Dans-iMac-335:[app-name-obscured] apple$ git add app/models/*
fatal: Unable to write new index file
</code>```

What's the best way to recover from this situation? There is a heroku repository version of this, but it is very out of sync with this one. presumably I could use a new clone as a basis, and update each file, but that seems over laborious and error prone.

What is git looking for here that it can't find, and is there a change that will restore it?

BTW, file permissions are correct from what I can tell - the files under control and the .git components are both owned by me with rw access...

答: I had the same error because Google Drive's Backup and Sync client for Windows had not released a lock on two files within this repository. A work around was, after the sync client had finished its work: Process Explorer -> Find -> Find handle or DLL -> Close Handle. </p>

Body:
I have an existing project that has been managed under git. I recently had to do a ground-up rebuild of the computer (OS X Snow Leopard), and returning to the project, git can track the changes in the project, but I can't save anything to git. I get the error in the title when I try :

Dans-iMac-335:[app-name-obscured] apple$ git add app/models/*
fatal: Unable to write new index file

What's the best way to recover from this situation? There is a heroku repository version of this, but it is very out of sync with this one. presumably I could use a new clone as a basis, and update each file, but that seems over laborious and error prone.

What is git looking for here that it can't find, and is there a change that will restore it?

BTW, file permissions are correct from what I can tell - the files under control and the .git components are both owned by me with rw access...


问:
Get element position in the DOM on React DnD drop?
I'm using React DnD and Redux (using Kea) to build a formbuilder. I've the drag & drop portion working just fine, and I've managed to dispatch an action when an element drops, and I render the builder afterwards using state that the dispatch changed. However, in order to render elements in the correct order, I (think I) need to save the dropped elements position relative to it's siblings but I'm unable to figure out anything that isn't absolutely insane. I've experimented with refs and querying the DOM with the unique ID (I know I shouldn't), but both approaches feel pretty terrible and do not even work.

Here's a simplified representation of my app structure:

```<code>@DragDropContext(HTML5Backend)
@connect({ /* redux things */ })
<Builder>
  <Workbench tree={this.props.tree} />
  <Sidebar fields={this.props.field}/>
</Builder>
</code>```

Workbench:

```<code>const boxTarget = {
  drop(props, monitor, component) {
    const item = monitor.getItem()
    console.log(component, item.unique, component[item.unique]); // last one is undefined
    window.component = component; // doing it manually works, so the element just isn't in the DOM yet

    return {
      key: 'workbench',
    }
  },
}

@DropTarget(ItemTypes.FIELD, boxTarget, (connect, monitor) => ({
  connectDropTarget: connect.dropTarget(),
  isOver: monitor.isOver(),
  canDrop: monitor.canDrop(),
}))
export default class Workbench extends Component {
  render() {
    const { tree } = this.props;
    const { canDrop, isOver, connectDropTarget } = this.props

    return connectDropTarget(
      <div className={this.props.className}>
        {tree.map((field, index) => {
          const { key, attributes, parent, unique } = field;
          if (parent === 'workbench') { // To render only root level nodes. I know how to render the children recursively, but to keep things simple...
            return (
              <Field
                unique={unique}
                key={key}
                _key={key}
                parent={this} // I'm passing the parent because the refs are useless in the Field instance (?) I don't know if this is a bad idea or not
              />
            );
          }

          return null;
        }).filter(Boolean)}
      </div>,
    )

    // ...
</code>```

Field:

```<code>const boxSource = {
  beginDrag(props) {
    return {
      key: props._key,
      unique: props.unique || shortid.generate(),
      attributes: props.attributes,
    }
  },

  endDrag(props, monitor) {
    const item = monitor.getItem()
    const dropResult = monitor.getDropResult()

    console.log(dropResult);

    if (dropResult) {
      props.actions.onDrop({
        item,
        dropResult,
      });
    }
  },
}

@connect({ /* redux stuff */ })
@DragSource(ItemTypes.FIELD, boxSource, (connect, monitor) => ({
  connectDragSource: connect.dragSource(),
  isDragging: monitor.isDragging(),
}))
export default class Field extends Component {
  render() {
    const { TagName, title, attributes, parent } = this.props
    const { isDragging, connectDragSource } = this.props
    const opacity = isDragging ? 0.4 : 1

    return connectDragSource(
      <div
        className={classes.frame}
        style={{opacity}}
        data-unique={this.props.unique || false}
        ref={(x) => parent[this.props.unique || this.props.key] = x} // If I save the ref to this instance, how do I access it in the drop function that works in context to boxTarget & Workbench?
      >
        <header className={classes.header}>
          <span className={classes.headerName}>{title}</span>
        </header>
      <div className={classes.wrapper}>
        <TagName {...attributes} />
      </div>
    </div>
    )
  }
}
</code>```

Sidebar isn't very relevant.

My state is a flat array, consisting of objects that I can use to render the fields, so I'm reordering it based on the element positions in the DOM.

```<code>[
  {
    key: 'field_type1',
    parent: 'workbench',
    children: ['DAWPNC'], // If there's more children, "mutate" this according to the DOM
    unique: 'AWJOPD',
    attributes: {},
  },
  {
    key: 'field_type2',
    parent: 'AWJOPD',
    children: false,
    unique: 'DAWPNC',
    attributes: {},
  },
]
</code>```

The relevant portion of this question revolves around

```<code>const boxTarget = {
  drop(props, monitor, component) {
    const item = monitor.getItem()
    console.log(component, item.unique, component[item.unique]); // last one is undefined
    window.component = component; // doing it manually works, so the element just isn't in the DOM yet

    return {
      key: 'workbench',
    }
  },
}
</code>```

I figured I'd just get the reference to the element somehow, but it doesn't seem to exist in the DOM, yet. It's the same thing if I try to hack with ReactDOM:

```<code> // still inside the drop function, "works" with the timeout, doesn't without, but this is a bad idea
 setTimeout(() => {
    const domNode = ReactDOM.findDOMNode(component);
    const itemEl = domNode.querySelector(`[data-unique="${item.unique}"]`);
    const parentEl = itemEl.parentNode;

    const index = Array.from(parentEl.children).findIndex(x => x.getAttribute('data-unique') === item.unique);

    console.log(domNode, itemEl, index);
  });
</code>```

How do I achieve what I want?

Apologies for my inconsistent usage of semicolons, I don't know what I want from them. I hate them.

答:
I think the key here is realizing that the Field component can be both a DragSource and a DropTarget. We can then define a standard set of drop types that would influence how the state is mutated.

```<code>const DropType = {
  After: 'DROP_AFTER',
  Before: 'DROP_BEFORE',
  Inside: 'DROP_INSIDE'
};
</code>```

After and Before would allow re-ordering of fields, while Inside would allow nesting of fields (or dropping into the workbench).

Now, the action creator for handling any drop would be:

```<code>const drop = (source, target, dropType) => ({
  type: actions.DROP,
  source,
  target,
  dropType
});
</code>```

It just takes the source and target objects, and the type of drop occurring, which will then be translated into the state mutation.

A drop type is really just a function of the target bounds, the drop position, and (optionally) the drag source, all within the context of a particular DropTarget type:

```<code>(bounds, position, source) => dropType
</code>```

This function should be defined for each type of DropTarget supported. This would allow each DropTarget to support a different set of drop types. For instance, the Workbench only knows how to drop something inside of itself, not before or after, so the implementation for the workbench could look like:

```<code>(bounds, position) => DropType.Inside
</code>```

For a Field, you could use the logic from the Simple Card Sort example, where the upper half of the DropTarget translates to a Before drop while the lower half translates to an After drop:

```<code>(bounds, position) => {
  const middleY = (bounds.bottom - bounds.top) / 2;
  const relativeY = position.y - bounds.top;
  return relativeY < middleY ? DropType.Before : DropType.After;
};
</code>```

This approach also means that each DropTarget could handle the drop() spec method in the same manner:

get bounds of the drop target's DOM element

get the drop position

calculate the drop type from the bounds, position, and source

if any drop type occurred, handle the drop action

With React DnD, we have to be careful to appropriately handle nested drop targets since we have Fields in a Workbench:

```<code>const configureDrop = getDropType => (props, monitor, component) => {
  // a nested element handled the drop already
  if (monitor.didDrop())
    return;

  // requires that the component attach the ref to a node property
  const { node } = component;
  if (!node) return;

  const bounds = node.getBoundingClientRect();
  const position = monitor.getClientOffset();
  const source = monitor.getItem();

  const dropType = getDropType(bounds, position, source);

  if (!dropType)
    return;

  const { onDrop, ...target } = props;
  onDrop(source, target, dropType);

  // won't be used, but need to declare that the drop was handled
  return { dropped: true };
};
</code>```

The Component class would end up looking something like this:

```<code>@connect(...)
@DragSource(ItemTypes.FIELD, {
  beginDrag: ({ unique, parent, attributes }) => ({ unique, parent, attributes })
}, dragCollect)
// IMPORTANT: DropTarget has to be applied first so we aren't receiving
// the wrapped DragSource component in the drop() component argument
@DropTarget(ItemTypes.FIELD, {
  drop: configureDrop(getFieldDropType)
  canDrop: ({ parent }) => parent // don't drop if it isn't on the Workbench
}, dropCollect)
class Field extends React.Component {
  render() {
    return (
      // ref prop used to provide access to the underlying DOM node in drop()
      <div ref={ref => this.node = ref}>
        // field stuff
      </div>
    );
}
</code>```

Couple things to note:

Be mindful of the decorator order. DropTarget should wrap the component, then DragSource should wrap the wrapped component. This way, we have access to the correct component instance inside drop().

The drop target's root node needs to be a native element node, not a custom component node.

Any component that will be decorated with the DropTarget utilizing configureDrop() will require that the component set its root node's DOM ref to a node property.

Since we are handling the drop in the DropTarget, the DragSource just needs to implement the beginDrag() method, which would just return whatever state you want mixed into your application state.

The last thing to do is handle each drop type in your reducer. Important to remember is that every time you move something around, you need to remove the source from its current parent (if applicable), then insert it into the new parent. Each action could mutate the state of up to three elements, the source's existing parent (to clean up its children), the source (to assign its parent reference), and the target's parent or the target if an Inside drop (to add
to its children).

You also might want to consider making your state an object instead of an array, which might be easier to work with when implementing the reducer.

```<code>{
  AWJOPD: { ... },
  DAWPNC: { ... },
  workbench: {
    key: 'workbench',
    parent: null,
    children: [ 'DAWPNC' ]
  }
}
</code>```

Body:
I'm using React DnD and Redux (using Kea) to build a formbuilder. I've the drag & drop portion working just fine, and I've managed to dispatch an action when an element drops, and I render the builder afterwards using state that the dispatch changed. However, in order to render elements in the correct order, I (think I) need to save the dropped elements position relative to it's siblings but I'm unable to figure out anything that isn't absolutely insane. I've experimented with refs and querying the DOM with the unique ID (I know I shouldn't), but both approaches feel pretty terrible and do not even work.

Here's a simplified representation of my app structure:

@DragDropContext(HTML5Backend)
@connect({ /* redux things */ })
<Builder>
  <Workbench tree={this.props.tree} />
  <Sidebar fields={this.props.field}/>
</Builder>

Workbench:

const boxTarget = {
  drop(props, monitor, component) {
    const item = monitor.getItem()
    console.log(component, item.unique, component[item.unique]); // last one is undefined
    window.component = component; // doing it manually works, so the element just isn't in the DOM yet

    return {
      key: 'workbench',
    }
  },
}

@DropTarget(ItemTypes.FIELD, boxTarget, (connect, monitor) => ({
  connectDropTarget: connect.dropTarget(),
  isOver: monitor.isOver(),
  canDrop: monitor.canDrop(),
}))
export default class Workbench extends Component {
  render() {
    const { tree } = this.props;
    const { canDrop, isOver, connectDropTarget } = this.props

    return connectDropTarget(

        {tree.map((field, index) => {
          const { key, attributes, parent, unique } = field;
          if (parent === 'workbench') { // To render only root level nodes. I know how to render the children recursively, but to keep things simple...
            return (
              <Field
                unique={unique}
                key={key}
                _key={key}
                parent={this} // I'm passing the parent because the refs are useless in the Field instance (?) I don't know if this is a bad idea or not
              />
            );
          }

          return null;
        }).filter(Boolean)}

,
    )

    // ...

Field:

const boxSource = {
  beginDrag(props) {
    return {
      key: props._key,
      unique: props.unique || shortid.generate(),
      attributes: props.attributes,
    }
  },

  endDrag(props, monitor) {
    const item = monitor.getItem()
    const dropResult = monitor.getDropResult()

    console.log(dropResult);

    if (dropResult) {
      props.actions.onDrop({
        item,
        dropResult,
      });
    }
  },
}

@connect({ /* redux stuff */ })
@DragSource(ItemTypes.FIELD, boxSource, (connect, monitor) => ({
  connectDragSource: connect.dragSource(),
  isDragging: monitor.isDragging(),
}))
export default class Field extends Component {
  render() {
    const { TagName, title, attributes, parent } = this.props
    const { isDragging, connectDragSource } = this.props
    const opacity = isDragging ? 0.4 : 1

    return connectDragSource(

 parent[this.props.unique || this.props.key] = x} // If I save the ref to this instance, how do I access it in the drop function that works in context to boxTarget & Workbench?
      >

          {title}

        <TagName {...attributes} />

    )
  }
}

Sidebar isn't very relevant.

My state is a flat array, consisting of objects that I can use to render the fields, so I'm reordering it based on the element positions in the DOM.

[
  {
    key: 'field_type1',
    parent: 'workbench',
    children: ['DAWPNC'], // If there's more children, "mutate" this according to the DOM
    unique: 'AWJOPD',
    attributes: {},
  },
  {
    key: 'field_type2',
    parent: 'AWJOPD',
    children: false,
    unique: 'DAWPNC',
    attributes: {},
  },
]

The relevant portion of this question revolves around

const boxTarget = {
  drop(props, monitor, component) {
    const item = monitor.getItem()
    console.log(component, item.unique, component[item.unique]); // last one is undefined
    window.component = component; // doing it manually works, so the element just isn't in the DOM yet

    return {
      key: 'workbench',
    }
  },
}

I figured I'd just get the reference to the element somehow, but it doesn't seem to exist in the DOM, yet. It's the same thing if I try to hack with ReactDOM:

 // still inside the drop function, "works" with the timeout, doesn't without, but this is a bad idea
 setTimeout(() => {
    const domNode = ReactDOM.findDOMNode(component);
    const itemEl = domNode.querySelector(`[data-unique="${item.unique}"]`);
    const parentEl = itemEl.parentNode;

    const index = Array.from(parentEl.children).findIndex(x => x.getAttribute('data-unique') === item.unique);

    console.log(domNode, itemEl, index);
  });

How do I achieve what I want?

Apologies for my inconsistent usage of semicolons, I don't know what I want from them. I hate them.

Body:
I think the key here is realizing that the Field component can be both a DragSource and a DropTarget. We can then define a standard set of drop types that would influence how the state is mutated.

const DropType = {
  After: 'DROP_AFTER',
  Before: 'DROP_BEFORE',
  Inside: 'DROP_INSIDE'
};

After and Before would allow re-ordering of fields, while Inside would allow nesting of fields (or dropping into the workbench).

Now, the action creator for handling any drop would be:

const drop = (source, target, dropType) => ({
  type: actions.DROP,
  source,
  target,
  dropType
});

It just takes the source and target objects, and the type of drop occurring, which will then be translated into the state mutation.

A drop type is really just a function of the target bounds, the drop position, and (optionally) the drag source, all within the context of a particular DropTarget type:

(bounds, position, source) => dropType

This function should be defined for each type of DropTarget supported. This would allow each DropTarget to support a different set of drop types. For instance, the Workbench only knows how to drop something inside of itself, not before or after, so the implementation for the workbench could look like:

(bounds, position) => DropType.Inside

For a Field, you could use the logic from the Simple Card Sort example, where the upper half of the DropTarget translates to a Before drop while the lower half translates to an After drop:

(bounds, position) => {
  const middleY = (bounds.bottom - bounds.top) / 2;
  const relativeY = position.y - bounds.top;
  return relativeY < middleY ? DropType.Before : DropType.After;
};

This approach also means that each DropTarget could handle the drop() spec method in the same manner:

get bounds of the drop target's DOM element

get the drop position

calculate the drop type from the bounds, position, and source

if any drop type occurred, handle the drop action

With React DnD, we have to be careful to appropriately handle nested drop targets since we have Fields in a Workbench:

const configureDrop = getDropType => (props, monitor, component) => {
  // a nested element handled the drop already
  if (monitor.didDrop())
    return;

  // requires that the component attach the ref to a node property
  const { node } = component;
  if (!node) return;

  const bounds = node.getBoundingClientRect();
  const position = monitor.getClientOffset();
  const source = monitor.getItem();

  const dropType = getDropType(bounds, position, source);

  if (!dropType)
    return;

  const { onDrop, ...target } = props;
  onDrop(source, target, dropType);

  // won't be used, but need to declare that the drop was handled
  return { dropped: true };
};

The Component class would end up looking something like this:

@connect(...)
@DragSource(ItemTypes.FIELD, {
  beginDrag: ({ unique, parent, attributes }) => ({ unique, parent, attributes })
}, dragCollect)
// IMPORTANT: DropTarget has to be applied first so we aren't receiving
// the wrapped DragSource component in the drop() component argument
@DropTarget(ItemTypes.FIELD, {
  drop: configureDrop(getFieldDropType)
  canDrop: ({ parent }) => parent // don't drop if it isn't on the Workbench
}, dropCollect)
class Field extends React.Component {
  render() {
    return (
      // ref prop used to provide access to the underlying DOM node in drop()
      <div ref={ref => this.node = ref}>
        // field stuff
      </div>
    );
}

Couple things to note:

Be mindful of the decorator order. DropTarget should wrap the component, then DragSource should wrap the wrapped component. This way, we have access to the correct component instance inside drop().

The drop target's root node needs to be a native element node, not a custom component node.

Any component that will be decorated with the DropTarget utilizing configureDrop() will require that the component set its root node's DOM ref to a node property.

Since we are handling the drop in the DropTarget, the DragSource just needs to implement the beginDrag() method, which would just return whatever state you want mixed into your application state.

The last thing to do is handle each drop type in your reducer. Important to remember is that every time you move something around, you need to remove the source from its current parent (if applicable), then insert it into the new parent. Each action could mutate the state of up to three elements, the source's existing parent (to clean up its children), the source (to assign its parent reference), and the target's parent or the target if an Inside drop (to add
to its children).

You also might want to consider making your state an object instead of an array, which might be easier to work with when implementing the reducer.

{
  AWJOPD: { ... },
  DAWPNC: { ... },
  workbench: {
    key: 'workbench',
    parent: null,
    children: [ 'DAWPNC' ]
  }
}


问:
OSGi @Activate breaks when method has parameters. Error: activate method not found; Component will fail
I'm trying to implement a graceful shutdown hook to my OSGi based app. I'm implementing it in a bundle as I don't have direct access to the launcher source.

Here is the class:

```<code>/**
 * Shutdown Hook for OSGi
 * Based On: https://stackoverflow.com/a/32216407/5284104
 */
@Component()
public class ShutdownHookActivator{

    @Activate
    public void start(ComponentContext cc, BundleContext bc, Map<String,Object> config) {
        Thread hook = new Thread() {
            @Override
            public void run() {
                System.out.println("Stopping OSGi Framework.");
            try {
                Framework systemBundle = bc.getBundle(0).adapt(Framework.class);
                systemBundle.stop();
                System.out.println("Waiting up to 2s for OSGi shutdown to complete...");
                systemBundle.waitForStop(2000);
            } catch (Exception e) {
                System.err.println("Failed to cleanly shutdown OSGi Framework: " + e.getMessage());
                    e.printStackTrace();
                }
            }
        };

        System.out.println("Installing shutdown hook.");
        Runtime.getRuntime().addShutdownHook(hook);
    }
}
</code>```

But whenever I launch it it returns an error:

ERROR: [ShutdownHookActivator(8)] activate method [start] not found;
  Component will fail

But when I remove the parameters from the start method then everything works. So now I'm confused, I've seen examples where the @Activate method had parameters that are auto-injected by the OSGi framework (http://enroute.osgi.org/services/org.osgi.service.component.html), and others that are just empty, so from what I understand this should work. (Feels like in OSGi it's all about luck)

What is the proper way to implement this by using DS Annotations and getting the Framework BundleContext? Is it even possible?

EDIT:
OSGi Environment:
BndTools (aQute Launcher?)
Apache Felix SCR 2.0.12 (OSGi DS Annotations - 6.0.1)
Source can be seen here: https://github.com/Jafre13/ISS-Product

EDIT 2:
The auto-generated ShutdownHookActivator.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<scr:component xmlns:scr="http://www.osgi.org/xmlns/scr/v1.3.0" name="dk.sdu.sso.sred.utils.ShutdownHookActivator" activate="start">
  <implementation class="dk.sdu.sso.sred.utils.ShutdownHookActivator"/>
</scr:component>
</code>```

Manifest:

```<code>Manifest-Version: 1.0
Bnd-LastModified: 1512410080758
Bundle-ManifestVersion: 2
Bundle-Name: dk.sdu.sso.sred
Bundle-SymbolicName: dk.sdu.sso.sred
Bundle-Version: 0.0.0.201712041754
Created-By: 1.8.0_151 (Oracle Corporation)
Import-Package: javax.security.auth.x500,junit.framework,org.junit,org
 .xml.sax,org.xml.sax.ext,org.xml.sax.helpers
Private-Package: dk.sdu.sso.sred.cmd,dk.sdu.sso.sred.lingpipe,dk.sdu.s
 so.sred.api;version="1.0.0",dk.sdu.sso.sred,com.aliasi.test.unit.xml,
 com.aliasi.test.unit.io,com.aliasi.suffixarray,com.aliasi.test.unit.u
 til,com.aliasi.test.unit.crf,com.aliasi.matrix,com.aliasi.test.unit.s
 entences,com.aliasi.test.unit,com.aliasi.tag,com.aliasi.test.unit.hmm
 ,com.aliasi.chunk,com.aliasi.coref,com.aliasi.spell,com.aliasi.test.u
 nit.chunk,com.aliasi.test.unit.features,com.aliasi.coref.matchers,com
 .aliasi.lm,com.aliasi.test.unit.coref,com.aliasi.cluster,com.aliasi.f
 eatures,com.aliasi.test.unit.symbol,com.aliasi.io,com.aliasi.test.uni
 t.tokenizer,com.aliasi.sentences,com.aliasi.test.unit.coref.matchers,
 com.aliasi.test.unit.spell,com.aliasi.test.unit.corpus,com.aliasi.uti
 l,com.aliasi.dca,com.aliasi.symbol,com.aliasi.test.unit.lm,com.aliasi
 .dict,com.aliasi.test.unit.tag,com.aliasi.corpus,com.aliasi.classify,
 com.aliasi.test.unit.dca,com.aliasi.tokenizer,com.aliasi.test.unit.cl
 assify,com.aliasi.crf,com.aliasi.test.unit.cluster,com.aliasi.stats,c
 om.aliasi.test.unit.stats,com.aliasi.test.unit.dict,com.aliasi.test.u
 nit.matrix,com.aliasi.test.unit.suffixarray,com.aliasi.xml,com.aliasi
 .hmm,dk.sdu.sso.sred.utils,org.apache.felix.service.command,org.osgi.
 framework;version="1.8",org.osgi.service.component;version="1.3"
Provide-Capability: osgi.service;objectClass:List<String>="dk.sdu.sso.
 sred.api.SRedAPI",osgi.service;objectClass:List<String>="dk.sdu.sso.s
 red.cmd.ModelCommands",osgi.service;objectClass:List<String>="dk.sdu.
 sso.sred.cmd.SRedCommands"
Require-Capability: osgi.extender;filter:="(&(osgi.extender=osgi.compo
 nent)(version>=1.3.0)(!(version>=2.0.0)))",osgi.ee;filter:="(&(osgi.e
 e=JavaSE)(version=1.8))"
Service-Component: OSGI-INF/dk.sdu.sso.sred.SRed.xml,OSGI-INF/dk.sdu.s
 so.sred.cmd.ModelCommands.xml,OSGI-INF/dk.sdu.sso.sred.cmd.SRedComman
 ds.xml,OSGI-INF/dk.sdu.sso.sred.utils.ShutdownHookActivator.xml
Tool: Bnd-3.5.0.201709291849
</code>```

答:
From the Manifest it is obvious why your problem happens. You have the OSGi APIs as private package. This means that the classes are embedded into your jar and so they will be incompatible to the spec classes used by the framework and DS.

So the solution is to make sure you only use private package for stuff you really need to embed. Never use it for OSGi api packages. You need to have an import for them to work.

Body:
I'm trying to implement a graceful shutdown hook to my OSGi based app. I'm implementing it in a bundle as I don't have direct access to the launcher source.

Here is the class:

/**
 * Shutdown Hook for OSGi
 * Based On: https://stackoverflow.com/a/32216407/5284104
 */
@Component()
public class ShutdownHookActivator{

    @Activate
    public void start(ComponentContext cc, BundleContext bc, Map<String,Object> config) {
        Thread hook = new Thread() {
            @Override
            public void run() {
                System.out.println("Stopping OSGi Framework.");
            try {
                Framework systemBundle = bc.getBundle(0).adapt(Framework.class);
                systemBundle.stop();
                System.out.println("Waiting up to 2s for OSGi shutdown to complete...");
                systemBundle.waitForStop(2000);
            } catch (Exception e) {
                System.err.println("Failed to cleanly shutdown OSGi Framework: " + e.getMessage());
                    e.printStackTrace();
                }
            }
        };

        System.out.println("Installing shutdown hook.");
        Runtime.getRuntime().addShutdownHook(hook);
    }
}

But whenever I launch it it returns an error:

ERROR: [ShutdownHookActivator(8)] activate method [start] not found;
  Component will fail

But when I remove the parameters from the start method then everything works. So now I'm confused, I've seen examples where the @Activate method had parameters that are auto-injected by the OSGi framework (http://enroute.osgi.org/services/org.osgi.service.component.html), and others that are just empty, so from what I understand this should work. (Feels like in OSGi it's all about luck)

What is the proper way to implement this by using DS Annotations and getting the Framework BundleContext? Is it even possible?

EDIT:
OSGi Environment:
BndTools (aQute Launcher?)
Apache Felix SCR 2.0.12 (OSGi DS Annotations - 6.0.1)
Source can be seen here: https://github.com/Jafre13/ISS-Product

EDIT 2:
The auto-generated ShutdownHookActivator.xml:

<?xml version="1.0" encoding="UTF-8"?>
<scr:component xmlns:scr="http://www.osgi.org/xmlns/scr/v1.3.0" name="dk.sdu.sso.sred.utils.ShutdownHookActivator" activate="start">
  <implementation class="dk.sdu.sso.sred.utils.ShutdownHookActivator"/>
</scr:component>

Manifest:

Manifest-Version: 1.0
Bnd-LastModified: 1512410080758
Bundle-ManifestVersion: 2
Bundle-Name: dk.sdu.sso.sred
Bundle-SymbolicName: dk.sdu.sso.sred
Bundle-Version: 0.0.0.201712041754
Created-By: 1.8.0_151 (Oracle Corporation)
Import-Package: javax.security.auth.x500,junit.framework,org.junit,org
 .xml.sax,org.xml.sax.ext,org.xml.sax.helpers
Private-Package: dk.sdu.sso.sred.cmd,dk.sdu.sso.sred.lingpipe,dk.sdu.s
 so.sred.api;version="1.0.0",dk.sdu.sso.sred,com.aliasi.test.unit.xml,
 com.aliasi.test.unit.io,com.aliasi.suffixarray,com.aliasi.test.unit.u
 til,com.aliasi.test.unit.crf,com.aliasi.matrix,com.aliasi.test.unit.s
 entences,com.aliasi.test.unit,com.aliasi.tag,com.aliasi.test.unit.hmm
 ,com.aliasi.chunk,com.aliasi.coref,com.aliasi.spell,com.aliasi.test.u
 nit.chunk,com.aliasi.test.unit.features,com.aliasi.coref.matchers,com
 .aliasi.lm,com.aliasi.test.unit.coref,com.aliasi.cluster,com.aliasi.f
 eatures,com.aliasi.test.unit.symbol,com.aliasi.io,com.aliasi.test.uni
 t.tokenizer,com.aliasi.sentences,com.aliasi.test.unit.coref.matchers,
 com.aliasi.test.unit.spell,com.aliasi.test.unit.corpus,com.aliasi.uti
 l,com.aliasi.dca,com.aliasi.symbol,com.aliasi.test.unit.lm,com.aliasi
 .dict,com.aliasi.test.unit.tag,com.aliasi.corpus,com.aliasi.classify,
 com.aliasi.test.unit.dca,com.aliasi.tokenizer,com.aliasi.test.unit.cl
 assify,com.aliasi.crf,com.aliasi.test.unit.cluster,com.aliasi.stats,c
 om.aliasi.test.unit.stats,com.aliasi.test.unit.dict,com.aliasi.test.u
 nit.matrix,com.aliasi.test.unit.suffixarray,com.aliasi.xml,com.aliasi
 .hmm,dk.sdu.sso.sred.utils,org.apache.felix.service.command,org.osgi.
 framework;version="1.8",org.osgi.service.component;version="1.3"
Provide-Capability: osgi.service;objectClass:List<String>="dk.sdu.sso.
 sred.api.SRedAPI",osgi.service;objectClass:List<String>="dk.sdu.sso.s
 red.cmd.ModelCommands",osgi.service;objectClass:List<String>="dk.sdu.
 sso.sred.cmd.SRedCommands"
Require-Capability: osgi.extender;filter:="(&(osgi.extender=osgi.compo
 nent)(version>=1.3.0)(!(version>=2.0.0)))",osgi.ee;filter:="(&(osgi.e
 e=JavaSE)(version=1.8))"
Service-Component: OSGI-INF/dk.sdu.sso.sred.SRed.xml,OSGI-INF/dk.sdu.s
 so.sred.cmd.ModelCommands.xml,OSGI-INF/dk.sdu.sso.sred.cmd.SRedComman
 ds.xml,OSGI-INF/dk.sdu.sso.sred.utils.ShutdownHookActivator.xml
Tool: Bnd-3.5.0.201709291849


问:
How to bind Vue data to a dropdown
I am learning Vue, and can't tell what I have done wrong here.  Data is being returned from the server (5 records), but is not getting put into the <select>; all I get is a single option that says {{dept.DName}}

```<code><html>
<head><link href="Content/bootstrap.min.css" rel="stylesheet" />
    <meta charset="utf-8" />
    <title></title>
</head>
<body class="container">
<div>
    <select id="deptList">
        <option v-model="selected" v-for="dept in app.depts" v-bind:value="dept.Did">
            {{dept.DName}}
        </option>
    </select>
</div>
<script src="Scripts/jquery-1.9.1.min.js"></script>
<script src="Scripts/moment.min.js"></script>
<script src="https://unpkg.com/vue"></script>
<script src="https://cdn.jsdelivr.net/npm/vue-resource@1.3.4"></script>
<script src="Scripts/vue-controller.js"></script>
<script src="Scripts/bootstrap.min.js"></script>
</body>
</html>
</code>```

Scripts/vue-controller.js contains:

```<code>var app = new Vue({
    data: {
        el: "body",
        depts: [],
        emps: [],
        selected: ""
    },
    methods: {
        getDepts: function () {
            console.log("I'm a little teapot");  // this appears in the log
            this.$http.get("/Dept/Index").then(function(response) {
                this.depts = response.data;
                console.log(this.depts);  //the expected data does appear in the log
                },
                function(error) {
                    console.log(error.statusText);
                });
        }
    },
    created: function () {
        this.getDepts();
    }
})
</code>```

I am a C# developer and so I am halfway sure I am messing up the this/that context stuff, but have been unable to figure out what is happening.

答:
Variables in template are scoped to "app" automatically, so you need to remove "app." from your template, so it will be </p>

```<code><select id="deptList" v-model="selected">
  <option v-for="dept in depts" v-bind:value="dept.Did">
    {{dept.DName}}
  </option>
</select>
</code>```

Title: How to bind Vue data to a dropdown

Body:
I am learning Vue, and can't tell what I have done wrong here.  Data is being returned from the server (5 records), but is not getting put into the <select>; all I get is a single option that says {{dept.DName}}

<link href="Content/bootstrap.min.css" rel="stylesheet" />
    <meta charset="utf-8" />
    <title></title>

    <select id="deptList">
        <option v-model="selected" v-for="dept in app.depts" v-bind:value="dept.Did">
            {{dept.DName}}
        </option>
    </select>

Scripts/vue-controller.js contains:

var app = new Vue({
    data: {
        el: "body",
        depts: [],
        emps: [],
        selected: ""
    },
    methods: {
        getDepts: function () {
            console.log("I'm a little teapot");  // this appears in the log
            this.$http.get("/Dept/Index").then(function(response) {
                this.depts = response.data;
                console.log(this.depts);  //the expected data does appear in the log
                },
                function(error) {
                    console.log(error.statusText);
                });
        }
    },
    created: function () {
        this.getDepts();
    }
})

I am a C# developer and so I am halfway sure I am messing up the this/that context stuff, but have been unable to figure out what is happening.

Body:
Variables in template are scoped to "app" automatically, so you need to remove "app." from your template, so it will be

<select id="deptList" v-model="selected">
  <option v-for="dept in depts" v-bind:value="dept.Did">
    {{dept.DName}}
  </option>
</select>