答:
You can get required output by -</p>

```<code>select [item] ,
      [variant descr],[variant order],
      left([variant descr],charindex('/', [variant descr]) - 1) AS [Dim_Colour],
      CASE WHEN [variant order] like '%/SIZE' THEN SUBSTRING([variant descr], CHARINDEX('/', [variant descr]) +1, 100)
       ELSE '' END  AS [Dim_Size],
      CASE WHEN [variant order] like '%/STYLE' THEN SUBSTRING([variant descr], CHARINDEX('/', [variant descr]) +1, 100)
       ELSE '' END  AS [Dim_Style]
    from your_table_name
</code>```

Title: Splitting a string and inserting the parts in the correct columns inside a table

Body:
I am trying to build a fact table with sql server. It currently looks like this:

[Item]  [Variant Descr.] [Variant Order] [Dim_Colour] [Dim_Size] [Dim_Style]
----------------------------------------------------------------------------
01         NAVY/44        COLOUR/SIZE     NULL         NULL       NULL
02         BLACK/S4       COLOUR/STYLE    NULL         NULL       NULL

I need to split the String in [Variant Descr.] and insert the parts into the correct Dim_ Column so the table will eventually look like this:

[Item]  [Variant Descr.] [Variant Order] [Dim_Colour] [Dim_Size] [Dim_Style]
----------------------------------------------------------------------------
01         NAVY/44        COLOUR/SIZE     NAVY         44       NULL
02         BLACK/S4       COLOUR/STYLE    BLACK        NULL     S4

The problem is that the parts of [Variant Order] and the number of parts of [Variant Descr.] may vary for each row. So I basically need to do something like:

Get the String before the '/' in [Variant Descr.]

Get the String before the '/' in [Variant Order]

Insert the first value into the column specified by the second value

Do this for all parts of [Variant Descr.]

Do this for every row in the table

I have already tried to solve this with a user-defined function, only to find out that I cannot use dynamic SQL within a UDF.

Any help would be greatly appreciated

Cheers!

Body:
You can get required output by -

select [item] ,
      [variant descr],[variant order],
      left([variant descr],charindex('/', [variant descr]) - 1) AS [Dim_Colour],
      CASE WHEN [variant order] like '%/SIZE' THEN SUBSTRING([variant descr], CHARINDEX('/', [variant descr]) +1, 100)
       ELSE '' END  AS [Dim_Size],
      CASE WHEN [variant order] like '%/STYLE' THEN SUBSTRING([variant descr], CHARINDEX('/', [variant descr]) +1, 100)
       ELSE '' END  AS [Dim_Style]
    from your_table_name


来源: stackexchange

问:
How can I order a dictionary list by one specified key with some values being None?
There is a list like

```<code>l = [{"n": 1, "m": 3}, {"n": None, "m": 1}, {"n": 3, "m": None}, {"n": None, "m": 0}]
</code>```

And I want to order it by one specified key, n for example.
Besides, some value of the key may be None, and I want to leave them at behind

Here's my trial

```<code>l = [{"n": 1, "m": 3}, {"n": None, "m": 1}, {"n": 3, "m": None}, {"n": None, "m": 0}]

from functools import partial
def order(key, item):
    if item[key]:
        return item[key]
    else:
        return 0
order_key = "n"
r = sorted(l, key=partial(order, order_key), reverse=True)
print(r)
</code>```

Is there a better way to make it happen?

ContentLicense: CC BY-SA 4.0

Body:
There is a list like

l = [{"n": 1, "m": 3}, {"n": None, "m": 1}, {"n": 3, "m": None}, {"n": None, "m": 0}]

And I want to order it by one specified key, n for example.
Besides, some value of the key may be None, and I want to leave them at behind

Here's my trial

l = [{"n": 1, "m": 3}, {"n": None, "m": 1}, {"n": 3, "m": None}, {"n": None, "m": 0}]

from functools import partial
def order(key, item):
    if item[key]:
        return item[key]
    else:
        return 0
order_key = "n"
r = sorted(l, key=partial(order, order_key), reverse=True)
print(r)

Is there a better way to make it happen?

Body:
l = [ {"n":1, "m":3}, {"n":None, "m":1}, {"n":3, "m":None}, {"n":None, "m":0}]
newlist = sorted(l, key=lambda k:  (k['n'] is None, k['n'] == 0, k['n']), reverse = True)
print (newlist)

output:

[{'n': None, 'm': 1}, {'n': None, 'm': 0}, {'n': 3, 'm': None}, {'n': 1, 'm': 3}]


问:
How can i use recursion properly on javascript for making license plates?
I want to know all the combinations for Costa Rica alphanumeric license plates, the format of these license plates are 3 consonants a dash and another 3 numbers (xxx-xxx)

I have already made some outputs of license plates, but I don't know if what I have done is okay

```<code>var letra = "";
var numLetra = 0;
var letras = ["B", "C", "D", "F", "G", "H", "J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "V", "W", "X", "Y", "Z"];
var tempPlaca = [];
var placas = [];
var placa = "";
function getRndInteger() {
    num = Math.floor(Math.random() * (9 - 0 + 1)) + 0;
}
function getRndLetra() {
    numLetra = Math.floor(Math.random() * (21 - 0 + 1)) + 0;
}
generatePlaca();

function generatePlaca() {
    // Genera las letras
    for (var u = 0; u < 3; u++) {
        getRndLetra();
        letra = letras[numLetra];
        tempPlaca.push(letra);
        letra = "";
    }
    tempPlaca.push("-");
    // Genera los numeros
    for (var i = 0; i < 3; i++) {
        getRndInteger();
        tempPlaca.push(num);
    }
    placa = tempPlaca.join("");
    if (findInArray(placas, placa) == false) {
        placas.push(placa);
        tempPlaca = [];
        placa = "";
        generatePlaca();
    }
}
console.log(JSON.stringify(placas));
function findInArray(ar, val) {
    for (var i = 0, len = ar.length; i < len; i++) {
        if (ar[i] === val) {
            return true;
        }
    }
    return false;
}

</code>```

My output:

```<code>["GCT-381","BYG-097","KMV-305","PRZ-046","HFC-147","LQC-268","MZL-631","NVH-843"....
</code>```

And I don't know why in some cases the license plate is not in the right format like this:

```<code>"PB-557","JT-536"
</code>```

答:
You could take the length of the array/string and multiply with it.

I changed the array to a string which works fo a single letter.

var letra = "";
var numLetra = 0;
var letras = "BCDFGHJKLMNPQRSTVWXYZ";
var tempPlaca = [];
var placas = [];
var placa = "";
function getRndInteger() {
    num = Math.floor(Math.random() * 10);
}
function getRndLetra() {
    numLetra = Math.floor(Math.random() * letras.length);
}
generatePlaca();

function generatePlaca() {
    // Genera las letras
    for (var u = 0; u < 3; u++) {
        getRndLetra();
        letra = letras[numLetra];
        tempPlaca.push(letra);
        letra = "";
    }
    tempPlaca.push("-");
    // Genera los numeros
    for (var i = 0; i < 3; i++) {
        getRndInteger();
        tempPlaca.push(num);
    }
    placa = tempPlaca.join("");
    if (findInArray(placas, placa) == false) {
        placas.push(placa);
        tempPlaca = [];
        placa = "";
        generatePlaca();
    }
}
console.log(JSON.stringify(placas));
function findInArray(ar, val) {
    for (var i = 0, len = ar.length; i < len; i++) {
        if (ar[i] === val) {
            return true;
        }
    }
    return false;
}```

Body:
I want to know all the combinations for Costa Rica alphanumeric license plates, the format of these license plates are 3 consonants a dash and another 3 numbers (xxx-xxx)

I have already made some outputs of license plates, but I don't know if what I have done is okay

var letra = "";
var numLetra = 0;
var letras = ["B", "C", "D", "F", "G", "H", "J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "V", "W", "X", "Y", "Z"];
var tempPlaca = [];
var placas = [];
var placa = "";
function getRndInteger() {
    num = Math.floor(Math.random() * (9 - 0 + 1)) + 0;
}
function getRndLetra() {
    numLetra = Math.floor(Math.random() * (21 - 0 + 1)) + 0;
}
generatePlaca();

function generatePlaca() {
    // Genera las letras
    for (var u = 0; u < 3; u++) {
        getRndLetra();
        letra = letras[numLetra];
        tempPlaca.push(letra);
        letra = "";
    }
    tempPlaca.push("-");
    // Genera los numeros
    for (var i = 0; i < 3; i++) {
        getRndInteger();
        tempPlaca.push(num);
    }
    placa = tempPlaca.join("");
    if (findInArray(placas, placa) == false) {
        placas.push(placa);
        tempPlaca = [];
        placa = "";
        generatePlaca();
    }
}
console.log(JSON.stringify(placas));
function findInArray(ar, val) {
    for (var i = 0, len = ar.length; i < len; i++) {
        if (ar[i] === val) {
            return true;
        }
    }
    return false;
}

My output:

["GCT-381","BYG-097","KMV-305","PRZ-046","HFC-147","LQC-268","MZL-631","NVH-843"....

And I don't know why in some cases the license plate is not in the right format like this:

"PB-557","JT-536"


问:
UserManager.CreateAsync does NOT create a new user profile inside my seeding class
For some reason, the 'UserManager' of 'Identity' does not store a new user when using inside my seeding class. Everything else in the seeding class works fine as expected, it is just that 'CreateAsync' method issue. Here is the code:</p>

```<code>public class WorldContextSeedData
{
    private WorldContext _context;
    private UserManager<WorldUser> _userManager;

    public WorldContextSeedData(WorldContext context, UserManager<WorldUser> userManager)
    {
        _context = context;
        _userManager = userManager;
    }

    public async Task EnsureSeedData()
    {
        if (await _userManager.FindByEmailAsync("lucas@test.com") == null)
        {
            //add user
            var newUser = new WorldUser
            {
                UserName = "Lucas",
                Email = "lucas@test.com"
            };

            await _userManager.CreateAsync(newUser, "MyP@ssword!");
        }

        if (!_context.Trips.Any())
        {
            //Add new Data
            var usTrip = new Trip()
            {
                Name = "US Trip",
                CreatedBy = "Lucas",
                Timestamp = DateTime.Now,
                Stops = new List<Stop>()
                {
                    new Stop { Name= "Atlanta, GA", Order = 0},
                    new Stop { Name= "NYC, NY", Order = 1},
                    new Stop { Name= "Tempe, AZ", Order = 2}
                }
            };

            var worldTrip = new Trip()
            {
                Name = "World Trip",
                CreatedBy = "Lucas",
                Timestamp = DateTime.Now,
                Stops = new List<Stop>()
                {
                    new Stop { Name= "Poland", Order = 0},
                    new Stop { Name= "France", Order = 1},
                    new Stop { Name= "Germany", Order = 2}
                }
            };

            _context.Trips.Add(usTrip);
            _context.Stops.AddRange(usTrip.Stops);

            _context.Trips.Add(worldTrip);
            _context.Stops.AddRange(worldTrip.Stops);

            _context.SaveChanges();
        }
    }
}
</code>```

答:
You can Use </p>

```<code>    IdentityResult result = await _userManager.CreateAsync(newUser, "MyP@ssword!");
</code>```

<p>to see what is the problem in result.
IdentityResult contains bool Succeeded for determine how the create going on. and contains Errors Property to show you what goes wrong. </p>

ContentLicense: CC BY-SA 3.0

Body:
For some reason, the 'UserManager' of 'Identity' does not store a new user when using inside my seeding class. Everything else in the seeding class works fine as expected, it is just that 'CreateAsync' method issue. Here is the code:

public class WorldContextSeedData
{
    private WorldContext _context;
    private UserManager<WorldUser> _userManager;

    public WorldContextSeedData(WorldContext context, UserManager<WorldUser> userManager)
    {
        _context = context;
        _userManager = userManager;
    }

    public async Task EnsureSeedData()
    {
        if (await _userManager.FindByEmailAsync("lucas@test.com") == null)
        {
            //add user
            var newUser = new WorldUser
            {
                UserName = "Lucas",
                Email = "lucas@test.com"
            };

            await _userManager.CreateAsync(newUser, "MyP@ssword!");
        }

        if (!_context.Trips.Any())
        {
            //Add new Data
            var usTrip = new Trip()
            {
                Name = "US Trip",
                CreatedBy = "Lucas",
                Timestamp = DateTime.Now,
                Stops = new List<Stop>()
                {
                    new Stop { Name= "Atlanta, GA", Order = 0},
                    new Stop { Name= "NYC, NY", Order = 1},
                    new Stop { Name= "Tempe, AZ", Order = 2}
                }
            };

            var worldTrip = new Trip()
            {
                Name = "World Trip",
                CreatedBy = "Lucas",
                Timestamp = DateTime.Now,
                Stops = new List<Stop>()
                {
                    new Stop { Name= "Poland", Order = 0},
                    new Stop { Name= "France", Order = 1},
                    new Stop { Name= "Germany", Order = 2}
                }
            };

            _context.Trips.Add(usTrip);
            _context.Stops.AddRange(usTrip.Stops);

            _context.Trips.Add(worldTrip);
            _context.Stops.AddRange(worldTrip.Stops);

            _context.SaveChanges();
        }
    }
}

Body:
You can Use

    IdentityResult result = await _userManager.CreateAsync(newUser, "MyP@ssword!");

to see what is the problem in result.
IdentityResult contains bool Succeeded for determine how the create going on. and contains Errors Property to show you what goes wrong.


问:
Is there an implicit default constructor in C++?
In the book I'm reading at the moment (C++ Without Fear) it says that if you don't declare a default constructor for a class, the compiler supplies one for you, which "zeroes out each data member". I've experimented with this, and I'm not seeing any zeroing -out behaviour. I also can't find anything that mentions this on Google. Is this just an error or a quirk of a specific compiler?</p>

答:
C++ does generate a default constructor but only if you don't provide one of your own.  The standard says nothing about zeroing out data members.  By default when you first construct any object, they're undefined.

This might be confusing because most of the C++ primitive types DO have default "constructors" that init them to zero (int(), bool(), double(), long(), etc.), but the compiler doesn't call them to init POD members like it does for object members.

It's worth noting that the STL does use these constructors to default-construct the contents of containers that hold primitive types.  You can take a look at this question for more details on how things in STL containers get inited.

OwnerDisplayName: Skilldrick

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: tgamblin

LastEditorDisplayName: tgamblin


问:
How can we export pdf created in jspdf as an image?
I've created a pdf in my program using jspdf, I'm providing an option to download as image or as pdf, so Can I use jspdf in some way or the pdf I created using jspdf in someway to store it as image?

I

答:
Transform HTML into image first and then into PDF. To turn HTML into image uses the html2canvas and through the addImage method you create the PDF.

Example:

```<code>const html_source = document.getElementById('contentID');   // Get html

 html2canvas(html_source).then(function(canvas) { // Convert to canvas

   let imgData = canvas.toDataURL('image/png'); // Generates image that you can store

   let pdf = new jsPDF('p', 'mm', 'a4'); //Create PDF, Note that you use the same image to create the PDF
   pdf.addImage(imgData, 'PNG', 10, 10);
   pdf.save('test.pdf');
 })
</code>```

Body:
Transform HTML into image first and then into PDF. To turn HTML into image uses the html2canvas and through the addImage method you create the PDF.

Example:

const html_source = document.getElementById('contentID');   // Get html

 html2canvas(html_source).then(function(canvas) { // Convert to canvas

   let imgData = canvas.toDataURL('image/png'); // Generates image that you can store

   let pdf = new jsPDF('p', 'mm', 'a4'); //Create PDF, Note that you use the same image to create the PDF
   pdf.addImage(imgData, 'PNG', 10, 10);
   pdf.save('test.pdf');
 })


问:
Creating a range for a field from internal table using RTTS
I want to create a function/custom class method that takes in 2 parameters:

1) IM_ITAB type ANY TABLE

2) IM_COMPONENT type STRING

and returns 1 parameter:

1) EX_RANGE type PIQ_SELOPT_T

So, algorithm is like this:

First of all, we check if the column with a component name at all exists

Then, we check that internal table is not empty.

Then, we loop through internal table assigning component and filling range table. Code is below.

```<code>METHODS compose_range_from_itab
    IMPORTING
      IM_ITAB      type ANY TABLE
      IM_COMPONENT type STRING
    EXPORTING
      EX_RANGE     type PIQ_SELOPT_T.
...
METHOD compose_range_from_itab.

  DATA: lo_obj   TYPE REF TO cl_abap_tabledescr,
        wa_range TYPE selopt,
        lt_range TYPE piq_selopt_t.

  FIELD-SYMBOLS: <fs_line> TYPE ANY,
                 <fs_component> TYPE ANY.

  lo_obj ?= cl_abap_typedescr=>describe_by_data( p_data = im_itab ).

  READ TABLE lo_obj->key TRANSPORTING NO FIELDS WITH KEY name = im_component.

  IF sy-subrc IS INITIAL.

    IF LINES( im_itab ) GT 0.

      LOOP AT im_itab ASSIGNING <fs_line>.

        ASSIGN COMPONENT im_component OF STRUCTURE <fs_line> TO <fs_component>.

        wa_range-sign = 'I'.
        wa_range-option = 'EQ'.
        wa_range-low = <fs_component>.

        APPEND wa_range TO lt_range.

      ENDLOOP.

      SORT lt_range BY low.
      DELETE ADJACENT DUPLICATES FROM lt_range COMPARING low.

      ex_range[] = lt_range[].

    ENDIF.

  ENDIF.

ENDMETHOD.
</code>```

But I want to improve the method further. If the imported internal table has, let's say, 255 columns, then it will take longer to loop through such table. But I need only one column to compose the range.

So I want to get components of internal table, then choose only one component, create a new line type containing only that component, then create internal table with that line type and copy.

Here is the pseudo code corresponding to what I want to achieve:

```<code>append corresponding fields of im_itab into new_line_type_internal_table.
</code>```

How can I "cut out" one component and create a new line type using RTTS?

答:
I would not go for a Macro.

```<code>Data:
      lr_data type ref to data.

FIELD-SYMBOLS:
      <lv_component> TYPE any,
      <ls_data> TYPE any.

CREATE DATA lr_data LIKE LINE OF im_itab.
ASSIGN lr_data->* TO <ls_data>.

"Check whether im_component exists
ASSIGN COMPONENT im_component OF STRUCTURE <ls_data> TO <lv_component>.

CHECK sy-subrc EQ 0.

LOOP AT im_itab INTO <ls_data>.
  APPEND VALUE #( sign = 'I' option = 'EQ' low = <lv_component> ) TO ex_range.
ENDLOOP.
</code>```

Body:
I want to create a function/custom class method that takes in 2 parameters:

1) IM_ITAB type ANY TABLE

2) IM_COMPONENT type STRING

and returns 1 parameter:

1) EX_RANGE type PIQ_SELOPT_T

So, algorithm is like this:

First of all, we check if the column with a component name at all exists

Then, we check that internal table is not empty.

Then, we loop through internal table assigning component and filling range table. Code is below.

METHODS compose_range_from_itab
    IMPORTING
      IM_ITAB      type ANY TABLE
      IM_COMPONENT type STRING
    EXPORTING
      EX_RANGE     type PIQ_SELOPT_T.
...
METHOD compose_range_from_itab.

  DATA: lo_obj   TYPE REF TO cl_abap_tabledescr,
        wa_range TYPE selopt,
        lt_range TYPE piq_selopt_t.

  FIELD-SYMBOLS: <fs_line> TYPE ANY,
                 <fs_component> TYPE ANY.

  lo_obj ?= cl_abap_typedescr=>describe_by_data( p_data = im_itab ).

  READ TABLE lo_obj->key TRANSPORTING NO FIELDS WITH KEY name = im_component.

  IF sy-subrc IS INITIAL.

    IF LINES( im_itab ) GT 0.

      LOOP AT im_itab ASSIGNING <fs_line>.

        ASSIGN COMPONENT im_component OF STRUCTURE <fs_line> TO <fs_component>.

        wa_range-sign = 'I'.
        wa_range-option = 'EQ'.
        wa_range-low = <fs_component>.

        APPEND wa_range TO lt_range.

      ENDLOOP.

      SORT lt_range BY low.
      DELETE ADJACENT DUPLICATES FROM lt_range COMPARING low.

      ex_range[] = lt_range[].

    ENDIF.

  ENDIF.

ENDMETHOD.

But I want to improve the method further. If the imported internal table has, let's say, 255 columns, then it will take longer to loop through such table. But I need only one column to compose the range.

So I want to get components of internal table, then choose only one component, create a new line type containing only that component, then create internal table with that line type and copy.

Here is the pseudo code corresponding to what I want to achieve:

append corresponding fields of im_itab into new_line_type_internal_table.

How can I "cut out" one component and create a new line type using RTTS?

Body:
I would not go for a Macro.

Data:
      lr_data type ref to data.

FIELD-SYMBOLS:
      <lv_component> TYPE any,
      <ls_data> TYPE any.

CREATE DATA lr_data LIKE LINE OF im_itab.
ASSIGN lr_data->* TO <ls_data>.

"Check whether im_component exists
ASSIGN COMPONENT im_component OF STRUCTURE <ls_data> TO <lv_component>.

CHECK sy-subrc EQ 0.

LOOP AT im_itab INTO <ls_data>.
  APPEND VALUE #( sign = 'I' option = 'EQ' low = <lv_component> ) TO ex_range.
ENDLOOP.


问:
why does this if statement give my a ValueError?
I'm trying to iterate over a numpy 2d array and check where the values 1,2 and 3 occur in the array, but i receive a value error, because numpy states that it's ambiguous. What is the best way to fix this problem?

for x in range(row):
        for y in range(row):
            if grid[x,y] == 1:
                pygame.draw.rect(window, (0,255,0), (x * distance, y * distance, distance, distance))
            elif grid[x,y] == 2:
                pygame.draw.rect(window, (0,255,0), (x * distance, y * distance, distance, distance))
            elif  grid[x,y] == 3:
                pygame.draw.rect(window, (255,0,0), (x * distance, y * distance, distance, distance))
```

``` if grid[x,y] == 1:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
```

答: Try using grid[x][y] instead of grid[x,y]

Body:
I'm trying to iterate over a numpy 2d array and check where the values 1,2 and 3 occur in the array, but i receive a value error, because numpy states that it's ambiguous. What is the best way to fix this problem?

for x in range(row):
        for y in range(row):
            if grid[x,y] == 1:
                pygame.draw.rect(window, (0,255,0), (x * distance, y * distance, distance, distance))
            elif grid[x,y] == 2:
                pygame.draw.rect(window, (0,255,0), (x * distance, y * distance, distance, distance))
            elif  grid[x,y] == 3:
                pygame.draw.rect(window, (255,0,0), (x * distance, y * distance, distance, distance))

 if grid[x,y] == 1:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()


问:
PureConfig ConfigLoader in Scala
I am following this link to use pureconfig to load the data
https://pureconfig.github.io/docs/overriding-behavior-for-case-classes.html.
Here is my code

```<code>import com.typesafe.config.ConfigFactory
import pureconfig._
private case class SampleConf(foo: Int, bar: String)
object TestConfigLoad {
  def main(args: Array[String]): Unit = {
    loadConfig[SampleConf](ConfigFactory.parseString("{ FOO: 2, BAR: two }"))
  }
}
</code>```

When I run it  , I am getting this error

```<code>Error:scalac: Error: scala.collection.immutable.$colon$colon.tl$1()Lscala/collection/immutable/List;
java.lang.NoSuchMethodError: scala.collection.immutable.$colon$colon.tl$1()Lscala/collection/immutable/List;
    at shapeless.LazyMacros$DerivationContext$State.addDependency(lazy.scala:363)
</code>```

These are the entries in the pom file

```<code>        <dependency>
                <groupId>org.scala-lang</groupId>
                <artifactId>scala-library</artifactId>
                     <version>2.11.7</version>
                </dependency>
                <dependency>
                    <groupId>org.scala-tools</groupId>
                    <artifactId>maven-scala-plugin</artifactId>
                    <version>2.15.2</version>
                </dependency>
                <dependency>
                    <groupId>com.github.pureconfig</groupId>
                    <artifactId>pureconfig_2.11</artifactId>
                    <version>0.8.0</version>
                </dependency>
           <dependency>

            <groupId>org.clapper</groupId>
            <artifactId>grizzled-slf4j_2.11</artifactId>
            <version>1.3.3</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.9</version>
        </dependency>

        <dependency>
            <groupId>com.lihaoyi</groupId>
            <artifactId>sourcecode_2.11</artifactId>
            <version>0.1.4</version>
        </dependency>
</code>```

答:
You have to match the Scala versions. Cannot mix 2.10 (scala-library) and 2.11 (pureconfig_2.11).

Unless you have a good reason, use the latest stable version (2.12.8 currently)

Title: PureConfig ConfigLoader in Scala

Body:
I am following this link to use pureconfig to load the data
https://pureconfig.github.io/docs/overriding-behavior-for-case-classes.html.
Here is my code

import com.typesafe.config.ConfigFactory
import pureconfig._
private case class SampleConf(foo: Int, bar: String)
object TestConfigLoad {
  def main(args: Array[String]): Unit = {
    loadConfig[SampleConf](ConfigFactory.parseString("{ FOO: 2, BAR: two }"))
  }
}

When I run it  , I am getting this error

Error:scalac: Error: scala.collection.immutable.$colon$colon.tl$1()Lscala/collection/immutable/List;
java.lang.NoSuchMethodError: scala.collection.immutable.$colon$colon.tl$1()Lscala/collection/immutable/List;
    at shapeless.LazyMacros$DerivationContext$State.addDependency(lazy.scala:363)

These are the entries in the pom file

        <dependency>
                <groupId>org.scala-lang</groupId>
                <artifactId>scala-library</artifactId>
                     <version>2.11.7</version>
                </dependency>
                <dependency>
                    <groupId>org.scala-tools</groupId>
                    <artifactId>maven-scala-plugin</artifactId>
                    <version>2.15.2</version>
                </dependency>
                <dependency>
                    <groupId>com.github.pureconfig</groupId>
                    <artifactId>pureconfig_2.11</artifactId>
                    <version>0.8.0</version>
                </dependency>
           <dependency>

            <groupId>org.clapper</groupId>
            <artifactId>grizzled-slf4j_2.11</artifactId>
            <version>1.3.3</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.9</version>
        </dependency>

        <dependency>
            <groupId>com.lihaoyi</groupId>
            <artifactId>sourcecode_2.11</artifactId>
            <version>0.1.4</version>
        </dependency>


问:
using Gadfly with a conda-installed julia
For a future use in a jupyter context, I want to try julia through a conda installation. To do so I did the following:

```<code>conda create -n test_julia
conda activate test_julia
conda install -c conda-forge julia
</code>```

From there I can start julia. However when trying, for instance, the gadfly module for doing basic test plots, I get the following error:

```<code>julia>using Pkg
julia>Pkg.add("Gadfly")
julia>using Gadfly

Error: Error building `Arpack`:
│ [ Info: Downloading https://github.com/JuliaLinearAlgebra/ArpackBuilder/releases/download/v3.5.0-3/Arpack.v3.5.0-3.x86_64-linux-gnu-gcc7.tar.gz to /home/pellegrini/.julia/packages/Arpack/UiiMc/deps/usr/downloads/Arpack.v3.5.0-3.x86_64-linux-gnu-gcc7.tar.gz...
│ ERROR: LoadError: LibraryProduct(nothing, ["libarpack"], :libarpack, "Prefix(/home/pellegrini/.julia/packages/Arpack/UiiMc/deps/usr)") is not satisfied, cannot generate deps.jl!
│ Stacktrace:
│  [1] error(::String) at ./error.jl:33
│  [2] #write_deps_file#152(::Bool, ::Function, ::String, ::Array{LibraryProduct,1}) at /home/pellegrini/.julia/packages/BinaryProvider/4F5Hq/src/Products.jl:414
│  [3] (::getfield(BinaryProvider, Symbol("#kw##write_deps_file")))(::NamedTuple{(:verbose,),Tuple{Bool}}, ::typeof(write_deps_file), ::String, ::Array{LibraryProduct,1}) at ./none:0
│  [4] top-level scope at none:0
│  [5] include at ./boot.jl:317 [inlined]
│  [6] include_relative(::Module, ::String) at ./loading.jl:1044
│  [7] include(::Module, ::String) at ./sysimg.jl:29
│  [8] include(::String) at ./client.jl:392
│  [9] top-level scope at none:0
│ in expression starting at /home/pellegrini/.julia/packages/Arpack/UiiMc/deps/build.jl:74
</code>```

I read that this problem could be due to the use of a julia built from source.
I suppose that it is not the case when using a conda installation. Being a bit new to conda and julia, I can't find why I have this error and how to solve it. Would you have any idea ?

答:
It sounds like it might be this known issue. Based on the discussion of this issue I fixed it on my machine by installing openblas and adding this link:

```<code>ln -s /usr/lib/libopenblas.so /usr/lib/libopenblas64_.so.0
</code>```

(Note that I'm not using conda, I was using the standard Arch package.)

Body:
For a future use in a jupyter context, I want to try julia through a conda installation. To do so I did the following:

conda create -n test_julia
conda activate test_julia
conda install -c conda-forge julia

From there I can start julia. However when trying, for instance, the gadfly module for doing basic test plots, I get the following error:

julia>using Pkg
julia>Pkg.add("Gadfly")
julia>using Gadfly

Error: Error building `Arpack`:
│ [ Info: Downloading https://github.com/JuliaLinearAlgebra/ArpackBuilder/releases/download/v3.5.0-3/Arpack.v3.5.0-3.x86_64-linux-gnu-gcc7.tar.gz to /home/pellegrini/.julia/packages/Arpack/UiiMc/deps/usr/downloads/Arpack.v3.5.0-3.x86_64-linux-gnu-gcc7.tar.gz...
│ ERROR: LoadError: LibraryProduct(nothing, ["libarpack"], :libarpack, "Prefix(/home/pellegrini/.julia/packages/Arpack/UiiMc/deps/usr)") is not satisfied, cannot generate deps.jl!
│ Stacktrace:
│  [1] error(::String) at ./error.jl:33
│  [2] #write_deps_file#152(::Bool, ::Function, ::String, ::Array{LibraryProduct,1}) at /home/pellegrini/.julia/packages/BinaryProvider/4F5Hq/src/Products.jl:414
│  [3] (::getfield(BinaryProvider, Symbol("#kw##write_deps_file")))(::NamedTuple{(:verbose,),Tuple{Bool}}, ::typeof(write_deps_file), ::String, ::Array{LibraryProduct,1}) at ./none:0
│  [4] top-level scope at none:0
│  [5] include at ./boot.jl:317 [inlined]
│  [6] include_relative(::Module, ::String) at ./loading.jl:1044
│  [7] include(::Module, ::String) at ./sysimg.jl:29
│  [8] include(::String) at ./client.jl:392
│  [9] top-level scope at none:0
│ in expression starting at /home/pellegrini/.julia/packages/Arpack/UiiMc/deps/build.jl:74

I read that this problem could be due to the use of a julia built from source.
I suppose that it is not the case when using a conda installation. Being a bit new to conda and julia, I can't find why I have this error and how to solve it. Would you have any idea ?

Body:
It sounds like it might be this known issue. Based on the discussion of this issue I fixed it on my machine by installing openblas and adding this link:

ln -s /usr/lib/libopenblas.so /usr/lib/libopenblas64_.so.0

(Note that I'm not using conda, I was using the standard Arch package.)


问:
Amazon S3 link expiration during download?
Does anyone know what happens if an Amazon S3 link expires during the download process? I'm using S3 to offer downloads of a 1.6gig file but I want to set the shortest expiration time possible, somewhere in the neighbourhood of 15 minutes.

If the download is initiated within the 15 minute period, but the download itself takes 1 or 2 hours will that be an issue? I'm assuming once the download is initiated everything is fine right?

答:
Any downloads initiated before the expiry time will continue to work.

Just be aware that you may run into problems with some file downloaders that attempt to download multiple segments at once. The downloader may not be able to begin new segments after the expiry time and the user may not be able to pause/resume downloads.


问:
Forgot password UI is not working properly in laravel
I am using laravel default authentication my Forgot password page UI is not working maybe there is something missing in JS or CSS files:

Here is my HTML view of ForgotPassword and by default laravel us using @extends(layouts.app) and @section('content') but things are not working properly your help needs here.

```<code>              @extends('layouts.app')
           @section('content')
        <div class="container">
       <div class="row">
    <div class="col-md-8 col-md-offset-2">
        <div class="panel panel-default">
                <div class="container">
                    <div class="row">
                        <div class="col-md-8 col-md-offset-2">
                            <div class="panel panel-default">

            <div class="panel-heading">Reset Password</div>

                                <div class="panel-body">
                <form class="form-horizontal" method="POST" action="{{ route('password.request') }}">
                    {{ csrf_field() }}

                    <input type="hidden" name="token" value="{{ $token }}">

                    <div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
                        <label for="email" class="col-md-4 control-label">E-Mail Address</label>

                        <div class="col-md-6">
                            <input id="email" type="email" class="form-control" name="email" value="{{ $email or old('email') }}" required autofocus>

                            @if ($errors->has('email'))
                                <span class="help-block">
                                    <strong>{{ $errors->first('email') }}</strong>
                                </span>
                            @endif
                        </div>
                    </div>

                    <div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}">
                        <label for="password" class="col-md-4 control-label">Password</label>

                        <div class="col-md-6">
                            <input id="password" type="password" class="form-control" name="password" required>

                            @if ($errors->has('password'))
                                <span class="help-block">
                                    <strong>{{ $errors->first('password') }}</strong>
                                </span>
                            @endif
                        </div>
                    </div>

                    <div class="form-group{{ $errors->has('password_confirmation') ? ' has-error' : '' }}">
                        <label for="password-confirm" class="col-md-4 control-label">Confirm Password</label>
                        <div class="col-md-6">
                            <input id="password-confirm" type="password" class="form-control" name="password_confirmation" required>

                            @if ($errors->has('password_confirmation'))
                                <span class="help-block">
                <strong>{{ $errors->first('password_confirmation') }}</strong>
            </span>
                            @endif
                        </div>
                    </div>

                            @if ($errors->has('password_confirmation'))
                                <span class="help-block">
                                    <strong>{{ $errors->first('password_confirmation') }}</strong>
                                </span>
                            @endif
                        </div>
                    </div>

                    <div class="form-group">
                        <div class="col-md-6 col-md-offset-4">
                            <button type="submit" class="btn btn-primary">
                                Reset Password
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
</code>```

     @endsection

I dont know what is wrong here i am also attaching the screen shot of my page UI.

答:
Please check your "network" tab in Chrome Dev-Tools (or similar). You should find that the app.css file is not loaded, and you should debug that error.

Please make sure also that in your resources/views/layouts/app.blade.php file a .css file is loaded somewhere in the head of the page. And make sure that file exists in the public directory of your project.

Body:
I am using laravel default authentication my Forgot password page UI is not working maybe there is something missing in JS or CSS files:

Here is my HTML view of ForgotPassword and by default laravel us using @extends(layouts.app) and @section('content') but things are not working properly your help needs here.

              @extends('layouts.app')
           @section('content')

Reset Password

                <form class="form-horizontal" method="POST" action="{{ route('password.request') }}">
                    {{ csrf_field() }}

                    <input type="hidden" name="token" value="{{ $token }}">

has('email') ? ' has-error' : '' }}">
                        E-Mail Address

                            <input id="email" type="email" class="form-control" name="email" value="{{ $email or old('email') }}" required autofocus>

                            @if ($errors->has('email'))

                                    {{ $errors->first('email') }}

                            @endif

has('password') ? ' has-error' : '' }}">
                        Password

                            <input id="password" type="password" class="form-control" name="password" required>

                            @if ($errors->has('password'))

                                    {{ $errors->first('password') }}

                            @endif

has('password_confirmation') ? ' has-error' : '' }}">
                        Confirm Password

                            <input id="password-confirm" type="password" class="form-control" name="password_confirmation" required>

                            @if ($errors->has('password_confirmation'))

                {{ $errors->first('password_confirmation') }}

                            @endif

                            @if ($errors->has('password_confirmation'))

                                    {{ $errors->first('password_confirmation') }}

                            @endif

                            <button type="submit" class="btn btn-primary">
                                Reset Password
                            </button>

                </form>

     @endsection

I dont know what is wrong here i am also attaching the screen shot of my page UI.


问:
How can I format a String number to have commas in android Edit Field
For what function I can use in android to display the number into different formats.

For eg:
If I enter 1000 then it should display like this 1,000.
If I enter 10000 then it should display like this 10,000.
If I enter 1000000 then it should display like this 1,000,000.

Please guide me.

答:
```<code>public static String formatNumber(int number){
    return NumberFormat.getNumberInstance(Locale.getDefault()).format(number);
}
public static String formatNumber(String number){
    return NumberFormat.getNumberInstance(Locale.getDefault()).format(Integer.parseInt(number));
}
</code>```


问:
How to select most recent record from a group of records that have the same datetime?
So I have some records that I'm trying to display in a graph. Currently if some records have the same datetime then they get grouped in the graph which is kind of what I want, but the graph shows the sum of these records instead of the last record but I'm just not sure on how to achieve this.

SUM(TAB.Amount) OVER(PARTITION BY TAB.AccountID  order by TAB.AccountID, TransactionValueDate, StatementNumber, SequenceNumber, TAB.RecordID) AS [IntraDayBalance]

This is the code I use to get these records which works perfect in the table but I can't use this in the graph as like I said it sums the records. So would there be a way to take the last record from this column that have the same datetime.

Not sure how to format this but this is an example. Let's say I have 3 records (532255.20 , 2199722.65 and 1995722.65) that have the exact same datetime (16/04/2019 06:41:04). Currently at this datetime point the graph shows me the summed figure of these records (4727700.50) but what I actually want it to show is the last record (1995722.65).

What I'm asking then is how would I display this last record instead of the summed amount. Keep in mind I can't change the line of code shown above as it works perfect for it's original use just not for the graph so another line will be needed for the graph, I just have no idea how to do it myself. Any help would be much appreciated!

EDIT: Thank you for your help. I feel like an idiot right now but I'm just unable to incorporate either of these statements into my code. I'm still quite new to T-SQL and still learning how to format code properly and where things go but this is my SELECT statement, any tips on how to incorporate either of these statements into this code would be very helpful!

```<code>        ,TAB.AccountID
        ,TAB.Amount
        ,AC.ShortName
        ,FX.FXRate
        ,FX.IsDivide
        ,CASE
            WHEN FXRate IS NOT NULL AND FXRate <> 0 THEN
                CASE
                    WHEN FX.IsDivide = 0 THEN
                        ROUND(TAB.Amount / FXRate,2)
                    ELSE
                        ROUND(TAB.Amount * FXRate,2)
                END
            ELSE
                0
        END AS BalanceUSD
        ,ITS.LimitAmount
        ,ITS.FloorAmount
        ,CR.SwiftCode AS Ccy
        ,TAB.RecordType
        ,AC.AccountNumber
        ,AC.BankFileIdentifier AS Accountidentifier
        ,DV.ShortName AS Division
        ,CP.ShortName AS Counterparty
        ,TAB.Amount
        ,SUM(TAB.Amount) OVER(PARTITION BY TAB.AccountID  order by TAB.AccountID, TransactionValueDate, StatementNumber, SequenceNumber, TAB.RecordID) AS [IntraDayBalance]
        ,CAST(29218 + TransactionValueDate AS DATETIME) AS TransactionValueDate
        ,CAST(29218 + TransactionEntryDate AS DATETIME) AS TransactionEntryDate
        ,CASE
            WHEN TransactionFlow = 0 THEN
                TransactionAmount
            ELSE
                -TransactionAmount
        END AS TransactionAmount
        ,CASE
            WHEN ITS.TransactionFlow = 0 THEN
                ITS.TransactionAmount
            ELSE
                0
        END AS Inflow
        ,CASE
            WHEN ITS.TransactionFlow = 1 THEN
                ITS.TransactionAmount
            ELSE
                0
        END AS Outflow
        ,TransactionFlow
        ,TransactionCode
        ,CustomerReference
        ,BankReference
        ,Right(RTRIM('0000000000' + CAST(StatementNumber AS CHAR (20))), 10) AS StatementNumber
        ,RTRIM(CAST(ITS.SequenceNumber AS CHAR (20))) AS SequenceNumber
        ,CAST(29218 + StatementDate AS DATETIME) AS StatementDate
        --,DATEADD(SECOND,ImportedByTime,CAST(29218 + StatementDate AS DATETIME))  AS StatementDateTime
        ,CASE
            WHEN TAB.RecordType = 'B' THEN
                @StartDate
            ELSE
                DATEADD(SECOND,ImportedByTime,CAST(29218 + StatementDate AS DATETIME))
        END AS StatementDateTime
        ,InformationToAccountOwner
        ,Information1
        ,Information2
        ,Information3
        ,Information4
        ,Information5
        ,Information6
        ,ImportedBy
        ,CAST(29218 + ImportedByDate AS DATETIME) AS ImportedByDate
        ,CASE
            WHEN TAB.RecordType = 'B' THEN
                @StartDate
            ELSE
                DATEADD(SECOND,ImportedByTime,CAST(29218 + ImportedByDate AS DATETIME))
        END AS ImportDateTime
        ,@StartDate AS StartDate
        ,@EndDate AS EndDate
        ,ITS.DebitAmount
        ,ITS.CreditAmount
        ,ITS.FloorAmount
        ,ITS.LimitAmount
        ,ITS.RecordID

FROM CTE_TransactionsAndBalances AS TAB

LEFT OUTER JOIN
    InterimTransactionStatement AS ITS ON TAB.RecordID = ITS.RecordID

LEFT OUTER JOIN
    Accounts AS AC ON TAB.AccountID = AC.ACRecordID

LEFT OUTER JOIN
    Currencies AS CR ON AC.CurrencyID = CR.CRRecordID

LEFT OUTER JOIN
    Divisions AS DV ON AC.DivisionID = DV.DVRecordID

LEFT OUTER JOIN
    Counterparties AS CP ON AC.CounterpartyID = CP.CPRecordID

LEFT OUTER JOIN
    @tbl_FXRates AS FX ON AC.CurrencyID = FX.FromCcyID
    AND FXRateDateN >= FX.StartDateN
    AND FXRateDateN <= FX.EndDateN
    AND FX.ToCcyID = @ReportingCcyID

--WHERE AC.ACRecordID = 94
 order by TAB.AccountID, TransactionValueDate, StatementNumber, SequenceNumber, TAB.RecordID ```
```

答:
use subquery and row_numberr()

```<code>select * from ( select
SUM(TAB.Amount) OVER(PARTITION BY TAB.AccountID  order by TAB.AccountID, TransactionValueDate, StatementNumber, SequenceNumber, TAB.RecordID) AS [IntraDayBalance],
row_number() over(partition by TAB.AccountID order by TransactionValueDate desc) rn
from table
) a where a.rn=1
</code>```

Body:
So I have some records that I'm trying to display in a graph. Currently if some records have the same datetime then they get grouped in the graph which is kind of what I want, but the graph shows the sum of these records instead of the last record but I'm just not sure on how to achieve this.

SUM(TAB.Amount) OVER(PARTITION BY TAB.AccountID  order by TAB.AccountID, TransactionValueDate, StatementNumber, SequenceNumber, TAB.RecordID) AS [IntraDayBalance]

This is the code I use to get these records which works perfect in the table but I can't use this in the graph as like I said it sums the records. So would there be a way to take the last record from this column that have the same datetime.

Not sure how to format this but this is an example. Let's say I have 3 records (532255.20 , 2199722.65 and 1995722.65) that have the exact same datetime (16/04/2019 06:41:04). Currently at this datetime point the graph shows me the summed figure of these records (4727700.50) but what I actually want it to show is the last record (1995722.65).

What I'm asking then is how would I display this last record instead of the summed amount. Keep in mind I can't change the line of code shown above as it works perfect for it's original use just not for the graph so another line will be needed for the graph, I just have no idea how to do it myself. Any help would be much appreciated!

EDIT: Thank you for your help. I feel like an idiot right now but I'm just unable to incorporate either of these statements into my code. I'm still quite new to T-SQL and still learning how to format code properly and where things go but this is my SELECT statement, any tips on how to incorporate either of these statements into this code would be very helpful!

        ,TAB.AccountID
        ,TAB.Amount
        ,AC.ShortName
        ,FX.FXRate
        ,FX.IsDivide
        ,CASE
            WHEN FXRate IS NOT NULL AND FXRate <> 0 THEN
                CASE
                    WHEN FX.IsDivide = 0 THEN
                        ROUND(TAB.Amount / FXRate,2)
                    ELSE
                        ROUND(TAB.Amount * FXRate,2)
                END
            ELSE
                0
        END AS BalanceUSD
        ,ITS.LimitAmount
        ,ITS.FloorAmount
        ,CR.SwiftCode AS Ccy
        ,TAB.RecordType
        ,AC.AccountNumber
        ,AC.BankFileIdentifier AS Accountidentifier
        ,DV.ShortName AS Division
        ,CP.ShortName AS Counterparty
        ,TAB.Amount
        ,SUM(TAB.Amount) OVER(PARTITION BY TAB.AccountID  order by TAB.AccountID, TransactionValueDate, StatementNumber, SequenceNumber, TAB.RecordID) AS [IntraDayBalance]
        ,CAST(29218 + TransactionValueDate AS DATETIME) AS TransactionValueDate
        ,CAST(29218 + TransactionEntryDate AS DATETIME) AS TransactionEntryDate
        ,CASE
            WHEN TransactionFlow = 0 THEN
                TransactionAmount
            ELSE
                -TransactionAmount
        END AS TransactionAmount
        ,CASE
            WHEN ITS.TransactionFlow = 0 THEN
                ITS.TransactionAmount
            ELSE
                0
        END AS Inflow
        ,CASE
            WHEN ITS.TransactionFlow = 1 THEN
                ITS.TransactionAmount
            ELSE
                0
        END AS Outflow
        ,TransactionFlow
        ,TransactionCode
        ,CustomerReference
        ,BankReference
        ,Right(RTRIM('0000000000' + CAST(StatementNumber AS CHAR (20))), 10) AS StatementNumber
        ,RTRIM(CAST(ITS.SequenceNumber AS CHAR (20))) AS SequenceNumber
        ,CAST(29218 + StatementDate AS DATETIME) AS StatementDate
        --,DATEADD(SECOND,ImportedByTime,CAST(29218 + StatementDate AS DATETIME))  AS StatementDateTime
        ,CASE
            WHEN TAB.RecordType = 'B' THEN
                @StartDate
            ELSE
                DATEADD(SECOND,ImportedByTime,CAST(29218 + StatementDate AS DATETIME))
        END AS StatementDateTime
        ,InformationToAccountOwner
        ,Information1
        ,Information2
        ,Information3
        ,Information4
        ,Information5
        ,Information6
        ,ImportedBy
        ,CAST(29218 + ImportedByDate AS DATETIME) AS ImportedByDate
        ,CASE
            WHEN TAB.RecordType = 'B' THEN
                @StartDate
            ELSE
                DATEADD(SECOND,ImportedByTime,CAST(29218 + ImportedByDate AS DATETIME))
        END AS ImportDateTime
        ,@StartDate AS StartDate
        ,@EndDate AS EndDate
        ,ITS.DebitAmount
        ,ITS.CreditAmount
        ,ITS.FloorAmount
        ,ITS.LimitAmount
        ,ITS.RecordID

FROM CTE_TransactionsAndBalances AS TAB

LEFT OUTER JOIN
    InterimTransactionStatement AS ITS ON TAB.RecordID = ITS.RecordID

LEFT OUTER JOIN
    Accounts AS AC ON TAB.AccountID = AC.ACRecordID

LEFT OUTER JOIN
    Currencies AS CR ON AC.CurrencyID = CR.CRRecordID

LEFT OUTER JOIN
    Divisions AS DV ON AC.DivisionID = DV.DVRecordID

LEFT OUTER JOIN
    Counterparties AS CP ON AC.CounterpartyID = CP.CPRecordID

LEFT OUTER JOIN
    @tbl_FXRates AS FX ON AC.CurrencyID = FX.FromCcyID
    AND FXRateDateN >= FX.StartDateN
    AND FXRateDateN <= FX.EndDateN
    AND FX.ToCcyID = @ReportingCcyID

--WHERE AC.ACRecordID = 94
 order by TAB.AccountID, TransactionValueDate, StatementNumber, SequenceNumber, TAB.RecordID ```

Body:
use subquery and row_numberr()

select * from ( select
SUM(TAB.Amount) OVER(PARTITION BY TAB.AccountID  order by TAB.AccountID, TransactionValueDate, StatementNumber, SequenceNumber, TAB.RecordID) AS [IntraDayBalance],
row_number() over(partition by TAB.AccountID order by TransactionValueDate desc) rn
from table
) a where a.rn=1


问:
ASP.NET - ADFS authentication hook
I have an ASP.NET web API that authenticates against the ADFS server. The Authentication startup class is defined as below:

```<code>public void ConfigureAuth(IAppBuilder app)

{

    app.UseCookieAuthentication(
        new CookieAuthenticationOptions
        {
        AuthenticationType = WsFederationAuthenticationDefaults.AuthenticationType
        });

    app.UseWsFederationAuthentication(
        new WsFederationAuthenticationOptions
        {
            MetadataAddress = ConfigurationManager.AppSettings["ADFSMetadata"],
            Wtrealm = ConfigurationManager.AppSettings["Wtrealm"]
        });

    app.SetDefaultSignInAsAuthenticationType(WsFederationAuthenticationDefaults.AuthenticationType);

}
</code>```

What I want is that when a user is successfully authenticated by the ADFS and the token is returned back, a user record in my SQL database should be created if the email found in the claim returned by ADFS does not exist in the database already.

Is there some way to intercept the response straight after the authentication to achieve the above task?

答:
I have found a solution. The WsFederationAuthenticationOptions class has a Notification property which can be used to hook the authentication success and failure responses.

For example

```<code>public void ConfigureAuth(IAppBuilder app)

{

    app.UseCookieAuthentication(
        new CookieAuthenticationOptions
        {
        AuthenticationType = WsFederationAuthenticationDefaults.AuthenticationType
        });

    app.UseWsFederationAuthentication(
        new WsFederationAuthenticationOptions
        {
            MetadataAddress = ConfigurationManager.AppSettings["ADFSMetadata"],
            Wtrealm = ConfigurationManager.AppSettings["Wtrealm"],
            Notifications = new WsFederationAuthenticationNotifications
            {
                AuthenticationFailed = context =>
                {
                    context.HandleResponse();
                    context.Response.Redirect("/Error?message=" + context.Exception.Message);
                    return Task.FromResult(0);
                },
                SecurityTokenReceived = context =>
                {
                    // Get the token
                    var token = context.ProtocolMessage.GetToken();
                    return Task.FromResult(0);
                }
            }
        });

    app.SetDefaultSignInAsAuthenticationType(WsFederationAuthenticationDefaults.AuthenticationType);

}
</code>```

Title: ASP.NET - ADFS authentication hook

Body:
I have an ASP.NET web API that authenticates against the ADFS server. The Authentication startup class is defined as below:

public void ConfigureAuth(IAppBuilder app)

{

    app.UseCookieAuthentication(
        new CookieAuthenticationOptions
        {
        AuthenticationType = WsFederationAuthenticationDefaults.AuthenticationType
        });

    app.UseWsFederationAuthentication(
        new WsFederationAuthenticationOptions
        {
            MetadataAddress = ConfigurationManager.AppSettings["ADFSMetadata"],
            Wtrealm = ConfigurationManager.AppSettings["Wtrealm"]
        });

    app.SetDefaultSignInAsAuthenticationType(WsFederationAuthenticationDefaults.AuthenticationType);

}

What I want is that when a user is successfully authenticated by the ADFS and the token is returned back, a user record in my SQL database should be created if the email found in the claim returned by ADFS does not exist in the database already.

Is there some way to intercept the response straight after the authentication to achieve the above task?

Body:
I have found a solution. The WsFederationAuthenticationOptions class has a Notification property which can be used to hook the authentication success and failure responses.

For example

public void ConfigureAuth(IAppBuilder app)

{

    app.UseCookieAuthentication(
        new CookieAuthenticationOptions
        {
        AuthenticationType = WsFederationAuthenticationDefaults.AuthenticationType
        });

    app.UseWsFederationAuthentication(
        new WsFederationAuthenticationOptions
        {
            MetadataAddress = ConfigurationManager.AppSettings["ADFSMetadata"],
            Wtrealm = ConfigurationManager.AppSettings["Wtrealm"],
            Notifications = new WsFederationAuthenticationNotifications
            {
                AuthenticationFailed = context =>
                {
                    context.HandleResponse();
                    context.Response.Redirect("/Error?message=" + context.Exception.Message);
                    return Task.FromResult(0);
                },
                SecurityTokenReceived = context =>
                {
                    // Get the token
                    var token = context.ProtocolMessage.GetToken();
                    return Task.FromResult(0);
                }
            }
        });

    app.SetDefaultSignInAsAuthenticationType(WsFederationAuthenticationDefaults.AuthenticationType);

}


问:
Angular: how to make localStorage works async
I trying to get data when I log in, by sending ID from localStorage. Everything I tried didn't work, and the only thing comes to my mind is that getting ID from local storage works synchronously. I hope someone can help me make it async. Unfortunately, I don't have permission to show API here. The code:

auth.service.ts

```<code>import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse, HttpHeaders, HttpParams } from '@angular/common/http';
import { throwError, Observable } from 'rxjs';
import { map, catchError } from 'rxjs/operators';

import { Restaurant } from '../models/Restaurant';
import { LocalStorage } from '@ngx-pwa/local-storage';

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  loginUrl = 'xxxxxxxxxx';
  errorData: {};

  constructor(private http: HttpClient) { }

  redirectUrl: string;

  login(email: string, password: string) {
    var postData = {email: email, password: password};
    return this.http.post<Restaurant>(this.loginUrl, postData)
    .pipe(map(restaurant => {
        if (restaurant) {
          localStorage.setItem('currentRestaurant', JSON.stringify(restaurant));
          return  restaurant;
        }
      }),
      catchError(this.handleError)
    );
  }

  isLoggedIn() {
    if (localStorage.getItem('currentRestaurant')) {
      return true;
    }
      return false;
  }

  getAuthorizationToken() {
    const currentRestaurant = JSON.parse(localStorage.getItem('currentRestaurant'));
    return currentRestaurant.token;
  }

  logout() {
    localStorage.removeItem('currentRestaurant');
  }

  private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {

      // A client-side or network error occurred. Handle it accordingly.
      console.error('An error occurred:', error.error.message);
    } else {

      // The backend returned an unsuccessful response code.
      // The response body may contain clues as to what went wrong.
      console.error(`Backend returned code ${error.status}, ` + `body was: ${error.error}`);
    }

    // return an observable with a user-facing error message
    this.errorData = {
      errorTitle: 'Oops! Request for document failed',
      errorDesc: 'Something bad happened. Please try again later.'
    };
    return throwError(this.errorData);
  }

  currRestaurant: Restaurant = JSON.parse(localStorage.getItem('currentRestaurant'));
  currID = this. currRestaurant.id;
}
</code>```

login.component.ts

```<code>import { Component, OnInit } from '@angular/core';
import { FormBuilder, Validators, FormGroup } from '@angular/forms';
import { Router } from '@angular/router';
import { AuthService } from '../services/auth.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {

  loginForm: FormGroup;
  submitted = false;
  returnUrl: string;
  error: {};
  loginError: string;

  constructor(
    private fb: FormBuilder,
    private router: Router,
    private authService: AuthService
    ) { }

  ngOnInit() {
    this.loginForm = this.fb.group({
      email: ['', Validators.required],
      password: ['', Validators.required]
    });

    this.authService.logout();
  }

  get email() { return this.loginForm.get('email'); }
  get password() { return this.loginForm.get('password'); }

  onSubmit() {
    this.submitted = true;
    this.authService.login( this.email.value, this.password.value).subscribe((data) => {

       if (this.authService.isLoggedIn) {
            const redirect = this.authService.redirectUrl ? this.authService.redirectUrl : '/';
                this.router.navigate([redirect]);
      } else {
            this.loginError = 'email or password is incorrect.';
    }
      },
      error => this.error = error
    );

  }

}

</code>```

Thanks everyone for their time

答:
There are some mistakes:

Are you aware that you use Native localStorage, not the one you import - import { LocalStorage } from '@ngx-pwa/local-storage'; (and also it should be injected in the constructor if you want to use it, and used in asynchronous way)

if (this.authService.isLoggedIn) { will always be true, because this.authService.isLoggedIn is a function and it is not a falsy value. You probably want to execute it - if (this.authService.isLoggedIn()) {

redirectUrl is always undefined because your provided snippets does not assign it any value.

Body:
I trying to get data when I log in, by sending ID from localStorage. Everything I tried didn't work, and the only thing comes to my mind is that getting ID from local storage works synchronously. I hope someone can help me make it async. Unfortunately, I don't have permission to show API here. The code:

auth.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse, HttpHeaders, HttpParams } from '@angular/common/http';
import { throwError, Observable } from 'rxjs';
import { map, catchError } from 'rxjs/operators';

import { Restaurant } from '../models/Restaurant';
import { LocalStorage } from '@ngx-pwa/local-storage';

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  loginUrl = 'xxxxxxxxxx';
  errorData: {};

  constructor(private http: HttpClient) { }

  redirectUrl: string;

  login(email: string, password: string) {
    var postData = {email: email, password: password};
    return this.http.post<Restaurant>(this.loginUrl, postData)
    .pipe(map(restaurant => {
        if (restaurant) {
          localStorage.setItem('currentRestaurant', JSON.stringify(restaurant));
          return  restaurant;
        }
      }),
      catchError(this.handleError)
    );
  }

  isLoggedIn() {
    if (localStorage.getItem('currentRestaurant')) {
      return true;
    }
      return false;
  }

  getAuthorizationToken() {
    const currentRestaurant = JSON.parse(localStorage.getItem('currentRestaurant'));
    return currentRestaurant.token;
  }

  logout() {
    localStorage.removeItem('currentRestaurant');
  }

  private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {

      // A client-side or network error occurred. Handle it accordingly.
      console.error('An error occurred:', error.error.message);
    } else {

      // The backend returned an unsuccessful response code.
      // The response body may contain clues as to what went wrong.
      console.error(`Backend returned code ${error.status}, ` + `body was: ${error.error}`);
    }

    // return an observable with a user-facing error message
    this.errorData = {
      errorTitle: 'Oops! Request for document failed',
      errorDesc: 'Something bad happened. Please try again later.'
    };
    return throwError(this.errorData);
  }

  currRestaurant: Restaurant = JSON.parse(localStorage.getItem('currentRestaurant'));
  currID = this. currRestaurant.id;
}

login.component.ts

import { Component, OnInit } from '@angular/core';
import { FormBuilder, Validators, FormGroup } from '@angular/forms';
import { Router } from '@angular/router';
import { AuthService } from '../services/auth.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {

  loginForm: FormGroup;
  submitted = false;
  returnUrl: string;
  error: {};
  loginError: string;

  constructor(
    private fb: FormBuilder,
    private router: Router,
    private authService: AuthService
    ) { }

  ngOnInit() {
    this.loginForm = this.fb.group({
      email: ['', Validators.required],
      password: ['', Validators.required]
    });

    this.authService.logout();
  }

  get email() { return this.loginForm.get('email'); }
  get password() { return this.loginForm.get('password'); }

  onSubmit() {
    this.submitted = true;
    this.authService.login( this.email.value, this.password.value).subscribe((data) => {

       if (this.authService.isLoggedIn) {
            const redirect = this.authService.redirectUrl ? this.authService.redirectUrl : '/';
                this.router.navigate([redirect]);
      } else {
            this.loginError = 'email or password is incorrect.';
    }
      },
      error => this.error = error
    );

  }

}

Thanks everyone for their time


问:
Passing data from CollectionView to DetailVC in Swift 4
My CollectionView should pass a class model to DetailViewController, but when I tap on a cell I get the nil error.

Fatal error: Unexpectedly found nil while implicitly unwrapping an
  Optional value

The CollectionViewController is embedded programmatically on a TabBarController.

Collection View

```<code>
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return soundArray.count
    }

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SoundCell", for: indexPath) as? SoundCell {
    let SoundClass = soundArray[indexPath.row]
    cell.updateUI(SoundClass: SoundClass)
    return cell

    } else {
    return UICollectionViewCell()
    }
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    self.performSegue(withIdentifier: "seguetosound", sender: self)

  }

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    if segue.identifier == "seguetosound" {
    if let detailVC = segue.destination as? DetailSecondVC
    let sound = sender as? SoundClass {
    detailVC.SoundClass = sound

    }
 }
</code>```

Detail View Controller

```<code>class DetailSecondVC: UIViewController, UIWebViewDelegate {

private var _SoundClass: SoundClass!

var SoundClass: SoundClass {
        get {
            return _SoundClass
        } set {
            _SoundClass = newValue
        }
    }
</code>```

Do you know what I am missing here? I tested the segue with a simple white screen and it works but when I try to pass the data, it fails.

答: Edited: I thought the solution was to make the segue from the view controller instead of from the cell, but as matt said, the segue was correct from the cell but I just had to remove the implementation of didSelectItemAt

Body:
My CollectionView should pass a class model to DetailViewController, but when I tap on a cell I get the nil error.

Fatal error: Unexpectedly found nil while implicitly unwrapping an
  Optional value

The CollectionViewController is embedded programmatically on a TabBarController.

Collection View

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return soundArray.count
    }

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SoundCell", for: indexPath) as? SoundCell {
    let SoundClass = soundArray[indexPath.row]
    cell.updateUI(SoundClass: SoundClass)
    return cell

    } else {
    return UICollectionViewCell()
    }
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    self.performSegue(withIdentifier: "seguetosound", sender: self)

  }

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    if segue.identifier == "seguetosound" {
    if let detailVC = segue.destination as? DetailSecondVC
    let sound = sender as? SoundClass {
    detailVC.SoundClass = sound

    }
 }

Detail View Controller

class DetailSecondVC: UIViewController, UIWebViewDelegate {

private var _SoundClass: SoundClass!

var SoundClass: SoundClass {
        get {
            return _SoundClass
        } set {
            _SoundClass = newValue
        }
    }

Do you know what I am missing here? I tested the segue with a simple white screen and it works but when I try to pass the data, it fails.


问:
Call Typescript Apollo Query from componentDidMount()
I have a React Component that calls a Query that expects to receive an array of objects (for validation data). I then use it to validate an html form, that is in turn defined inside of an apollo Mutation element. The way it is structured within the return statement of the component render() method works but it looks cumbersome and it reminds me of the callback hell era. What I really want to do is to get rid of the <QueryCustomerValidations> element in the render() method and move it into (ideally) the componentDidMount lifecycle event. So that the validators can be loaded there for later use within the form, then leave the <MutationCreateCustomer>inside render().

Right now, I have to wrap the form inside the mutation. The mutation inside the arrow function that the query returns in order to receive the async data in the proper order.

    //-------------------------------------------------------------------------
    // Component Lifecycle Eventhandler Methods
    //-------------------------------------------------------------------------
    componentDidMount()
    {

    }

    //-------------------------------------------------------------------------
    // Render Method Section
    //-------------------------------------------------------------------------
    public render(): JSX.Element
    {
        // Return Form
        return (
            <React.Fragment>
                {/* PAGE TITLE  */}

Agregar Nuevo Cliente

                {/* LOAD VALIDATIONS INTO STATE  */}
                <QueryCustomerValidations
                    query={Q_GET_CUSTOMER_VALIDATIONS}
                >
                    {({ loading: loadingValidations, error: errorValidations, data: dataValidations }) =>
                    {
                        if (loadingValidations)
                        {
                            return "Cargando..."
                        }
                        if (errorValidations)
                        {
                            return `Error: ${errorValidations.message}`
                        }
                        if (dataValidations)
                        {
                            const validators: ValidationDescriptor[] = []
                            dataValidations.getCustomerValidations.forEach((validator) => {
                                validators.push(validator as ValidationDescriptor)
                            })
                            this.validators.setValidators(validators)
                        }

                        /* DATA ENTRY FORM  */
                        return (

                                <MutationCreateCustomer
                                    mutation={M_CREATE_CUSTOMER}
                                    onCompleted={() => this.props.history.push('/')}
                                >
                                    {(createCustomer: any) => {
                                        return (
                                            <form name="frmNewCustomer"
                                                    className="col-md-8 m-3"
                                                    onSubmit={e => this.frmNewCustomer_submit(e, createCustomer)}
                                            >

                                                { this.ctrl_form_layout(this.props, this.state, this.validators) }

                                            </form>
                                        )
                                    }}
                                </MutationCreateCustomer>

                        )
                    }}

                </QueryCustomerValidations>

            </React.Fragment>
        );
    }

```

<p>Here for documentation purposes are the interfaces to create the Query. Since I get some of this data from the server using the apollo client, a simple graphql query solution on the <code>onDidMount()</code> would not work in this case.</p>

<p><code>getCustomerValidations.ts (Interfaces)</code></p>

<pre class="lang-js prettyprint-override"><code>
// ====================================================
// GraphQL query operation: getCustomerValidations
// ====================================================

export interface getCustomerValidations_getCustomerValidations {
  __typename: "ValidationDescriptor";
  field: string | null;
  type: string | null;
  required: boolean;
  max: number | null;
  min: number | null;
  regex: string | null;
}

export interface getCustomerValidations {
  getCustomerValidations: getCustomerValidations_getCustomerValidations[];
}

</code>```

customer-validations.query.ts (Client side query types)

//---------------------------------------------------------------------------------
// Imports Section (React/Apollo Libs)
//---------------------------------------------------------------------------------
import { gql }                              from 'apollo-boost';
import { Query }                            from 'react-apollo'

import { getCustomerValidations }            from '../../typeDefs/operations/getCustomerValidations'

//---------------------------------------------------------------------------------
// GQL Query: Customers
//---------------------------------------------------------------------------------
export const Q_GET_CUSTOMER_VALIDATIONS = gql`
    query getCustomerValidations {
        getCustomerValidations
        {
            field
            type
            required
            max
            min
            regex
        }
    }
`;

//---------------------------------------------------------------------------------
// Query Class: Customers
//---------------------------------------------------------------------------------
export class QueryCustomerValidations extends Query<getCustomerValidations> { }

```

The right solution can be a way to copy -and trigger- the <QueryCustomerValidations>element from the componentDidMount() method or, how to take the element away from the render() method and call it like with some sort of "await" way of doing it so it can be called first and the mutation after (and using the data from the query).

Thanks, I know this one is not really easy to figure out.

答:
You're looking for 'old' (used before <Query/> component) HOC pattern (with compose) described here, here and here.

Composing "graphql(gqlquery ..." requested at start (without conditional skip option) with one or more (named) "gqlmutation ..." (called on demand) gives you a clear, readable solution.

```<code>compose(
  graphql(Q_GET_CUSTOMER_VALIDATIONS),
  graphql(gql`mutation { ... }`, { name: 'createSth' })
)(SomeComponent)
</code>```

will pass data and createSth props to <SomeComponent/> then this.props.data object will contain loading, error and getCustomerValidations fields/properties. It's described here.

Query will be called at start (you can expect true in this.props.data.loading), no need to run query at cDM(). Mutation can be run using this.props.createSth() - custom name defined above (instead default prop name mutate).

Of course you can mix them with other required HOC's, f.e. redux connect(), withFormik() etc. - simply by adding single line of code.

Body:
I have a React Component that calls a Query that expects to receive an array of objects (for validation data). I then use it to validate an html form, that is in turn defined inside of an apollo Mutation element. The way it is structured within the return statement of the component render() method works but it looks cumbersome and it reminds me of the callback hell era. What I really want to do is to get rid of the <QueryCustomerValidations> element in the render() method and move it into (ideally) the componentDidMount lifecycle event. So that the validators can be loaded there for later use within the form, then leave the <MutationCreateCustomer>inside render().

Right now, I have to wrap the form inside the mutation. The mutation inside the arrow function that the query returns in order to receive the async data in the proper order.

    //-------------------------------------------------------------------------
    // Component Lifecycle Eventhandler Methods
    //-------------------------------------------------------------------------
    componentDidMount()
    {

    }

    //-------------------------------------------------------------------------
    // Render Method Section
    //-------------------------------------------------------------------------
    public render(): JSX.Element
    {
        // Return Form
        return (
            <React.Fragment>
                {/* PAGE TITLE  */}

Agregar Nuevo Cliente

                {/* LOAD VALIDATIONS INTO STATE  */}
                <QueryCustomerValidations
                    query={Q_GET_CUSTOMER_VALIDATIONS}
                >
                    {({ loading: loadingValidations, error: errorValidations, data: dataValidations }) =>
                    {
                        if (loadingValidations)
                        {
                            return "Cargando..."
                        }
                        if (errorValidations)
                        {
                            return `Error: ${errorValidations.message}`
                        }
                        if (dataValidations)
                        {
                            const validators: ValidationDescriptor[] = []
                            dataValidations.getCustomerValidations.forEach((validator) => {
                                validators.push(validator as ValidationDescriptor)
                            })
                            this.validators.setValidators(validators)
                        }

                        /* DATA ENTRY FORM  */
                        return (

                                <MutationCreateCustomer
                                    mutation={M_CREATE_CUSTOMER}
                                    onCompleted={() => this.props.history.push('/')}
                                >
                                    {(createCustomer: any) => {
                                        return (
                                            <form name="frmNewCustomer"
                                                    className="col-md-8 m-3"
                                                    onSubmit={e => this.frmNewCustomer_submit(e, createCustomer)}
                                            >

                                                { this.ctrl_form_layout(this.props, this.state, this.validators) }

                                            </form>
                                        )
                                    }}
                                </MutationCreateCustomer>

                        )
                    }}

                </QueryCustomerValidations>

            </React.Fragment>
        );
    }

Here for documentation purposes are the interfaces to create the Query. Since I get some of this data from the server using the apollo client, a simple graphql query solution on the onDidMount() would not work in this case.

getCustomerValidations.ts (Interfaces)

// ====================================================
// GraphQL query operation: getCustomerValidations
// ====================================================

export interface getCustomerValidations_getCustomerValidations {
  __typename: "ValidationDescriptor";
  field: string | null;
  type: string | null;
  required: boolean;
  max: number | null;
  min: number | null;
  regex: string | null;
}

export interface getCustomerValidations {
  getCustomerValidations: getCustomerValidations_getCustomerValidations[];
}

customer-validations.query.ts (Client side query types)

//---------------------------------------------------------------------------------
// Imports Section (React/Apollo Libs)
//---------------------------------------------------------------------------------
import { gql }                              from 'apollo-boost';
import { Query }                            from 'react-apollo'

import { getCustomerValidations }            from '../../typeDefs/operations/getCustomerValidations'

//---------------------------------------------------------------------------------
// GQL Query: Customers
//---------------------------------------------------------------------------------
export const Q_GET_CUSTOMER_VALIDATIONS = gql`
    query getCustomerValidations {
        getCustomerValidations
        {
            field
            type
            required
            max
            min
            regex
        }
    }
`;

//---------------------------------------------------------------------------------
// Query Class: Customers
//---------------------------------------------------------------------------------
export class QueryCustomerValidations extends Query<getCustomerValidations> { }

The right solution can be a way to copy -and trigger- the <QueryCustomerValidations>element from the componentDidMount() method or, how to take the element away from the render() method and call it like with some sort of "await" way of doing it so it can be called first and the mutation after (and using the data from the query).

Thanks, I know this one is not really easy to figure out.

Body:
You're looking for 'old' (used before <Query/> component) HOC pattern (with compose) described here, here and here.

Composing "graphql(gqlquery ..." requested at start (without conditional skip option) with one or more (named) "gqlmutation ..." (called on demand) gives you a clear, readable solution.

compose(
  graphql(Q_GET_CUSTOMER_VALIDATIONS),
  graphql(gql`mutation { ... }`, { name: 'createSth' })
)(SomeComponent)

will pass data and createSth props to <SomeComponent/> then this.props.data object will contain loading, error and getCustomerValidations fields/properties. It's described here.

Query will be called at start (you can expect true in this.props.data.loading), no need to run query at cDM(). Mutation can be run using this.props.createSth() - custom name defined above (instead default prop name mutate).

Of course you can mix them with other required HOC's, f.e. redux connect(), withFormik() etc. - simply by adding single line of code.


问:
gets() problem in C
I wrote the following code:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define SIZE 128

int main ()

{
    char mychar , string [SIZE];
    int i;
    int const count =0 ;

    printf ("Please enter your string: \n\n");
    fgets (string, SIZE, stdin);

    printf ("Please enter char to find: ");
    mychar = getchar();

    for (i=0 ; (string[i] == '\0') ; i++ )
        if ( string[i]  == mychar )
            count++;

    printf ("The char %c appears %d times" ,mychar ,count);

    return 0;
}
</code>```

The problem is that the gcc gives me an error for the 'int const count': " increment of read-only variable ‘count’".

What seems to be wrong ?

Thank !

答: gets is dangerous because it lets you read in more data than you've allocated space for, you can use fgets which specifies how many characters it is going to read in and stops if it finds a newline. </p>

Title: gets() problem in C

Body:
I wrote the following code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define SIZE 128

int main ()

{
    char mychar , string [SIZE];
    int i;
    int const count =0 ;

    printf ("Please enter your string: \n\n");
    fgets (string, SIZE, stdin);

    printf ("Please enter char to find: ");
    mychar = getchar();

    for (i=0 ; (string[i] == '\0') ; i++ )
        if ( string[i]  == mychar )
            count++;

    printf ("The char %c appears %d times" ,mychar ,count);

    return 0;
}

The problem is that the gcc gives me an error for the 'int const count': " increment of read-only variable ‘count’".

What seems to be wrong ?

Thank !


问:
Flask Server for Listening to HTTP Responses
I am working on making a Flask server that can listen to a node that would like to contact the server at any point of time and then the flask server process the response. I would like to ask whether there's any method to listen to the connection attempted by the remote node.</p>

答:
Flask has a development server, documented here:

FLASK_APP=hello.py flask run
```

Note that the server is not intended for production. If you're looking for production server, you can read this page. There are several solutions, such as Gunicorn, uWSGI and more.

Body:
Flask has a development server, documented here:

FLASK_APP=hello.py flask run

Note that the server is not intended for production. If you're looking for production server, you can read this page. There are several solutions, such as Gunicorn, uWSGI and more.


问:
How to send an HTTPS link to telegram chat ID. using sendmessage ("https://---", chatID)
I like to send a link to my Telegram application-Bot using python#. so, While I send a text I can do it but I can't send Https or Http to my app chat. also, some links are also possible to send. also, I can print it in the terminal of pycharm

```<code>if text == "link":
sendMessage("https://www.bousai.pref.kanagawa.jp/K_PUB_VF_DetailCity?cityid=", chatId)
</code>```

no error and no print in Telegram-app-Bot

答:
in the link we have (K_PUB_VF_) one
when I remove _, _, _ then I can print it </p>

<p>the next question
(How to do it with _ one not to be removed it)  </p>

Body:
I like to send a link to my Telegram application-Bot using python#. so, While I send a text I can do it but I can't send Https or Http to my app chat. also, some links are also possible to send. also, I can print it in the terminal of pycharm

if text == "link":
sendMessage("https://www.bousai.pref.kanagawa.jp/K_PUB_VF_DetailCity?cityid=", chatId)

no error and no print in Telegram-app-Bot

Body:
in the link we have (K_PUB_VF_) one
when I remove _, _, _ then I can print it

the next question
(How to do it with _ one not to be removed it)


问:
How can I properly load A page or A div automatically?
I'm creating A simple queuing system, right now when ever I click my button called BtnNxt() it will dequeue my enqueued data and render it to my page. and it also render from another page. which is my call screen page, but when I click it again my call screen page needs to be refresh to update the current number from my queue. so what I want is , Ithink i need to refresh my page or maybe my div to update it?

Here is my BtnNext() controller :

```<code>   public ActionResult BtnNext()
    {
        System.Threading.Thread.Sleep(500);
        var first = MyQueue.todayQueue.Dequeue();
        MyQueue.todayQueue.Count();
        TempData["QueueItem"] = first;
        TempData.Keep();
        return PartialView("_queuenumber");
    }
</code>```

and here is my callscreen page:

```<code>@{
    var item = (Rosh.QueueMe.Web.Models.MyQueue)TempData["QueueItem"];
}
<table>
    <tr>
        <th scope="tickets">TICKETS</th>
        <th scope="name">NAME</th>
        <th scope="counter">COUNTER</th>
        <th scope="service">SERVICE</th>
    </tr>
    <tr class="data">
        <td>#@item.QueueNumber</td>
        <td>@item.Name</td>
        <td>Desk 1</td>
        <td>@item.ServiceId</td>
    </tr>
</table>
</code>```

I tried to use this code

```<code><meta http-equiv="refresh" content="1" />
</code>```

this code refresh my page every 1 sec, but is it possible to just reload the div? maybe using ajax?

答:
```<code><script type="text/javascript">
    $(function() {
        setInterval(loadData,1000);  // invoke load every second
        loadData(); // load on initial page loaded
    });

    function loadData() {
        $('#Div').load( '/controller/BtnNext' );
    }
</script>
</code>```

Body:
I'm creating A simple queuing system, right now when ever I click my button called BtnNxt() it will dequeue my enqueued data and render it to my page. and it also render from another page. which is my call screen page, but when I click it again my call screen page needs to be refresh to update the current number from my queue. so what I want is , Ithink i need to refresh my page or maybe my div to update it?

Here is my BtnNext() controller :

   public ActionResult BtnNext()
    {
        System.Threading.Thread.Sleep(500);
        var first = MyQueue.todayQueue.Dequeue();
        MyQueue.todayQueue.Count();
        TempData["QueueItem"] = first;
        TempData.Keep();
        return PartialView("_queuenumber");
    }

and here is my callscreen page:

@{
    var item = (Rosh.QueueMe.Web.Models.MyQueue)TempData["QueueItem"];
}

        TICKETS
        NAME
        COUNTER
        SERVICE

        #@item.QueueNumber
        @item.Name
        Desk 1
        @item.ServiceId

I tried to use this code

<meta http-equiv="refresh" content="1" />

this code refresh my page every 1 sec, but is it possible to just reload the div? maybe using ajax?


问:
Docker - How to delete image from a private registry
There is no good answer yet to "How to delete an image from a private registry" in docker.

Already tried the following:

Can't delete Docker Image from Registry

How to delete images from a private docker registry?

How to "delete" an image from a private Docker Registry?

But none of the above seems to work.

As everyone else, I already tried:

```<code>DELETE /v2/orassayag/osr_streamer_nginx/manifests/sha256:051adb935bff30abba811fd64da28a5f3b19a48f07c74b067e3bd61ab91152b5 HTTP/1.1
</code>```

AND

```<code>DELETE /v2/orassayag/osr_streamer_nginx/manifests/051adb935bff30abba811fd64da28a5f3b19a48f07c74b067e3bd61ab91152b5 HTTP/1.1
</code>```

and get every time:

```<code>{"errors":[{"code":"UNSUPPORTED","message":"The operation is unsupported."}]}
</code>```

Anybody had success with this?

Update:

None of the solutions in the links I gave works, and still get 'unsupported' error.

答:
This is a python script delete all image in private registry, it work on my private registry.</p>

```<code>import requests
for repo in requests.get('https://192.168.2.31:5000/v2/_catalog', verify=False).json()['repositories']:
    headers = requests.get('https://192.168.2.31:5000/v2/%s/manifests/v1' % repo, headers = {'Accept': 'application/vnd.docker.distribution.manifest.v2+json'}, verify=False).headers
    if 'Docker-Content-Digest' in headers:
        requests.delete('https://192.168.2.31:5000/v2/%s/manifests/%s' % (repo, headers['Docker-Content-Digest']), verify=False)
</code>```

Body:
There is no good answer yet to "How to delete an image from a private registry" in docker.

Already tried the following:

Can't delete Docker Image from Registry

How to delete images from a private docker registry?

How to "delete" an image from a private Docker Registry?

But none of the above seems to work.

As everyone else, I already tried:

DELETE /v2/orassayag/osr_streamer_nginx/manifests/sha256:051adb935bff30abba811fd64da28a5f3b19a48f07c74b067e3bd61ab91152b5 HTTP/1.1

AND

DELETE /v2/orassayag/osr_streamer_nginx/manifests/051adb935bff30abba811fd64da28a5f3b19a48f07c74b067e3bd61ab91152b5 HTTP/1.1

and get every time:

{"errors":[{"code":"UNSUPPORTED","message":"The operation is unsupported."}]}

Anybody had success with this?

Update:

None of the solutions in the links I gave works, and still get 'unsupported' error.

Body:
This is a python script delete all image in private registry, it work on my private registry.

import requests
for repo in requests.get('https://192.168.2.31:5000/v2/_catalog', verify=False).json()['repositories']:
    headers = requests.get('https://192.168.2.31:5000/v2/%s/manifests/v1' % repo, headers = {'Accept': 'application/vnd.docker.distribution.manifest.v2+json'}, verify=False).headers
    if 'Docker-Content-Digest' in headers:
        requests.delete('https://192.168.2.31:5000/v2/%s/manifests/%s' % (repo, headers['Docker-Content-Digest']), verify=False)


问:
How do I check if each UITextField in an Array has a user input?
I have a list of UITextFields in an Array for users to key in phone numbers. When I click the Send Button, it will connect with my server to send an automated message to the numbers listed. This portion works well. What I want to do now is to check which of the UITextFields has a phone number in it and to check if it has the prefix + before it connects to my server. If any of the UITextField has a phone number without the prefix +, the border color of that UITextField should change colours. If the UITextField does not have a phone number, no action should be taken. How do I go about achieving that?

This is the portion of the code that I need help in

```<code>
    @IBAction func sendbutton(_ sender: Any) {

        var numArray: Array<Any>

        numArray = [phonenumber.text!, phonenumber1.text!, phonenumber2.text!, phonenumber3.text!]

        let myColor = UIColor.red

        for num in numArray {
            if (num as AnyObject).hasPrefix("+") {
                print("Has + symbol")

            } else {
                print("Does Not Have Symbol")

            }
        }

</code>```

答:
Please try this solution i'll work.</p>

```<code>private var arrTextFilds = [phonenumber.text ?? "", phonenumber1.text ?? "",
phonenumber2.text!, phonenumber3.text ?? ""]
private var numArray : [String] = []
arrTextFilds {
   if let text = $0.text,text.hasPrefix(“+”) {
       numArray.append(text)
       $0.layer.borderWidth = 0.0
   } else {
      $0.layer.borderColor = UIColor.red.cgColor
      $0.layer.borderWidth = 1.0
  }
}
</code>```

Body:
I have a list of UITextFields in an Array for users to key in phone numbers. When I click the Send Button, it will connect with my server to send an automated message to the numbers listed. This portion works well. What I want to do now is to check which of the UITextFields has a phone number in it and to check if it has the prefix + before it connects to my server. If any of the UITextField has a phone number without the prefix +, the border color of that UITextField should change colours. If the UITextField does not have a phone number, no action should be taken. How do I go about achieving that?

This is the portion of the code that I need help in

    @IBAction func sendbutton(_ sender: Any) {

        var numArray: Array<Any>

        numArray = [phonenumber.text!, phonenumber1.text!, phonenumber2.text!, phonenumber3.text!]

        let myColor = UIColor.red

        for num in numArray {
            if (num as AnyObject).hasPrefix("+") {
                print("Has + symbol")

            } else {
                print("Does Not Have Symbol")

            }
        }

Body:
Please try this solution i'll work.

private var arrTextFilds = [phonenumber.text ?? "", phonenumber1.text ?? "",
phonenumber2.text!, phonenumber3.text ?? ""]
private var numArray : [String] = []
arrTextFilds {
   if let text = $0.text,text.hasPrefix(“+”) {
       numArray.append(text)
       $0.layer.borderWidth = 0.0
   } else {
      $0.layer.borderColor = UIColor.red.cgColor
      $0.layer.borderWidth = 1.0
  }
}


问:
template and std::forward in c++
The first lines of code will return 112 but why? 1 is not supposed to be of type int&&? And why it is working in the second example of code i.e. returning 312?

```<code>void fun(int&) { cout << 1; }
void fun(int const&) { cout << 2; }
void fun(int&&) { cout << 3; }

template
<typename T>
void fun2(T&& t) { fun(t); }

int main() {
  int x{};
  int const y{};
  fun2(1);
  fun2(x);
  fun2(y);
}
</code>```

```<code>void fun(int&) { cout << 1; }
void fun(int const&) { cout << 2; }
void fun(int&&) { cout << 3; }

template
<typename T>
void fun2(T&& t) { fun(std::forward<T>(t)); }

int main() {
  int x{};
  int const y{};
  fun2(1);
  fun2(x);
  fun2(y);
}
</code>```

答:
std::forward basically means that you want to preserve the lvalueness or rvalueness of the calling argument when passing/forwarding it to another function.

So in the second example you keep the rvalueness, while in the first example you pass t as a lvalue reference.

You might want to read a bit more on universal/forwarding reference for example here:
https://isocpp.org/blog/2012/11/universal-references-in-c11-scott-meyers

Title: template and std::forward in c++

Body:
The first lines of code will return 112 but why? 1 is not supposed to be of type int&&? And why it is working in the second example of code i.e. returning 312?

void fun(int&) { cout << 1; }
void fun(int const&) { cout << 2; }
void fun(int&&) { cout << 3; }

template
<typename T>
void fun2(T&& t) { fun(t); }

int main() {
  int x{};
  int const y{};
  fun2(1);
  fun2(x);
  fun2(y);
}

void fun(int&) { cout << 1; }
void fun(int const&) { cout << 2; }
void fun(int&&) { cout << 3; }

template
<typename T>
void fun2(T&& t) { fun(std::forward<T>(t)); }

int main() {
  int x{};
  int const y{};
  fun2(1);
  fun2(x);
  fun2(y);
}


问:
Google Query - "NOT LIKE" Statement Doesn't work
The following line doesn't work:

```<code>=QUERY(AB:AE,"select AB,AC,AD,AE where AB NOT LIKE '%Info%'",1)
</code>```

Throws:

Unable to parse query string for Function QUERY parameter 2: PARSE_ERROR: Encountered "  "AH "" at line 1, column 26. Was expecting one of: "(" ... "("

However, this one does:

```<code>=QUERY(AB:AE,"select AB,AC,AD,AE where AB LIKE '%Info%'",1)
</code>```

答:
NOT should be before column identifier:    </p>

```<code>=QUERY(AB:AE,"select AB,AC,AD,AE where NOT AB LIKE '%Info%'",1)
</code>```

Body:
The following line doesn't work:

=QUERY(AB:AE,"select AB,AC,AD,AE where AB NOT LIKE '%Info%'",1)

Throws:

Unable to parse query string for Function QUERY parameter 2: PARSE_ERROR: Encountered "  "AH "" at line 1, column 26. Was expecting one of: "(" ... "("

However, this one does:

=QUERY(AB:AE,"select AB,AC,AD,AE where AB LIKE '%Info%'",1)

Body:
NOT should be before column identifier:

=QUERY(AB:AE,"select AB,AC,AD,AE where NOT AB LIKE '%Info%'",1)