答:
You have to check whether malloc return a valid pointer or fails to allocate the memory. In that case, it returns a null. pointer.

```<code>int max = 1399469912;
int *arr = (int*) malloc((max+1) * sizeof(int));
if( arr == NULL )
{
     /* Malloc failed, deal with it */
}else{
 //fine here
 arr[0] = 1;
}
</code>```

Quoting the man page

If successful, calloc(), malloc(), realloc(), reallocf(), and valloc()
  functions return a pointer to allocated memory. If there is an error,
  they return a NULL pointer and set errno to ENOMEM.

Body:
You have to check whether malloc return a valid pointer or fails to allocate the memory. In that case, it returns a null. pointer.

int max = 1399469912;
int *arr = (int*) malloc((max+1) * sizeof(int));
if( arr == NULL )
{
     /* Malloc failed, deal with it */
}else{
 //fine here
 arr[0] = 1;
}

Quoting the man page

If successful, calloc(), malloc(), realloc(), reallocf(), and valloc()
  functions return a pointer to allocated memory. If there is an error,
  they return a NULL pointer and set errno to ENOMEM.


来源: stackexchange

问:
Dynamic networks import available in 0.8v is missing in 0.9.1v
In gephi version 0.8, it is possible to import a network and assign a date or an id to this network to represent a time stamp for multiple networks as dynamic network.

In the newer version, version 0.9.1, this property is missing.
How can we import multiple networks and assign an id for each of them to represent a dynamic networks in the new version?
Is there a workaround?

答: This might answer your question: https://github.com/gephi/gephi/issues/1546</p>

ContentLicense: CC BY-SA 3.0


问:
How to bind XML to a TreeView without code behind for (MVVM, dataContext from XAML)
I have a window with a tree view control inside and a XML file. I want to bind the tree view to the XML file entirely from the XAML, without any C# code behind.

This is how I'm doing it now:

XAML

```<code><Window.Resources>
    <HierarchicalDataTemplate ItemsSource="{Binding Path=Elements}" x:Key="TreeViewItemData">
        <TreeViewItem Header="{Binding Path=Attribute[text].Value}" IsExpanded="True"/>
    </HierarchicalDataTemplate>
</Window.Resources>
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="40" />
        <RowDefinition Height="370*" />
    </Grid.RowDefinitions>
    <TextBlock Text="RD Admin Tool" Grid.Row="0" FontSize="22" FontWeight="Bold" Padding="50,5"></TextBlock>
    <StackPanel Orientation="Horizontal" Grid.Row ="1">
        <Border BorderBrush="#FF7C7B7B" BorderThickness="1" Name="tBorder" Width="200" CornerRadius="5" Background="#FFF5F2F2">
            <TreeView Name="OptionsTree"
                      ItemsSource="{Binding Path=Root.Elements}"
                      ItemTemplate="{StaticResource TreeViewItemData}"
                      HorizontalAlignment="Left" VerticalAlignment="Top"
                      Margin="5,0,0,0" FontSize="18" Background="#FFF5F2F2">
            </TreeView>
        </Border>
        <Canvas Name="OptionContent" Width="445">
        </Canvas>
    </StackPanel>
</Grid>
</code>```

Constructor in code behind:

```<code> public MyWindow()
    {
        InitializeComponent();

        XDocument doc = XDocument.Parse(File.ReadAllText(@"C:\Tree.xml"));
        this.MyTreeView.DataContext = doc;
    }
</code>```

But I'd really like to write it from the XAML and have no code behind.

Any suggestion?

答:
You can use XmlDataProvider to specify the xml data source and then bind to that.

This article discusses the technique: http://msdn.microsoft.com/en-us/magazine/cc163299.aspx

ContentLicense: CC BY-SA 2.5

Body:
I have a window with a tree view control inside and a XML file. I want to bind the tree view to the XML file entirely from the XAML, without any C# code behind.

This is how I'm doing it now:

XAML

<Window.Resources>
    <HierarchicalDataTemplate ItemsSource="{Binding Path=Elements}" x:Key="TreeViewItemData">
        <TreeViewItem Header="{Binding Path=Attribute[text].Value}" IsExpanded="True"/>
    </HierarchicalDataTemplate>
</Window.Resources>
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="40" />
        <RowDefinition Height="370*" />
    </Grid.RowDefinitions>
    <TextBlock Text="RD Admin Tool" Grid.Row="0" FontSize="22" FontWeight="Bold" Padding="50,5"></TextBlock>
    <StackPanel Orientation="Horizontal" Grid.Row ="1">
        <Border BorderBrush="#FF7C7B7B" BorderThickness="1" Name="tBorder" Width="200" CornerRadius="5" Background="#FFF5F2F2">
            <TreeView Name="OptionsTree"
                      ItemsSource="{Binding Path=Root.Elements}"
                      ItemTemplate="{StaticResource TreeViewItemData}"
                      HorizontalAlignment="Left" VerticalAlignment="Top"
                      Margin="5,0,0,0" FontSize="18" Background="#FFF5F2F2">
            </TreeView>
        </Border>
        <Canvas Name="OptionContent" Width="445">
        </Canvas>
    </StackPanel>
</Grid>

Constructor in code behind:

 public MyWindow()
    {
        InitializeComponent();

        XDocument doc = XDocument.Parse(File.ReadAllText(@"C:\Tree.xml"));
        this.MyTreeView.DataContext = doc;
    }

But I'd really like to write it from the XAML and have no code behind.

Any suggestion?


问:
Finding consistent assignments for logical formulas
I am about to implement a prover for logical terms in Prolog. My current code is not really presentable, therefore, I will just state, what I want my program to do and hopefully you can give me some good advice for that :)

It should take a list of variables (so to say the logical arguments) and secondly a logical formula containing these arguments (e.g. 'not'(A 'and' B) 'or' 'not'(B 'and' C) 'or' ... and so forth).

As output I would like my program to respond with the possible consistent assignments. The single arguments can either be true (1) or false (0).

So I aim for a return like A=0, B=0, C=0 ; A=1 and so forth.

I am happy for every help concerning my program :)

答:
There are several ways one could approach this. One way that is convenient in terms of syntax would be to define operators, something like this:

:- op(500, fx, not).
:- op(600, xfx, and).
:- op(700, xfx, or).
```

<p>(I am just guessing at reasonable precedence settings here, but just for illustration. See the <code>op</code> documentation for details.)</p>

<p>Having done that, you can write an expression such as: <code>A and B</code> and Prolog will "see" it as <code>and(A, B)</code>:</p>

<pre class="lang-erlang prettyprint-override"><code>| ?- write_canonical(A and B).
and(_23,_24)
</code>```

From there, you need to have a way to evaluate an expression. There are lots of questions on SO here in this regard (do a search in this site on [prolog] boolean expression evaluation), but I'll provide a simple example. It's now all about how you want to represent a result, and about recursion.

When it comes to representing a result, you could use Prolog's success/fail mechanism since you are dealing with boolean results. Or, you can have an explicit result, such as 0 and 1. Let's try 0 and 1 since that's your representation for true and false.

% Describe a valid boolean
bool(0).
bool(1).

% The evaluation of a valid boolean is itself
exp_eval(X, X) :- bool(X).

% Evaluation of an 'and' expression
exp_eval(and(A, B), Result) :-
    exp_eval(A, ResultA),
    exp_eval(B, ResultB),
    Result #= ResultA * ResultB.

% Evaluation of an 'or' expression
exp_eval(or(A, B), Result) :-
    exp_eval(A, ResultA),
    exp_eval(B, ResultB),
    % Just a little trick to get 1 if either ResultA or ResultB or both are 1
    Result #= (ResultA + ResultB + 1) // 2.

% Evaluation of a 'not' expression
exp_eval(not(A), Result) :-
    exp_eval(A, ResultNot),
    Result #= 1 - ResultNot.  % 0 ---> 1, and 1 ---> 0
```

<p>Instead of calculating "boolean" 1/0 results as I've done above, you could, instead, assert them as facts like so:</p>

<pre class="lang-erlang prettyprint-override"><code>bool_not(0, 1).
bool_not(1, 0).

bool_and(0, 0, 0).
bool_and(0, 1, 0).
bool_and(1, 0, 0).
bool_and(1, 1, 1).

bool_or(0, 0, 0).
bool_or(0, 1, 1).
bool_or(1, 0, 1).
bool_or(1, 1, 1).
</code>```

And then, for example, instead of Result #= (ResultA + ResultB + 1) // 2 you could just have, bool_or(ResultA, ResultB, Result).

Now that we can evaluate expressions, we want a solver:

solve(Exp) :-
    term_variables(Exp, Variables),
    maplist(bool, Variables),  % Variables should be valid booleans
    exp_eval(Exp, 1).          % We only want true results for the expression
```

<p>Note that in the original problem statement, it's said that the variable list would be given as an argument, but you can use <code>term_variables/2</code> to obtain the variables from an expression.</p>

<p>Then you can run the solver:</p>

<pre class="lang-erlang prettyprint-override"><code>| ?- solve(not(A and B) or not(B and C)).

A = 0
B = 0
C = 0 ? a

A = 0
B = 0
C = 1

A = 0
B = 1
C = 0

A = 0
B = 1
C = 1

A = 1
B = 0
C = 0

A = 1
B = 0
C = 1

A = 1
B = 1
C = 0

no
| ?-
</code>```

I don't know what your representation is for an expression. But whatever it is, you can map it to the above solution. What I've shown is simple and clear. You could skip the op/3 stuff and use standard term expressions, like, or(not(and(A,B)), not(and(B,C))) using the above code. If you have your input as some kind of token sequence, like, [not, (, A, and, B, ...] then you'll have to do a little list processing.

Body:
There are several ways one could approach this. One way that is convenient in terms of syntax would be to define operators, something like this:

:- op(500, fx, not).
:- op(600, xfx, and).
:- op(700, xfx, or).

(I am just guessing at reasonable precedence settings here, but just for illustration. See the op documentation for details.)

Having done that, you can write an expression such as: A and B and Prolog will "see" it as and(A, B):

| ?- write_canonical(A and B).
and(_23,_24)

From there, you need to have a way to evaluate an expression. There are lots of questions on SO here in this regard (do a search in this site on [prolog] boolean expression evaluation), but I'll provide a simple example. It's now all about how you want to represent a result, and about recursion.

When it comes to representing a result, you could use Prolog's success/fail mechanism since you are dealing with boolean results. Or, you can have an explicit result, such as 0 and 1. Let's try 0 and 1 since that's your representation for true and false.

% Describe a valid boolean
bool(0).
bool(1).

% The evaluation of a valid boolean is itself
exp_eval(X, X) :- bool(X).

% Evaluation of an 'and' expression
exp_eval(and(A, B), Result) :-
    exp_eval(A, ResultA),
    exp_eval(B, ResultB),
    Result #= ResultA * ResultB.

% Evaluation of an 'or' expression
exp_eval(or(A, B), Result) :-
    exp_eval(A, ResultA),
    exp_eval(B, ResultB),
    % Just a little trick to get 1 if either ResultA or ResultB or both are 1
    Result #= (ResultA + ResultB + 1) // 2.

% Evaluation of a 'not' expression
exp_eval(not(A), Result) :-
    exp_eval(A, ResultNot),
    Result #= 1 - ResultNot.  % 0 ---> 1, and 1 ---> 0

Instead of calculating "boolean" 1/0 results as I've done above, you could, instead, assert them as facts like so:

bool_not(0, 1).
bool_not(1, 0).

bool_and(0, 0, 0).
bool_and(0, 1, 0).
bool_and(1, 0, 0).
bool_and(1, 1, 1).

bool_or(0, 0, 0).
bool_or(0, 1, 1).
bool_or(1, 0, 1).
bool_or(1, 1, 1).

And then, for example, instead of Result #= (ResultA + ResultB + 1) // 2 you could just have, bool_or(ResultA, ResultB, Result).

Now that we can evaluate expressions, we want a solver:

solve(Exp) :-
    term_variables(Exp, Variables),
    maplist(bool, Variables),  % Variables should be valid booleans
    exp_eval(Exp, 1).          % We only want true results for the expression

Note that in the original problem statement, it's said that the variable list would be given as an argument, but you can use term_variables/2 to obtain the variables from an expression.

Then you can run the solver:

| ?- solve(not(A and B) or not(B and C)).

A = 0
B = 0
C = 0 ? a

A = 0
B = 0
C = 1

A = 0
B = 1
C = 0

A = 0
B = 1
C = 1

A = 1
B = 0
C = 0

A = 1
B = 0
C = 1

A = 1
B = 1
C = 0

no
| ?-

I don't know what your representation is for an expression. But whatever it is, you can map it to the above solution. What I've shown is simple and clear. You could skip the op/3 stuff and use standard term expressions, like, or(not(and(A,B)), not(and(B,C))) using the above code. If you have your input as some kind of token sequence, like, [not, (, A, and, B, ...] then you'll have to do a little list processing.


问:
Get email from user using Google actions
I want to recieve the user email using Google Actions as documented here but docs talks about EMAIL permission, but when I read the permission docs here I can't find any EMAIL permission. Any help? How can I receive the user email?</p>

答:
Ya, unfortunately the Assistant's SDK doesn't give you the email address. But if you implement account linking (like Ahmed mentioned) and use the Streamlined Flows, then you'll be getting the email provided to you; you just need to use the jsonwebtoken library and you can decode the assertion JWT and grab the email address.

That being said, this happens during "sign in" and token exchange... not during the actual action fulfillment. You'll need to issue a refresh token / access token :S


问:
share objects between controllers using services
I have to controllers the first controller is "cockpitController"and the other one  "idCardSupplierWarnController" .In the first controller i set my objects and i checked if the set work and it work i can see all my objects but when i want to get my objects in the other controller then all my objects are null .

PS: I checked this solution it's working for the case that the controller is in the same Window of the navigator but in my case it's in new window using $window.open(url).

Le service idCardSupplierWarnService :

```<code>var app = angular.module('idCardSupplierWarn');

app.service('idCardSupplierWarnService', function () {

    this.idRefNum = "";
    this.idSupNum = "";
    this.codeSuppNum = "";

    this.setParam = function (paramSet) {

        console.log(paramSet);

        this.idRefNum = paramSet.designRefPart;
        this.idSupNum = paramSet.idSuppNumber;
        this.codeSuppNum = paramSet.codeSupp;

    };

    this.getParamSupNum = function () {

        return this.idSupNum;

    };

    this.getParamCodeSupNum = function () {

        return this.codeSuppNum;

    };

    this.getParamIdRefNum = function () {

        return this.idRefNum;

    };

});
</code>```

Le controller cockpitController :

```<code>    (function () {
        angular
            .module("cockpit", ['mm.foundation', 'security', 'message', "isteven-multi-select"])
            .controller('cockpitController', ['$scope', '$translate', 'serviceCockpit','idCardSupplierWarnService', '$window', function ($scope, $translate, serviceCockpit,idCardSupplierWarnService,$window) {

                var urlSuppliersWarning = 'rest/suppliers/warnings';
                var urlSuppliersWarningByRefForDetails = 'rest/suppliers/warnings/supplier/ref/search';

                var self = this;

                serviceCockpit.loadData([urlSuppliersWarning]).then(function (results) {
                    self.suppliersWarning = results[0].data;
                });

                this.change = function () {

                    if (this.openWindow) {
                        this.openWindow = false;
                    }
                    else {
                        this.openWindow = true;
                    }

                };

                $scope.openNewWindowRef = function (url, params) {
                    console.log(params);
                    idCardSupplierWarnService.setParam(params);
                    console.log(idCardSupplierWarnService.getParams());
                    $window.open(url, '_blank', 'left=0, top=0, width=1100,height=600,scrollbars=yes, resizable=1');
                };

                $scope.openNewWindowSupp = function (url, params) {
                    idCardSupplierWarnService.setParam(params);
                    console.log(idCardSupplierWarnService);
                    $window.open(url, '_blank', 'left=0, top=0, width=1100,height=600,scrollbars=yes, resizable=1');
                };

                this.process = function (items) {

                    if (items.origin == 'reference' || items.origin == 'suppliers' || items.origin == 'supplierAccounts' || items.origin == 'supplierAddressCodes' || items.origin == 'reset') {

                        serviceCockpit.loadData([urlSuppliersWarningByRefForDetails], items).then(function (results) {
                            self.suppliersWarningDetails = results[0].data;
                        });
                    }

                    serviceCockpit.loadData([urlSuppliersWarning], items).then(function (results) {
                        self.suppliersWarning = results[0].data;
                    });
                }

            }]);
    })();
</code>```

Le controller **idCardSupplierWarnController :**

```<code> (function () {
    angular
        .module("idCardSupplierWarn", ['mm.foundation', 'security', 'message', "isteven-multi-select"])
        .controller('idCardSupplierWarnController', ['$translate', '$scope', 'serviceCockpit','idCardSupplierWarnService', function ($translate, $scope, serviceCockpit,idCardSupplierWarnService) {

            var urlSupplierWarningByRefDetail = 'rest/suppliers/warnings/supplier/details';

            var self = this;

             var params = {} ;

             params.idRefNum = idCardSupplierWarnService.getParamIdRefNum();
             params.idSupNum = idCardSupplierWarnService.getParamSupNum();
             params.codeSuppNum = idCardSupplierWarnService.getParamCodeSupNum();
                      console.log(params.codeSuppNum);

            serviceCockpit.loadData([urlSupplierWarningByRefDetail], params).then(function (results) {
                self.suppliersWarningsList = results[0].data;
            });

        }]);
})();
</code>```

答:
"This" in the functions of your service refers to the individual functions in your service, not the service itself.

Modify your service to look like this:

```<code>app.service('idCardSupplierWarnService', function () {

    var service = this
    service.idRefNum = "";
    service.idSupNum = "";
    service.codeSuppNum = "";

    service.setParam = function (paramSet) {

        console.log(paramSet);

        service.idRefNum = paramSet.designRefPart;
        service.idSupNum = paramSet.idSuppNumber;
        service.codeSuppNum = paramSet.codeSupp;

    };

    service.getParamSupNum = function () {

        return service.idSupNum;

    };

    service.getParamCodeSupNum = function () {

        return service.codeSuppNum;

    };

    service.getParamIdRefNum = function () {

        service this.idRefNum;

    };

    return service

});
</code>```

Body:
I have to controllers the first controller is "cockpitController"and the other one  "idCardSupplierWarnController" .In the first controller i set my objects and i checked if the set work and it work i can see all my objects but when i want to get my objects in the other controller then all my objects are null .

PS: I checked this solution it's working for the case that the controller is in the same Window of the navigator but in my case it's in new window using $window.open(url).

Le service idCardSupplierWarnService :

var app = angular.module('idCardSupplierWarn');

app.service('idCardSupplierWarnService', function () {

    this.idRefNum = "";
    this.idSupNum = "";
    this.codeSuppNum = "";

    this.setParam = function (paramSet) {

        console.log(paramSet);

        this.idRefNum = paramSet.designRefPart;
        this.idSupNum = paramSet.idSuppNumber;
        this.codeSuppNum = paramSet.codeSupp;

    };

    this.getParamSupNum = function () {

        return this.idSupNum;

    };

    this.getParamCodeSupNum = function () {

        return this.codeSuppNum;

    };

    this.getParamIdRefNum = function () {

        return this.idRefNum;

    };

});

Le controller cockpitController :

    (function () {
        angular
            .module("cockpit", ['mm.foundation', 'security', 'message', "isteven-multi-select"])
            .controller('cockpitController', ['$scope', '$translate', 'serviceCockpit','idCardSupplierWarnService', '$window', function ($scope, $translate, serviceCockpit,idCardSupplierWarnService,$window) {

                var urlSuppliersWarning = 'rest/suppliers/warnings';
                var urlSuppliersWarningByRefForDetails = 'rest/suppliers/warnings/supplier/ref/search';

                var self = this;

                serviceCockpit.loadData([urlSuppliersWarning]).then(function (results) {
                    self.suppliersWarning = results[0].data;
                });

                this.change = function () {

                    if (this.openWindow) {
                        this.openWindow = false;
                    }
                    else {
                        this.openWindow = true;
                    }

                };

                $scope.openNewWindowRef = function (url, params) {
                    console.log(params);
                    idCardSupplierWarnService.setParam(params);
                    console.log(idCardSupplierWarnService.getParams());
                    $window.open(url, '_blank', 'left=0, top=0, width=1100,height=600,scrollbars=yes, resizable=1');
                };

                $scope.openNewWindowSupp = function (url, params) {
                    idCardSupplierWarnService.setParam(params);
                    console.log(idCardSupplierWarnService);
                    $window.open(url, '_blank', 'left=0, top=0, width=1100,height=600,scrollbars=yes, resizable=1');
                };

                this.process = function (items) {

                    if (items.origin == 'reference' || items.origin == 'suppliers' || items.origin == 'supplierAccounts' || items.origin == 'supplierAddressCodes' || items.origin == 'reset') {

                        serviceCockpit.loadData([urlSuppliersWarningByRefForDetails], items).then(function (results) {
                            self.suppliersWarningDetails = results[0].data;
                        });
                    }

                    serviceCockpit.loadData([urlSuppliersWarning], items).then(function (results) {
                        self.suppliersWarning = results[0].data;
                    });
                }

            }]);
    })();

Le controller **idCardSupplierWarnController :**

 (function () {
    angular
        .module("idCardSupplierWarn", ['mm.foundation', 'security', 'message', "isteven-multi-select"])
        .controller('idCardSupplierWarnController', ['$translate', '$scope', 'serviceCockpit','idCardSupplierWarnService', function ($translate, $scope, serviceCockpit,idCardSupplierWarnService) {

            var urlSupplierWarningByRefDetail = 'rest/suppliers/warnings/supplier/details';

            var self = this;

             var params = {} ;

             params.idRefNum = idCardSupplierWarnService.getParamIdRefNum();
             params.idSupNum = idCardSupplierWarnService.getParamSupNum();
             params.codeSuppNum = idCardSupplierWarnService.getParamCodeSupNum();
                      console.log(params.codeSuppNum);

            serviceCockpit.loadData([urlSupplierWarningByRefDetail], params).then(function (results) {
                self.suppliersWarningsList = results[0].data;
            });

        }]);
})();

Body:
"This" in the functions of your service refers to the individual functions in your service, not the service itself.

Modify your service to look like this:

app.service('idCardSupplierWarnService', function () {

    var service = this
    service.idRefNum = "";
    service.idSupNum = "";
    service.codeSuppNum = "";

    service.setParam = function (paramSet) {

        console.log(paramSet);

        service.idRefNum = paramSet.designRefPart;
        service.idSupNum = paramSet.idSuppNumber;
        service.codeSuppNum = paramSet.codeSupp;

    };

    service.getParamSupNum = function () {

        return service.idSupNum;

    };

    service.getParamCodeSupNum = function () {

        return service.codeSuppNum;

    };

    service.getParamIdRefNum = function () {

        service this.idRefNum;

    };

    return service

});


问:
Angular4: router, children (optional) parameters
So, I am looking to produce paths like these:

matches/:page/:team/:season

where :team and :season are optional parameters
so I could have an url like

```<code>matches/results/4/2017 or
matches/results/4 or
matches/results
</code>```

all should be valid and come through in this.route.snapshot.params

I tried this:

```<code>  {path: 'matches', children: [
    {path: '', pathMatch: 'full', redirectTo: 'fixtures'},
    {path: 'competitions', component: CompetitionsPageComponent},
    {path: ':page', component: PageComponent, children: [
      {path: ':team', children:[
          {path: ':season', children:[]}
      ]}
    ]},
  ]},
</code>```

with no luck, only :page comes through as param

答:
@user2623919 answers close enough...

this is what is working for me... all the routes point to the same PageComponent and in my params I get the ones I set....
this way

```<code>{path: 'matches', children: [
  {path: '', pathMatch: 'full', redirectTo: 'fixtures'},
  {path: 'competitions-table', component: CompetitionsPageComponent},
  {path: ':page', component: PageComponent},
  {path: ':page/:team', component: PageComponent},
  {path: ':page/:team/:competition', component: PageComponent},
  {path: ':page/:team/:competition/:season', component: PageComponent}
]},
</code>```

/matches/results

gives me params {page: 'results'} and

/matches/results/20

gives me  params {page: 'results', team: '20'} and so on

Cheers guys

Body:
So, I am looking to produce paths like these:

matches/:page/:team/:season

where :team and :season are optional parameters
so I could have an url like

matches/results/4/2017 or
matches/results/4 or
matches/results

all should be valid and come through in this.route.snapshot.params

I tried this:

  {path: 'matches', children: [
    {path: '', pathMatch: 'full', redirectTo: 'fixtures'},
    {path: 'competitions', component: CompetitionsPageComponent},
    {path: ':page', component: PageComponent, children: [
      {path: ':team', children:[
          {path: ':season', children:[]}
      ]}
    ]},
  ]},

with no luck, only :page comes through as param

Body:
@user2623919 answers close enough...

this is what is working for me... all the routes point to the same PageComponent and in my params I get the ones I set....
this way

{path: 'matches', children: [
  {path: '', pathMatch: 'full', redirectTo: 'fixtures'},
  {path: 'competitions-table', component: CompetitionsPageComponent},
  {path: ':page', component: PageComponent},
  {path: ':page/:team', component: PageComponent},
  {path: ':page/:team/:competition', component: PageComponent},
  {path: ':page/:team/:competition/:season', component: PageComponent}
]},

/matches/results

gives me params {page: 'results'} and

/matches/results/20

gives me  params {page: 'results', team: '20'} and so on

Cheers guys


问:
How can I convert an int number from decimal to binary
how to convert an int array of length 8 to  an int array of length 32 each 4 indexes are the binary representation of an index of the first array is there such a method that do all overhead.

Edit, PST: I updated the title. However, this doesn't quite reflect with the notion of "binary", it's just decomposing integers into bytes. Correct and/or add examples if this is not accurate.

ok programers the main thing that i want is >> How can I convert an int number from decimal to binary

答:
Probably using all or some of the following (there is no direct way to achieve it):

Integer.toBinaryString to get binary representation of your integer at your index.

Array.newInstance

System.arrayCopy

simple for loop etc.


问:
SSRS can't find server on which SQL Server is installed
I'm running SQL Server 2012, and I'm trying to configure Reporting Services. I've confirmed that the service is running on my system, but when I start up Reporting Services Configuration Manager, there is no server listed in the start up screen, where it asks to Connect to a Server. When I type in the name of the server, I get a pop up saying,

Cannot Find <Server Name>

That's as far as I get, and I cannot understand why it would not automatically populate the server name or, even less clear, why it wouldn't be able to find the Server once I entered the name in manually.

I wish I could give more information but that's really as far as I get. Are there some basic configurations I can check to see why it's not "aware" of itself as a SQL server?

答:
In my case SSRS was installed but not correctly configured.

I had to use Reporting Services Configuration Manager to create a database (Database panel) and then enable the web services using the 'Web Service URL' panel.

Once both these steps had been completed, I was able to connect via SSMS.

ContentLicense: CC BY-SA 4.0


问:
Why can't I call system functions in R that clearly work in my terminal?
I am trying to call system functions in R. I am using a mac. If I pass a built-in function (e.g. ln), it works no problem:

```<code>command <- "ls"
cat(command, "\n")
try(system(command))
</code>```

I get a list of the directory.

However, if I install functions from third parties (e.g. binaries), it doesn't work (even if it works in the terminal).

```<code>command <- "bedtools ..."
cat(command, "\n")
try(system(command))
</code>```

I get the following error:

```<code>sh: bedtool..:command not found
</code>```

Do you think it's a PATH problem?

Thank you!

答:
Considered for sure that you 'installed' the command (it exists in a bin somewhere) and after reading yout comment:

if I open RStudio where the function's binaries are located (e.g. open -a RStudio), it works no problem.

I guess that it is a PATH problem indeed. A possible fix would be:

```<code>Sys.setenv(PATH=paste(Sys.getenv("PATH"), "/the/bin/folder/of/bedtools", sep=":"))
</code>```

Body:
I am trying to call system functions in R. I am using a mac. If I pass a built-in function (e.g. ln), it works no problem:

command <- "ls"
cat(command, "\n")
try(system(command))

I get a list of the directory.

However, if I install functions from third parties (e.g. binaries), it doesn't work (even if it works in the terminal).

command <- "bedtools ..."
cat(command, "\n")
try(system(command))

I get the following error:

sh: bedtool..:command not found

Do you think it's a PATH problem?

Thank you!

Body:
Considered for sure that you 'installed' the command (it exists in a bin somewhere) and after reading yout comment:

if I open RStudio where the function's binaries are located (e.g. open -a RStudio), it works no problem.

I guess that it is a PATH problem indeed. A possible fix would be:

Sys.setenv(PATH=paste(Sys.getenv("PATH"), "/the/bin/folder/of/bedtools", sep=":"))


问:
TransactionTooLargeException in Nougat
Exception

```<code> 05-12 15:42:45.791 11043-11043/ E/UncaughtException: java.lang.RuntimeException: android.os.TransactionTooLargeException: data parcel size 631792 bytes
                                                                       at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3776)
                                                                       at android.os.Handler.handleCallback(Handler.java:751)
                                                                       at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                       at android.os.Looper.loop(Looper.java:154)
                                                                       at android.app.ActivityThread.main(ActivityThread.java:6123)
                                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
                                                                    Caused by: android.os.TransactionTooLargeException: data parcel size 631792 bytes
                                                                       at android.os.BinderProxy.transactNative(Native Method)
                                                                       at android.os.BinderProxy.transact(Binder.java:615)
                                                                       at android.app.ActivityManagerProxy.activityStopped(ActivityManagerNative.java:3700)
                                                                       at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3768)
                                                                       at android.os.Handler.handleCallback(Handler.java:751)
                                                                       at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                       at android.os.Looper.loop(Looper.java:154)
                                                                       at android.app.ActivityThread.main(ActivityThread.java:6123)
                                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
05-12 15:42:47.247 11043-11043/ E/AndroidRuntime: FATAL EXCEPTION: main
                                                                Process: , PID: 11043
                                                                java.lang.RuntimeException: android.os.TransactionTooLargeException: data parcel size 631792 bytes
                                                                    at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3776)
                                                                    at android.os.Handler.handleCallback(Handler.java:751)
                                                                    at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                    at android.os.Looper.loop(Looper.java:154)
                                                                    at android.app.ActivityThread.main(ActivityThread.java:6123)
                                                                    at java.lang.reflect.Method.invoke(Native Method)
                                                                    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
                                                                    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
                                                                 Caused by: android.os.TransactionTooLargeException: data parcel size 631792 bytes
                                                                    at android.os.BinderProxy.transactNative(Native Method)
                                                                    at android.os.BinderProxy.transact(Binder.java:615)
                                                                    at android.app.ActivityManagerProxy.activityStopped(ActivityManagerNative.java:3700)
                                                                    at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3768)
                                                                    at android.os.Handler.handleCallback(Handler.java:751)
                                                                    at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                    at android.os.Looper.loop(Looper.java:154)
                                                                    at android.app.ActivityThread.main(ActivityThread.java:6123)
                                                                    at java.lang.reflect.Method.invoke(Native Method)
                                                                    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
                                                                    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
</code>```

Fragment OnItemClick:-

```<code> listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {

            Bundle bundle = new Bundle();
            ProdModel mProdModel = prodList.get(position);
            bundle.putSerializable("object", mProdModel);
            Intent intent = new Intent(getActivity(), DetailActivity.class);
            intent.putExtra("bundle", bundle);
            startActivityForResult(intent, 1);

        }

    });
</code>```

In DetailActivity,

```<code>Bundle bundle = getIntent().getBundleExtra("bundle");
    if (bundle != null) {
        ProdModel model = (ProdModel) bundle.getSerializable("object");
    }
</code>```

DetailActivity Manifest,

```<code>  <activity
        android:name="com.mass.mysample.DetailActivity"
        android:screenOrientation="portrait" />
</code>```

Image Loading Using Picasso,

```<code> Picasso.with(this).load(model.getImage())
             .placeholder(R.drawable.logo_without)
             .fit().into(productimage);
</code>```

Model Class

```<code>public class ProdModel implements Serializable {
private String seller_id;
String name;
private String image;
private float price;
private float specialprice;
private String entity_id;
private String productNumQuantity;
private String storetitle;
private String description;
private String discount;
private String max_price;
private String store_name;
private String StoreUrl;

public String getProductNumQuantity() {
    return productNumQuantity;
}

public void setProductNumQuantity(String productNumQuantity) {
    this.productNumQuantity = productNumQuantity;
}

public String getDiscount() {
    return discount;
}

public void setDiscount(String discount) {
    this.discount = discount;
}

public String getMax_price() {
    return max_price;
}

public void setMax_price(String max_price) {
    this.max_price = max_price;
}

public String getStore_name() {
    return store_name;
}

public void setStore_name(String store_name) {
    this.store_name = store_name;
}

public String getStoreUrl() {
    return StoreUrl;
}

public void setStoreUrl(String storeUrl) {
    StoreUrl = storeUrl;
}

public String getStoretitle() {
    return storetitle;
}

public void setStoretitle(String storetitle) {
    this.storetitle = storetitle;
}

public String getSeller_id() {
    return seller_id;
}

public void setSeller_id(String seller_id) {
    this.seller_id = seller_id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getImage() {
    return image;
}

public void setImage(String image) {
    this.image = image;
}

public String getEntity_id() {
    return entity_id;
}

public void setEntity_id(String entity_id) {
    this.entity_id = entity_id;
}

public String getDescription() {
    return description;
}

public void setDescription(String description) {
    this.description = description;
}

public float getPrice() {
    return price;
}

public void setPrice(float price) {
    this.price = price;
}

public float getSpecialPrice() {
    return specialprice;
}

public void setSpecialPrice(float specialprice) {
    this.specialprice = specialprice;
}

}
</code>```

Data flow from TabActivity to fragment,

```<code>1.I have a TabActivity with ViewPager and Fragment.
2.In Fragment, I have a ListView.
3.The Data to fragment is passed from view pager adapter by set arguments.
</code>```

Solutions I tried

```<code>1.A POJO class that implements Serialization.
2.I use Picasso to load the image from image URL.
3.This exception is thrown when OnItemClick on ListView in fragment passes data to DetailActivity to show all passed data.
4.I get this exception after the DetailActivity load's image and other data then app suddenly crashes.
5.I pass data in Intent was all POJO Object with Id, Name, Image URL, Price etc.,
</code>```

Note:-
App Crash only in NOUGAT

Finally, The fix I implemented

changing the targetSdkVersion to 23 from 25

After changing, my application not crashing in Nougat too.

All I have to Know is this proper solution or is there any workaround.

Please Guide to the proper way.

Thanks in advance.

Fragment

```<code>public class ProdFragment extends Fragment {
ListView listview;
SharedPreferences spref;
Boolean isInternetPresent = false;
ConnectionDetector cd;

private String toBeDisplayed,CatID;
private static final String TAG = ProdFragment.class.getSimpleName();
String totalProductCart;
private ArrayList<Root_SubCatModel> subCatList;
private ArrayList<ProdModel> prodList;
ProdAdapter adapter;

public ProdFragment() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    spref = getActivity().getSharedPreferences(getResources().getString(R.string.myPref),
            Context.MODE_PRIVATE);
    Bundle bundle = getArguments();
    if (bundle != null) {
        int tabPosition = bundle.getInt("Tab_Position");
        toBeDisplayed = bundle.getString("Tab_ToBeDisplayed");
        CatID = bundle.getString("CategoryId");
        subCatList = (ArrayList<Root_SubCatModel>) bundle.getSerializable("Tab_Data");
    }
}

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

    cd = new ConnectionDetector(getActivity());
    listview = (ListView) rootView.findViewById(R.id.prodlist);
    if (subCatList != null) {
        adapter = new ProdAdapter(getActivity(),
                CatID,
                toBeDisplayed,
                R.layout.list_product,
                subCatList,
                (ProductCartCountListener)getActivity());
        listview.setAdapter(adapter);
        adapter.notifyDataSetChanged();

        prodList = new ArrayList<>();
        for(int i = 0; i<subCatList.size();i++){
            if (subCatList.get(i).getProd() != null) {
                if(toBeDisplayed.equals("SubCategory")){
                    if (CatID.equals(subCatList.get(i).getCategory_id())) {
                        this.prodList = subCatList.get(i).getProd();
                    }
                }else if(toBeDisplayed.equals("Products")) {
                    this.prodList = subCatList.get(i).getProd();
                }
            }
        }

    }

    listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {

            Bundle bundle = new Bundle();
            bundle.putSerializable("object", prodList.get(position));
            Intent intent = new Intent(getActivity(), DetailActivity.class);
            intent.putExtra("bundle", bundle);
            startActivityForResult(intent,1);
        }

    });

    return rootView;
}

public void showAlertDialog(Context context, String title, String message, Boolean status) {
    AlertDialog alertDialog = new AlertDialog.Builder(context).create();

    // Setting Dialog Title
    alertDialog.setTitle(title);

    // Setting Dialog Message
    alertDialog.setMessage(message);

    // Setting alert dialog icon
    //alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);

    // Setting OK Button
    alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
        }
    });

    // Showing Alert Message
    alertDialog.show();
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 1) {
        if (resultCode == Activity.RESULT_OK) {
            Bundle b = data.getExtras();
            if (b != null) {
                ProdModel myobj = (ProdModel) b.getSerializable("Cart_Quantity");
                if (myobj != null) {
                    if (prodList != null) {
                        for (ProdModel P : prodList) {
                            if (P.getEntity_id().equals(myobj.getEntity_id())) {
                                P.setProductNumQuantity(myobj.getProductNumQuantity());
                            }
                        }
                    }
                    Log.d(TAG,"Product_Id : " + myobj.getEntity_id()
                            + ", Product_Cart_Count : " + myobj.getProductNumQuantity());
                }
            }
        } else if (resultCode == 0) {
            Log.d(TAG,"RESULT CANCELLED");
        }
    }
    adapter.notifyDataSetChanged();
    String totalProductCart = spref.getString("Cart_Count_Tool", "0");
    Activity activity = getActivity();
    if(activity instanceof TabActivity){
        TabActivity myActivity = (TabActivity) activity;
        Toolbar toolbar = (Toolbar) myActivity.findViewById(R.id.back_toolbar);
        ImageView cart_imageview = (ImageView) toolbar.findViewById(R.id.cart_imageview);
        cart_imageview.setImageDrawable(myActivity.buildCounterDrawable(
                Integer.parseInt(totalProductCart)));
    }
    Log.d(TAG,"RESULT NOTIFIED");
}

public void refreshData(String productId, boolean isAddAsyncTaskComplete,
                        boolean isAddAsyncTaskLimitReached, boolean isDeleteAsyncTaskComplete){
    adapter.setQuantityCount(prodList, productId, isAddAsyncTaskComplete,
            isAddAsyncTaskLimitReached, isDeleteAsyncTaskComplete);

}
</code>```

TabActivity Layout

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/storeimage"
        android:textAlignment="center"
        android:elevation="2dp"
        android:minHeight="?attr/actionBarSize"
        app:tabMode="scrollable"
        app:tabTextColor="@color/color_dark_blue"
        app:tabSelectedTextColor="@color/color_orange"/>
</android.support.design.widget.AppBarLayout>

<android.support.v4.view.ViewPager
    android:id="@+id/viewpager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />
 </android.support.design.widget.CoordinatorLayout>
</code>```

ListView

```<code> listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {

            Bundle bundle = new Bundle();
            ProdModel mProdModel = prodList.get(position);
            bundle.putSerializable("object", mProdModel);
            Intent intent = new Intent(getActivity(), DetailActivity.class);
            intent.putExtra("bundle", bundle);
            startActivityForResult(intent, 1);

        }

    });
</code>```0

答:
Your are passing too much data to your Fragment in setArguments(). Your Fragment will work, but when it tries to save its instance state it overflows the transaction buffer. This throws a RuntimeException if you target Android 7.0 (API 24 or higher). To preserve backwards compatibility and not break existing apps, the new behaviour is only used if you target API 24 or higher. If you target API < 24, the transaction buffer overflow exception is caught and silently ignored. This means that your data will not be persistently saved, which you may (or may not) notice.

Your code is broken. You should not pass large amounts of data to the Fragment in setArguments(). You can keep your data in your Activity. When the Fragment wants to access the data, it can always so something like this:

```<code>// Get the owning Activity
MyActivity activity = (MyActivity)getActivity();
// Get the data from the Activity
List<Data> data = activity.getData();
</code>```

In your Activity, write a getData() method that returns a reference to whatever data the Fragment needs.

In this way, the data is held in the Activity and the Fragment can get access to it whenever it needs to.

Title: TransactionTooLargeException in Nougat

Body:
Exception

 05-12 15:42:45.791 11043-11043/ E/UncaughtException: java.lang.RuntimeException: android.os.TransactionTooLargeException: data parcel size 631792 bytes
                                                                       at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3776)
                                                                       at android.os.Handler.handleCallback(Handler.java:751)
                                                                       at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                       at android.os.Looper.loop(Looper.java:154)
                                                                       at android.app.ActivityThread.main(ActivityThread.java:6123)
                                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
                                                                    Caused by: android.os.TransactionTooLargeException: data parcel size 631792 bytes
                                                                       at android.os.BinderProxy.transactNative(Native Method)
                                                                       at android.os.BinderProxy.transact(Binder.java:615)
                                                                       at android.app.ActivityManagerProxy.activityStopped(ActivityManagerNative.java:3700)
                                                                       at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3768)
                                                                       at android.os.Handler.handleCallback(Handler.java:751)
                                                                       at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                       at android.os.Looper.loop(Looper.java:154)
                                                                       at android.app.ActivityThread.main(ActivityThread.java:6123)
                                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
05-12 15:42:47.247 11043-11043/ E/AndroidRuntime: FATAL EXCEPTION: main
                                                                Process: , PID: 11043
                                                                java.lang.RuntimeException: android.os.TransactionTooLargeException: data parcel size 631792 bytes
                                                                    at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3776)
                                                                    at android.os.Handler.handleCallback(Handler.java:751)
                                                                    at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                    at android.os.Looper.loop(Looper.java:154)
                                                                    at android.app.ActivityThread.main(ActivityThread.java:6123)
                                                                    at java.lang.reflect.Method.invoke(Native Method)
                                                                    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
                                                                    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
                                                                 Caused by: android.os.TransactionTooLargeException: data parcel size 631792 bytes
                                                                    at android.os.BinderProxy.transactNative(Native Method)
                                                                    at android.os.BinderProxy.transact(Binder.java:615)
                                                                    at android.app.ActivityManagerProxy.activityStopped(ActivityManagerNative.java:3700)
                                                                    at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3768)
                                                                    at android.os.Handler.handleCallback(Handler.java:751)
                                                                    at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                    at android.os.Looper.loop(Looper.java:154)
                                                                    at android.app.ActivityThread.main(ActivityThread.java:6123)
                                                                    at java.lang.reflect.Method.invoke(Native Method)
                                                                    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
                                                                    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)

Fragment OnItemClick:-

 listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {

            Bundle bundle = new Bundle();
            ProdModel mProdModel = prodList.get(position);
            bundle.putSerializable("object", mProdModel);
            Intent intent = new Intent(getActivity(), DetailActivity.class);
            intent.putExtra("bundle", bundle);
            startActivityForResult(intent, 1);

        }

    });

In DetailActivity,

Bundle bundle = getIntent().getBundleExtra("bundle");
    if (bundle != null) {
        ProdModel model = (ProdModel) bundle.getSerializable("object");
    }

DetailActivity Manifest,

  <activity
        android:name="com.mass.mysample.DetailActivity"
        android:screenOrientation="portrait" />

Image Loading Using Picasso,

 Picasso.with(this).load(model.getImage())
             .placeholder(R.drawable.logo_without)
             .fit().into(productimage);

Model Class

public class ProdModel implements Serializable {
private String seller_id;
String name;
private String image;
private float price;
private float specialprice;
private String entity_id;
private String productNumQuantity;
private String storetitle;
private String description;
private String discount;
private String max_price;
private String store_name;
private String StoreUrl;

public String getProductNumQuantity() {
    return productNumQuantity;
}

public void setProductNumQuantity(String productNumQuantity) {
    this.productNumQuantity = productNumQuantity;
}

public String getDiscount() {
    return discount;
}

public void setDiscount(String discount) {
    this.discount = discount;
}

public String getMax_price() {
    return max_price;
}

public void setMax_price(String max_price) {
    this.max_price = max_price;
}

public String getStore_name() {
    return store_name;
}

public void setStore_name(String store_name) {
    this.store_name = store_name;
}

public String getStoreUrl() {
    return StoreUrl;
}

public void setStoreUrl(String storeUrl) {
    StoreUrl = storeUrl;
}

public String getStoretitle() {
    return storetitle;
}

public void setStoretitle(String storetitle) {
    this.storetitle = storetitle;
}

public String getSeller_id() {
    return seller_id;
}

public void setSeller_id(String seller_id) {
    this.seller_id = seller_id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getImage() {
    return image;
}

public void setImage(String image) {
    this.image = image;
}

public String getEntity_id() {
    return entity_id;
}

public void setEntity_id(String entity_id) {
    this.entity_id = entity_id;
}

public String getDescription() {
    return description;
}

public void setDescription(String description) {
    this.description = description;
}

public float getPrice() {
    return price;
}

public void setPrice(float price) {
    this.price = price;
}

public float getSpecialPrice() {
    return specialprice;
}

public void setSpecialPrice(float specialprice) {
    this.specialprice = specialprice;
}

}

Data flow from TabActivity to fragment,

1.I have a TabActivity with ViewPager and Fragment.
2.In Fragment, I have a ListView.
3.The Data to fragment is passed from view pager adapter by set arguments.

Solutions I tried

1.A POJO class that implements Serialization.
2.I use Picasso to load the image from image URL.
3.This exception is thrown when OnItemClick on ListView in fragment passes data to DetailActivity to show all passed data.
4.I get this exception after the DetailActivity load's image and other data then app suddenly crashes.
5.I pass data in Intent was all POJO Object with Id, Name, Image URL, Price etc.,

Note:-
App Crash only in NOUGAT

Finally, The fix I implemented

changing the targetSdkVersion to 23 from 25

After changing, my application not crashing in Nougat too.

All I have to Know is this proper solution or is there any workaround.

Please Guide to the proper way.

Thanks in advance.

Fragment

public class ProdFragment extends Fragment {
ListView listview;
SharedPreferences spref;
Boolean isInternetPresent = false;
ConnectionDetector cd;

private String toBeDisplayed,CatID;
private static final String TAG = ProdFragment.class.getSimpleName();
String totalProductCart;
private ArrayList<Root_SubCatModel> subCatList;
private ArrayList<ProdModel> prodList;
ProdAdapter adapter;

public ProdFragment() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    spref = getActivity().getSharedPreferences(getResources().getString(R.string.myPref),
            Context.MODE_PRIVATE);
    Bundle bundle = getArguments();
    if (bundle != null) {
        int tabPosition = bundle.getInt("Tab_Position");
        toBeDisplayed = bundle.getString("Tab_ToBeDisplayed");
        CatID = bundle.getString("CategoryId");
        subCatList = (ArrayList<Root_SubCatModel>) bundle.getSerializable("Tab_Data");
    }
}

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

    cd = new ConnectionDetector(getActivity());
    listview = (ListView) rootView.findViewById(R.id.prodlist);
    if (subCatList != null) {
        adapter = new ProdAdapter(getActivity(),
                CatID,
                toBeDisplayed,
                R.layout.list_product,
                subCatList,
                (ProductCartCountListener)getActivity());
        listview.setAdapter(adapter);
        adapter.notifyDataSetChanged();

        prodList = new ArrayList<>();
        for(int i = 0; i<subCatList.size();i++){
            if (subCatList.get(i).getProd() != null) {
                if(toBeDisplayed.equals("SubCategory")){
                    if (CatID.equals(subCatList.get(i).getCategory_id())) {
                        this.prodList = subCatList.get(i).getProd();
                    }
                }else if(toBeDisplayed.equals("Products")) {
                    this.prodList = subCatList.get(i).getProd();
                }
            }
        }

    }

    listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {

            Bundle bundle = new Bundle();
            bundle.putSerializable("object", prodList.get(position));
            Intent intent = new Intent(getActivity(), DetailActivity.class);
            intent.putExtra("bundle", bundle);
            startActivityForResult(intent,1);
        }

    });

    return rootView;
}

public void showAlertDialog(Context context, String title, String message, Boolean status) {
    AlertDialog alertDialog = new AlertDialog.Builder(context).create();

    // Setting Dialog Title
    alertDialog.setTitle(title);

    // Setting Dialog Message
    alertDialog.setMessage(message);

    // Setting alert dialog icon
    //alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);

    // Setting OK Button
    alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
        }
    });

    // Showing Alert Message
    alertDialog.show();
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 1) {
        if (resultCode == Activity.RESULT_OK) {
            Bundle b = data.getExtras();
            if (b != null) {
                ProdModel myobj = (ProdModel) b.getSerializable("Cart_Quantity");
                if (myobj != null) {
                    if (prodList != null) {
                        for (ProdModel P : prodList) {
                            if (P.getEntity_id().equals(myobj.getEntity_id())) {
                                P.setProductNumQuantity(myobj.getProductNumQuantity());
                            }
                        }
                    }
                    Log.d(TAG,"Product_Id : " + myobj.getEntity_id()
                            + ", Product_Cart_Count : " + myobj.getProductNumQuantity());
                }
            }
        } else if (resultCode == 0) {
            Log.d(TAG,"RESULT CANCELLED");
        }
    }
    adapter.notifyDataSetChanged();
    String totalProductCart = spref.getString("Cart_Count_Tool", "0");
    Activity activity = getActivity();
    if(activity instanceof TabActivity){
        TabActivity myActivity = (TabActivity) activity;
        Toolbar toolbar = (Toolbar) myActivity.findViewById(R.id.back_toolbar);
        ImageView cart_imageview = (ImageView) toolbar.findViewById(R.id.cart_imageview);
        cart_imageview.setImageDrawable(myActivity.buildCounterDrawable(
                Integer.parseInt(totalProductCart)));
    }
    Log.d(TAG,"RESULT NOTIFIED");
}

public void refreshData(String productId, boolean isAddAsyncTaskComplete,
                        boolean isAddAsyncTaskLimitReached, boolean isDeleteAsyncTaskComplete){
    adapter.setQuantityCount(prodList, productId, isAddAsyncTaskComplete,
            isAddAsyncTaskLimitReached, isDeleteAsyncTaskComplete);

}

TabActivity Layout

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/storeimage"
        android:textAlignment="center"
        android:elevation="2dp"
        android:minHeight="?attr/actionBarSize"
        app:tabMode="scrollable"
        app:tabTextColor="@color/color_dark_blue"
        app:tabSelectedTextColor="@color/color_orange"/>
</android.support.design.widget.AppBarLayout>

<android.support.v4.view.ViewPager
    android:id="@+id/viewpager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />
 </android.support.design.widget.CoordinatorLayout>

ListView

<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ListView
    android:id="@+id/prodlist"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

</FrameLayout>

Body:
Your are passing too much data to your Fragment in setArguments(). Your Fragment will work, but when it tries to save its instance state it overflows the transaction buffer. This throws a RuntimeException if you target Android 7.0 (API 24 or higher). To preserve backwards compatibility and not break existing apps, the new behaviour is only used if you target API 24 or higher. If you target API < 24, the transaction buffer overflow exception is caught and silently ignored. This means that your data will not be persistently saved, which you may (or may not) notice.

Your code is broken. You should not pass large amounts of data to the Fragment in setArguments(). You can keep your data in your Activity. When the Fragment wants to access the data, it can always so something like this:

// Get the owning Activity
MyActivity activity = (MyActivity)getActivity();
// Get the data from the Activity
List<Data> data = activity.getData();

In your Activity, write a getData() method that returns a reference to whatever data the Fragment needs.

In this way, the data is held in the Activity and the Fragment can get access to it whenever it needs to.


问:
how to calculate the intersection area of two circles in shiny or R code
Anyone has shiny code or R code about how to calculate the intersection area of two circles?

UI

library(shiny)

# Define UI for application that draws a histogram
ui <- fluidPage(
   # Application title
   titlePanel("Choose your probability"),
   # Sidebar with a slider input for number of bins
   sidebarLayout(
      sidebarPanel(
         sliderInput("radius",
                     "Probability of A",
                     min = 0,
                     max = 0.4,
                     value = 0.2),
         sliderInput("radius2",
                     "Probability of B",
                     min = 0,
                     max = 0.4,
                     value = 0.2)
      ),
      mainPanel(
         plotOutput("distPlot")
      )
   )
)
```
<h1>Server</h1>
<pre class="lang-r prettyprint-override"><code>library(shiny)
library(plotrix)
library(grid)

# Define server logic required to draw a histogram
server <- function(input, output) {
   output$distPlot <- renderPlot({
      isolate({
         plot(c(-1,1),c(-1,1), type = 'n')
      })
      draw.circle(-0.25,0,input$radius)
      draw.circle(0.25,0,input$radius2)
   })
}

shinyApp(ui, server)
</code>```

答:
you can use this:</p>
```<code>circle_intersection <- function(x1, y1, r1, x2, y2, r2){
  rr1 <- r1 * r1
  rr2 <- r2 * r2
  d <- sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1))

  if (d > r2 + r1) # Circles do not overlap
  {
    return(0)
  } else if (d <= abs(r1 - r2) && r1 >= r2){ # Circle2 is completely inside circle1
    return(pi*rr2)
  } else if (d <= abs(r1 - r2) && r1 < r2){ # Circle1 is completely inside circle2
    return(pi*rr1)
  } else { # Circles partially overlap
    phi <- (acos((rr1 + (d * d) - rr2) / (2 * r1 * d))) * 2
    theta <- (acos((rr2 + (d * d) - rr1) / (2 * r2 * d))) * 2
    area2 <- 0.5 * theta * rr2 - 0.5 * rr2 * sin(theta)
    area1 <- 0.5 * phi * rr1 - 0.5 * rr1 * sin(phi)
    return(area1 + area2)
  }
}

circle_intersection(-0.25,0,0.2,0.25,0,0.2)  # 0 (Circles do not overlap)
circle_intersection(-0.25,0,0.2,-0.25,0,0.1) # 0.031 (Circle2 is completely inside circle1)
circle_intersection(-0.25,0,0.1,-0.25,0,0.2) # 0.031 (Circle1 is completely inside circle2)
circle_intersection(-0.25,0,0.3,0.25,0,0.4)  # 0.06641675 (Circles partially overlap)
</code>```

Body:
Anyone has shiny code or R code about how to calculate the intersection area of two circles?

UI

library(shiny)

# Define UI for application that draws a histogram
ui <- fluidPage(
   # Application title
   titlePanel("Choose your probability"),
   # Sidebar with a slider input for number of bins
   sidebarLayout(
      sidebarPanel(
         sliderInput("radius",
                     "Probability of A",
                     min = 0,
                     max = 0.4,
                     value = 0.2),
         sliderInput("radius2",
                     "Probability of B",
                     min = 0,
                     max = 0.4,
                     value = 0.2)
      ),
      mainPanel(
         plotOutput("distPlot")
      )
   )
)

Server

library(shiny)
library(plotrix)
library(grid)

# Define server logic required to draw a histogram
server <- function(input, output) {
   output$distPlot <- renderPlot({
      isolate({
         plot(c(-1,1),c(-1,1), type = 'n')
      })
      draw.circle(-0.25,0,input$radius)
      draw.circle(0.25,0,input$radius2)
   })
}

shinyApp(ui, server)

Body:
you can use this:

circle_intersection <- function(x1, y1, r1, x2, y2, r2){
  rr1 <- r1 * r1
  rr2 <- r2 * r2
  d <- sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1))

  if (d > r2 + r1) # Circles do not overlap
  {
    return(0)
  } else if (d <= abs(r1 - r2) && r1 >= r2){ # Circle2 is completely inside circle1
    return(pi*rr2)
  } else if (d <= abs(r1 - r2) && r1 < r2){ # Circle1 is completely inside circle2
    return(pi*rr1)
  } else { # Circles partially overlap
    phi <- (acos((rr1 + (d * d) - rr2) / (2 * r1 * d))) * 2
    theta <- (acos((rr2 + (d * d) - rr1) / (2 * r2 * d))) * 2
    area2 <- 0.5 * theta * rr2 - 0.5 * rr2 * sin(theta)
    area1 <- 0.5 * phi * rr1 - 0.5 * rr1 * sin(phi)
    return(area1 + area2)
  }
}

circle_intersection(-0.25,0,0.2,0.25,0,0.2)  # 0 (Circles do not overlap)
circle_intersection(-0.25,0,0.2,-0.25,0,0.1) # 0.031 (Circle2 is completely inside circle1)
circle_intersection(-0.25,0,0.1,-0.25,0,0.2) # 0.031 (Circle1 is completely inside circle2)
circle_intersection(-0.25,0,0.3,0.25,0,0.4)  # 0.06641675 (Circles partially overlap)


问:
OnClick: Passing String as Parameter
I would like to pass a string as a parameter of the following:

How would I make "hello" become a parameter. The integers pass without problem.

Thank you.

答:
The content of the onclick property is handled as Javascript

```<code><div onclick="HERE IS JAVASCRIPT"></div>
</code>```

So you should use 'hello' while you are using double quote for onclick property,

or "hello" else using single quote.

Should either use one of it to represent that hello is a string, not a variable name.

Title: OnClick: Passing String as Parameter

Body:
The content of the onclick property is handled as Javascript

<div onclick="HERE IS JAVASCRIPT"></div>

So you should use 'hello' while you are using double quote for onclick property,

or "hello" else using single quote.

Should either use one of it to represent that hello is a string, not a variable name.


问:
Problems with setState Handlers in React
I'm simply trying to change the state of my component via handlers in react, but at the moment of executing the functions the state doesnt change. Here you have the handlers, the state, setStates and the components which I send the handlers as properties

BTW: I'm using webpack with babel loader

```<code>export default class Game extends React.Component{
constructor(){
    super()
    this.state={
        pause: null
    }

}
PauseShow(){
    this.setState={ pause: "block" }
    console.log("pauseshow")
}
PauseHide(){
    this.setState={ pause: "none" }
    console.log("pausehide")
}
render(){

    return(
        <div className="big-box">
            <Player idc="Game" src="assets/Fly_Me_to_the_Aegis_Seven_Moon.mp3"/>
            <GameOutput/>
            <GameData pauseMethod={this.PauseShow.bind(this)}/>
            <GameInput />
            <GamePause display={this.state.pause} pauseMethod={this.PauseHide.bind(this)}/>

        </div>
    )
}
</code>```

}
Aquí llamo al un handler que pasé por props

```<code>export default class GameData extends React.Component{
constructor(){
    super()
}
render(){
    return(
        <div id="GameData">
            <button onClick={this.props.pauseMethod}>pause</button>
        </div>

    )
}
</code>```

}
Here we have the error showed at console when clicking on a button that makes the handler execute

backend.js:8730 Uncaught TypeError: inst.setState.bind is not a function at getData (chrome-extension://fmkadmapgofadopljbjfkapdkoienihi/build/backend.js:8730:49) at walkNode (chrome-extension://fmkadmapgofadopljbjfkapdkoienihi/build/backend.js:8576:57) at chrome-extension://fmkadmapgofadopljbjfkapdkoienihi/build/backend.js:8579:15 at Array.forEach (native) at walkNode (chrome-extension://fmkadmapgofadopljbjfkapdkoienihi/build/backend.js:8578:20) at chrome-extension://fmkadmapgofadopljbjfkapdkoienihi/build/backend.js:8579:15 at Array.forEach (native) at walkNode (chrome-extension://fmkadmapgofadopljbjfkapdkoienihi/build/backend.js:8578:20) at chrome-extension://fmkadmapgofadopljbjfkapdkoienihi/build/backend.js:8579:15 at Array.forEach (native)

答:
You can't update your state as this.setState{pause: "block"}. Your state is an function and you need to pass it an object as parameter. Thus:

```<code>this.setState({pause: "block"})
</code>```

is the right way to update your state.

See this code:

```<code>class Test extends React.Component {
  constructor(){
      super();
      this.state = {
        text: ""
      }
  }
  pauseMethod(){
      this.setState({text: "paused"}, () => console.log(this.state.text))
  }

  render(){
    return (
        <div><GameData pauseMethod={this.pauseMethod.bind(this)} /></div>
      )
  }
}

class GameData extends React.Component{
  render(){
      return(
          <div id="GameData">
              <button onClick={this.props.pauseMethod}>pause</button>
          </div>
      )
  }
}

React.render(<Test />, document.getElementById('container'));
</code>```

Here is the fiddle.

Body:
I'm simply trying to change the state of my component via handlers in react, but at the moment of executing the functions the state doesnt change. Here you have the handlers, the state, setStates and the components which I send the handlers as properties

BTW: I'm using webpack with babel loader

export default class Game extends React.Component{
constructor(){
    super()
    this.state={
        pause: null
    }

}
PauseShow(){
    this.setState={ pause: "block" }
    console.log("pauseshow")
}
PauseHide(){
    this.setState={ pause: "none" }
    console.log("pausehide")
}
render(){

    return(

            <Player idc="Game" src="assets/Fly_Me_to_the_Aegis_Seven_Moon.mp3"/>
            <GameOutput/>
            <GameData pauseMethod={this.PauseShow.bind(this)}/>
            <GameInput />
            <GamePause display={this.state.pause} pauseMethod={this.PauseHide.bind(this)}/>

    )
}

}
Aquí llamo al un handler que pasé por props

export default class GameData extends React.Component{
constructor(){
    super()
}
render(){
    return(

            <button onClick={this.props.pauseMethod}>pause</button>

    )
}

}
Here we have the error showed at console when clicking on a button that makes the handler execute

backend.js:8730 Uncaught TypeError: inst.setState.bind is not a function at getData (chrome-extension://fmkadmapgofadopljbjfkapdkoienihi/build/backend.js:8730:49) at walkNode (chrome-extension://fmkadmapgofadopljbjfkapdkoienihi/build/backend.js:8576:57) at chrome-extension://fmkadmapgofadopljbjfkapdkoienihi/build/backend.js:8579:15 at Array.forEach (native) at walkNode (chrome-extension://fmkadmapgofadopljbjfkapdkoienihi/build/backend.js:8578:20) at chrome-extension://fmkadmapgofadopljbjfkapdkoienihi/build/backend.js:8579:15 at Array.forEach (native) at walkNode (chrome-extension://fmkadmapgofadopljbjfkapdkoienihi/build/backend.js:8578:20) at chrome-extension://fmkadmapgofadopljbjfkapdkoienihi/build/backend.js:8579:15 at Array.forEach (native)

Body:
You can't update your state as this.setState{pause: "block"}. Your state is an function and you need to pass it an object as parameter. Thus:

this.setState({pause: "block"})

is the right way to update your state.

See this code:

class Test extends React.Component {
  constructor(){
      super();
      this.state = {
        text: ""
      }
  }
  pauseMethod(){
      this.setState({text: "paused"}, () => console.log(this.state.text))
  }

  render(){
    return (
        <div><GameData pauseMethod={this.pauseMethod.bind(this)} /></div>
      )
  }
}

class GameData extends React.Component{
  render(){
      return(
          <div id="GameData">
              <button onClick={this.props.pauseMethod}>pause</button>
          </div>
      )
  }
}

React.render(<Test />, document.getElementById('container'));

Here is the fiddle.


问:
Can we print error message before form begin in mvc?
can we print error message before form start, I am using mvc v4

this is my controller action code
          [HttpGet]

```<code>        public ActionResult ChangePassword(string aToken)
        {
          aToken = Server.UrlDecode(aToken);

          if (aToken != null)
          {
           .........
           }
          else
          {
      ViewBag.Error = "Sorry, this link is not being recognized as valid.
          }

    return view();`enter code here`
        }
</code>```

this is my cshtml file

```<code>    @if (ViewBag.Error != null)

    {
      <p class="text-danger">
        @ViewBag.Error
      </p>
    }
    else
    {
      using (Html.BeginForm("ChangePassword", "Account", FormMethod.Post, new {
     @class = "form-horizontal ", role = "form" }))
      {

         ........................
      }

    }`enter code here`
</code>```

technicality, is this correct?

答: Is this solves the problem? Yes. However, it would be more secure just to Redirect user to another page with static text instead. Also, you can use ModelState but it will create problems on post actions.

Body:
can we print error message before form start, I am using mvc v4

this is my controller action code
          [HttpGet]

        public ActionResult ChangePassword(string aToken)
        {
          aToken = Server.UrlDecode(aToken);

          if (aToken != null)
          {
           .........
           }
          else
          {
      ViewBag.Error = "Sorry, this link is not being recognized as valid.
          }

    return view();`enter code here`
        }

this is my cshtml file

    @if (ViewBag.Error != null)

    {

        @ViewBag.Error

    }
    else
    {
      using (Html.BeginForm("ChangePassword", "Account", FormMethod.Post, new {
     @class = "form-horizontal ", role = "form" }))
      {

         ........................
      }

    }`enter code here`

technicality, is this correct?


问:
How to remove all line breaks from a string
I have a text in a textarea and I read it out using the .value attribute.

Now I would like to remove all linebreaks (the character that is produced when you press Enter) from my text now using .replace with a regular expression, but how do I indicate a linebreak in a regex?

If that is not possible, is there another way?

答:
The answer provided by PointedEars is everything most of us need. But by following  Mathias Bynens's answer, I went on a Wikipedia trip and found this: https://en.wikipedia.org/wiki/Newline.

The following is a drop-in function that implements everything the above Wiki page considers "new line" at the time of this answer.

If something doesn't fit your case, just remove it. Also, if you're looking for performance this might not be it, but for a quick tool that does the job in any case, this should be useful.

```<code>// replaces all "new line" characters contained in `someString` with the given `replacementString`
const replaceNewLineChars = ((someString, replacementString = ``) => { // defaults to just removing
  const LF = `\u{000a}`; // Line Feed (\n)
  const VT = `\u{000b}`; // Vertical Tab
  const FF = `\u{000c}`; // Form Feed
  const CR = `\u{000d}`; // Carriage Return (\r)
  const CRLF = `${CR}${LF}`; // (\r\n)
  const NEL = `\u{0085}`; // Next Line
  const LS = `\u{2028}`; // Line Separator
  const PS = `\u{2029}`; // Paragraph Separator
  const lineTerminators = [LF, VT, FF, CR, CRLF, NEL, LS, PS]; // all Unicode `lineTerminators`
  let finalString = someString.normalize(`NFD`); // better safe than sorry? Or is it?
  for (let lineTerminator of lineTerminators) {
    if (finalString.includes(lineTerminator)) { // check if the string contains the current `lineTerminator`
      let regex = new RegExp(lineTerminator.normalize(`NFD`), `gu`); // create the `regex` for the current `lineTerminator`
      finalString = finalString.replace(regex, replacementString); // perform the replacement
    };
  };
  return finalString.normalize(`NFC`); // return the `finalString` (without any Unicode `lineTerminators`)
});
</code>```

Body:
The answer provided by PointedEars is everything most of us need. But by following  Mathias Bynens's answer, I went on a Wikipedia trip and found this: https://en.wikipedia.org/wiki/Newline.

The following is a drop-in function that implements everything the above Wiki page considers "new line" at the time of this answer.

If something doesn't fit your case, just remove it. Also, if you're looking for performance this might not be it, but for a quick tool that does the job in any case, this should be useful.

// replaces all "new line" characters contained in `someString` with the given `replacementString`
const replaceNewLineChars = ((someString, replacementString = ``) => { // defaults to just removing
  const LF = `\u{000a}`; // Line Feed (\n)
  const VT = `\u{000b}`; // Vertical Tab
  const FF = `\u{000c}`; // Form Feed
  const CR = `\u{000d}`; // Carriage Return (\r)
  const CRLF = `${CR}${LF}`; // (\r\n)
  const NEL = `\u{0085}`; // Next Line
  const LS = `\u{2028}`; // Line Separator
  const PS = `\u{2029}`; // Paragraph Separator
  const lineTerminators = [LF, VT, FF, CR, CRLF, NEL, LS, PS]; // all Unicode `lineTerminators`
  let finalString = someString.normalize(`NFD`); // better safe than sorry? Or is it?
  for (let lineTerminator of lineTerminators) {
    if (finalString.includes(lineTerminator)) { // check if the string contains the current `lineTerminator`
      let regex = new RegExp(lineTerminator.normalize(`NFD`), `gu`); // create the `regex` for the current `lineTerminator`
      finalString = finalString.replace(regex, replacementString); // perform the replacement
    };
  };
  return finalString.normalize(`NFC`); // return the `finalString` (without any Unicode `lineTerminators`)
});


问:
How do I convert flac to wav on iOS?
I have a file which is encoded with FLAC and I want to convert it to WAV.

I have added this FFMpeg lib to my project and imported it.

I see some code from this answer, but I am unclear on how to use it:

```<code>#import "avformat.h"

// Some code goes here

/*
 *   avformat_open_input(AVFormatContext **ps, const char *filename, AVInputFormat *fmt, AVDictionary **options)
 */
int openInputValue = avformat_open_input(&pFormatCtx, utf8FilePath, inputFormat, nil);
NSLog(@"%s - %d # openInputValue = %d", __PRETTY_FUNCTION__, __LINE__, openInputValue);
</code>```

I currently have this code in a function which takes NSData holding the FLAC file. If avformat_open_input is the correct call, how do I set the variable? If it is not the correct call, what is?

This question seems like a duplicate but it doesn't really have a good answer.

Also note that I don't want a player. This file contains MQA so I need to run it through my own custom decoder.

答:
I was able to implement this using this code for decoding and this code to actually write the WAV header/body.

As an added bonus, this was very helpful in decoding NSData instead of a file.

Here is my finished decoder, though I wouldn't expect it to work in any case except mine.

```<code>//
//  FlacToWavConverter.m
//  SuperpoweredMQAExample
//
//  Created by Tony Lawrence on 5/18/17.
//  Copyright © 2017 imect. All rights reserved.
//

#import "FlacToWavConverter.h"
#import "avformat.h"
#import "avcodec.h"
#import "avutil.h"
#import "swresample.h"
#import "file.h"

@implementation FlacToWavConverter

+(NSURL*)convertFlacToWav:(NSData*)data {

    //const char* input_filename = [filePath UTF8String];
    int buffer_size = 16384;

    // This call is necessarily done once in your app to initialize
    // libavformat to register all the muxers, demuxers and protocols.
    av_register_all();

    // A media container
    AVFormatContext* container = avformat_alloc_context();

    //Make a custom IO context so that we can read from memory instead of a file...
    unsigned char* iobuffer = av_malloc(buffer_size);
    struct buffer_data bd = { 0 };
    bd.ptr = (uint8_t*)data.bytes;
    bd.size = data.length;
    AVIOContext* ioContext = avio_alloc_context(iobuffer, buffer_size, 0, &bd, &read_packet, NULL, NULL);

    container->pb = ioContext;

    if (avformat_open_input(&container, "arbitrary", NULL, NULL) < 0) {
        NSLog(@"Could not open file");
    }

    if (avformat_find_stream_info(container, NULL) < 0) {
        NSLog(@"Could not find file info");
    }

    int stream_id = -1;

    // To find the first audio stream. This process may not be necessary
    // if you can gurarantee that the container contains only the desired
    // audio stream
    int i;
    for (i = 0; i < container->nb_streams; i++) {
        if (container->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
            stream_id = i;
            break;
        }
    }

    if (stream_id == -1) {
        NSLog(@"Could not find an audio stream");
    }

    // Extract some metadata
    AVDictionary* metadata = container->metadata;

    // Find the apropriate codec and open it
    AVCodecContext* codec_context = container->streams[stream_id]->codec;

    AVCodec* codec = avcodec_find_decoder(codec_context->codec_id);

    if (avcodec_open2(codec_context, codec, NULL) < 0) {
        NSLog(@"Could not find open the needed codec");
    }

    NSMutableData *pcmFile = [NSMutableData new];

    AVPacket packet;
    int8_t buffer[buffer_size];

    while (1) {

        //buffer_size = AVCODEC_MAX_AUDIO_FRAME_SIZE;

        // Read one packet into `packet`
        if (av_read_frame(container, &packet) < 0) {
            break;  // End of stream. Done decoding.
        }

        // Decodes from `packet` into the buffer
        if (avcodec_decode_audio3(codec_context, (int16_t*)buffer, &buffer_size, &packet) < 1) {
            break;  // Error in decoding
        }

        // Send the buffer contents to the audio device
        [pcmFile appendBytes:buffer length:buffer_size];

    }

    avformat_close_input(&container);

    //fprintf(stdout, "Done playing. Exiting...");

    NSURL *file = [FlacToWavConverter getAndCreatePlayableFileFromPcmData:pcmFile];

    NSLog(@"Got a playable file maybe? %@", [file absoluteString]);

    return file;
}

+(NSURL *) getAndCreatePlayableFileFromPcmData:(NSData *)data
{
    NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docsDir = [dirPaths objectAtIndex:0];
    NSString *wavFilePath = [docsDir stringByAppendingPathComponent:@"output.wav"];

    //NSLog(@"PCM data : %@",data);

    FILE *fout;

    short NumChannels = 2;
    short BitsPerSample = 16;
    int SamplingRate = 44100;
    int numOfSamples = [data length];

    int ByteRate = NumChannels*BitsPerSample*SamplingRate/8;
    short BlockAlign = NumChannels*BitsPerSample/8;
    int DataSize = NumChannels*numOfSamples*BitsPerSample/8;
    int chunkSize = 16;
    int totalSize = 46 + DataSize;
    short audioFormat = 1;

    if((fout = fopen([wavFilePath cStringUsingEncoding:1], "w")) == NULL)
    {
        printf("Error opening out file ");
    }

    fwrite("RIFF", sizeof(char), 4,fout);
    fwrite(&totalSize, sizeof(int), 1, fout);
    fwrite("WAVE", sizeof(char), 4, fout);
    fwrite("fmt ", sizeof(char), 4, fout);
    fwrite(&chunkSize, sizeof(int),1,fout);
    fwrite(&audioFormat, sizeof(short), 1, fout);
    fwrite(&NumChannels, sizeof(short),1,fout);
    fwrite(&SamplingRate, sizeof(int), 1, fout);
    fwrite(&ByteRate, sizeof(int), 1, fout);
    fwrite(&BlockAlign, sizeof(short), 1, fout);
    fwrite(&BitsPerSample, sizeof(short), 1, fout);
    fwrite("data", sizeof(char), 4, fout);
    fwrite(&DataSize, sizeof(int), 1, fout);

    fclose(fout);

    NSMutableData *pamdata = [NSMutableData dataWithData:data];
    NSFileHandle *handle;
    handle = [NSFileHandle fileHandleForUpdatingAtPath:wavFilePath];
    [handle seekToEndOfFile];
    [handle writeData:pamdata];
    [handle closeFile];

    NSLog(@"Saved wav: %@", wavFilePath);

    return [NSURL URLWithString:wavFilePath];
}

struct buffer_data {
    uint8_t *ptr;
    size_t size; ///< size left in the buffer
};

static int read_packet(void *opaque, uint8_t *buf, int buf_size)
{
    struct buffer_data *bd = (struct buffer_data *)opaque;
    buf_size = FFMIN(buf_size, bd->size);
    //printf("ptr:%p size:%zu\n", bd->ptr, bd->size);
    /* copy internal buffer data to buf */
    memcpy(buf, bd->ptr, buf_size);
    bd->ptr  += buf_size;
    bd->size -= buf_size;
    return buf_size;
}

@end
</code>```

Title: How do I convert flac to wav on iOS?

Body:
I have a file which is encoded with FLAC and I want to convert it to WAV.

I have added this FFMpeg lib to my project and imported it.

I see some code from this answer, but I am unclear on how to use it:

#import "avformat.h"

// Some code goes here

/*
 *   avformat_open_input(AVFormatContext **ps, const char *filename, AVInputFormat *fmt, AVDictionary **options)
 */
int openInputValue = avformat_open_input(&pFormatCtx, utf8FilePath, inputFormat, nil);
NSLog(@"%s - %d # openInputValue = %d", __PRETTY_FUNCTION__, __LINE__, openInputValue);

I currently have this code in a function which takes NSData holding the FLAC file. If avformat_open_input is the correct call, how do I set the variable? If it is not the correct call, what is?

This question seems like a duplicate but it doesn't really have a good answer.

Also note that I don't want a player. This file contains MQA so I need to run it through my own custom decoder.

Body:
I was able to implement this using this code for decoding and this code to actually write the WAV header/body.

As an added bonus, this was very helpful in decoding NSData instead of a file.

Here is my finished decoder, though I wouldn't expect it to work in any case except mine.

//
//  FlacToWavConverter.m
//  SuperpoweredMQAExample
//
//  Created by Tony Lawrence on 5/18/17.
//  Copyright © 2017 imect. All rights reserved.
//

#import "FlacToWavConverter.h"
#import "avformat.h"
#import "avcodec.h"
#import "avutil.h"
#import "swresample.h"
#import "file.h"

@implementation FlacToWavConverter

+(NSURL*)convertFlacToWav:(NSData*)data {

    //const char* input_filename = [filePath UTF8String];
    int buffer_size = 16384;

    // This call is necessarily done once in your app to initialize
    // libavformat to register all the muxers, demuxers and protocols.
    av_register_all();

    // A media container
    AVFormatContext* container = avformat_alloc_context();

    //Make a custom IO context so that we can read from memory instead of a file...
    unsigned char* iobuffer = av_malloc(buffer_size);
    struct buffer_data bd = { 0 };
    bd.ptr = (uint8_t*)data.bytes;
    bd.size = data.length;
    AVIOContext* ioContext = avio_alloc_context(iobuffer, buffer_size, 0, &bd, &read_packet, NULL, NULL);

    container->pb = ioContext;

    if (avformat_open_input(&container, "arbitrary", NULL, NULL) < 0) {
        NSLog(@"Could not open file");
    }

    if (avformat_find_stream_info(container, NULL) < 0) {
        NSLog(@"Could not find file info");
    }

    int stream_id = -1;

    // To find the first audio stream. This process may not be necessary
    // if you can gurarantee that the container contains only the desired
    // audio stream
    int i;
    for (i = 0; i < container->nb_streams; i++) {
        if (container->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
            stream_id = i;
            break;
        }
    }

    if (stream_id == -1) {
        NSLog(@"Could not find an audio stream");
    }

    // Extract some metadata
    AVDictionary* metadata = container->metadata;

    // Find the apropriate codec and open it
    AVCodecContext* codec_context = container->streams[stream_id]->codec;

    AVCodec* codec = avcodec_find_decoder(codec_context->codec_id);

    if (avcodec_open2(codec_context, codec, NULL) < 0) {
        NSLog(@"Could not find open the needed codec");
    }

    NSMutableData *pcmFile = [NSMutableData new];

    AVPacket packet;
    int8_t buffer[buffer_size];

    while (1) {

        //buffer_size = AVCODEC_MAX_AUDIO_FRAME_SIZE;

        // Read one packet into `packet`
        if (av_read_frame(container, &packet) < 0) {
            break;  // End of stream. Done decoding.
        }

        // Decodes from `packet` into the buffer
        if (avcodec_decode_audio3(codec_context, (int16_t*)buffer, &buffer_size, &packet) < 1) {
            break;  // Error in decoding
        }

        // Send the buffer contents to the audio device
        [pcmFile appendBytes:buffer length:buffer_size];

    }

    avformat_close_input(&container);

    //fprintf(stdout, "Done playing. Exiting...");

    NSURL *file = [FlacToWavConverter getAndCreatePlayableFileFromPcmData:pcmFile];

    NSLog(@"Got a playable file maybe? %@", [file absoluteString]);

    return file;
}

+(NSURL *) getAndCreatePlayableFileFromPcmData:(NSData *)data
{
    NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docsDir = [dirPaths objectAtIndex:0];
    NSString *wavFilePath = [docsDir stringByAppendingPathComponent:@"output.wav"];

    //NSLog(@"PCM data : %@",data);

    FILE *fout;

    short NumChannels = 2;
    short BitsPerSample = 16;
    int SamplingRate = 44100;
    int numOfSamples = [data length];

    int ByteRate = NumChannels*BitsPerSample*SamplingRate/8;
    short BlockAlign = NumChannels*BitsPerSample/8;
    int DataSize = NumChannels*numOfSamples*BitsPerSample/8;
    int chunkSize = 16;
    int totalSize = 46 + DataSize;
    short audioFormat = 1;

    if((fout = fopen([wavFilePath cStringUsingEncoding:1], "w")) == NULL)
    {
        printf("Error opening out file ");
    }

    fwrite("RIFF", sizeof(char), 4,fout);
    fwrite(&totalSize, sizeof(int), 1, fout);
    fwrite("WAVE", sizeof(char), 4, fout);
    fwrite("fmt ", sizeof(char), 4, fout);
    fwrite(&chunkSize, sizeof(int),1,fout);
    fwrite(&audioFormat, sizeof(short), 1, fout);
    fwrite(&NumChannels, sizeof(short),1,fout);
    fwrite(&SamplingRate, sizeof(int), 1, fout);
    fwrite(&ByteRate, sizeof(int), 1, fout);
    fwrite(&BlockAlign, sizeof(short), 1, fout);
    fwrite(&BitsPerSample, sizeof(short), 1, fout);
    fwrite("data", sizeof(char), 4, fout);
    fwrite(&DataSize, sizeof(int), 1, fout);

    fclose(fout);

    NSMutableData *pamdata = [NSMutableData dataWithData:data];
    NSFileHandle *handle;
    handle = [NSFileHandle fileHandleForUpdatingAtPath:wavFilePath];
    [handle seekToEndOfFile];
    [handle writeData:pamdata];
    [handle closeFile];

    NSLog(@"Saved wav: %@", wavFilePath);

    return [NSURL URLWithString:wavFilePath];
}

struct buffer_data {
    uint8_t *ptr;
    size_t size; ///< size left in the buffer
};

static int read_packet(void *opaque, uint8_t *buf, int buf_size)
{
    struct buffer_data *bd = (struct buffer_data *)opaque;
    buf_size = FFMIN(buf_size, bd->size);
    //printf("ptr:%p size:%zu\n", bd->ptr, bd->size);
    /* copy internal buffer data to buf */
    memcpy(buf, bd->ptr, buf_size);
    bd->ptr  += buf_size;
    bd->size -= buf_size;
    return buf_size;
}

@end