问:
Optimising code with a lot of "if" statements
I want to optimise this code to reduce the number of if statements. Maybe it'd be better to use a lot of classes, and let the classes handle each required action?

It could be fabric pattern? Or is it OK to use 30+ similar if statements?

I've tried to make a Dictionary with string and object class. But I couldn't get it to work (or my skills are not good enough)

```<code>if (node[DATA_CONNECTION_ELEMENT] != null)
{
    return new DataConnectionPropertyDataBinding(form, node[DATA_CONNECTION_ELEMENT], inputableEntity);
}
else if (node[FORM_PARAMETER_ELEMENT] != null)
{
    return new FormParameterDataBinding(form, node[FORM_PARAMETER_ELEMENT], inputableEntity);
}

// + 30 more else ifs

else if (node[COMMAND_ELEMENT] != null)
{
    return new CommandResultDataBinding(form, node[COMMAND_ELEMENT], inputableEntity);
}
else if (node[CONDITION_ELEMENT] != null)
{
    return new ConditionDataBinding(form, node[CONDITION_ELEMENT], inputableEntity);
}
else if (node[CLIPBOARD_ELEMENT] != null)
{
    return new ClipboardDataBinding(form, node[CLIPBOARD_ELEMENT], inputableEntity);
}
else
{
    return new ConstantDataBinding(form, node);
}
</code>```

Want to make it look something like

```<code>foreach (var item in allThatShareSomeInterface)
{
    if (item.CanHandle(node.Atributes[0]))
    {
        return item.neededObject();
    }
}
</code>```

Here is the answer. How it really works.

```<code>        Dictionary<string, Type> allObjects = new Dictionary<string, Type>();
        allObjects.Add(CONDITION_ELEMENT, typeof(ConditionDataBinding));
        allObjects.Add(DATA_TYPE_FORMAT_ELEMENT, typeof(DataTypeFormatDataBinding));
        allObjects.Add(DATA_TYPE_CONVERT_ELEMENT, typeof(DataTypeConvertDataBinding));
        allObjects.Add(FORM_PARAMETER_ELEMENT, typeof(FormParameterDataBinding));
        allObjects.Add(FORM_ELEMENT, typeof(FormPropertyDataBinding));
        allObjects.Add(STRING_ELEMENT, typeof(StringFormatDataBinding));
        allObjects.Add(FORMULA_ELEMENT, typeof(FormulaDataBinding));
        allObjects.Add(COMMAND_ELEMENT, typeof(CommandResultDataBinding));
        // + many

        foreach (var pair in allObjects)
        {
            if (node[pair.Key] != null)
            {
                ConstructorInfo ctor = pair.Value.GetConstructor(new[] { typeof(IWorkflowForm), typeof(XmlNode), typeof(IInputable) });
                return ctor.Invoke(new object[] { form, node[pair.Key], inputableEntity });
            }
        }
</code>```

答:
You may be able to make this work using reflection. It's probably going to make your code a bit slower though.
It should look something like this (not tested):</p>

```<code>    var pairs = new Dictionary<string, Type>()
    {
        {
            DATA_CONNECTION_ELEMENT, typeof(DataConnectionPropertyDataBinding)
        },
        {
            FORM_PARAMETER_ELEMENT, typeof(FormParameterDataBinding)
        }
    };

    foreach (var pair in pairs)
    {
        if (node[pair.Key] != null)
        {
            ConstructorInfo ctor = pair.Value.GetConstructor(new[] { typeof(object), typeof(object), typeof(object) });
            return ctor.Invoke(new object[] { form, node[pair.Key], inputableEntity });
        }
    }
</code>```

Body:
I want to optimise this code to reduce the number of if statements. Maybe it'd be better to use a lot of classes, and let the classes handle each required action?

It could be fabric pattern? Or is it OK to use 30+ similar if statements?

I've tried to make a Dictionary with string and object class. But I couldn't get it to work (or my skills are not good enough)

if (node[DATA_CONNECTION_ELEMENT] != null)
{
    return new DataConnectionPropertyDataBinding(form, node[DATA_CONNECTION_ELEMENT], inputableEntity);
}
else if (node[FORM_PARAMETER_ELEMENT] != null)
{
    return new FormParameterDataBinding(form, node[FORM_PARAMETER_ELEMENT], inputableEntity);
}

// + 30 more else ifs

else if (node[COMMAND_ELEMENT] != null)
{
    return new CommandResultDataBinding(form, node[COMMAND_ELEMENT], inputableEntity);
}
else if (node[CONDITION_ELEMENT] != null)
{
    return new ConditionDataBinding(form, node[CONDITION_ELEMENT], inputableEntity);
}
else if (node[CLIPBOARD_ELEMENT] != null)
{
    return new ClipboardDataBinding(form, node[CLIPBOARD_ELEMENT], inputableEntity);
}
else
{
    return new ConstantDataBinding(form, node);
}

Want to make it look something like

foreach (var item in allThatShareSomeInterface)
{
    if (item.CanHandle(node.Atributes[0]))
    {
        return item.neededObject();
    }
}

Here is the answer. How it really works.

        Dictionary<string, Type> allObjects = new Dictionary<string, Type>();
        allObjects.Add(CONDITION_ELEMENT, typeof(ConditionDataBinding));
        allObjects.Add(DATA_TYPE_FORMAT_ELEMENT, typeof(DataTypeFormatDataBinding));
        allObjects.Add(DATA_TYPE_CONVERT_ELEMENT, typeof(DataTypeConvertDataBinding));
        allObjects.Add(FORM_PARAMETER_ELEMENT, typeof(FormParameterDataBinding));
        allObjects.Add(FORM_ELEMENT, typeof(FormPropertyDataBinding));
        allObjects.Add(STRING_ELEMENT, typeof(StringFormatDataBinding));
        allObjects.Add(FORMULA_ELEMENT, typeof(FormulaDataBinding));
        allObjects.Add(COMMAND_ELEMENT, typeof(CommandResultDataBinding));
        // + many

        foreach (var pair in allObjects)
        {
            if (node[pair.Key] != null)
            {
                ConstructorInfo ctor = pair.Value.GetConstructor(new[] { typeof(IWorkflowForm), typeof(XmlNode), typeof(IInputable) });
                return ctor.Invoke(new object[] { form, node[pair.Key], inputableEntity });
            }
        }

Body:
You may be able to make this work using reflection. It's probably going to make your code a bit slower though.
It should look something like this (not tested):

    var pairs = new Dictionary<string, Type>()
    {
        {
            DATA_CONNECTION_ELEMENT, typeof(DataConnectionPropertyDataBinding)
        },
        {
            FORM_PARAMETER_ELEMENT, typeof(FormParameterDataBinding)
        }
    };

    foreach (var pair in pairs)
    {
        if (node[pair.Key] != null)
        {
            ConstructorInfo ctor = pair.Value.GetConstructor(new[] { typeof(object), typeof(object), typeof(object) });
            return ctor.Invoke(new object[] { form, node[pair.Key], inputableEntity });
        }
    }


来源: stackexchange

问:
line fading while hovering on synchronized chart in highchart
I am having a synchronized highchart with two different containers. I have used a script to synchronize the charts. Synchronization works perfectly. My first chart is having 3 lines and second chart is having only 1 line.

When I hover the first chart, the third line fading out. When I
  disable the script for synchronisation it works fine.

This is my script for synchronisation.

```<code>$('#container, #container2').bind('mousemove touchmove touchstart', function(e) {
        var chart,
        points,
        i,
        secSeriesIndex = 1;

        for (i = 0; i < Highcharts.charts.length; i++) {
            chart = Highcharts.charts[i];
            e = chart.pointer.normalize(e); // Find coordinates within the chart
            points = [chart.series[0].searchPoint(e, true), chart.series[1].searchPoint(e, true)]; // Get the hovered point

            if (points[0] && points[1]) {
                if (!points[0].series.visible) {
                    points.shift();
                    secSeriesIndex = 0;
                }
                if (!points[secSeriesIndex].series.visible) {
                    points.splice(secSeriesIndex,1);
                }
                if (points.length) {
                    chart.tooltip.refresh(points); // Show the tooltip
                    chart.xAxis[0].drawCrosshair(e, points[0]); // Show the crosshair
                }
            }
        }
  });
</code>```

This is the jsfiddle link for the same.

Can any one please help me with this?

答:
You need to add all of the hovered points to the points array, not only the first two:

```<code>for (i = 0; i < Highcharts.charts.length; i++) {
    chart = Highcharts.charts[i];
    e = chart.pointer.normalize(e); // Find coordinates within the chart
    points = [];

    chart.series.forEach(function(s) {
        points.push(s.searchPoint(e, true));
    });

    ...
}
</code>```

Live demo: https://jsfiddle.net/BlackLabel/goxm5q3e/

ContentLicense: CC BY-SA 4.0

Body:
I am having a synchronized highchart with two different containers. I have used a script to synchronize the charts. Synchronization works perfectly. My first chart is having 3 lines and second chart is having only 1 line.

When I hover the first chart, the third line fading out. When I
  disable the script for synchronisation it works fine.

This is my script for synchronisation.

$('#container, #container2').bind('mousemove touchmove touchstart', function(e) {
        var chart,
        points,
        i,
        secSeriesIndex = 1;

        for (i = 0; i < Highcharts.charts.length; i++) {
            chart = Highcharts.charts[i];
            e = chart.pointer.normalize(e); // Find coordinates within the chart
            points = [chart.series[0].searchPoint(e, true), chart.series[1].searchPoint(e, true)]; // Get the hovered point

            if (points[0] && points[1]) {
                if (!points[0].series.visible) {
                    points.shift();
                    secSeriesIndex = 0;
                }
                if (!points[secSeriesIndex].series.visible) {
                    points.splice(secSeriesIndex,1);
                }
                if (points.length) {
                    chart.tooltip.refresh(points); // Show the tooltip
                    chart.xAxis[0].drawCrosshair(e, points[0]); // Show the crosshair
                }
            }
        }
  });

This is the jsfiddle link for the same.

Can any one please help me with this?

Body:
You need to add all of the hovered points to the points array, not only the first two:

for (i = 0; i < Highcharts.charts.length; i++) {
    chart = Highcharts.charts[i];
    e = chart.pointer.normalize(e); // Find coordinates within the chart
    points = [];

    chart.series.forEach(function(s) {
        points.push(s.searchPoint(e, true));
    });

    ...
}

Live demo: https://jsfiddle.net/BlackLabel/goxm5q3e/


问:
How "Data access expires" affects on reponses from webhook?
Me and our team are in the process of implementation small backend providing facebook chatbot functionality, which has to be able to handle multiple fanpages attached to it.

When facebook callback arrives to webhook, we can easily recognize which fanpage it belongs to and select from db valid page access token, which we receive during process of integration of fanpage and our frontend application (integration understood as process which user logged to our application gives us permissions to his fanpage).

We decided to extend page access token that it never expires and that solves problem of repeating whole process of giving us permissions to fanpage by user (integration mentioned before).

We are wondering about "Data access expires". From our knowledge, this term is always 90 days, and it cannot be extended. How it affects on sending responses to messenger users ? Will we be able to correctly response on messages sent to webhook after this term expires ?

答:
https://developers.facebook.com/docs/facebook-login/auth-vs-data#data-access:

The following permissions do not expire:

ads_read business_management

configure_page_transactions

manage_pages

pages_manage_cta

pages_manage_instant_articles

pages_messaging

pages_show_list

publish_pages

read_audience_network_insights

read_insights ads_management

manage_pages and pages_messaging are the only two that are necessary for your purpose, so that should cover it.


问:
Can floating point computation be used in any reliable function notably containers and algorithms?
In C and C++ floating point computations are non deterministic by default as not even the true datatype is chosen by user, as for any intermediate computation of a FP subexpression, the compiler can choose to represent a value with higher precision (that is as another real datatype).

[Some compilers (GCC) were known to do that for any automatic variable, not just the (anonymous) intermediate result of a subexpression.]

The compiler can do that for a few computations, in some functions; it can do it in some cases and not other for exactly the same subexpression.

It can even inline a function and use a different precision each time a function is called in the source code. It means that any inlinable function can have its semantics call dependent; only separately compiled, ABI-called functions (those functions that are called according to conventions described by the ABI and which act essentially as a black box) have the absolute guarantee of having only one floating point behavior, fixed during separate compilation (that means that no global optimization occurs).

[Note that this is similar to how string literals are defined: any two computation of the same string literal in the source code can refer to the same or different character arrays.]

That means that even for a purely applicative functions the fundamental equality f(x) == f(x) is only guaranteed if floating point operations (and string literals) are not used (or that the address of a string literal is only used to access its elements).

So floating point operations have non deterministic semantics with an arbitrary choice made by the compiler for each and every FP operations (which seems a lot more perverse that the very small issue of letting the compiler choose which subexpression A or B to compute first in A+B).

It seems that function that does any computation with intermediate floating point values cannot be used in any STL container or algorithm that expects a functor satisfying axioms, such that

sorted containers: set, map, multiset, multimap

hashed containers

sorting algorithms: sort, stable_sort

algorithm operating on sorted ranges: lower_bound, set_union, set_intersection...

as all binary predicates and hash functions must be deterministic before axioms can even be conceived, that they must be is purely applicative, mathematical function with a defined value of all possible inputs, which is never the case with C++ non-deterministic floating point intermediate values?

In other words, are floating point operations by default almost unusable based on the standard alone, and only usable using in real world implementations that have some (vague) implicit guarantees of determinism?

答:
A compiler is allowed to use higher precision operations and temporary values when evaluating floating-point arithmetic expressions. So if you do a1 = b+c; a2 = b+c;, then yes, it's possible for a1 and a2 to not be equal to each other (due to double rounding).

That really doesn't matter to the algorithms and containers you mentioned, though; those don't do any arithmetic on their values. The "axioms" that those rely on are those of ordering relationships at most.

The worst you could say is that if you'd previously stored b+c in, say, a set, doing mySet.find(b+c) might fail. So yeah, don't do that. But that's something you don't generally do anyway, the rounding error produced by floating-point arithmetic already making it rare to expect exact equality from derived quantities.

About the only time that you do start having to worry about extended precision is when you're calculating theoretical FP error bounds on a sequence of operations. When you're doing that, you'll know what to look for. Until then, this problem is not a problem.


问:
If I assign a method to a variable is the method called in java?
these are my two classes

```<code>   public class Main {
         public static void main(String[] args) throws IOException {
          Init init = new Init();
         final String init1 = init.init(); }}

public class Init {

protected String init() throws IOException {
     final String command = "ipconfig";
     Runtime rt = Runtime.getRuntime(); //executing commands on cmd
     Process process = rt.exec(command);
     InputStream is = process.getInputStream();
    Scanner s = new Scanner(is).useDelimiter("\\A");
    String val = "";

    if (s.hasNext()){
        val = s.next();
    } else {
        val = "";
    }

    return val;
</code>```

would init1 being initialized cause my program to execute the command line command? or would i have to call init.init(); everytime i wanted the command to run?

答:
You are storing a String in your variable inti1.
Therefore, if you "initialize" init1, you will get the String that your first call of init.init() returned. This is the only line where your init.init() call is done. If you reference init1 afterwards, no function gets called because the variable is just a String.

If you want to call a function in Java, you have to call the function. You can not store a function in a variable name and call the variable name as you could in JS.

Body:
these are my two classes

   public class Main {
         public static void main(String[] args) throws IOException {
          Init init = new Init();
         final String init1 = init.init(); }}

public class Init {

protected String init() throws IOException {
     final String command = "ipconfig";
     Runtime rt = Runtime.getRuntime(); //executing commands on cmd
     Process process = rt.exec(command);
     InputStream is = process.getInputStream();
    Scanner s = new Scanner(is).useDelimiter("\\A");
    String val = "";

    if (s.hasNext()){
        val = s.next();
    } else {
        val = "";
    }

    return val;

would init1 being initialized cause my program to execute the command line command? or would i have to call init.init(); everytime i wanted the command to run?


问:
How to read content from a file , uploaded using "Input Type" = file in HTML
I have a simple HTML form, where I have a field with browse button for uploading local files.

When fetching the uploaded file's path, it is showing as C:/fakepath/filename.xls. I came to know that it is the browser security that is not allowing to read exact file path from local Computer.

Is there any way that I can read contents from the Uploaded file.

```<code><input type="file" id = "FilePath" name="FilePath" size="18">
</code>```

So when I do document.getElementById("FilePath"). I got C:/fakepath/filename.xls.

Can anyone please help how to read file content from uploaded file

答:
you can use the following URL as a reference to read the file using js.

reference

Body:
I have a simple HTML form, where I have a field with browse button for uploading local files.

When fetching the uploaded file's path, it is showing as C:/fakepath/filename.xls. I came to know that it is the browser security that is not allowing to read exact file path from local Computer.

Is there any way that I can read contents from the Uploaded file.

<input type="file" id = "FilePath" name="FilePath" size="18">

So when I do document.getElementById("FilePath"). I got C:/fakepath/filename.xls.

Can anyone please help how to read file content from uploaded file


问:
How do I pull variables from an array in order to use those to within my query parameters? I'm using T-SQL in SQL Server Management Studio
I'm creating a query for my work involving running a query then using the results of that query within an iteration through the dbs of our system. I'm trying to beak this down into a few needed components.

Run query that will get the dataset to be iterated through

Begin an loop that will run 1 time for each result from the first query.

Each time the loop runs it will make a query into a database. The name of the DB will be changed each time by a variable taken from the first dataset and the results will all be appended into a single table or result.

With each iteration of the loop change a variable into the ID of each item within the results being iterated through.

I'm not very familiar with setting up loops or variables in SQL and am having trouble understanding it.

This is running in SQL Server Management Studio.

This is what I've figured out so far: the code starts off making a select statement in order to find all the names of the databases that I'll need to iterate through. There are two status codes that when it is that status the table is to be iterated through for its item numbers and its size.

The second select statement grabs all the information that will need to be converted and puts it into a table. The loop would begin before this query then run it multiple times, using the ids of each result from the first table as the name of the db to be queried.

```<code>/* This is the code I have so far. I'll explain what I'm doing and thinking in the comments*/

/* In this first select statement I'm finding all the databases that
   will need to be iterated through. I figure I can pull the names,
   create a table or array that contains them then run the iteration
   once per item in the array using the DB name as a variable that will
   change with each iteration */

select *
from edds.eddsdbo.[Case]
where statuscodeartifactid like 178079
   or StatusCodeArtifactID like 103428

/* Once this first statement has been run I will now I have a
   number column that is the artificatID. Each database has an area that is
   titled [EDDS'artifactID']. So if the artifactID = 1111111,
   then the DB would be accessed at [EDDS1111111] */

Drop Table #temptable

/* If the temptable has been created before this drops the table
   so the operation can be run again and refill the table.*/

/* This select statement pulls the information that will be placed
   into the temptable. This second statement should be inside the loop.
   One time for each DB that appeared in the first query's results. */

SELECT
    [DestinationWorkspace],
    [TotalItems], [FilesSize],
    CAST(LEFT(FilesSize, PATINDEX('%[0-9-.][^0-9-.]%', FilesSize )) AS MONEY) AS Filenumber,
    LTRIM(RIGHT(FilesSize, LEN(FilesSize) - PATINDEX('%[a - z]%', FilesSize ))) AS Unit
INTO
    #temptable
/* The 'from' portion of the statement is where I'll be needing to put
   in the artifactID variable. Where it says [EDDS1111111] I'd like to
   be able to have to say [EDDS@variable] where that variable is
   whatever the artifactID is of that particular round of iteration*/
FROM
    [EDDS1111111].[EDDSDBO].[JobHistory]
WHERE
    ItemsTransferred > 0
    AND Overwrite = 'Append Only'
    AND endtimeutc > '2019-03-31'

/* After the above statement has been run multiple times and
   appended all queries into the temp table the final select statement
   does some math on the entire table and converts the values into the
   desired units.*/

select
    DestinationWorkspace, TotalItems,
    case
       when right([Unit], 2) = 'KB'
          then FileNumber / 1024 / 1024
       when right([Unit], 2) = 'MB'
          then FileNumber / 1024
       else FileNumber
    end as 'Gigs'
from
    #temptable
</code>```

Right now the above code works fine but I need to figure out how to put the iteration around the middle statement and create then set the variable to change with each iteration to be the id of the entry that is being iterated over in the first table.

Thank you for any help you can offer.

答:
I don't know the structure of your database or the column names (hence I've just guessed at the database name column) but here is how I would structure the looping mechanism. The query example below only populates the database engine name however it could be extended to populate the database and table names.</p>

```<code>/*check if the #databases table is already present and then drop it*/
IF OBJECT_ID('tempdb..#databases', 'U') IS NOT NULL
begin
    drop table #databases;
end

 select
                * into #databases
                from edds.eddsdbo.[Case]
                where statuscodeartifactid like 178079 or StatusCodeArtifactID like 103428

            /*Once this first statement has been run I will now I have a
number column that is the artificatID. Each database has an area that is
titled [EDDS'artifactID']. So if the artifactID = 1111111 then the DB would
be accessed at [EDDS1111111]*/

declare @runs int = 1; /*this will track the number of times you iterate over the result set*/
declare @max int = 0; /*this will be the limit*/
declare @sql nvarchar(max)=''; /*this will allow you to dynamically populate the sql*/
declare @databasename sysname='' /*this will allow you to populate each database name*/

select @max=count(*) from #databases;
 /*the limit is now the number of databases inserted in to this table*/

/*check if your temp table exists and drop if neccessary*/
IF OBJECT_ID('tempdb..#temptable', 'U') IS NOT NULL
begin
    drop table #temptable;
end
/*create the temp table as you won't be able to use select into on each loop as your table will already exist on the second loop*/
create table #temptable
(
    DestinationWorkSpace nvarchar(150),
    TotalItem nvarchar(30),
    Filesize int,
    FileNumber money
);

while @runs<=@max
begin

            /*If the temptable has been created before this drops the table
so the operation can be run again and refill the table.*/

            /*This select statement pulls the information that will be placed
into the temptable. This second statment should be inside the loop. One time
for each DB that appeared in the first query's results.*/
/*begin the loop by assigning your dsatabase name, I don't know what the column is called so I have just called it databasename for now*/
select top 1 @databasename = databasename from #databases;
/*generate your sql using the @databasename variable, if you want to make the database and table names dynamic too then you can use the same formula*/
select @sql=N' insert #temptable (DestinationWorkspace, TotalItems, FileSize, FileNumber)
            SELECT
                  [DestinationWorkspace]
                  ,[TotalItems]
                     ,[FilesSize]
                 ,CAST(LEFT(FilesSize, PATINDEX(''%[0-9-.][^0-9-.]%'', FilesSize )) AS
            money) as Filenumber,
                        LTRIM(RIGHT(FilesSize, LEN(FilesSize) - PATINDEX(''%[a - z]%'', FilesSize ))) As Unit
                         into #temptable FROM ['+cast(@databasename as nvarchar(128))+'].[EDDSDBO].[JobHistory]
              where ItemsTransferred > 0 and Overwrite = ''Append Only'' and endtimeutc > ''2019-03-31''';
/*execute the sql*/
    exec (@sql);
/*remove that row from the databases table so you don't re-do that row*/
delete from #databases where databasename=@databasename;

            /* The 'from' portion of the statement is where I'll be needing to put in the artifiactID variable. Where it says [EDDS1111111] I'd like to
be able to have to say [EDDS@variable] where that variable is whatever the
artifactID is of that particular round of iteration*/

/*end the loop*/
select @runs=@runs+1;
end

            /* After the above statement has been run multiple times and
appended all queries into the temp table the final select statement does some
 math on the entire table and converts the values into the desired units.*/

              select DestinationWorkspace, TotalItems,
                        case
                         when right([Unit],2) = 'KB'
                         then FileNumber/1024/1024
                         when right([Unit],2) = 'MB'
                         then FileNumber/1024
                         else FileNumber
                         end as 'Gigs'
              from #temptable
</code>```

Body:
I'm creating a query for my work involving running a query then using the results of that query within an iteration through the dbs of our system. I'm trying to beak this down into a few needed components.

Run query that will get the dataset to be iterated through

Begin an loop that will run 1 time for each result from the first query.

Each time the loop runs it will make a query into a database. The name of the DB will be changed each time by a variable taken from the first dataset and the results will all be appended into a single table or result.

With each iteration of the loop change a variable into the ID of each item within the results being iterated through.

I'm not very familiar with setting up loops or variables in SQL and am having trouble understanding it.

This is running in SQL Server Management Studio.

This is what I've figured out so far: the code starts off making a select statement in order to find all the names of the databases that I'll need to iterate through. There are two status codes that when it is that status the table is to be iterated through for its item numbers and its size.

The second select statement grabs all the information that will need to be converted and puts it into a table. The loop would begin before this query then run it multiple times, using the ids of each result from the first table as the name of the db to be queried.

/* This is the code I have so far. I'll explain what I'm doing and thinking in the comments*/

/* In this first select statement I'm finding all the databases that
   will need to be iterated through. I figure I can pull the names,
   create a table or array that contains them then run the iteration
   once per item in the array using the DB name as a variable that will
   change with each iteration */

select *
from edds.eddsdbo.[Case]
where statuscodeartifactid like 178079
   or StatusCodeArtifactID like 103428

/* Once this first statement has been run I will now I have a
   number column that is the artificatID. Each database has an area that is
   titled [EDDS'artifactID']. So if the artifactID = 1111111,
   then the DB would be accessed at [EDDS1111111] */

Drop Table #temptable

/* If the temptable has been created before this drops the table
   so the operation can be run again and refill the table.*/

/* This select statement pulls the information that will be placed
   into the temptable. This second statement should be inside the loop.
   One time for each DB that appeared in the first query's results. */

SELECT
    [DestinationWorkspace],
    [TotalItems], [FilesSize],
    CAST(LEFT(FilesSize, PATINDEX('%[0-9-.][^0-9-.]%', FilesSize )) AS MONEY) AS Filenumber,
    LTRIM(RIGHT(FilesSize, LEN(FilesSize) - PATINDEX('%[a - z]%', FilesSize ))) AS Unit
INTO
    #temptable
/* The 'from' portion of the statement is where I'll be needing to put
   in the artifactID variable. Where it says [EDDS1111111] I'd like to
   be able to have to say [EDDS@variable] where that variable is
   whatever the artifactID is of that particular round of iteration*/
FROM
    [EDDS1111111].[EDDSDBO].[JobHistory]
WHERE
    ItemsTransferred > 0
    AND Overwrite = 'Append Only'
    AND endtimeutc > '2019-03-31'

/* After the above statement has been run multiple times and
   appended all queries into the temp table the final select statement
   does some math on the entire table and converts the values into the
   desired units.*/

select
    DestinationWorkspace, TotalItems,
    case
       when right([Unit], 2) = 'KB'
          then FileNumber / 1024 / 1024
       when right([Unit], 2) = 'MB'
          then FileNumber / 1024
       else FileNumber
    end as 'Gigs'
from
    #temptable

Right now the above code works fine but I need to figure out how to put the iteration around the middle statement and create then set the variable to change with each iteration to be the id of the entry that is being iterated over in the first table.

Thank you for any help you can offer.

Body:
I don't know the structure of your database or the column names (hence I've just guessed at the database name column) but here is how I would structure the looping mechanism. The query example below only populates the database engine name however it could be extended to populate the database and table names.

/*check if the #databases table is already present and then drop it*/
IF OBJECT_ID('tempdb..#databases', 'U') IS NOT NULL
begin
    drop table #databases;
end

 select
                * into #databases
                from edds.eddsdbo.[Case]
                where statuscodeartifactid like 178079 or StatusCodeArtifactID like 103428

            /*Once this first statement has been run I will now I have a
number column that is the artificatID. Each database has an area that is
titled [EDDS'artifactID']. So if the artifactID = 1111111 then the DB would
be accessed at [EDDS1111111]*/

declare @runs int = 1; /*this will track the number of times you iterate over the result set*/
declare @max int = 0; /*this will be the limit*/
declare @sql nvarchar(max)=''; /*this will allow you to dynamically populate the sql*/
declare @databasename sysname='' /*this will allow you to populate each database name*/

select @max=count(*) from #databases;
 /*the limit is now the number of databases inserted in to this table*/

/*check if your temp table exists and drop if neccessary*/
IF OBJECT_ID('tempdb..#temptable', 'U') IS NOT NULL
begin
    drop table #temptable;
end
/*create the temp table as you won't be able to use select into on each loop as your table will already exist on the second loop*/
create table #temptable
(
    DestinationWorkSpace nvarchar(150),
    TotalItem nvarchar(30),
    Filesize int,
    FileNumber money
);

while @runs<=@max
begin

            /*If the temptable has been created before this drops the table
so the operation can be run again and refill the table.*/

            /*This select statement pulls the information that will be placed
into the temptable. This second statment should be inside the loop. One time
for each DB that appeared in the first query's results.*/
/*begin the loop by assigning your dsatabase name, I don't know what the column is called so I have just called it databasename for now*/
select top 1 @databasename = databasename from #databases;
/*generate your sql using the @databasename variable, if you want to make the database and table names dynamic too then you can use the same formula*/
select @sql=N' insert #temptable (DestinationWorkspace, TotalItems, FileSize, FileNumber)
            SELECT
                  [DestinationWorkspace]
                  ,[TotalItems]
                     ,[FilesSize]
                 ,CAST(LEFT(FilesSize, PATINDEX(''%[0-9-.][^0-9-.]%'', FilesSize )) AS
            money) as Filenumber,
                        LTRIM(RIGHT(FilesSize, LEN(FilesSize) - PATINDEX(''%[a - z]%'', FilesSize ))) As Unit
                         into #temptable FROM ['+cast(@databasename as nvarchar(128))+'].[EDDSDBO].[JobHistory]
              where ItemsTransferred > 0 and Overwrite = ''Append Only'' and endtimeutc > ''2019-03-31''';
/*execute the sql*/
    exec (@sql);
/*remove that row from the databases table so you don't re-do that row*/
delete from #databases where databasename=@databasename;

            /* The 'from' portion of the statement is where I'll be needing to put in the artifiactID variable. Where it says [EDDS1111111] I'd like to
be able to have to say [EDDS@variable] where that variable is whatever the
artifactID is of that particular round of iteration*/

/*end the loop*/
select @runs=@runs+1;
end

            /* After the above statement has been run multiple times and
appended all queries into the temp table the final select statement does some
 math on the entire table and converts the values into the desired units.*/

              select DestinationWorkspace, TotalItems,
                        case
                         when right([Unit],2) = 'KB'
                         then FileNumber/1024/1024
                         when right([Unit],2) = 'MB'
                         then FileNumber/1024
                         else FileNumber
                         end as 'Gigs'
              from #temptable


问:
XMPP/facebook chat connection for android
```<code>public class ClientJabberActivity extends Activity {

private final static String SERVER_HOST = "chat.facebook.com";
private final static int SERVER_PORT = 5222;
private final static String SERVICE_NAME = "chat.facebook.com";
private final static String LOGIN = "xxxxx@chat.facebook.com";
private final static String PASSWORD = "xxxxxx";

private List<String> m_discussionThread;
private ArrayAdapter<String> m_discussionThreadAdapter;
private XMPPConnection m_connection;
private Handler m_handler;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    m_handler = new Handler();
    try {
        initConnection();
    } catch (XMPPException e) {
        e.printStackTrace();
    }

    final EditText recipient = (EditText) this.findViewById(R.id.recipient);
    final EditText message = (EditText) this.findViewById(R.id.message);
    ListView list = (ListView) this.findViewById(R.id.thread);

    m_discussionThread = new ArrayList<String>();
    m_discussionThreadAdapter = new ArrayAdapter<String>(this,
            R.layout.multi_line_list_item, m_discussionThread);
    list.setAdapter(m_discussionThreadAdapter);

    Button send = (Button) this.findViewById(R.id.send);
    send.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            String to = recipient.getText().toString();
            String text = message.getText().toString();

            Message msg = new Message(to, Message.Type.chat);
            msg.setBody(text);
            m_connection.sendPacket(msg);
            m_discussionThread.add("moi :");
            m_discussionThread.add(text);
            m_discussionThreadAdapter.notifyDataSetChanged();
        }
    });
}

private void initConnection() throws XMPPException {
    //Initialisation de la connexion
    ConnectionConfiguration config =
            new ConnectionConfiguration(SERVER_HOST, SERVER_PORT, SERVICE_NAME);
    m_connection = new XMPPConnection(config);
    m_connection.connect();
    m_connection.login(LOGIN, PASSWORD);
    Presence presence = new Presence(Presence.Type.available);
    m_connection.sendPacket(presence);

    //enregistrement de l'écouteur de messages
    PacketFilter filter = new MessageTypeFilter(Message.Type.chat);
    m_connection.addPacketListener(new PacketListener() {
            public void processPacket(Packet packet) {
                Message message = (Message) packet;
                if (message.getBody() != null) {
                    String fromName = StringUtils.parseBareAddress(message
                            .getFrom());
                    m_discussionThread.add(fromName + ":");
                    m_discussionThread.add(message.getBody());

                    m_handler.post(new Runnable() {
                        public void run() {
                            m_discussionThreadAdapter.notifyDataSetChanged();
                        }
                    });
                }
            }
        }, filter);
}

}
</code>```

<p>this code i used to make connection with facebook chat, but the connection can not be established i don't know why . it works well with gmail </p>

```<code>02-18 16:06:20.178: ERROR/AndroidRuntime(453): java.lang.IllegalStateException: Not connected to server.
02-18 16:06:20.178: ERROR/AndroidRuntime(453):     at org.jivesoftware.smack.XMPPConnection.sendPacket(XMPPConnection.java:665)
02-18 16:06:20.178: ERROR/AndroidRuntime(453):     at com.developpez.florentgarin.android.ClientJabberActivity$1.onClick(ClientJabberActivity.java:61)
02-18 16:06:20.178: ERROR/AndroidRuntime(453):     at android.view.View.performClick(View.java:2485)
02-18 16:06:20.178: ERROR/AndroidRuntime(453):     at android.view.View$PerformClick.run(View.java:9080)
02-18 16:06:20.178: ERROR/AndroidRuntime(453):     at android.os.Handler.handleCallback(Handler.java:587)
02-18 16:06:20.178: ERROR/AndroidRuntime(453):     at android.os.Handler.dispatchMessage(Handler.java:92)
02-18 16:06:20.178: ERROR/AndroidRuntime(453):     at android.os.Looper.loop(Looper.java:123)
02-18 16:06:20.178: ERROR/AndroidRuntime(453):     at android.app.ActivityThread.main(ActivityThread.java:3647)
02-18 16:06:20.178: ERROR/AndroidRuntime(453):     at java.lang.reflect.Method.invokeNative(Native Method)
02-18 16:06:20.178: ERROR/AndroidRuntime(453):     at java.lang.reflect.Method.invoke(Method.java:507)
02-18 16:06:20.178: ERROR/AndroidRuntime(453):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
02-18 16:06:20.178: ERROR/AndroidRuntime(453):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
02-18 16:06:20.178: ERROR/AndroidRuntime(453):     at dalvik.system.NativeStart.main(Native Method)
02-18 16:06:43.167: ERROR/installd(35): eof
02-18 16:06:43.167: ERROR/installd(35): failed to read size
02-18 16:07:11.857: ERROR/Zygote(470): setreuid() failed. errno: 17
02-18 16:07:16.408: ERROR/BatteryService(477): usbOnlinePath not found
02-18 16:07:16.408: ERROR/BatteryService(477): batteryVoltagePath not found
02-18 16:07:16.408: ERROR/BatteryService(477): batteryTemperaturePath not found
02-18 16:07:16.477: ERROR/SurfaceFlinger(477): Couldn't open /sys/power/wait_for_fb_sleep or /sys/power/wait_for_fb_wake
02-18 16:07:16.758: ERROR/SensorService(477): couldn't open device for module sensors (Invalid argument)
</code>```

答:
Change:

```<code>private final static String LOGIN = "xxxxx@chat.facebook.com";
</code>```

To:

```<code>private final static String LOGIN = "xxxxx";
</code>```

Well not exactly ;). You get the idea though..

XMPP spec for facebook does not include the @server.here for login. Either include it in your username string or delete your server string entirely.

ContentLicense: CC BY-SA 2.5

Body:
public class ClientJabberActivity extends Activity {

private final static String SERVER_HOST = "chat.facebook.com";
private final static int SERVER_PORT = 5222;
private final static String SERVICE_NAME = "chat.facebook.com";
private final static String LOGIN = "xxxxx@chat.facebook.com";
private final static String PASSWORD = "xxxxxx";

private List<String> m_discussionThread;
private ArrayAdapter<String> m_discussionThreadAdapter;
private XMPPConnection m_connection;
private Handler m_handler;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    m_handler = new Handler();
    try {
        initConnection();
    } catch (XMPPException e) {
        e.printStackTrace();
    }

    final EditText recipient = (EditText) this.findViewById(R.id.recipient);
    final EditText message = (EditText) this.findViewById(R.id.message);
    ListView list = (ListView) this.findViewById(R.id.thread);

    m_discussionThread = new ArrayList<String>();
    m_discussionThreadAdapter = new ArrayAdapter<String>(this,
            R.layout.multi_line_list_item, m_discussionThread);
    list.setAdapter(m_discussionThreadAdapter);

    Button send = (Button) this.findViewById(R.id.send);
    send.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            String to = recipient.getText().toString();
            String text = message.getText().toString();

            Message msg = new Message(to, Message.Type.chat);
            msg.setBody(text);
            m_connection.sendPacket(msg);
            m_discussionThread.add("moi :");
            m_discussionThread.add(text);
            m_discussionThreadAdapter.notifyDataSetChanged();
        }
    });
}

private void initConnection() throws XMPPException {
    //Initialisation de la connexion
    ConnectionConfiguration config =
            new ConnectionConfiguration(SERVER_HOST, SERVER_PORT, SERVICE_NAME);
    m_connection = new XMPPConnection(config);
    m_connection.connect();
    m_connection.login(LOGIN, PASSWORD);
    Presence presence = new Presence(Presence.Type.available);
    m_connection.sendPacket(presence);

    //enregistrement de l'écouteur de messages
    PacketFilter filter = new MessageTypeFilter(Message.Type.chat);
    m_connection.addPacketListener(new PacketListener() {
            public void processPacket(Packet packet) {
                Message message = (Message) packet;
                if (message.getBody() != null) {
                    String fromName = StringUtils.parseBareAddress(message
                            .getFrom());
                    m_discussionThread.add(fromName + ":");
                    m_discussionThread.add(message.getBody());

                    m_handler.post(new Runnable() {
                        public void run() {
                            m_discussionThreadAdapter.notifyDataSetChanged();
                        }
                    });
                }
            }
        }, filter);
}

}

this code i used to make connection with facebook chat, but the connection can not be established i don't know why . it works well with gmail

02-18 16:06:20.178: ERROR/AndroidRuntime(453): java.lang.IllegalStateException: Not connected to server.
02-18 16:06:20.178: ERROR/AndroidRuntime(453):     at org.jivesoftware.smack.XMPPConnection.sendPacket(XMPPConnection.java:665)
02-18 16:06:20.178: ERROR/AndroidRuntime(453):     at com.developpez.florentgarin.android.ClientJabberActivity$1.onClick(ClientJabberActivity.java:61)
02-18 16:06:20.178: ERROR/AndroidRuntime(453):     at android.view.View.performClick(View.java:2485)
02-18 16:06:20.178: ERROR/AndroidRuntime(453):     at android.view.View$PerformClick.run(View.java:9080)
02-18 16:06:20.178: ERROR/AndroidRuntime(453):     at android.os.Handler.handleCallback(Handler.java:587)
02-18 16:06:20.178: ERROR/AndroidRuntime(453):     at android.os.Handler.dispatchMessage(Handler.java:92)
02-18 16:06:20.178: ERROR/AndroidRuntime(453):     at android.os.Looper.loop(Looper.java:123)
02-18 16:06:20.178: ERROR/AndroidRuntime(453):     at android.app.ActivityThread.main(ActivityThread.java:3647)
02-18 16:06:20.178: ERROR/AndroidRuntime(453):     at java.lang.reflect.Method.invokeNative(Native Method)
02-18 16:06:20.178: ERROR/AndroidRuntime(453):     at java.lang.reflect.Method.invoke(Method.java:507)
02-18 16:06:20.178: ERROR/AndroidRuntime(453):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
02-18 16:06:20.178: ERROR/AndroidRuntime(453):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
02-18 16:06:20.178: ERROR/AndroidRuntime(453):     at dalvik.system.NativeStart.main(Native Method)
02-18 16:06:43.167: ERROR/installd(35): eof
02-18 16:06:43.167: ERROR/installd(35): failed to read size
02-18 16:07:11.857: ERROR/Zygote(470): setreuid() failed. errno: 17
02-18 16:07:16.408: ERROR/BatteryService(477): usbOnlinePath not found
02-18 16:07:16.408: ERROR/BatteryService(477): batteryVoltagePath not found
02-18 16:07:16.408: ERROR/BatteryService(477): batteryTemperaturePath not found
02-18 16:07:16.477: ERROR/SurfaceFlinger(477): Couldn't open /sys/power/wait_for_fb_sleep or /sys/power/wait_for_fb_wake
02-18 16:07:16.758: ERROR/SensorService(477): couldn't open device for module sensors (Invalid argument)

Body:
Change:

private final static String LOGIN = "xxxxx@chat.facebook.com";

To:

private final static String LOGIN = "xxxxx";

Well not exactly ;). You get the idea though..

XMPP spec for facebook does not include the @server.here for login. Either include it in your username string or delete your server string entirely.

ContentLicense: CC BY-SA 3.0


问:
Shiny app is not available when singularity container is run as instance
I built singularity container from docker image kfoltynski/shinyproxy-demo:singularity. When I run

```<code>singularity run shiny.simg 3839
</code>```

shiny app is available on localhost:3839, but after running singularity container as instance

```<code>singularity instance start shiny.simg shiny 3839
</code>```

it is not. Why?

Steps to reproduce:

Dockerfile:

```<code>FROM openanalytics/r-base

MAINTAINER Tobias Verbeke "Tazovsky"

RUN apt-get update && apt-get install -y \
    sudo \
    pandoc \
    pandoc-citeproc \
    libcurl4-gnutls-dev \
    libcairo2-dev \
    libxt-dev \
    libssl-dev \
    libssh2-1-dev \
    libssl1.0.0

# packages needed for basic shiny functionality
RUN R -e "install.packages(c('shiny', 'rmarkdown'), repos='https://cloud.r-project.org')"

# install shinyproxy package with demo shiny application
COPY shinyproxy /shinyproxy
RUN R CMD INSTALL /shinyproxy
RUN rm /shinyproxy

# set host and port
COPY Rprofile.site /usr/lib/R/etc/

EXPOSE 3838

ENV PORT=3839

CMD ["R", "-e", "shinyproxy::run_01_hello(as.numeric(Sys.getenv(\"PORT\")))"]
</code>```

Singularity def/recipe file Singularity.recipe:

```<code>Bootstrap: docker

From: kfoltynski/shinyproxy-demo:singularity

%environment

    export PORT=3839

%runscript

    echo "Running Shiny app on port $*"

    exec R -e "shinyproxy::run_01_hello($@)"
</code>```

Build singularity image shiny.simg:

```<code> sudo singularity build shiny.simg Singularity.recipe
</code>```

Run container:

```<code>singularity run shiny.simg 3839 # app is available on port 3839
</code>```

Run container as instance:

```<code>singularity instance start shiny.simg shiny 3839 # app is not available on port 3839
</code>```

Why app is not available when running singularity container as instance?

答:
singularity instance start shiny.simg shiny 3839 is creating and starting a new instance named 3839, and not passing that as a param to the %runscript. To get the response you want you need to run:

singularity instance start shiny.simg shiny_instance
singularity run instance://shiny_instance 3839
```

<p>The <code>%runscript</code> block is not called when the instance is started. If you want a process to run when the instance is started you need to use the <code>%startscript</code> directive, shown in the docs here.</p>

<p>e.g.,</p>

```Bootstrap: docker

From: kfoltynski/shinyproxy-demo:singularity

%environment
    export PORT=3839

%runscript
    echo "Running Shiny app on port $*"
    exec R -e "shinyproxy::run_01_hello($@)"

%startscript
    exec R -e "shinyproxy::run_01_hello($@)"
```

Body:
I built singularity container from docker image kfoltynski/shinyproxy-demo:singularity. When I run

singularity run shiny.simg 3839

shiny app is available on localhost:3839, but after running singularity container as instance

singularity instance start shiny.simg shiny 3839

it is not. Why?

Steps to reproduce:

Dockerfile:

FROM openanalytics/r-base

MAINTAINER Tobias Verbeke "Tazovsky"

RUN apt-get update && apt-get install -y \
    sudo \
    pandoc \
    pandoc-citeproc \
    libcurl4-gnutls-dev \
    libcairo2-dev \
    libxt-dev \
    libssl-dev \
    libssh2-1-dev \
    libssl1.0.0

# packages needed for basic shiny functionality
RUN R -e "install.packages(c('shiny', 'rmarkdown'), repos='https://cloud.r-project.org')"

# install shinyproxy package with demo shiny application
COPY shinyproxy /shinyproxy
RUN R CMD INSTALL /shinyproxy
RUN rm /shinyproxy

# set host and port
COPY Rprofile.site /usr/lib/R/etc/

EXPOSE 3838

ENV PORT=3839

CMD ["R", "-e", "shinyproxy::run_01_hello(as.numeric(Sys.getenv(\"PORT\")))"]

Singularity def/recipe file Singularity.recipe:

Bootstrap: docker

From: kfoltynski/shinyproxy-demo:singularity

%environment

    export PORT=3839

%runscript

    echo "Running Shiny app on port $*"

    exec R -e "shinyproxy::run_01_hello($@)"

Build singularity image shiny.simg:

 sudo singularity build shiny.simg Singularity.recipe

Run container:

singularity run shiny.simg 3839 # app is available on port 3839

Run container as instance:

singularity instance start shiny.simg shiny 3839 # app is not available on port 3839

Why app is not available when running singularity container as instance?

Body:
singularity instance start shiny.simg shiny 3839 is creating and starting a new instance named 3839, and not passing that as a param to the %runscript. To get the response you want you need to run:

singularity instance start shiny.simg shiny_instance
singularity run instance://shiny_instance 3839

The %runscript block is not called when the instance is started. If you want a process to run when the instance is started you need to use the %startscript directive, shown in the docs here.

e.g.,

Bootstrap: docker

From: kfoltynski/shinyproxy-demo:singularity

%environment
    export PORT=3839

%runscript
    echo "Running Shiny app on port $*"
    exec R -e "shinyproxy::run_01_hello($@)"

%startscript
    exec R -e "shinyproxy::run_01_hello($@)"


问:
Vimscript get what command to be executed
I want my Vimscript to know if a specific command(tabmove) is going to be executed now, either by reading a predefined register or invoking a function.

I've searched all the information I can get from google or vim document. But found nothing.

```<code>if current_command == 'tabmove*'
    dowhat
endif
</code>```

For now I still don't figure out an effective way to make this, can someone Vim expert offer some advice?

答:
In vimscript, autocmd is the best way to make a trigger for one event.

Please check Autocommands for more details about autocmd. If there are too many operations you want to use, please read Autocommand Groups.

Before define your own events, please check the list of autocmd-events bulit in vim.

Maybe you should try how to define CursorMoved in a tabpage???

```<code>autocmd CursorMoved call fucntab()

func fucntab()
    if (tabpage)
        "do your work??
endfunc
</code>```

PS. tabpage in vim manual

Body:
I want my Vimscript to know if a specific command(tabmove) is going to be executed now, either by reading a predefined register or invoking a function.

I've searched all the information I can get from google or vim document. But found nothing.

if current_command == 'tabmove*'
    dowhat
endif

For now I still don't figure out an effective way to make this, can someone Vim expert offer some advice?

Body:
In vimscript, autocmd is the best way to make a trigger for one event.

Please check Autocommands for more details about autocmd. If there are too many operations you want to use, please read Autocommand Groups.

Before define your own events, please check the list of autocmd-events bulit in vim.

Maybe you should try how to define CursorMoved in a tabpage???

autocmd CursorMoved call fucntab()

func fucntab()
    if (tabpage)
        "do your work??
endfunc

PS. tabpage in vim manual


问:
Can i compare these two dates in JS?
```<code>console.log("201905300545_201905300555"  < "201905300535_201905300545")
</code>```

How can i compare two dates in string format?

答:
First of all you have to get the range they are representing (by subtracting them):</p>

```<code> const range = r => {
   const [start, end] = r.split("_");
   return +end - +start;
 };

 console.log(range("201905300545_201905300555") < range("201905300535_201905300545"));
</code>```

Title: Can i compare these two dates in JS?

Body:
console.log("201905300545_201905300555"  < "201905300535_201905300545")

How can i compare two dates in string format?

Body:
First of all you have to get the range they are representing (by subtracting them):

 const range = r => {
   const [start, end] = r.split("_");
   return +end - +start;
 };

 console.log(range("201905300545_201905300555") < range("201905300535_201905300545"));


问:
Response getting back from the ibm mq is not match for the request sometimes
I copy the java client code for how to call IBM MQ, and pass the request to the queue, but sometimes I getting the wrong response back from the queue.

For example, if I submit the following request:
F                    LOYFI6331760101046481882

I expect from the response I should get
F                    LOYFA36331760101046481882

But actually I getting
F                    LOYFA36331760101051292448

As you can see the card number is wrong.

Here is the code

import javax.jms.BytesMessage;
import javax.jms.Destination;
import javax.jms.JMSConsumer;
import javax.jms.JMSContext;
import javax.jms.JMSException;
import javax.jms.JMSProducer;
import javax.jms.TextMessage;

import com.ibm.msg.client.jms.JmsConnectionFactory;
import com.ibm.msg.client.jms.JmsFactoryFactory;
import com.ibm.msg.client.wmq.WMQConstants;

public class MQClient {
    // System exit status value (assume unset value to be 1)
    private static int status = 1;

    public static byte[] sendAndReceive(String HOST, Integer PORT, String QMGR, String CHANNEL, String requestQueue, String responseQueue, String payload) {
        // Variables
        JMSContext context = null;
        Destination destination = null;
        JMSProducer producer = null;
        JMSConsumer consumer = null;
        BytesMessage receivedMessage = null;
        byte[] result = null;
        try {
            // Create a connection factory
            JmsFactoryFactory ff = JmsFactoryFactory.getInstance(WMQConstants.WMQ_PROVIDER);
            JmsConnectionFactory cf = ff.createConnectionFactory();

            // Set the properties
            cf.setStringProperty(WMQConstants.WMQ_HOST_NAME, HOST);
            cf.setIntProperty(WMQConstants.WMQ_PORT, PORT);
            cf.setStringProperty(WMQConstants.WMQ_CHANNEL, CHANNEL);
            cf.setIntProperty(WMQConstants.WMQ_CONNECTION_MODE, WMQConstants.WMQ_CM_CLIENT);
            cf.setStringProperty(WMQConstants.WMQ_QUEUE_MANAGER, QMGR);
            cf.setStringProperty(WMQConstants.WMQ_APPLICATIONNAME, "JmsPutGet (JMS)");
            cf.setStringProperty(WMQConstants.WMQ_TARGET_CLIENT, "1");
            // Create JMS objects
            context = cf.createContext();
            destination = context.createQueue("queue:///" + requestQueue +"?targetClient=1");

            TextMessage message = context.createTextMessage(payload);

            producer = context.createProducer();
            producer.send(destination, message);
            System.out.println("Sent message:\n" + message);

            destination = context.createQueue("queue:///" + responseQueue + "?targetClient=1");
            consumer = context.createConsumer(destination); // autoclosable
            receivedMessage= (BytesMessage)consumer.receive();
            System.out.println("Receiving message:" + receivedMessage);
            int text_length = new Long(receivedMessage.getBodyLength()).intValue();
            result = new byte[text_length];
            receivedMessage.readBytes(result, text_length);

            System.out.println("\nReceived message:\n" + new String(result));

            recordSuccess();

        } catch (JMSException jmsex) {
            recordFailure(jmsex);
        }finally {
            context.close();
        }

        return result;

    }
}
```

I have another project to run concurrently to call MQClient.sendAndReceive() method, with same host, port, QMGR, channel, requestQueue and responseQueue, only payload is different.

So how do I fix the code above to make sure I always getting the correct response corresponding to the request?

EDIT:
1. For JoshMac questions, app means the IBM MQ one? Or the app that will call my sendAndReceive function?

Here is the flow I have, I using mule flow take the request from the POS, process the request, which need to call IBM MQ (which sit on AS400), to get the response back from MQ, and send back to POS. (In this example, I need to submit my request to INQ1 and get the response from INQR1). Based on the answer below, it seems like the sendAndReceive function is treat as Requester, I need another flow to call the Responder to handle the response, so receivedMessage= (BytesMessage)consumer.receive(); will not getting stuck? Correct me if I am wrong

答:
It looks like all responses are being sent to INQR1. To help your app identify which of the responses are for it and which it can ignore, you can make use of a selector, and normally the selector is by correlation id, though you could use other fields.

Essentially you are using a request / response pattern for which there are JMS samples - https://github.com/ibm-messaging/mq-dev-patterns/tree/master/JMS

Your requester would have logic like:

```<code>String correlationID = String.format("%24.24s", UUID.randomUUID().toString());
message.setJMSCorrelationIDAsBytes(b);
</code>```

to generate a correlation id, and add it to the message.

Your requester would then create a correlation id based selector to filter the response queue:

```<code>try {
      b = correlationID.getBytes();
      selector = "JMSCorrelationID='ID:" + getHexString(b) + "'";
    } catch (Exception e) {
       ...
    }
</code>```

which you use to construct your message consumer:

```<code>JMSConsumer consumer = context.createConsumer(requestQueue, selector);
Message receivedMessage = consumer.receive();
</code>```

When your responder receives the initial request, it can get hold of the correlation id:

```<code>String correlationID = receivedMessage.getJMSCorrelationID();
</code>```

and use it to set the correlation id for the response:

```<code>message.setJMSCorrelationID(correlationID);
</code>```

Body:
I copy the java client code for how to call IBM MQ, and pass the request to the queue, but sometimes I getting the wrong response back from the queue.

For example, if I submit the following request:
F                    LOYFI6331760101046481882

I expect from the response I should get
F                    LOYFA36331760101046481882

But actually I getting
F                    LOYFA36331760101051292448

As you can see the card number is wrong.

Here is the code

import javax.jms.BytesMessage;
import javax.jms.Destination;
import javax.jms.JMSConsumer;
import javax.jms.JMSContext;
import javax.jms.JMSException;
import javax.jms.JMSProducer;
import javax.jms.TextMessage;

import com.ibm.msg.client.jms.JmsConnectionFactory;
import com.ibm.msg.client.jms.JmsFactoryFactory;
import com.ibm.msg.client.wmq.WMQConstants;

public class MQClient {
    // System exit status value (assume unset value to be 1)
    private static int status = 1;

    public static byte[] sendAndReceive(String HOST, Integer PORT, String QMGR, String CHANNEL, String requestQueue, String responseQueue, String payload) {
        // Variables
        JMSContext context = null;
        Destination destination = null;
        JMSProducer producer = null;
        JMSConsumer consumer = null;
        BytesMessage receivedMessage = null;
        byte[] result = null;
        try {
            // Create a connection factory
            JmsFactoryFactory ff = JmsFactoryFactory.getInstance(WMQConstants.WMQ_PROVIDER);
            JmsConnectionFactory cf = ff.createConnectionFactory();

            // Set the properties
            cf.setStringProperty(WMQConstants.WMQ_HOST_NAME, HOST);
            cf.setIntProperty(WMQConstants.WMQ_PORT, PORT);
            cf.setStringProperty(WMQConstants.WMQ_CHANNEL, CHANNEL);
            cf.setIntProperty(WMQConstants.WMQ_CONNECTION_MODE, WMQConstants.WMQ_CM_CLIENT);
            cf.setStringProperty(WMQConstants.WMQ_QUEUE_MANAGER, QMGR);
            cf.setStringProperty(WMQConstants.WMQ_APPLICATIONNAME, "JmsPutGet (JMS)");
            cf.setStringProperty(WMQConstants.WMQ_TARGET_CLIENT, "1");
            // Create JMS objects
            context = cf.createContext();
            destination = context.createQueue("queue:///" + requestQueue +"?targetClient=1");

            TextMessage message = context.createTextMessage(payload);

            producer = context.createProducer();
            producer.send(destination, message);
            System.out.println("Sent message:\n" + message);

            destination = context.createQueue("queue:///" + responseQueue + "?targetClient=1");
            consumer = context.createConsumer(destination); // autoclosable
            receivedMessage= (BytesMessage)consumer.receive();
            System.out.println("Receiving message:" + receivedMessage);
            int text_length = new Long(receivedMessage.getBodyLength()).intValue();
            result = new byte[text_length];
            receivedMessage.readBytes(result, text_length);

            System.out.println("\nReceived message:\n" + new String(result));

            recordSuccess();

        } catch (JMSException jmsex) {
            recordFailure(jmsex);
        }finally {
            context.close();
        }

        return result;

    }
}

I have another project to run concurrently to call MQClient.sendAndReceive() method, with same host, port, QMGR, channel, requestQueue and responseQueue, only payload is different.

So how do I fix the code above to make sure I always getting the correct response corresponding to the request?

EDIT:
1. For JoshMac questions, app means the IBM MQ one? Or the app that will call my sendAndReceive function?

Here is the flow I have, I using mule flow take the request from the POS, process the request, which need to call IBM MQ (which sit on AS400), to get the response back from MQ, and send back to POS. (In this example, I need to submit my request to INQ1 and get the response from INQR1). Based on the answer below, it seems like the sendAndReceive function is treat as Requester, I need another flow to call the Responder to handle the response, so receivedMessage= (BytesMessage)consumer.receive(); will not getting stuck? Correct me if I am wrong

Body:
It looks like all responses are being sent to INQR1. To help your app identify which of the responses are for it and which it can ignore, you can make use of a selector, and normally the selector is by correlation id, though you could use other fields.

Essentially you are using a request / response pattern for which there are JMS samples - https://github.com/ibm-messaging/mq-dev-patterns/tree/master/JMS

Your requester would have logic like:

String correlationID = String.format("%24.24s", UUID.randomUUID().toString());
message.setJMSCorrelationIDAsBytes(b);

to generate a correlation id, and add it to the message.

Your requester would then create a correlation id based selector to filter the response queue:

try {
      b = correlationID.getBytes();
      selector = "JMSCorrelationID='ID:" + getHexString(b) + "'";
    } catch (Exception e) {
       ...
    }

which you use to construct your message consumer:

JMSConsumer consumer = context.createConsumer(requestQueue, selector);
Message receivedMessage = consumer.receive();

When your responder receives the initial request, it can get hold of the correlation id:

String correlationID = receivedMessage.getJMSCorrelationID();

and use it to set the correlation id for the response:

message.setJMSCorrelationID(correlationID);


问:
how to set a color based on base color value and alpha value in xml?
I want to set a custom color.

In the spec I was given this color definition:

```<code>#5F6368(google_grey700) and 10% opacity
</code>```

How can I define my color using this base resource + alpha value?

Possible via xml? or has to be grammatically?

```<code><?xml version="1.0" encoding="utf-8"?>
<resources>

  <style name="ripple_theme">
    <item name="colorControlHighlight">@color/green</item>
  </style>
</resources>
</code>```

答:
You can define your color as #1A5F6368 in your colors xml as 1A at start of color specify 10% opacity. color defination in hexadecimal is #AARRGGBB

Explanation

```<code># AA(Alpha) RR(Red) GG(Green) BB(Blue)
</code>```

Body:
I want to set a custom color.

In the spec I was given this color definition:

#5F6368(google_grey700) and 10% opacity

How can I define my color using this base resource + alpha value?

Possible via xml? or has to be grammatically?

<?xml version="1.0" encoding="utf-8"?>
<resources>

</resources>

Body:
You can define your color as #1A5F6368 in your colors xml as 1A at start of color specify 10% opacity. color defination in hexadecimal is #AARRGGBB

Explanation

# AA(Alpha) RR(Red) GG(Green) BB(Blue)


问:
How can I append this value in addition to what the user inputs?
I have a script that implements FindNext in order to search a sheet for a row to match two column values that the user inputs via Application.InputBox. Works flawlessly. But there is an instance where I'd like one of the msgboxs to display another cell value in that row without the user input.

Example: User inputs Job code 000001 found in column A, cost-center 100100010001 Found in column C.

The msgbox will match it and say: MsgBox "Job Code (" & lJobCode & ") is eligible for this cost-center.

What if I also wanted that message box to add in a value found in another column, but automatically? Like, without the user input because they wouldn't know this info off hand.

New MsgBox Example: MsgBox "Job Code (" & lJobCode & ") is eligible for this (" & Column H Value for this row & ") cost-center.

I was thinking something like a str variable and reference the column, but I'm having trouble having VBA trigger that value once the row is matched.

Rest of script:

```<code>Option Explicit
Sub findJC_CC()

Dim wsData As Worksheet
Dim rFound As Range
Dim lJobCode As String
Dim lCC As String
Dim sFirst As String
Dim matched As Boolean

lJobCode = Application.InputBox("Please provide a job code", "Job Code", Type:=2)
If lJobCode = "False" Then Exit Sub 'Pressed cancel
lCC = Application.InputBox("Please enter in a cost-center", "CC", Type:=2)
If lCC = "False" Then Exit Sub 'Pressed cancel

matched = False
Set wsData = ThisWorkbook.Worksheets("Sheet2")
Set rFound = wsData.Columns("A").Find(lJobCode, wsData.Cells(wsData.Rows.Count, "A"), xlValues, xlWhole)

If Not rFound Is Nothing Then
    sFirst = rFound.Address
    Do

        If rFound.Offset(, 2).Value = lCC Then
            matched = True

            'if criteria is met, display msgbox and exit
            If rFound.Offset(, 4).Value = "Exempt" Then
                MsgBox "The business identified this exempt job as being eligible for schedule pay allowance ."
                Exit Sub
            End If

            'if criteria is met, display msgbox and exit
            If rFound.Offset(, 5).Value = "Eligible - Employee Level" Then
                MsgBox "This job is only eligible at the employee level. If you have further questions, please reach out to your HRBP."
                Exit Sub
            End If

            'if non-exempt role, and matched, display msgbox and exit
            MsgBox "Job Code (" & lJobCode & ") is eligible for this cost-center."
            Exit Sub
        End If

        'loop after first address found until column C has lCC value matched
        Set rFound = wsData.Columns("A").FindNext(rFound)
    Loop While rFound.Address <> sFirst

    'lJobCode value matched, lCC value not matched
    If Not matched Then MsgBox "Job Code (" & lJobCode & ") found, but not eligible for this cost-center."
Else

    'lJobCode not matched
    MsgBox "Job Code (" & lJobCode & ") not eligible."

End If

End Sub
</code>```

答:
You can add that line:</p>

```<code>Option Explicit
Sub findJC_CC()

Dim wsData As Worksheet
Dim rFound As Range
Dim lJobCode As String
Dim lCC As String
Dim sFirst As String
Dim matched As Boolean

lJobCode = Application.InputBox("Please provide a job code", "Job Code", Type:=2)
If lJobCode = "False" Then Exit Sub 'Pressed cancel
lCC = Application.InputBox("Please enter in a cost-center", "CC", Type:=2)
If lCC = "False" Then Exit Sub 'Pressed cancel

matched = False
Set wsData = ThisWorkbook.Worksheets("Sheet2")
Set rFound = wsData.Columns("A").Find(lJobCode, wsData.Cells(wsData.Rows.Count, "A"), xlValues, xlWhole)

If Not rFound Is Nothing Then
    sFirst = rFound.Address
    Do

        If rFound.Offset(, 2).Value = lCC Then
            matched = True

            'if criteria is met, display msgbox and exit
            If rFound.Offset(, 4).Value = "Exempt" Then
                MsgBox "The business identified this exempt job as being eligible for schedule pay allowance ."
                Exit Sub
            End If

            'if criteria is met, display msgbox and exit
            If rFound.Offset(, 5).Value = "Eligible - Employee Level" Then
                MsgBox "This job is only eligible at the employee level. If you have further questions, please reach out to your HRBP."
                Exit Sub
            End If

            'if non-exempt role, and matched, display msgbox and exit
            MsgBox "Job Code (" & lJobCode & ") is eligible for this (" & rFound.Offset(, 7).Value & ") cost-center."
            Exit Sub
        End If

        'loop after first address found until column C has lCC value matched
        Set rFound = wsData.Columns("A").FindNext(rFound)
    Loop While rFound.Address <> sFirst

    'lJobCode value matched, lCC value not matched
    If Not matched Then MsgBox "Job Code (" & lJobCode & ") found, but not eligible for this cost-center."
Else

    'lJobCode not matched
    MsgBox "Job Code (" & lJobCode & ") not eligible."

End If

End Sub
</code>```

Body:
I have a script that implements FindNext in order to search a sheet for a row to match two column values that the user inputs via Application.InputBox. Works flawlessly. But there is an instance where I'd like one of the msgboxs to display another cell value in that row without the user input.

Example: User inputs Job code 000001 found in column A, cost-center 100100010001 Found in column C.

The msgbox will match it and say: MsgBox "Job Code (" & lJobCode & ") is eligible for this cost-center.

What if I also wanted that message box to add in a value found in another column, but automatically? Like, without the user input because they wouldn't know this info off hand.

New MsgBox Example: MsgBox "Job Code (" & lJobCode & ") is eligible for this (" & Column H Value for this row & ") cost-center.

I was thinking something like a str variable and reference the column, but I'm having trouble having VBA trigger that value once the row is matched.

Rest of script:

Option Explicit
Sub findJC_CC()

Dim wsData As Worksheet
Dim rFound As Range
Dim lJobCode As String
Dim lCC As String
Dim sFirst As String
Dim matched As Boolean

lJobCode = Application.InputBox("Please provide a job code", "Job Code", Type:=2)
If lJobCode = "False" Then Exit Sub 'Pressed cancel
lCC = Application.InputBox("Please enter in a cost-center", "CC", Type:=2)
If lCC = "False" Then Exit Sub 'Pressed cancel

matched = False
Set wsData = ThisWorkbook.Worksheets("Sheet2")
Set rFound = wsData.Columns("A").Find(lJobCode, wsData.Cells(wsData.Rows.Count, "A"), xlValues, xlWhole)

If Not rFound Is Nothing Then
    sFirst = rFound.Address
    Do

        If rFound.Offset(, 2).Value = lCC Then
            matched = True

            'if criteria is met, display msgbox and exit
            If rFound.Offset(, 4).Value = "Exempt" Then
                MsgBox "The business identified this exempt job as being eligible for schedule pay allowance ."
                Exit Sub
            End If

            'if criteria is met, display msgbox and exit
            If rFound.Offset(, 5).Value = "Eligible - Employee Level" Then
                MsgBox "This job is only eligible at the employee level. If you have further questions, please reach out to your HRBP."
                Exit Sub
            End If

            'if non-exempt role, and matched, display msgbox and exit
            MsgBox "Job Code (" & lJobCode & ") is eligible for this cost-center."
            Exit Sub
        End If

        'loop after first address found until column C has lCC value matched
        Set rFound = wsData.Columns("A").FindNext(rFound)
    Loop While rFound.Address <> sFirst

    'lJobCode value matched, lCC value not matched
    If Not matched Then MsgBox "Job Code (" & lJobCode & ") found, but not eligible for this cost-center."
Else

    'lJobCode not matched
    MsgBox "Job Code (" & lJobCode & ") not eligible."

End If

End Sub

Body:
You can add that line:

Option Explicit
Sub findJC_CC()

Dim wsData As Worksheet
Dim rFound As Range
Dim lJobCode As String
Dim lCC As String
Dim sFirst As String
Dim matched As Boolean

lJobCode = Application.InputBox("Please provide a job code", "Job Code", Type:=2)
If lJobCode = "False" Then Exit Sub 'Pressed cancel
lCC = Application.InputBox("Please enter in a cost-center", "CC", Type:=2)
If lCC = "False" Then Exit Sub 'Pressed cancel

matched = False
Set wsData = ThisWorkbook.Worksheets("Sheet2")
Set rFound = wsData.Columns("A").Find(lJobCode, wsData.Cells(wsData.Rows.Count, "A"), xlValues, xlWhole)

If Not rFound Is Nothing Then
    sFirst = rFound.Address
    Do

        If rFound.Offset(, 2).Value = lCC Then
            matched = True

            'if criteria is met, display msgbox and exit
            If rFound.Offset(, 4).Value = "Exempt" Then
                MsgBox "The business identified this exempt job as being eligible for schedule pay allowance ."
                Exit Sub
            End If

            'if criteria is met, display msgbox and exit
            If rFound.Offset(, 5).Value = "Eligible - Employee Level" Then
                MsgBox "This job is only eligible at the employee level. If you have further questions, please reach out to your HRBP."
                Exit Sub
            End If

            'if non-exempt role, and matched, display msgbox and exit
            MsgBox "Job Code (" & lJobCode & ") is eligible for this (" & rFound.Offset(, 7).Value & ") cost-center."
            Exit Sub
        End If

        'loop after first address found until column C has lCC value matched
        Set rFound = wsData.Columns("A").FindNext(rFound)
    Loop While rFound.Address <> sFirst

    'lJobCode value matched, lCC value not matched
    If Not matched Then MsgBox "Job Code (" & lJobCode & ") found, but not eligible for this cost-center."
Else

    'lJobCode not matched
    MsgBox "Job Code (" & lJobCode & ") not eligible."

End If

End Sub


问:
jQuery - how can I get a value of the next option in a dropdown after the selected one?
I have a drop down with a selected option at index = 0.
How can I in jquery get the value of the next option at index = 1?
Of course I need to do that without specifying the value of the next option because I can;t assume what it will be at this point.

thx

答:
Try:</p>

```<code>$('#selectId>option:selected').next().val()
</code>```

Body:
Try:

$('#selectId>option:selected').next().val()


问:
How to learn content-type of PDF when HTML URL generates download
I am trying to determine if the MIME type of URLs are PDF files or not, using requests content-type.

The below script works fine if the queried URL actually leads to a hosted PDF file. However, with the current URL below, the content-type is detected as text/html; charset=utf-8 even though it results in forcing a web download of a PDF file (the file itself is not readable in Chrome directly from the URL).

```<code>import requests

url = 'https://derinet.vontobel.ch/api/kid?isin=DE000VS0URS6&language=en'

def getContentType(url):
    r = requests.Session().head(url, allow_redirects=True)
    contentType = r.headers['content-type']

    print 'Content type: ' + contentType

    if (contentType == 'application/pdf') | (contentType == 'application/x-pdf'):
        print "content-type is PDF"
    else:
        print "content-type is not PDF!"

getContentType(url)
</code>```

Is there any way of checking the MIME type of the actual resulting PDF download, and not the html page (blob??) that generates it?

I have set allow_redirects=True, but it doesn't seem to matter here.

答:
If instead of making a HEAD request you make a GET, you'll get the header you're looking for:

```<code>$ python
Python 3.7.2 (default, Feb 12 2019, 08:15:36)
[Clang 10.0.0 (clang-1000.11.45.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>> url = 'https://derinet.vontobel.ch/api/kid?isin=DE000VS0URS6&language=en'
>>> r = requests.get(url)
>>> r.headers
{
    'Date': 'Wed, 29 May 2019 14:26:56 GMT',
    'Server': 'Apache',
    'Set-Cookie': 'AL_LB=$xc/70TgziJYWEd9zZwhLxXFDJHocFA0gS9gdbEQS0N0LhFme3uS; Path=/; HTTPOnly; Domain=.vontobel.ch',
    'Content-Length': '51764',
    'Cache-Control': 'private',
    'Content-Disposition': 'attachment; filename=KID_DE000VS0URS6_en.pdf',
    'X-Frame-Options': 'SAMEORIGIN',
    'Pragma': 'blah',
    'Vary': 'User-Agent',
    'Keep-Alive': 'timeout=2, max=500',
    'Connection': 'Keep-Alive',
    'Content-Type': 'application/pdf',
}
</code>```

The difference in the headers is something decided by the server, so I don't think there is a way to get the correct header without a GET request.

Body:
I am trying to determine if the MIME type of URLs are PDF files or not, using requests content-type.

The below script works fine if the queried URL actually leads to a hosted PDF file. However, with the current URL below, the content-type is detected as text/html; charset=utf-8 even though it results in forcing a web download of a PDF file (the file itself is not readable in Chrome directly from the URL).

import requests

url = 'https://derinet.vontobel.ch/api/kid?isin=DE000VS0URS6&language=en'

def getContentType(url):
    r = requests.Session().head(url, allow_redirects=True)
    contentType = r.headers['content-type']

    print 'Content type: ' + contentType

    if (contentType == 'application/pdf') | (contentType == 'application/x-pdf'):
        print "content-type is PDF"
    else:
        print "content-type is not PDF!"

getContentType(url)

Is there any way of checking the MIME type of the actual resulting PDF download, and not the html page (blob??) that generates it?

I have set allow_redirects=True, but it doesn't seem to matter here.

Body:
If instead of making a HEAD request you make a GET, you'll get the header you're looking for:

$ python
Python 3.7.2 (default, Feb 12 2019, 08:15:36)
[Clang 10.0.0 (clang-1000.11.45.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>> url = 'https://derinet.vontobel.ch/api/kid?isin=DE000VS0URS6&language=en'
>>> r = requests.get(url)
>>> r.headers
{
    'Date': 'Wed, 29 May 2019 14:26:56 GMT',
    'Server': 'Apache',
    'Set-Cookie': 'AL_LB=$xc/70TgziJYWEd9zZwhLxXFDJHocFA0gS9gdbEQS0N0LhFme3uS; Path=/; HTTPOnly; Domain=.vontobel.ch',
    'Content-Length': '51764',
    'Cache-Control': 'private',
    'Content-Disposition': 'attachment; filename=KID_DE000VS0URS6_en.pdf',
    'X-Frame-Options': 'SAMEORIGIN',
    'Pragma': 'blah',
    'Vary': 'User-Agent',
    'Keep-Alive': 'timeout=2, max=500',
    'Connection': 'Keep-Alive',
    'Content-Type': 'application/pdf',
}

The difference in the headers is something decided by the server, so I don't think there is a way to get the correct header without a GET request.


问:
Using item-text as a function to customize Vietify v-combobox items
I'd like to customize my combobox items, to as using item-text prop as described here:
https://vuetifyjs.com/en/components/combobox

Here is a fork of a vuetify example where I define a function whick always returns 'test':

```<code>:item-text="() => 'test'"
</code>```

Codepen : https://codepen.io/anon/pen/yWxQdN?editors=1010

Is there a reason why my function is not called?

答:
As said in documentation, "item-text" seems to be used only if items are objects, and not if they are primitives.

When using objects, will look for a text and value field. This can be
  changed using the item-text and item-value props

Body:
I'd like to customize my combobox items, to as using item-text prop as described here:
https://vuetifyjs.com/en/components/combobox

Here is a fork of a vuetify example where I define a function whick always returns 'test':

:item-text="() => 'test'"

Codepen : https://codepen.io/anon/pen/yWxQdN?editors=1010

Is there a reason why my function is not called?


问:
Why template specialization doesn't work in gcc
I'd like to write typelist methods to operate with microcontrollers GPIO's.

I'd like to create list of GPIO's and select only pins of specific port.
So, GetPinWithPort template has specialisation which checks provided type.

template <typename... Ts>
struct tlist
{
    using type = tlist;
};

template <typename T> class debug_t;

#define MAKE_PORT(NAME, ID)\
    class NAME\
    {\
        public:\
        static void Set(uint32_t v) { };\
        static void Reset(uint32_t v) { };\
        enum { id = ID };\
    };

MAKE_PORT(Porta, 'A');
MAKE_PORT(Portb, 'B');

template <class PORT, uint8_t PIN>
class TPin
{
public:
    static void Set() { PORT::Set(1 << PIN); }
    static void Reset() { PORT::Reset(1 << PIN); }

    typedef PORT port;
    enum { pin = PIN };
};

template <class TPort, class T>
struct GetPinWithPort {
    using type = tlist<>;
};

template <typename TPort, uint32_t N>
struct GetPinWithPort<TPort, TPin<TPort, N>>
{
    using type = TPin<TPort, N>;
};

int main()
{

    using pina = GetPinWithPort<Porta, TPin<Porta, 1> >::type;

    // std::cout << typeid(pina).name() << std::endl;  //Visual Studio gives: class TPin<class Porta,1>
    debug_t<pina> d; //gcc output: tlist<>

}
```

Visual Studio gives expected result. But gcc - empty list.
What is wrong here?

答:
In this line using pina = GetPinWithPort<Porta, TPin<Porta, 1> >::type;
1 has the type of int not uint32_t.  So you instantiate GetPinWithPort<Porta, int> (the non-specialized definition), not GetPinWithPort<Porta, uint32_t>.

Here is what the specialization should look like to pass the right template parameter to TPin:

```<code>template <typename TPort, uint8_t N>
struct GetPinWithPort<TPort, TPin<TPort, N>>
{
    using type = TPin<TPort, N>;
};
</code>```

Here is how it should be used:

```<code>using pina = GetPinWithPort<Porta, TPin<Porta, static_cast<uint8_t>(1)> >::type;
</code>```

The reason for this is that C++ is very strict about using types instide of templates: very limited conversion of types is allowed.

Body:
I'd like to write typelist methods to operate with microcontrollers GPIO's.

I'd like to create list of GPIO's and select only pins of specific port.
So, GetPinWithPort template has specialisation which checks provided type.

template <typename... Ts>
struct tlist
{
    using type = tlist;
};

template <typename T> class debug_t;

#define MAKE_PORT(NAME, ID)\
    class NAME\
    {\
        public:\
        static void Set(uint32_t v) { };\
        static void Reset(uint32_t v) { };\
        enum { id = ID };\
    };

MAKE_PORT(Porta, 'A');
MAKE_PORT(Portb, 'B');

template <class PORT, uint8_t PIN>
class TPin
{
public:
    static void Set() { PORT::Set(1 << PIN); }
    static void Reset() { PORT::Reset(1 << PIN); }

    typedef PORT port;
    enum { pin = PIN };
};

template <class TPort, class T>
struct GetPinWithPort {
    using type = tlist<>;
};

template <typename TPort, uint32_t N>
struct GetPinWithPort<TPort, TPin<TPort, N>>
{
    using type = TPin<TPort, N>;
};

int main()
{

    using pina = GetPinWithPort<Porta, TPin<Porta, 1> >::type;

    // std::cout << typeid(pina).name() << std::endl;  //Visual Studio gives: class TPin<class Porta,1>
    debug_t<pina> d; //gcc output: tlist<>

}

Visual Studio gives expected result. But gcc - empty list.
What is wrong here?

Body:
In this line using pina = GetPinWithPort<Porta, TPin<Porta, 1> >::type;
1 has the type of int not uint32_t.  So you instantiate GetPinWithPort<Porta, int> (the non-specialized definition), not GetPinWithPort<Porta, uint32_t>.

Here is what the specialization should look like to pass the right template parameter to TPin:

template <typename TPort, uint8_t N>
struct GetPinWithPort<TPort, TPin<TPort, N>>
{
    using type = TPin<TPort, N>;
};

Here is how it should be used:

using pina = GetPinWithPort<Porta, TPin<Porta, static_cast<uint8_t>(1)> >::type;

The reason for this is that C++ is very strict about using types instide of templates: very limited conversion of types is allowed.