问:
Checking whether a sequence of integers is increasing
I'm stuck only partially passing the below problem.

Given a sequence of integers, check whether it is possible to obtain a strictly increasing sequence by erasing no more than one element from it.

Example

```<code>sequence = [1, 3, 2, 1]
almostIncreasingSequence(sequence) = false

sequence = [1, 3, 2]
almostIncreasingSequence(sequence) = true
</code>```

My code that is only passing some examples:

```<code>bool almostIncreasingSequence(int[] sequence) {
   int seqIncreasing = 0;
    if (sequence.Length == 1) return true;
    for (int i = 0;i < sequence.Length-2;i++)
    {
        if ((sequence[i] == sequence[++i]+1)||(sequence[i] == sequence[++i]))
        {
            seqIncreasing++;
        }
    }
    return ((seqIncreasing == sequence.Length) || (--seqIncreasing == sequence.Length));
}
</code>```

Failed Examples:

```<code>Input:
    sequence: [1, 3, 2]
Output:
    false
Expected Output:
    true

Input:
    sequence: [10, 1, 2, 3, 4, 5]
Output:
    false
Expected Output:
    true

Input:
    sequence: [0, -2, 5, 6]
Output:
    false
Expected Output:
    true

Input:
    sequence: [1, 1]
Output:
    false
Expected Output:
    true
</code>```

答:
Here is my version. It has similarities with Peter Duniho's first solution.</p>

```<code>static bool AlmostIncreasingSequence(int[] sequence)
{
    int problemIndex = -1;
    for (int i = 0; i < sequence.Length - 1; i++)
    {
        if (sequence[i] < sequence[i + 1])
            continue; // The elements i and i + 1 are in order
        if (problemIndex != -1)
            return false; // The sequence has more than one problems, so it cannot be fixed
        problemIndex = i; // This is the first problem found so far
    }
    if (problemIndex == -1)
        return true; // The sequence has no problems
    if (problemIndex == 0)
        return true; // The sequence can be fixed by removing the first element
    if (problemIndex == sequence.Length - 2)
        return true; // The sequence can be fixed by removing the last element
    if (sequence[problemIndex - 1] < sequence[problemIndex + 1])
        return true; // The sequence can be fixed by removing the (problemIndex) element
    if (sequence[problemIndex] < sequence[problemIndex + 2])
        return true; // The sequence can be fixed by removing the (problemIndex + 1) element
    return false; // The sequence cannot be fixed
}
</code>```

Body:
I'm stuck only partially passing the below problem.

Given a sequence of integers, check whether it is possible to obtain a strictly increasing sequence by erasing no more than one element from it.

Example

sequence = [1, 3, 2, 1]
almostIncreasingSequence(sequence) = false

sequence = [1, 3, 2]
almostIncreasingSequence(sequence) = true

My code that is only passing some examples:

bool almostIncreasingSequence(int[] sequence) {
   int seqIncreasing = 0;
    if (sequence.Length == 1) return true;
    for (int i = 0;i < sequence.Length-2;i++)
    {
        if ((sequence[i] == sequence[++i]+1)||(sequence[i] == sequence[++i]))
        {
            seqIncreasing++;
        }
    }
    return ((seqIncreasing == sequence.Length) || (--seqIncreasing == sequence.Length));
}

Failed Examples:

Input:
    sequence: [1, 3, 2]
Output:
    false
Expected Output:
    true

Input:
    sequence: [10, 1, 2, 3, 4, 5]
Output:
    false
Expected Output:
    true

Input:
    sequence: [0, -2, 5, 6]
Output:
    false
Expected Output:
    true

Input:
    sequence: [1, 1]
Output:
    false
Expected Output:
    true

Body:
Here is my version. It has similarities with Peter Duniho's first solution.

static bool AlmostIncreasingSequence(int[] sequence)
{
    int problemIndex = -1;
    for (int i = 0; i < sequence.Length - 1; i++)
    {
        if (sequence[i] < sequence[i + 1])
            continue; // The elements i and i + 1 are in order
        if (problemIndex != -1)
            return false; // The sequence has more than one problems, so it cannot be fixed
        problemIndex = i; // This is the first problem found so far
    }
    if (problemIndex == -1)
        return true; // The sequence has no problems
    if (problemIndex == 0)
        return true; // The sequence can be fixed by removing the first element
    if (problemIndex == sequence.Length - 2)
        return true; // The sequence can be fixed by removing the last element
    if (sequence[problemIndex - 1] < sequence[problemIndex + 1])
        return true; // The sequence can be fixed by removing the (problemIndex) element
    if (sequence[problemIndex] < sequence[problemIndex + 2])
        return true; // The sequence can be fixed by removing the (problemIndex + 1) element
    return false; // The sequence cannot be fixed
}


来源: stackexchange

问:
How to achieve the following using functions/stored procedure in SQL Server database
I have the following table with following data as

```<code>                                            Tab1
FutureMISBoundaryVersion  CurrentMISBoundaryVersion  FutureHAMBoundaryVersion  CurrentHAMBoundaryVersion
2:21,5:50,4:55,7:80,9:33  2:12,5:40,4:35,7:60,9:87   2:52,5:90,4:75,7:30,9:57  2:42,5:60,4:95,7:70,9:37
</code>```

This key value pair has to be split into and the value of each key has to be inserted into another table in the following fashion

```<code>FutureMIS-OAKVersion |FutureMIS-HAMVersion |FutureMIS-DURVersion | FutureMIS-BURVersion| FutureMIS-YRTVersion |DeviceMIS-OAKVersion|DeviceMIS-HAMVersion |DeviceMIS-DURVersion| DeviceMIS-BURVersion| DeviceMIS-YRTVersion
              33     |              80     |            21       |            55       |  50                  | 87                 |  60                 |12                  |35                   | 40
</code>```

i,e: when it finds column 'FutureMISBoundaryVersion' in tab1 then its value
'2:21,5:50,4:55,7:80,9:33' will be split and its value is inserted in such a way that the corresponding value of key 2 i,e:21 will be inserted into FutureMIS-DURVersion column.

Similarly key 5's value 50 will be inserted into FutureMIS-BURVersion column and so on for other keys

when it finds column 'CurrentMISBoundaryVersion' then

'2:12,5:40,4:35,7:60,9:87' will be split and its value is inserted in such a way that the corresponding value of key 2 i,e:12 will be inserted into CurrentMIS-DURVersion column similarly key 5's 40 value will be inserted into DeviceMIS-YRTVersion column and so on for other columns of the source table.

The table structure may extend as I have shown only 4 source table column  but logic for all the columns remain same

答:
This is a pain in SQL Server.  You can do this with recursive CTEs:

```<code> with cte as (
      select convert(varchar(max), left(FutureMISBoundaryVersion, charindex(',', FutureMISBoundaryVersion) - 1)) as FutureMISBoundaryVersion,
             convert(varchar(max), left(CurrentMISBoundaryVersion, charindex(',', CurrentMISBoundaryVersion) - 1)) as CurrentMISBoundaryVersion,
             convert(varchar(max), left(FutureHAMBoundaryVersion, charindex(',', FutureHAMBoundaryVersion) - 1)) as FutureHAMBoundaryVersion,
             convert(varchar(max), left(CurrentHAMBoundaryVersion, charindex(',', FutureMISBoundaryVersion) - 1)) as CurrentHAMBoundaryVersion,
             stuff(FutureMISBoundaryVersion, 1, charindex(',', FutureMISBoundaryVersion), '') + ',' as FutureMISBoundaryVersion_rest,
             stuff(CurrentMISBoundaryVersion, 1, charindex(',', CurrentMISBoundaryVersion), '') + ',' as CurrentMISBoundaryVersion_rest,
             stuff(FutureHAMBoundaryVersion, 1, charindex(',', FutureHAMBoundaryVersion), '') + ',' as FutureHAMBoundaryVersion_rest,
             stuff(CurrentHAMBoundaryVersion, 1, charindex(',', CurrentHAMBoundaryVersion), '') + ',' as CurrentHAMBoundaryVersion_rest,
             1 as lev
      from t
      union all
      select convert(varchar(max), left(FutureMISBoundaryVersion_rest, charindex(',', FutureMISBoundaryVersion_rest) - 1)) as FutureMISBoundaryVersion,
             convert(varchar(max), left(CurrentMISBoundaryVersion_rest, charindex(',', CurrentMISBoundaryVersion_rest) - 1)) as CurrentMISBoundaryVersion,
             convert(varchar(max), left(FutureHAMBoundaryVersion_rest, charindex(',', FutureHAMBoundaryVersion_rest) - 1)) as FutureHAMBoundaryVersion,
             convert(varchar(max), left(CurrentHAMBoundaryVersion_rest, charindex(',', CurrentHAMBoundaryVersion_rest) - 1)) as CurrentHAMBoundaryVersion,
             stuff(FutureMISBoundaryVersion_rest, 1, charindex(',', FutureMISBoundaryVersion_rest), '') as FutureMISBoundaryVersion_rest,
             stuff(CurrentMISBoundaryVersion_rest, 1, charindex(',', CurrentMISBoundaryVersion_rest), '') as CurrentMISBoundaryVersion_rest,
             stuff(FutureHAMBoundaryVersion_rest, 1, charindex(',', FutureHAMBoundaryVersion_rest), '') as FutureHAMBoundaryVersion_rest,
             stuff(CurrentHAMBoundaryVersion_rest, 1, charindex(',', CurrentHAMBoundaryVersion_rest), '') as CurrentHAMBoundaryVersion_rest,
             lev + 1
      from cte
      where FutureMISBoundaryVersion_rest like '%,%'
     )
select FutureMISBoundaryVersion, CurrentMISBoundaryVersion, FutureHAMBoundaryVersion, CurrentHAMBoundaryVersion, lev
from cte;
</code>```

Here is a db<>fiddle.

ContentLicense: CC BY-SA 4.0

Body:
I have the following table with following data as

                                            Tab1
FutureMISBoundaryVersion  CurrentMISBoundaryVersion  FutureHAMBoundaryVersion  CurrentHAMBoundaryVersion
2:21,5:50,4:55,7:80,9:33  2:12,5:40,4:35,7:60,9:87   2:52,5:90,4:75,7:30,9:57  2:42,5:60,4:95,7:70,9:37

This key value pair has to be split into and the value of each key has to be inserted into another table in the following fashion

FutureMIS-OAKVersion |FutureMIS-HAMVersion |FutureMIS-DURVersion | FutureMIS-BURVersion| FutureMIS-YRTVersion |DeviceMIS-OAKVersion|DeviceMIS-HAMVersion |DeviceMIS-DURVersion| DeviceMIS-BURVersion| DeviceMIS-YRTVersion
              33     |              80     |            21       |            55       |  50                  | 87                 |  60                 |12                  |35                   | 40

i,e: when it finds column 'FutureMISBoundaryVersion' in tab1 then its value
'2:21,5:50,4:55,7:80,9:33' will be split and its value is inserted in such a way that the corresponding value of key 2 i,e:21 will be inserted into FutureMIS-DURVersion column.

Similarly key 5's value 50 will be inserted into FutureMIS-BURVersion column and so on for other keys

when it finds column 'CurrentMISBoundaryVersion' then

'2:12,5:40,4:35,7:60,9:87' will be split and its value is inserted in such a way that the corresponding value of key 2 i,e:12 will be inserted into CurrentMIS-DURVersion column similarly key 5's 40 value will be inserted into DeviceMIS-YRTVersion column and so on for other columns of the source table.

The table structure may extend as I have shown only 4 source table column  but logic for all the columns remain same

Body:
This is a pain in SQL Server.  You can do this with recursive CTEs:

 with cte as (
      select convert(varchar(max), left(FutureMISBoundaryVersion, charindex(',', FutureMISBoundaryVersion) - 1)) as FutureMISBoundaryVersion,
             convert(varchar(max), left(CurrentMISBoundaryVersion, charindex(',', CurrentMISBoundaryVersion) - 1)) as CurrentMISBoundaryVersion,
             convert(varchar(max), left(FutureHAMBoundaryVersion, charindex(',', FutureHAMBoundaryVersion) - 1)) as FutureHAMBoundaryVersion,
             convert(varchar(max), left(CurrentHAMBoundaryVersion, charindex(',', FutureMISBoundaryVersion) - 1)) as CurrentHAMBoundaryVersion,
             stuff(FutureMISBoundaryVersion, 1, charindex(',', FutureMISBoundaryVersion), '') + ',' as FutureMISBoundaryVersion_rest,
             stuff(CurrentMISBoundaryVersion, 1, charindex(',', CurrentMISBoundaryVersion), '') + ',' as CurrentMISBoundaryVersion_rest,
             stuff(FutureHAMBoundaryVersion, 1, charindex(',', FutureHAMBoundaryVersion), '') + ',' as FutureHAMBoundaryVersion_rest,
             stuff(CurrentHAMBoundaryVersion, 1, charindex(',', CurrentHAMBoundaryVersion), '') + ',' as CurrentHAMBoundaryVersion_rest,
             1 as lev
      from t
      union all
      select convert(varchar(max), left(FutureMISBoundaryVersion_rest, charindex(',', FutureMISBoundaryVersion_rest) - 1)) as FutureMISBoundaryVersion,
             convert(varchar(max), left(CurrentMISBoundaryVersion_rest, charindex(',', CurrentMISBoundaryVersion_rest) - 1)) as CurrentMISBoundaryVersion,
             convert(varchar(max), left(FutureHAMBoundaryVersion_rest, charindex(',', FutureHAMBoundaryVersion_rest) - 1)) as FutureHAMBoundaryVersion,
             convert(varchar(max), left(CurrentHAMBoundaryVersion_rest, charindex(',', CurrentHAMBoundaryVersion_rest) - 1)) as CurrentHAMBoundaryVersion,
             stuff(FutureMISBoundaryVersion_rest, 1, charindex(',', FutureMISBoundaryVersion_rest), '') as FutureMISBoundaryVersion_rest,
             stuff(CurrentMISBoundaryVersion_rest, 1, charindex(',', CurrentMISBoundaryVersion_rest), '') as CurrentMISBoundaryVersion_rest,
             stuff(FutureHAMBoundaryVersion_rest, 1, charindex(',', FutureHAMBoundaryVersion_rest), '') as FutureHAMBoundaryVersion_rest,
             stuff(CurrentHAMBoundaryVersion_rest, 1, charindex(',', CurrentHAMBoundaryVersion_rest), '') as CurrentHAMBoundaryVersion_rest,
             lev + 1
      from cte
      where FutureMISBoundaryVersion_rest like '%,%'
     )
select FutureMISBoundaryVersion, CurrentMISBoundaryVersion, FutureHAMBoundaryVersion, CurrentHAMBoundaryVersion, lev
from cte;

Here is a db<>fiddle.


问:
Python : Joining separated numeric characters in text but leave alphabetic texts
I've some sample strings like :

```<code>sample_lt1 = 'CANCEL Bitcoin kev 1 96 35 2 0 5 7 5 6'
sample_lt2 = 'CANCEL Bitcoln key 1 6 3 5 20 5 7 56 Cash 2 9 00'
sample_lt3 = 'CANCEL Bitcein key 0 1 5 0 0 4 4 1 6 Cash '
</code>```

I'm trying to join the numbers separated by spaces in the string but leave the chunk of alphabetic characters. The desired output for those sample inputs would be :

```<code>sample_out1 = 'CANCEL Bitcoin kev 19635205756'
sample_out2 = 'CANCEL Bitcoln key 1635205756 Cash 2900'
sample_out3 = 'CANCEL Bitcein key 015004416 Cash ' # Removal of last space is ok.
</code>```

Till now, I have done this :

```<code>def ReForm(lt):
    lts = lt.split()
    c = 0
    new = []
    temp = []
    while c<len(lts):
        if lts[c].isnumeric():
            temp.append(lts[c])
        else:
            if temp:
                s = ''.join(temp)
                new.append(s)
            new.append(lts[c])
        c += 1
    ret = ' '.join(new)
    return ret
</code>```

The output given by my code is :

```<code>CANCEL Bitcoin kev
CANCEL Bitcoln key 1635205756 Cash
CANCEL Bitcein key 015004416 Cash
</code>```

It fails to join the space separated numbers in the first and second case. What am I doing wrong?

答:
```<code>import re
s1 = 'CANCEL Bitcoin kev 1 96 35 2 0 5 7 5 6'
print(re.sub(r"(?<=\d) (?=\d)", "", s1))
CANCEL Bitcoin kev 19635205756
s2 = 'CANCEL Bitcoln key 1 6 3 5 20 5 7 56 Cash 2 9 00'
print(re.sub(r"(?<=\d) (?=\d)", "", s2))
CANCEL Bitcoln key 1635205756 Cash 2900
</code>```

Body:
I've some sample strings like :

sample_lt1 = 'CANCEL Bitcoin kev 1 96 35 2 0 5 7 5 6'
sample_lt2 = 'CANCEL Bitcoln key 1 6 3 5 20 5 7 56 Cash 2 9 00'
sample_lt3 = 'CANCEL Bitcein key 0 1 5 0 0 4 4 1 6 Cash '

I'm trying to join the numbers separated by spaces in the string but leave the chunk of alphabetic characters. The desired output for those sample inputs would be :

sample_out1 = 'CANCEL Bitcoin kev 19635205756'
sample_out2 = 'CANCEL Bitcoln key 1635205756 Cash 2900'
sample_out3 = 'CANCEL Bitcein key 015004416 Cash ' # Removal of last space is ok.

Till now, I have done this :

def ReForm(lt):
    lts = lt.split()
    c = 0
    new = []
    temp = []
    while c<len(lts):
        if lts[c].isnumeric():
            temp.append(lts[c])
        else:
            if temp:
                s = ''.join(temp)
                new.append(s)
            new.append(lts[c])
        c += 1
    ret = ' '.join(new)
    return ret

The output given by my code is :

CANCEL Bitcoin kev
CANCEL Bitcoln key 1635205756 Cash
CANCEL Bitcein key 015004416 Cash

It fails to join the space separated numbers in the first and second case. What am I doing wrong?


问:
How to do a rewrite in a premise?
```<code>Any-comm : ∀ {A : Set} {P : A → Set} (xs ys : List A) →
           Any P (xs ++ ys) → Any P (ys ++ xs)
Any-comm xs [] prf = {!!}
</code>```

```<code>Goal: Any P xs
————————————————————————————————————————————————————————————
prf : Any P (xs ++ [])
xs  : List A
P   : A → Set  (not in scope)
A   : Set  (not in scope)
</code>```

How do I rewrite prf with the append identity here? I suppose I could rewrite the goal to match instead, but would it be possible to do the same in the premise? I feel the later would be more neat.

答:
Ah, it seems my assumption of how rewrite works was wrong.

```<code>Any-comm xs [] prf rewrite sym (++-identityʳ xs) = {!!}
</code>```

```<code>Goal: Any P (xs ++ [])
————————————————————————————————————————————————————————————
prf : Any P ((xs ++ []) ++ [])
P   : A → Set  (not in scope)
xs  : List A
A   : Set  (not in scope)
</code>```

When I tried the above I was surprised to see it rewrite both the goal and the premise. So from that the way to rewrite the premise is.

```<code>Any-comm xs [] prf rewrite ++-identityʳ xs = prf
</code>```

I am not sure if this is supposed to be so surprising, but I had not noticed this despite nearly going through the entirety of vol 1 of the PLFA book. This behavior is different from Coq's rewrite.

Title: How to do a rewrite in a premise?

Body:
Any-comm : ∀ {A : Set} {P : A → Set} (xs ys : List A) →
           Any P (xs ++ ys) → Any P (ys ++ xs)
Any-comm xs [] prf = {!!}

Goal: Any P xs
————————————————————————————————————————————————————————————
prf : Any P (xs ++ [])
xs  : List A
P   : A → Set  (not in scope)
A   : Set  (not in scope)

How do I rewrite prf with the append identity here? I suppose I could rewrite the goal to match instead, but would it be possible to do the same in the premise? I feel the later would be more neat.

Body:
Ah, it seems my assumption of how rewrite works was wrong.

Any-comm xs [] prf rewrite sym (++-identityʳ xs) = {!!}

Goal: Any P (xs ++ [])
————————————————————————————————————————————————————————————
prf : Any P ((xs ++ []) ++ [])
P   : A → Set  (not in scope)
xs  : List A
A   : Set  (not in scope)

When I tried the above I was surprised to see it rewrite both the goal and the premise. So from that the way to rewrite the premise is.

Any-comm xs [] prf rewrite ++-identityʳ xs = prf

I am not sure if this is supposed to be so surprising, but I had not noticed this despite nearly going through the entirety of vol 1 of the PLFA book. This behavior is different from Coq's rewrite.


问:
Files gets uploaded twice from Azure storage. Possible problem with deleting?
This is an issue regarding Azure Storage and Azure Functions in Microsoft Azure.

I have a container inside a storage, aswell as a timer function. The idea is that whenever someone drops zip files (containing JSON files) into the container, the timer function will upload the content to a database. The timer function checks the storage continously if it contains any zip files. The reason I choose a timer function instead of a blob trigger is that the database can't handle too many queries at the same time in case someone the container recieves a large amount of zip files.

Now, the problem is that, sometimes the function will upload the same file twice to the database, even tho I delete the file in the storage after it has been uploaded. I have no idea why because it seems to me that the files have been removed successfully every time I have tested it.

So far I've tested uploading local files from a console app, which works fine, so it's nothing wrong with the uploading itself.
I've tested running the method after I've uploaded all the zips to the storage. This works fine too.
The problem seem to occur when the timer function is running and reading the zip files, while more zip files are added to the storage.

Timer function:

static ConcurrentQueue<CloudBlockBlob> queue;

[FunctionName("RezippedUploadFunction")]
public static async System.Threading.Tasks.Task RunAsync([TimerTrigger("0 * * * * *")]TimerInfo myTimer, ILogger log)
{
    var storage = new Storage();
    var blobs = await storage.GetCloudBlockBlobsAsync("rezipped");

    if (blobs.Count == 0) return;
    queue = new ConcurrentQueue<CloudBlockBlob>(blobs);
    var ctasks = 30;
    var tasks = new Task[ctasks];

    for (var i = 0; i < ctasks; i++)
    {
        tasks[i] = Task.Factory.StartNew(() => UploadTaskTest());
    }
    Task.WaitAll(tasks);
    blobs.ForEach(x => Task.WaitAll(storage.HardDeleteBlobAsync(x.Name, "rezipped")));

    Thread.Sleep(1000 * 60);
    log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
}
```

<p>Upload method:</p>

<pre class="lang-cs prettyprint-override"><code>static void UploadTaskTest()
{
    var finish = DateTime.Now.AddMinutes(5);
    var zip = new Zip();
    var storage = new Storage();
    CloudBlockBlob blob;

    while (queue.TryDequeue(out blob))
    {
        var stream = storage.DownloadBlobAsync(blob.Name, "rezipped");
        Task.WaitAll(stream);
        zip.UploadZip(stream.Result);
        //if (DateTime.Now > finish) break;
    }
}
</code>```

Additional methods:

public async Task HardDeleteBlobAsync(string name, string container)
{
    await GetContainer(container).GetBlockBlobReference(name).DeleteAsync();
}
```

The expected result is that every file uploaded to the storage should only be read and uploaded once to the database.
The actual result is that sometimes (this varies alot, maybe between 1 in 10-100 files) a file is read and uploaded twice.

答:
I believe there is more than one instance has been triggered rather than a single instance. But I am not 100% sure

Alternatively, you can use a Event Grid to Trigger the Azure Function. Since Event will contain will have only context, Which may help you to decide, whether to process the file or ignore if it is a bigger size. This solution will be optimal and also reduce cost of running the function (you can switch to consumption rather than app service plan).

Body:
This is an issue regarding Azure Storage and Azure Functions in Microsoft Azure.

I have a container inside a storage, aswell as a timer function. The idea is that whenever someone drops zip files (containing JSON files) into the container, the timer function will upload the content to a database. The timer function checks the storage continously if it contains any zip files. The reason I choose a timer function instead of a blob trigger is that the database can't handle too many queries at the same time in case someone the container recieves a large amount of zip files.

Now, the problem is that, sometimes the function will upload the same file twice to the database, even tho I delete the file in the storage after it has been uploaded. I have no idea why because it seems to me that the files have been removed successfully every time I have tested it.

So far I've tested uploading local files from a console app, which works fine, so it's nothing wrong with the uploading itself.
I've tested running the method after I've uploaded all the zips to the storage. This works fine too.
The problem seem to occur when the timer function is running and reading the zip files, while more zip files are added to the storage.

Timer function:

static ConcurrentQueue<CloudBlockBlob> queue;

[FunctionName("RezippedUploadFunction")]
public static async System.Threading.Tasks.Task RunAsync([TimerTrigger("0 * * * * *")]TimerInfo myTimer, ILogger log)
{
    var storage = new Storage();
    var blobs = await storage.GetCloudBlockBlobsAsync("rezipped");

    if (blobs.Count == 0) return;
    queue = new ConcurrentQueue<CloudBlockBlob>(blobs);
    var ctasks = 30;
    var tasks = new Task[ctasks];

    for (var i = 0; i < ctasks; i++)
    {
        tasks[i] = Task.Factory.StartNew(() => UploadTaskTest());
    }
    Task.WaitAll(tasks);
    blobs.ForEach(x => Task.WaitAll(storage.HardDeleteBlobAsync(x.Name, "rezipped")));

    Thread.Sleep(1000 * 60);
    log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
}

Upload method:

static void UploadTaskTest()
{
    var finish = DateTime.Now.AddMinutes(5);
    var zip = new Zip();
    var storage = new Storage();
    CloudBlockBlob blob;

    while (queue.TryDequeue(out blob))
    {
        var stream = storage.DownloadBlobAsync(blob.Name, "rezipped");
        Task.WaitAll(stream);
        zip.UploadZip(stream.Result);
        //if (DateTime.Now > finish) break;
    }
}

Additional methods:

public async Task HardDeleteBlobAsync(string name, string container)
{
    await GetContainer(container).GetBlockBlobReference(name).DeleteAsync();
}

The expected result is that every file uploaded to the storage should only be read and uploaded once to the database.
The actual result is that sometimes (this varies alot, maybe between 1 in 10-100 files) a file is read and uploaded twice.


问:
WPF ListView control is populated but invisible
I have a ListView, populated with ItemsSource pointing to a list of login histories, so that I can choose from previous successful logins instead of having to type user, host, etc. over. This seemed to be working fine, but for some reason now the databinding is working fine but the items in the control are invisible. I can tell the control is being populated correctly because "ghosts" of the items are available and highlight when I mouseover them, in the correct number as in my ItemsSource,  and they are bound correctly - for instance if my ItemsSource has LoginA, LoginQ, and LoginZ and click on the second 'invisible' item, LoginQ happens. I've tried messing with opacity, changing where ItemsSource is bound (after/before login dialog appears, etc). with no joy. Compared to an older working version I can't see anything that appears to be relevant. Hints, suggestions, and catcalls welcome.....</p>

答: It sounds like the properties in your list item type are either not actually properties (they could be public fields instead, which you cannot bind to), or their values change later in your code and you haven't implemented INotifyPropertyChanged to notify the XAML binding engine that their values have updated.</p>

ContentLicense: CC BY-SA 3.0


问:
I was trying to complete a palindrome-check but reverse variable is not having the expected value
The following code should perform a check if the number provided by a user is palindrome or not, but the code in while loop reverse is always not equal to the number even when I enter 12321 as a value.

```<code>number=input("Type the number:")

temp=number
reverse=0
reminder=0

while temp!=0 :
      reminder=int(temp)%10
      reverse=reverse*10+reminder
      temp=int(temp)/10

if reverse==number :
      print("this is a palindrome number")
else:
      print("this is not a palindrome number")
</code>```

答:
for floor division, use "//"

```<code>number=int(input("Type the number:"))

temp=number
reverse=0
reminder=0

while temp!=0 :
      reminder=temp%10
      reverse=reverse*10+reminder
      temp=temp//10 # <-------
      # or u can use
      # temp=int(temp/10) # <-------
if reverse==number :
      print("this is a palindrome number")
else:
      print("this is not a palindrome number")
</code>```

// floor division

Description:

Returns the integral part of the quotient.

Syntax:

```<code>A // B
</code>```

A: Any expression evaluating to a numeric type.

B: Any expression evaluating to a numeric type.

Return Value:

According to coercion rules.

Remarks:

Also referred to as integer division. The resultant value is a whole
  integer, though the result’s type is not necessarily int.

Example:

```<code>>>> 5.0 / 2
2.5
>>> 5.0 // 2
2.0
</code>```

.

NOTE:

In Python 3.0, 5 / 2 will return 2.5 and 5 // 2 will return 2. The
  former is floating point division, and the latter is floor division,
  sometimes also called integer division.

In Python 2.2 or later in the 2.x line, there is no difference for
  integers unless you perform a from future import division, which
  causes Python 2.x to adopt the behavior of 3.0

Regardless of the future import, 5.0 // 2 will return 2.0 since that's
  the floor division result of the operation.

Body:
The following code should perform a check if the number provided by a user is palindrome or not, but the code in while loop reverse is always not equal to the number even when I enter 12321 as a value.

number=input("Type the number:")

temp=number
reverse=0
reminder=0

while temp!=0 :
      reminder=int(temp)%10
      reverse=reverse*10+reminder
      temp=int(temp)/10

if reverse==number :
      print("this is a palindrome number")
else:
      print("this is not a palindrome number")

Body:
for floor division, use "//"

number=int(input("Type the number:"))

temp=number
reverse=0
reminder=0

while temp!=0 :
      reminder=temp%10
      reverse=reverse*10+reminder
      temp=temp//10 # <-------
      # or u can use
      # temp=int(temp/10) # <-------
if reverse==number :
      print("this is a palindrome number")
else:
      print("this is not a palindrome number")

// floor division

Description:

Returns the integral part of the quotient.

Syntax:

A // B

A: Any expression evaluating to a numeric type.

B: Any expression evaluating to a numeric type.

Return Value:

According to coercion rules.

Remarks:

Also referred to as integer division. The resultant value is a whole
  integer, though the result’s type is not necessarily int.

Example:

>>> 5.0 / 2
2.5
>>> 5.0 // 2
2.0

.

NOTE:

In Python 3.0, 5 / 2 will return 2.5 and 5 // 2 will return 2. The
  former is floating point division, and the latter is floor division,
  sometimes also called integer division.

In Python 2.2 or later in the 2.x line, there is no difference for
  integers unless you perform a from future import division, which
  causes Python 2.x to adopt the behavior of 3.0

Regardless of the future import, 5.0 // 2 will return 2.0 since that's
  the floor division result of the operation.


问:
How to use numeric array in AWK command for comparison?
I have a string called x. This array contains 12 numbers separated by new line. (I simply typed "$x" which gave 1\n2\n3\n4\n5\n6\n7\n8\n53\n54\n55 74) Inside a for loop I want to check whether the loop index matches with any of the elements of the array x.

This is how I tried.

```<code>echo $x  # This return 1 2 3 4 5 6 7 8 53 54 55 74
for ((i=1; i<=$(cat Reaction_names | wc -l); i++)); do
 Condition=$(awk 'BEGIN{print ('${i}'=='$x')?1:0}')
if [ $Condition = 1 ]
     then
       bla bla bla ......
fi

done
</code>```

This code produces an error like "1^unexpected newline or end of string"

答:
I think you're looking for something like that :

```<code>for ((i=1; i<=$(cat Reaction_names | wc -l); i++)); do
    if grep -qx "$i" <<<"$x"; then
         echo "number $i found !"
    fi
done
</code>```

You can try it here.

The line if grep -qx "$i" <<<"$x"; then can be understood as follows :

if command; then: if the commands returns with a zero exit code, then execute the code (grep will exit with 0 if it matches something and another code otherwise)

grep's -q flag makes grep suppress its output, which we don't need since we only rely on the exit code.

grep's -x flag makes it match only full lines, which makes sure you don't match "123" when looking for "12" (regex alternative : match ^12$ instead of 12)

<<<"$x" is a herestring which provides your list of numbers as input to grep.

Body:
I have a string called x. This array contains 12 numbers separated by new line. (I simply typed "$x" which gave 1\n2\n3\n4\n5\n6\n7\n8\n53\n54\n55 74) Inside a for loop I want to check whether the loop index matches with any of the elements of the array x.

This is how I tried.

echo $x  # This return 1 2 3 4 5 6 7 8 53 54 55 74
for ((i=1; i<=$(cat Reaction_names | wc -l); i++)); do
 Condition=$(awk 'BEGIN{print ('${i}'=='$x')?1:0}')
if [ $Condition = 1 ]
     then
       bla bla bla ......
fi

done

This code produces an error like "1^unexpected newline or end of string"

Body:
I think you're looking for something like that :

for ((i=1; i<=$(cat Reaction_names | wc -l); i++)); do
    if grep -qx "$i" <<<"$x"; then
         echo "number $i found !"
    fi
done

You can try it here.

The line if grep -qx "$i" <<<"$x"; then can be understood as follows :

if command; then: if the commands returns with a zero exit code, then execute the code (grep will exit with 0 if it matches something and another code otherwise)

grep's -q flag makes grep suppress its output, which we don't need since we only rely on the exit code.

grep's -x flag makes it match only full lines, which makes sure you don't match "123" when looking for "12" (regex alternative : match ^12$ instead of 12)

<<<"$x" is a herestring which provides your list of numbers as input to grep.


问:
How to dismiss a dialog fragment from a recyclerview adapter
A silly question but I am new to Android and I’ve spent a few hours looking around but can’t find the answer.

I have a dialog fragment with a recyclerview in it. I want the dialog to close when the user clicks a recyclerview item. How do I call dismiss() from the listener in recyclerview adapter?

I've tried a listener for the recyclerview in the dialog fragment but it does nothing. please help.

This is the dialog fragment. At the bottom onClick dismisses it:

```<code>public class EvMySchedDlg extends DialogFragment implements View.OnClickListener {
View view;
String eventId;

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

    ImageView closeButton = view.findViewById(R.id.closeButton3);
    closeButton.setOnClickListener(this);
    final TextView eventNameBox = view.findViewById(R.id.eventNameBox);
    eventNameBox.setOnClickListener(this);
    TextView coNameBox = view.findViewById(R.id.coNameBox);

    Bundle extraData = getArguments();
    eventId = extraData.getString("eventId");
    String coName = extraData.getString("coName");
    String eventName = extraData.getString("eventName");

    coNameBox.setText(coName);
    eventNameBox.setText(eventName);
    //get list of days from server
    String userId = ((DrawerActivity)getContext()).getUserData("userId");
    final String[] cred = new String[]{"user_id", userId, "event_id", eventId};
    VolleyCalls.postRequest(this.getContext(), "getEventDays", cred, new VolleyCalls.ServerReply() {
        @Override
        public void onSuccess(String theReply){
            final List<EvMySchedData> dayList = new ArrayList<>();
            EvMySchedAdapter tAdapter = new EvMySchedAdapter(dayList);

            RecyclerView recyclerView = view.findViewById(R.id.schedRecycler);
            RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(recyclerView.getContext());
            recyclerView.setLayoutManager(mLayoutManager);
            recyclerView.setItemAnimator(new DefaultItemAnimator());
            recyclerView.setAdapter(tAdapter);
            tAdapter.emptyRecycler();

            try {
                JSONObject jsonServerReply = new JSONObject(theReply);
                int evCount = jsonServerReply.getInt("recCount");

                EvMySchedData thisLine;

                if (evCount > 0) {
                    JSONObject cRec =null;
                    for (int thisRec=0; thisRec<evCount; thisRec++ ) {
                        cRec = jsonServerReply.getJSONObject(String.valueOf(thisRec));
                        thisLine = new EvMySchedData(cRec.getString("day_date"), cRec.getString("day_times"), cRec.getString("role"), cRec.getString("room"), view.getContext());
                        dayList.add(thisLine);
                    }
                }

            } catch (Exception e) {

            }
        }
        public void onError(String error) {

        }
    });

    return view;
} // end onCreateView

public void onClick(View v) {
    this.dismiss();
}
</code>```

}

The recyclerview has the picture of an eye on each line. I want to load a new fragment and close the dialog fragment when the eye is clickd. This is the adapter code:

```<code>public class EvMySchedAdapter extends RecyclerView.Adapter<EvMySchedAdapter.EventViewHolder> {

private List<EvMySchedData> dayList;

public EvMySchedAdapter(List<EvMySchedData> dayList) {
    this.dayList = dayList;
}

@Override
public EvMySchedAdapter.EventViewHolder onCreateViewHolder(final ViewGroup parent, int viewType) {
    final View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.event_my_sched_row, parent, false);
    ImageView eye = itemView.findViewById(R.id.dayOverviewButton);

    try {
        eye.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

//Load a new fragment
//dismiss the dialog
            }
        });

    } catch (Exception e) {

    }

    return new EvMySchedAdapter.EventViewHolder(itemView);
}

@Override
public void onBindViewHolder(EvMySchedAdapter.EventViewHolder holder, int position) {
    holder.dayDateBox.setText(dayList.get(position).getDayDate());
    holder.dayTimeBox.setText(dayList.get(position).getDayTime());
    holder.dayRoleBox.setText(dayList.get(position).getDayRole());
    holder.dayRoomBox.setText(dayList.get(position).getDayRoom());

} // end onBindViewHolder

@Override
public int getItemCount() {
    return dayList.size();
}

public class EventViewHolder extends RecyclerView.ViewHolder {
    public TextView dayDateBox;
    public TextView dayTimeBox;
    public TextView dayRoleBox;
    public TextView dayRoomBox;
    public Context context;

    public EventViewHolder(View view) {
        super(view);
        dayDateBox = view.findViewById(R.id.dateBox);
        dayTimeBox = view.findViewById(R.id.timeBox);
        dayRoleBox = view.findViewById(R.id.roleBox);
        dayRoomBox = view.findViewById(R.id.roomBox);
    }
}

public void emptyRecycler() {
    final int size = dayList.size();
    dayList.clear();
    notifyItemRangeRemoved(0, size);
}
</code>```

}

Thanks

答:
Add to the adapter a constructor that receive DialogFragment and save it as a field.

When you create the Adapter do new EvMySchedAdapter(dayList, EvMySchedDlg.this);

Inside the onClick call dialgFragment.dismiss();

Body:
A silly question but I am new to Android and I’ve spent a few hours looking around but can’t find the answer.

I have a dialog fragment with a recyclerview in it. I want the dialog to close when the user clicks a recyclerview item. How do I call dismiss() from the listener in recyclerview adapter?

I've tried a listener for the recyclerview in the dialog fragment but it does nothing. please help.

This is the dialog fragment. At the bottom onClick dismisses it:

public class EvMySchedDlg extends DialogFragment implements View.OnClickListener {
View view;
String eventId;

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

    ImageView closeButton = view.findViewById(R.id.closeButton3);
    closeButton.setOnClickListener(this);
    final TextView eventNameBox = view.findViewById(R.id.eventNameBox);
    eventNameBox.setOnClickListener(this);
    TextView coNameBox = view.findViewById(R.id.coNameBox);

    Bundle extraData = getArguments();
    eventId = extraData.getString("eventId");
    String coName = extraData.getString("coName");
    String eventName = extraData.getString("eventName");

    coNameBox.setText(coName);
    eventNameBox.setText(eventName);
    //get list of days from server
    String userId = ((DrawerActivity)getContext()).getUserData("userId");
    final String[] cred = new String[]{"user_id", userId, "event_id", eventId};
    VolleyCalls.postRequest(this.getContext(), "getEventDays", cred, new VolleyCalls.ServerReply() {
        @Override
        public void onSuccess(String theReply){
            final List<EvMySchedData> dayList = new ArrayList<>();
            EvMySchedAdapter tAdapter = new EvMySchedAdapter(dayList);

            RecyclerView recyclerView = view.findViewById(R.id.schedRecycler);
            RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(recyclerView.getContext());
            recyclerView.setLayoutManager(mLayoutManager);
            recyclerView.setItemAnimator(new DefaultItemAnimator());
            recyclerView.setAdapter(tAdapter);
            tAdapter.emptyRecycler();

            try {
                JSONObject jsonServerReply = new JSONObject(theReply);
                int evCount = jsonServerReply.getInt("recCount");

                EvMySchedData thisLine;

                if (evCount > 0) {
                    JSONObject cRec =null;
                    for (int thisRec=0; thisRec<evCount; thisRec++ ) {
                        cRec = jsonServerReply.getJSONObject(String.valueOf(thisRec));
                        thisLine = new EvMySchedData(cRec.getString("day_date"), cRec.getString("day_times"), cRec.getString("role"), cRec.getString("room"), view.getContext());
                        dayList.add(thisLine);
                    }
                }

            } catch (Exception e) {

            }
        }
        public void onError(String error) {

        }
    });

    return view;
} // end onCreateView

public void onClick(View v) {
    this.dismiss();
}

}

The recyclerview has the picture of an eye on each line. I want to load a new fragment and close the dialog fragment when the eye is clickd. This is the adapter code:

public class EvMySchedAdapter extends RecyclerView.Adapter<EvMySchedAdapter.EventViewHolder> {

private List<EvMySchedData> dayList;

public EvMySchedAdapter(List<EvMySchedData> dayList) {
    this.dayList = dayList;
}

@Override
public EvMySchedAdapter.EventViewHolder onCreateViewHolder(final ViewGroup parent, int viewType) {
    final View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.event_my_sched_row, parent, false);
    ImageView eye = itemView.findViewById(R.id.dayOverviewButton);

    try {
        eye.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

//Load a new fragment
//dismiss the dialog
            }
        });

    } catch (Exception e) {

    }

    return new EvMySchedAdapter.EventViewHolder(itemView);
}

@Override
public void onBindViewHolder(EvMySchedAdapter.EventViewHolder holder, int position) {
    holder.dayDateBox.setText(dayList.get(position).getDayDate());
    holder.dayTimeBox.setText(dayList.get(position).getDayTime());
    holder.dayRoleBox.setText(dayList.get(position).getDayRole());
    holder.dayRoomBox.setText(dayList.get(position).getDayRoom());

} // end onBindViewHolder

@Override
public int getItemCount() {
    return dayList.size();
}

public class EventViewHolder extends RecyclerView.ViewHolder {
    public TextView dayDateBox;
    public TextView dayTimeBox;
    public TextView dayRoleBox;
    public TextView dayRoomBox;
    public Context context;

    public EventViewHolder(View view) {
        super(view);
        dayDateBox = view.findViewById(R.id.dateBox);
        dayTimeBox = view.findViewById(R.id.timeBox);
        dayRoleBox = view.findViewById(R.id.roleBox);
        dayRoomBox = view.findViewById(R.id.roomBox);
    }
}

public void emptyRecycler() {
    final int size = dayList.size();
    dayList.clear();
    notifyItemRangeRemoved(0, size);
}

}

Thanks


问:
Create a class with fields automatic in TypeScript
See my code:

```<code>interface IMyInterface{
  a:string
  b:string
  c:number
  //and more...
}
class MyClass extends IMyInterface{ //err 1
  //the class has all fields from IMyInterface
  constructor(opt:IMyInterface){
    for(let key in opt){
      this[key]=opt[key] //err2
    }
  }
  myOtherMethods(){}
}
</code>```

I want a class has all fields extends from an interface(returned from a HTTP request) and auto construct it with values. Above code has 2 errors:

Classes can not extends an interface, but if I use implements, I need to write all fields and types in the class again.

The type of the key is string, and I can not access the field trough it on this.

答:
what about generic type

```<code>interface IMyInterface {
  a: string;
  b: string;
  c: number;
  // and more...
}

class MyClass<T extends IMyInterface> { // or whatever interface you want
  public data: T;

  constructor(opt: T) {
    this.data = opt;
  }
}
</code>```

if you need them to  be exactly class fields you can check this solution

Body:
See my code:

interface IMyInterface{
  a:string
  b:string
  c:number
  //and more...
}
class MyClass extends IMyInterface{ //err 1
  //the class has all fields from IMyInterface
  constructor(opt:IMyInterface){
    for(let key in opt){
      this[key]=opt[key] //err2
    }
  }
  myOtherMethods(){}
}

I want a class has all fields extends from an interface(returned from a HTTP request) and auto construct it with values. Above code has 2 errors:

Classes can not extends an interface, but if I use implements, I need to write all fields and types in the class again.

The type of the key is string, and I can not access the field trough it on this.

Body:
what about generic type

interface IMyInterface {
  a: string;
  b: string;
  c: number;
  // and more...
}

class MyClass<T extends IMyInterface> { // or whatever interface you want
  public data: T;

  constructor(opt: T) {
    this.data = opt;
  }
}

if you need them to  be exactly class fields you can check this solution


问:
TPC-DS queries generator
I need to test my data warehouse using TPC-DS. How can I generate queries for my data warehouse using TPC-DS?
I tried to generate but it generate for a specific data warehouse.

Thanks.

答:
I'm not sure what you mean by "testing your data warehouse" using TPC-DS.

TPC-DS is a benchmark for database engines, focused on typical decision support access patterns; a data warehouse is an information systems concept that is usually built using a variety of database management systems (and other tools).

This being clarified, you can use TPC-DS to benchmark the database engine that you plan to use as a data store for your data warehouse. If that's your goal, you need to:

either generate the data using the official TPC-DS tool, or download the dataset if you can find it online (alternatively, maybe your database vendor provides it already).

load the data into the benchmark's model on the database you're testing.

run the benchmark (the queries) over the data model you created. You can find an example of the queries here (for Impala, in this case), but you may have to translate them into the SQL idiom used by whatever DBMS you're using.

The TPC-DS specification doc not only provides this information but it can also help you understand some essential concepts on this topic: http://www.tpc.org/tpc_documents_current_versions/pdf/tpc-ds_v2.11.0.pdf

Title: TPC-DS queries generator


问:
Pagination help in SQL
The below inner SELECT returns huge amount of rows (1000000+) and the outer SELECTs(alpha BETWEEN #startRec# AND #endRec#) is used for PAGINATION
to display data with 25 in each page.

Issue is:-This PAGINATION done below is very slow and slows the entire display of data.So could all please help me on doing this below
pagination in a BETTER WAY? COde about pagination would be best.

**I am very sorry to put in this way but i am very new to Pagination concepts and so need your help.

```<code>/*********ORIGINAL QUERY ****/
SELECT
*
FROM
(
SELECT
beta.*, rownum as alpha
FROM
(
SELECT
p.lastname, p.firstname, porg.DEPARTMENT,
porg.org_relationship,
porg.enterprise_name,
(
SELECT
count(*)
FROM
test_person p, test_contact c1, test_org_person porg
WHERE
p.p_id = c1.ref_id(+)
AND p.p_id = porg.o_p_id
$where_clause$

) AS results
FROM
test_person p, test_contact c1, test_org_person porg
WHERE
p.p_id = c1.ref_id(+)
AND p.p_id = porg.o_p_id
$where_clause$

ORDER BY
upper(p.lastname), upper(p.firstname)
) beta
)
WHERE
alpha BETWEEN #startRec# AND #endRec#
</code>```

My tried implementation below

(1)The inner most query..is the 1st QUERY fetching the data.
(2)Then,we do a total COUNT on the above data.

Now,main issue is running the query goes on forever....and finally i have to forcibly cancel it.
I feel there is something missing in the below query for which it hangs off.

Also,I came to know doing the COUNT outside is the best approach for performance.So,could you please correct the query below so that I am able return the COUNT
*** DATA using Pagination,rownum etc.Mainly with the aliases below,rownum and getting data.

```<code>select * from
( select x.* ,rownum rnum

from ( SELECT
count(*) as results /****2nd QUERY is OUTSIDE to get total count**/
</code>```

Question is here,how do i access the data selected inside the 1st query below

```<code>from ( /****1st query to SELECT data***/

SELECT
p.lastname, p.firstname, porg.DEPARTMENT,
porg.org_relationship,
porg.enterprise_name

FROM
t_person p, t_contact c1, t_o_person porg
WHERE rownum <10
and
p.person_id = c1.ref_id(+)
AND p.person_id = porg.o_person_id

ORDER BY
upper(p.lastname), upper(p.firstname)

) y ------------------>alias defined Y from data of the 1st query

)x ------------------>alias defined X
where rownum <= 20 )
where rnum >= 1
</code>```

答:
My suggestion is :

Create an index on test_person by lastname + firstname (in this order)

If possible, remove the upper functions (some DBs allow creating indexes using functions)

Remove the external SELECT and do the pagination in the client (not in DB)

I suspect that the internal subquery must be resolved first, and that's costly if there are no proper indexes. Usually ordering by computed columns do not use indexes, temporal tables are created etcetera.

Cheers

OwnerDisplayName: Neer

LastEditorDisplayName: Tom H.

ContentLicense: CC BY-SA 2.5

Title: Pagination help in SQL

Body:
The below inner SELECT returns huge amount of rows (1000000+) and the outer SELECTs(alpha BETWEEN #startRec# AND #endRec#) is used for PAGINATION
to display data with 25 in each page.

Issue is:-This PAGINATION done below is very slow and slows the entire display of data.So could all please help me on doing this below
pagination in a BETTER WAY? COde about pagination would be best.

**I am very sorry to put in this way but i am very new to Pagination concepts and so need your help.

/*********ORIGINAL QUERY ****/
SELECT
*
FROM
(
SELECT
beta.*, rownum as alpha
FROM
(
SELECT
p.lastname, p.firstname, porg.DEPARTMENT,
porg.org_relationship,
porg.enterprise_name,
(
SELECT
count(*)
FROM
test_person p, test_contact c1, test_org_person porg
WHERE
p.p_id = c1.ref_id(+)
AND p.p_id = porg.o_p_id
$where_clause$

) AS results
FROM
test_person p, test_contact c1, test_org_person porg
WHERE
p.p_id = c1.ref_id(+)
AND p.p_id = porg.o_p_id
$where_clause$

ORDER BY
upper(p.lastname), upper(p.firstname)
) beta
)
WHERE
alpha BETWEEN #startRec# AND #endRec#

My tried implementation below

(1)The inner most query..is the 1st QUERY fetching the data.
(2)Then,we do a total COUNT on the above data.

Now,main issue is running the query goes on forever....and finally i have to forcibly cancel it.
I feel there is something missing in the below query for which it hangs off.

Also,I came to know doing the COUNT outside is the best approach for performance.So,could you please correct the query below so that I am able return the COUNT
*** DATA using Pagination,rownum etc.Mainly with the aliases below,rownum and getting data.

select * from
( select x.* ,rownum rnum

from ( SELECT
count(*) as results /****2nd QUERY is OUTSIDE to get total count**/

Question is here,how do i access the data selected inside the 1st query below

from ( /****1st query to SELECT data***/

SELECT
p.lastname, p.firstname, porg.DEPARTMENT,
porg.org_relationship,
porg.enterprise_name

FROM
t_person p, t_contact c1, t_o_person porg
WHERE rownum <10
and
p.person_id = c1.ref_id(+)
AND p.person_id = porg.o_person_id

ORDER BY
upper(p.lastname), upper(p.firstname)

) y ------------------>alias defined Y from data of the 1st query

)x ------------------>alias defined X
where rownum <= 20 )
where rnum >= 1

OwnerDisplayName: Lluís


问:
I am trying to use datepicker from mdbootstrap but date shows as 0000-00-00 in database
I am using a form to submit date, subject, content text and an image to mysql using php. I see that all the data get inserted into the DB properly except date which shows up as 0000-00-00 in the table row.

I have unable to figure out how to change date format to be sent to DB.

<form action="#" enctype="multipart/form-data" method="post">

           Event Date :
          <input type="date" name='news_event_date' id="date-picker-example" class="form-control datepicker"/>

            Update Header:
            <textarea id="form7" class="md-textarea form-control" rows="1" type="text" name="news_header" ></textarea>

          Update Body:
          <textarea type="text" id="form8" class="md-textarea form-control" name="news_body" rows="2" ></textarea>

          Password :
          <input id="form9" type="password" name="news_password" class="md-textarea form-control" autocomplete="new-password"/>

                  Choose files
                  <input type="file" accept="image/*" name="news_single_file">

              <input  class="file-path validate" type="text" placeholder="Upload one or more files">

          <button class="btn btn-outline-info btn-rounded btn-block z-depth-0 my-4 waves-effect" type="submit" name="news_submit" value="Subm"/>

  </form>
```

All values are updated as required apart from date.

答:
Which format of date you use in the datepicker?

If you want to store date from datepicker to DB you should set right format when you initialize Datepicker:

$( ".selector" ).datepicker({
  dateFormat: "yy-mm-dd"
});

Default datepicker format is "mm/dd/yy"

Another option, you can process date before storing it in the DB (convert it from one format to another). Keep in mind that if you want to show date in case of form errors, you should convert it back and show in form in the initial format.

Body:
I am using a form to submit date, subject, content text and an image to mysql using php. I see that all the data get inserted into the DB properly except date which shows up as 0000-00-00 in the table row.

I have unable to figure out how to change date format to be sent to DB.

<form action="#" enctype="multipart/form-data" method="post">

           Event Date :
          <input type="date" name='news_event_date' id="date-picker-example" class="form-control datepicker"/>

            Update Header:
            <textarea id="form7" class="md-textarea form-control" rows="1" type="text" name="news_header" ></textarea>

          Update Body:
          <textarea type="text" id="form8" class="md-textarea form-control" name="news_body" rows="2" ></textarea>

          Password :
          <input id="form9" type="password" name="news_password" class="md-textarea form-control" autocomplete="new-password"/>

                  Choose files
                  <input type="file" accept="image/*" name="news_single_file">

              <input  class="file-path validate" type="text" placeholder="Upload one or more files">

          <button class="btn btn-outline-info btn-rounded btn-block z-depth-0 my-4 waves-effect" type="submit" name="news_submit" value="Subm"/>

  </form>

All values are updated as required apart from date.


问:
Spring @Transaction method call by the method within the same class, does not work?
I am new to Spring Transaction. Something that I found really odd, probably I did understand this properly.

I wanted to have a transactional around method level and I have a caller method within the same class and it seems like it does not like that, it has to be called from the separate class. I don't understand how is that possible.

If anyone has an idea how to resolve this issue, I would greatly appreciate. I would like to use the same class to call the annotated transactional method.

Here is the code:

```<code>public class UserService {

    @Transactional
    public boolean addUser(String userName, String password) {
        try {
            // call DAO layer and adds to database.
        } catch (Throwable e) {
            TransactionAspectSupport.currentTransactionStatus()
                    .setRollbackOnly();

        }
    }

    public boolean addUsers(List<User> users) {
        for (User user : users) {
            addUser(user.getUserName, user.getPassword);
        }
    }
}
</code>```

答:
In Java 8+ there's another possibility, which I prefer for the reasons given below:

```<code>@Service
public class UserService {

    @Autowired
    private TransactionHandler transactionHandler;

    public boolean addUsers(List<User> users) {
        for (User user : users) {
            transactionHandler.runInTransaction(() -> addUser(user.getUsername, user.getPassword));
        }
    }

    private boolean addUser(String username, String password) {
        // TODO call userRepository
    }
}

@Service
public class TransactionHandler {

    @Transactional(propagation = Propagation.REQUIRED)
    public <T> T runInTransaction(Supplier<T> supplier) {
        return supplier.get();
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public <T> T runInNewTransaction(Supplier<T> supplier) {
        return supplier.get();
    }
}
</code>```

This approach has the following advantages:

It may be applied to private methods. So you don't have to break encapsulation by making a method public just to satisfy Spring limitations.

Same method may be called within different transaction propagations and it is up to the caller to choose the suitable one. Compare these 2 lines:

transactionHandler.runInTransaction(() -> userService.addUser(user.getUserName, user.getPassword));

transactionHandler.runInNewTransaction(() -> userService.addUser(user.getUserName, user.getPassword));

It is explicit, thus more readable.

Body:
I am new to Spring Transaction. Something that I found really odd, probably I did understand this properly.

I wanted to have a transactional around method level and I have a caller method within the same class and it seems like it does not like that, it has to be called from the separate class. I don't understand how is that possible.

If anyone has an idea how to resolve this issue, I would greatly appreciate. I would like to use the same class to call the annotated transactional method.

Here is the code:

public class UserService {

    @Transactional
    public boolean addUser(String userName, String password) {
        try {
            // call DAO layer and adds to database.
        } catch (Throwable e) {
            TransactionAspectSupport.currentTransactionStatus()
                    .setRollbackOnly();

        }
    }

    public boolean addUsers(List<User> users) {
        for (User user : users) {
            addUser(user.getUserName, user.getPassword);
        }
    }
}

Body:
In Java 8+ there's another possibility, which I prefer for the reasons given below:

@Service
public class UserService {

    @Autowired
    private TransactionHandler transactionHandler;

    public boolean addUsers(List<User> users) {
        for (User user : users) {
            transactionHandler.runInTransaction(() -> addUser(user.getUsername, user.getPassword));
        }
    }

    private boolean addUser(String username, String password) {
        // TODO call userRepository
    }
}

@Service
public class TransactionHandler {

    @Transactional(propagation = Propagation.REQUIRED)
    public <T> T runInTransaction(Supplier<T> supplier) {
        return supplier.get();
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public <T> T runInNewTransaction(Supplier<T> supplier) {
        return supplier.get();
    }
}

This approach has the following advantages:

It may be applied to private methods. So you don't have to break encapsulation by making a method public just to satisfy Spring limitations.

Same method may be called within different transaction propagations and it is up to the caller to choose the suitable one. Compare these 2 lines:

transactionHandler.runInTransaction(() -> userService.addUser(user.getUserName, user.getPassword));

transactionHandler.runInNewTransaction(() -> userService.addUser(user.getUserName, user.getPassword));

It is explicit, thus more readable.


问:
How to fix "Could not initialize class org.apache.ignite.IgniteJdbcThinDriver" error in Apache Ignite?

The Problem

I'm trying to connect to a Apache Ignite server with Apache Ignite built-in tool, SQLLine. I get the error: java.lang.NoClassDefFoundError: Could not initialize class org.apache.ignite.IgniteJdbcThinDriver

Background

I have Apache Ignite running in a container and CentOS7 running in another container. Both containers running in the same network (pinging works both ways). The tried connection is happening from CentOS7 to Apache Ignite.

Apache Ignite seems to be running fine with just the default configuration. In the CentOS7 container, I have installed Oracle JDK 12.0.1 and I have Apache Ignite 2.7.0 binary files in a folder. I have also set the IGNITE_HOME environmental variable.

Here, (https://apacheignite-sql.readme.io/docs/sqlline), it says I can connect to my cluster with just: ./sqlline.sh --verbose=true -u jdbc:ignite:thin://127.0.0.1/. However, this throws the previously mentioned error.

SQLLine should come with Ignite JDBC drivers. I have tried downloading them manually (https://apacheignite-sql.readme.io/docs/jdbc-driver#section-multiple-endpoints). When I downloaded the driver, which is said to be the ignite-core-{version}.jar, I put it in the same folder as sqlline.jar files.

Output

```<code>[root@bc72c4fbf47e bin]# ./sqlline.sh
sqlline version 1.3.0
sqlline> !connect jdbc:ignite:thin://172.19.0.2/
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.apache.ignite.internal.util.GridUnsafe$2 (file:/var/tmp/apache-ignite/libs/ignite-core-2.7.0.jar) to field java.nio.Buffer.address
WARNING: Please consider reporting this to the maintainers of org.apache.ignite.internal.util.GridUnsafe$2
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
java.lang.NoClassDefFoundError: Could not initialize class org.apache.ignite.IgniteJdbcThinDriver
    at java.base/java.lang.Class.forName0(Native Method)
    at java.base/java.lang.Class.forName(Class.java:415)
    at java.sql/java.sql.DriverManager.isDriverAllowed(DriverManager.java:555)
    at java.sql/java.sql.DriverManager.isDriverAllowed(DriverManager.java:547)
    at java.sql/java.sql.DriverManager.getDrivers(DriverManager.java:449)
    at java.sql/java.sql.DriverManager.getDrivers(DriverManager.java:426)
    at sqlline.SqlLine.findRegisteredDriver(SqlLine.java:1568)
    at sqlline.SqlLine.scanForDriver(SqlLine.java:1542)
    at sqlline.Commands.connect(Commands.java:1074)
    at sqlline.Commands.connect(Commands.java:1001)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at sqlline.ReflectiveCommandHandler.execute(ReflectiveCommandHandler.java:38)
    at sqlline.SqlLine.dispatch(SqlLine.java:791)
    at sqlline.SqlLine.begin(SqlLine.java:668)
    at sqlline.SqlLine.start(SqlLine.java:373)
    at sqlline.SqlLine.main(SqlLine.java:265)
</code>```

Conclusion

I should be able to connect to my Ignite server with !connect jdbc:ignite:thin://172.19.0.2/ command in sqlline.
This does not work, and throws Could not initialize class org.apache.ignite.IgniteJdbcThinDriver
IgniteJDBCThinDriver is installed/available.

答:
Thank you @alamar, that worked!

I uninstalled JDK12 that i had installed with RPM.
Check the package name:
rpm -qa | grep jdk.
Delete the package:
rpm -e jdk-12.0.1-12.0.1-ga.x86_64.

I'm working on a isolated system, so I downloaded and transferred JDK8.rpm from another machine.
Install JDK8:
rpm -ihv jdk-8u211-linux-x64.rpm.

Now when I run:
./sqlline.sh --verbose=true -u jdbc:ignite:thin://172.19.0.2,
I get:
issuing: !connect jdbc:ignite:thin://172.19.0.2/ '' '' org.apache.ignite.IgniteJdbcTh
Connecting to jdbc:ignite:thin://172.19.0.2/
Connected to: Apache Ignite (version 2.7.0#20181130-sha1:256ae401)
Driver: Apache Ignite Thin JDBC Driver (version 2.7.0#20181130-sha1:256ae401)
Autocommit status: true
Transaction isolation: TRANSACTION_REPEATABLE_READ
sqlline version 1.3.0.

I can now query my database.

Body:
The Problem

I'm trying to connect to a Apache Ignite server with Apache Ignite built-in tool, SQLLine. I get the error: java.lang.NoClassDefFoundError: Could not initialize class org.apache.ignite.IgniteJdbcThinDriver

Background

I have Apache Ignite running in a container and CentOS7 running in another container. Both containers running in the same network (pinging works both ways). The tried connection is happening from CentOS7 to Apache Ignite.

Apache Ignite seems to be running fine with just the default configuration. In the CentOS7 container, I have installed Oracle JDK 12.0.1 and I have Apache Ignite 2.7.0 binary files in a folder. I have also set the IGNITE_HOME environmental variable.

Here, (https://apacheignite-sql.readme.io/docs/sqlline), it says I can connect to my cluster with just: ./sqlline.sh --verbose=true -u jdbc:ignite:thin://127.0.0.1/. However, this throws the previously mentioned error.

SQLLine should come with Ignite JDBC drivers. I have tried downloading them manually (https://apacheignite-sql.readme.io/docs/jdbc-driver#section-multiple-endpoints). When I downloaded the driver, which is said to be the ignite-core-{version}.jar, I put it in the same folder as sqlline.jar files.

Output

[root@bc72c4fbf47e bin]# ./sqlline.sh
sqlline version 1.3.0
sqlline> !connect jdbc:ignite:thin://172.19.0.2/
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.apache.ignite.internal.util.GridUnsafe$2 (file:/var/tmp/apache-ignite/libs/ignite-core-2.7.0.jar) to field java.nio.Buffer.address
WARNING: Please consider reporting this to the maintainers of org.apache.ignite.internal.util.GridUnsafe$2
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
java.lang.NoClassDefFoundError: Could not initialize class org.apache.ignite.IgniteJdbcThinDriver
    at java.base/java.lang.Class.forName0(Native Method)
    at java.base/java.lang.Class.forName(Class.java:415)
    at java.sql/java.sql.DriverManager.isDriverAllowed(DriverManager.java:555)
    at java.sql/java.sql.DriverManager.isDriverAllowed(DriverManager.java:547)
    at java.sql/java.sql.DriverManager.getDrivers(DriverManager.java:449)
    at java.sql/java.sql.DriverManager.getDrivers(DriverManager.java:426)
    at sqlline.SqlLine.findRegisteredDriver(SqlLine.java:1568)
    at sqlline.SqlLine.scanForDriver(SqlLine.java:1542)
    at sqlline.Commands.connect(Commands.java:1074)
    at sqlline.Commands.connect(Commands.java:1001)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at sqlline.ReflectiveCommandHandler.execute(ReflectiveCommandHandler.java:38)
    at sqlline.SqlLine.dispatch(SqlLine.java:791)
    at sqlline.SqlLine.begin(SqlLine.java:668)
    at sqlline.SqlLine.start(SqlLine.java:373)
    at sqlline.SqlLine.main(SqlLine.java:265)

Conclusion

I should be able to connect to my Ignite server with !connect jdbc:ignite:thin://172.19.0.2/ command in sqlline.
This does not work, and throws Could not initialize class org.apache.ignite.IgniteJdbcThinDriver
IgniteJDBCThinDriver is installed/available.


问:
How to get Sum from List in another List as a property with linq
My classes are like below.

```<code>public class ModelMMaster
{
    public string OrderID { get; set; }
    public bool IsActive { get; set; }
    public List<ModelDetail> _detail { get; set; }
}
public class ModelDetail
{
    public string SKUCode { get; set; }
    public int Quantity { get; set; }
    public double Price { get; set; }
}
</code>```

And I have an order list like

```<code>List<ModelMMaster> _listMaster = new List<ModelMMaster>
</code>```

I want to calculate Sum(Quantity * Price) with LINQ, over _listMaster.

I am stuck at this.

```<code>double _sum =_listMaster.Where(f => f.IsActive == true).Select(f => f._detail)......
</code>```

How can i calculate Sum(Quantity * Price) from _listMaster  with LINQ?

答:
```<code>        List<ModelMMaster> _listMaster = new List<ModelMMaster>();
        List<ModelDetail> _listDetail = new List<ModelDetail>();

        _listDetail.Add(new ModelDetail { SKUCode = "SKUCode-1", Quantity = 1, Price = 1 });
        _listMaster.Add(new ModelMMaster { OrderID = "OrderID-1", IsActive = true, _detail = _listDetail });

        _listDetail = new List<ModelDetail>();
        _listDetail.Add(new ModelDetail { SKUCode = "SKUCode-2", Quantity = 2, Price = 2 });
        _listDetail.Add(new ModelDetail { SKUCode = "SKUCode-3", Quantity = 3, Price = 3 });
        _listMaster.Add(new ModelMMaster { OrderID = "OrderID-2", IsActive = true, _detail = _listDetail });

        var totalSum = _listMaster.Where(t=>t.IsActive).SelectMany(t => t._detail).Sum(t => t.Quantity * t.Price);
</code>```

Body:
My classes are like below.

public class ModelMMaster
{
    public string OrderID { get; set; }
    public bool IsActive { get; set; }
    public List<ModelDetail> _detail { get; set; }
}
public class ModelDetail
{
    public string SKUCode { get; set; }
    public int Quantity { get; set; }
    public double Price { get; set; }
}

And I have an order list like

List<ModelMMaster> _listMaster = new List<ModelMMaster>

I want to calculate Sum(Quantity * Price) with LINQ, over _listMaster.

I am stuck at this.

double _sum =_listMaster.Where(f => f.IsActive == true).Select(f => f._detail)......

How can i calculate Sum(Quantity * Price) from _listMaster  with LINQ?


问:
Creating parent child items
I have the following text and need to create a parent-child relationship between some things.

For example, whenever I encounter start inside another start its considered a child for the earlier parent so in the example step3 is child of step2.

I had opened the file and using regex. I'm trying to extract the steps
and then create a dictionary based on parent-child relationship.

The example text:

```<code>-----Starting Step for step1-----
text1
text2
text3
-----Ending Step for step1-----
-----Starting Step for step2-----
text4
text5
text6
-----Starting Step for step3-----
text7
text8
text9
-----Ending Step for step3-----

text10
text11
text12
-----Ending Step for step2-----
</code>```

My code is:

```<code>with open('notepad_1.txt','r') as f1:
    for line in f1:
        value=re.findall(r'Starting Step for (\w+)',line)
        new_value=re.findall(r'Ending Step for (\w+)',line)
        if value:
            if parent_tag_start:
                parent_tag_start[-1][parent_tag_start[-1].keys()[0]]=value[0]
            else:
                parent_tag_start.append(value[0])
        elif new_value:
            parent_tag_start.remove(new_value[0])
</code>```

Expected output

```<code>{'step1':None,step2:{step3}} # could extend up to n levels
</code>```

答:
You could just use a stack list keeping track of the last active dictionary.

As dictionaries are mutable you are actually editing the same objects regardless how you access it. So if you have

new = {}
out['a'] = new
stack[-1] = new
```

<p>Then <code>out['a']</code> and <code>stack[-1]</code> are actually the same element and you can edit it by calling either.</p>

<p>Here is the proposed code:</p>

<pre class="lang-py prettyprint-override"><code>import re

with open('notepad_1.txt','r') as f:
    out = {}
    stack = [out]
    for line in f.readlines():
        start=re.findall(r'Starting Step for (\w+)',line)
        end=re.findall(r'Ending Step for (\w+)',line)

        if start:
            new = dict()
            stack[-1][start[0]] = new
            # Add the new dict to the stack
            stack.append(new)
        elif end:
            # remove the last dict as it is completed
            stack.pop()
print(out)
</code>```

Output:

{'step1': {}, 'step2': {'step3': {}}}

Head-up

If the file structure is invalid and contains too few end-tags, it will throw an IndexError.

You could still iterate afterwards over the result and replace empty dicts. {} with None, but I don't see the benefit of it.

Title: Creating parent child items

Body:
I have the following text and need to create a parent-child relationship between some things.

For example, whenever I encounter start inside another start its considered a child for the earlier parent so in the example step3 is child of step2.

I had opened the file and using regex. I'm trying to extract the steps
and then create a dictionary based on parent-child relationship.

The example text:

-----Starting Step for step1-----
text1
text2
text3
-----Ending Step for step1-----
-----Starting Step for step2-----
text4
text5
text6
-----Starting Step for step3-----
text7
text8
text9
-----Ending Step for step3-----

text10
text11
text12
-----Ending Step for step2-----

My code is:

with open('notepad_1.txt','r') as f1:
    for line in f1:
        value=re.findall(r'Starting Step for (\w+)',line)
        new_value=re.findall(r'Ending Step for (\w+)',line)
        if value:
            if parent_tag_start:
                parent_tag_start[-1][parent_tag_start[-1].keys()[0]]=value[0]
            else:
                parent_tag_start.append(value[0])
        elif new_value:
            parent_tag_start.remove(new_value[0])

Expected output

{'step1':None,step2:{step3}} # could extend up to n levels

Body:
You could just use a stack list keeping track of the last active dictionary.

As dictionaries are mutable you are actually editing the same objects regardless how you access it. So if you have

new = {}
out['a'] = new
stack[-1] = new

Then out['a'] and stack[-1] are actually the same element and you can edit it by calling either.

Here is the proposed code:

import re

with open('notepad_1.txt','r') as f:
    out = {}
    stack = [out]
    for line in f.readlines():
        start=re.findall(r'Starting Step for (\w+)',line)
        end=re.findall(r'Ending Step for (\w+)',line)

        if start:
            new = dict()
            stack[-1][start[0]] = new
            # Add the new dict to the stack
            stack.append(new)
        elif end:
            # remove the last dict as it is completed
            stack.pop()
print(out)

Output:

{'step1': {}, 'step2': {'step3': {}}}

Head-up

If the file structure is invalid and contains too few end-tags, it will throw an IndexError.

You could still iterate afterwards over the result and replace empty dicts. {} with None, but I don't see the benefit of it.


问:
How to try if lines in a file match with lines in an other file in Python
How do I "brute" every line in a file Until I find what matches it, what I mean is I turned every line in save.data and brute.txt into two lists (For easy access), here is brute.txt:

```<code>username
username1
password
password1
</code>```

And here is save.data (Since this is for a Batch-file game, there is no need to quote strings like "username1"):

```<code>username1 = PlayerName
password1 = PlayerPass
</code>```

So, my request is, I want to try if line 1 from brute.txt matches the the thing before the equal sign in save.data (which is 'username1'), if it doesn't match with it pass to the next line, and so on until it reaches the end of the file (save.data) then try if line 2 from brute.txt matches line 1 from save.data (which matches) if not, pass to if line 2 from brute.txt matches the thing before the qual sign in line 2 in save.data and so on ... And finally, when "username" matches "username", make a variable called username with the value of what is after the equal sign in save.data. So, when the "bruting" process is finished, I must have two variables, one is username = PlayerName and the other is password = PlayerPass for further use. I tried while, for and try loops but I got stuck because to do so I need to know what is in save.data.

-If you didn't understand something, kindly comment it and I will clear it up.

答:
There are probably more efficient ways to do this, but to answer the question you asked..

First open the save.data file and read the contents into a list:

```<code>with open('save.data') as fp:
    save_data = [line.split(' = ') for line in fp.read().splitlines()]
</code>```

do the same for the brute.txt file:

```<code>with open('brute.txt') as fp:
    brute = fp.read().splitlines()
</code>```

then just iterate through usernames and passwords:

```<code>for username, password in save_data:
    if username in brute:
        break
else:
    print("didn't find the username")
</code>```

the username and password variables from the for-loop will have the correct values after the for-loop breaks.

(please note that the else: is on the for-loop, not the if..)

Body:
How do I "brute" every line in a file Until I find what matches it, what I mean is I turned every line in save.data and brute.txt into two lists (For easy access), here is brute.txt:

username
username1
password
password1

And here is save.data (Since this is for a Batch-file game, there is no need to quote strings like "username1"):

username1 = PlayerName
password1 = PlayerPass

So, my request is, I want to try if line 1 from brute.txt matches the the thing before the equal sign in save.data (which is 'username1'), if it doesn't match with it pass to the next line, and so on until it reaches the end of the file (save.data) then try if line 2 from brute.txt matches line 1 from save.data (which matches) if not, pass to if line 2 from brute.txt matches the thing before the qual sign in line 2 in save.data and so on ... And finally, when "username" matches "username", make a variable called username with the value of what is after the equal sign in save.data. So, when the "bruting" process is finished, I must have two variables, one is username = PlayerName and the other is password = PlayerPass for further use. I tried while, for and try loops but I got stuck because to do so I need to know what is in save.data.

-If you didn't understand something, kindly comment it and I will clear it up.

Body:
There are probably more efficient ways to do this, but to answer the question you asked..

First open the save.data file and read the contents into a list:

with open('save.data') as fp:
    save_data = [line.split(' = ') for line in fp.read().splitlines()]

do the same for the brute.txt file:

with open('brute.txt') as fp:
    brute = fp.read().splitlines()

then just iterate through usernames and passwords:

for username, password in save_data:
    if username in brute:
        break
else:
    print("didn't find the username")

the username and password variables from the for-loop will have the correct values after the for-loop breaks.

(please note that the else: is on the for-loop, not the if..)


问:
POST API response blocked by CORS policy - React and Django Rest Framwork
I have created a backend server in Django with Django Rest Framework, and a React frontend. My front retrieves data from the back through APIs. Each app is on a different subdomain of the same domain. I use
Cloudflare to manage DNS and for SSL / security.

I have had no problem with GET calls. For POST calls, I send the POST data to the server through a form, and I know it works as there is a change to the database (record created in this instance). However, I have implemented a 'retry until' function using axios and polly-js. This method waits until it receives a 201 CREATED response, otherwise retries.

My problem is that when I submit the form on React, the POST is indeed received and processed by my backend server, but the response is blocked. So after 10-15 seconds, I receive an error message through the console and my 'retry until' method sends another POST request. The response of this second one is not blocked by Chrome, and I receive the 201 status. But the overall effect is that I have now 2 identical records in the database because the first call did not 'receive' the response and retried.

The error in the console I get is:

```<code>Access to XMLHttpRequest at 'https://subdomain.domain.io/' from origin 'https://api.domain.io' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
</code>```

What I have already done and has not worked:

I don' think it's a backend problem as the POST goes through and the record created. But I have whitelisted all CORS origins in Django

I have added the header 'Access-Control-Allow-Origin': '*' to my POST request through axios

I have manually added the same 'Access-Control-Allow-Origin': '*' header from my Django DRF response.

Both request that I send (first one through form submission, second one through automatic retry) are identical (seen through Chrome network tab):

```<code>Accept: application/json, text/plain, */*
Content-Type: application/json;charset=UTF-8
Origin: https://subdomain.domain.io
Referer: https://subdomain.domain.io/path
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36
</code>```

My POST and retry method:

```<code>const postData = (url, data, headers) => {

    headers['Access-Control-Allow-Origin'] = "*"

    return polly()
      .waitAndRetry([100, 200, 400, 1000])
      .executeForPromise(async () => {
        const rsp = await axios.post(url, data, headers);

        if (rsp.status < 210) {

          return rsp.data;

        }

        return Promise.reject(rsp);
      });
  };
</code>```

The response I get when the second try succeeds:

```<code>access-control-allow-origin: *
allow: GET, POST, HEAD, OPTIONS
cf-ray: 4dd7cbccce256948-CDG
content-length: 364
content-type: application/json
date: Mon, 27 May 2019 11:54:47 GMT
expect-ct: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
server: cloudflare
status: 201
strict-transport-security: max-age=2592000; includeSubDomains; preload
vary: Accept, Origin
x-content-type-options: nosniff
x-frame-options: SAMEORIGIN
</code>```

For reference, the CORS settings in Django

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django_otp.middleware.OTPMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

CORS_ORIGIN_ALLOW_ALL = True

CORS_ALLOW_HEADERS = (
    'accept',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
    'access-control-allow-origin'
)
```

<p><strong>EDIT</strong> </p>

<p>Firefox shows me the response for the 504 GATEWAY TIMEOUT of the first POST request: </p>

```cf-ray: 4dd82ac15f42cd97-CDG
content-type: text/html; charset=UTF-8
date: Mon, 27 May 2019 13:00:36 GMT
expect-ct: max-age=604800, report-uri="ht….com/cdn-cgi/beacon/expect-ct"
expires: Thu, 01 Jan 1970 00:00:01 GMT
pragma: no-cache
server: cloudflare
set-cookie: __cfduid=d0a3a9ee872171ada14cb…n=.wisly.io; HttpOnly; Secure
set-cookie: cf_use_ob=0; path=/; expires=Mon, 27-May-19 13:01:06 GMT
strict-transport-security: max-age=2592000; includeSubDomains; preload
x-content-type-options: nosniff
X-Firefox-Spdy: h2
```

The Access-Control-Allow-Origin is missing, but it is part of my backend code. Could anything be happening with Cloudflare?

The expected result would be that, when I POST through the form, receive the 201 back (which would be accepted and read by Chrome) so that I can

Show the user the form has been correctly saved to the database

Not retry the POST, resulting in dual entry.

Thank you!

答:
You don't need to put access-control-allow-origin in your CORS_ALLOW_HEADERS.

The Django CORS will add automatically on requests based on your configurations.

Some tips you could try:

Use default_headers instead of put all default headers (just to improve the code)

I already had problems with some basic headers that Chrome was sending and my app didn't allow them, so I had to add

```<code>from corsheaders.defaults import default_headers

CORS_ALLOW_HEADERS = default_headers + (
    'Cache-Control', 'If-Modified-Since',
)
</code>```

Try adding "trusted origins"

```<code>CSRF_TRUSTED_ORIGINS = (
    '*.yourdomain.com',
)
</code>```

Body:
I have created a backend server in Django with Django Rest Framework, and a React frontend. My front retrieves data from the back through APIs. Each app is on a different subdomain of the same domain. I use
Cloudflare to manage DNS and for SSL / security.

I have had no problem with GET calls. For POST calls, I send the POST data to the server through a form, and I know it works as there is a change to the database (record created in this instance). However, I have implemented a 'retry until' function using axios and polly-js. This method waits until it receives a 201 CREATED response, otherwise retries.

My problem is that when I submit the form on React, the POST is indeed received and processed by my backend server, but the response is blocked. So after 10-15 seconds, I receive an error message through the console and my 'retry until' method sends another POST request. The response of this second one is not blocked by Chrome, and I receive the 201 status. But the overall effect is that I have now 2 identical records in the database because the first call did not 'receive' the response and retried.

The error in the console I get is:

Access to XMLHttpRequest at 'https://subdomain.domain.io/' from origin 'https://api.domain.io' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

What I have already done and has not worked:

I don' think it's a backend problem as the POST goes through and the record created. But I have whitelisted all CORS origins in Django

I have added the header 'Access-Control-Allow-Origin': '*' to my POST request through axios

I have manually added the same 'Access-Control-Allow-Origin': '*' header from my Django DRF response.

Both request that I send (first one through form submission, second one through automatic retry) are identical (seen through Chrome network tab):

Accept: application/json, text/plain, */*
Content-Type: application/json;charset=UTF-8
Origin: https://subdomain.domain.io
Referer: https://subdomain.domain.io/path
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36

My POST and retry method:

const postData = (url, data, headers) => {

    headers['Access-Control-Allow-Origin'] = "*"

    return polly()
      .waitAndRetry([100, 200, 400, 1000])
      .executeForPromise(async () => {
        const rsp = await axios.post(url, data, headers);

        if (rsp.status < 210) {

          return rsp.data;

        }

        return Promise.reject(rsp);
      });
  };

The response I get when the second try succeeds:

access-control-allow-origin: *
allow: GET, POST, HEAD, OPTIONS
cf-ray: 4dd7cbccce256948-CDG
content-length: 364
content-type: application/json
date: Mon, 27 May 2019 11:54:47 GMT
expect-ct: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
server: cloudflare
status: 201
strict-transport-security: max-age=2592000; includeSubDomains; preload
vary: Accept, Origin
x-content-type-options: nosniff
x-frame-options: SAMEORIGIN

For reference, the CORS settings in Django

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django_otp.middleware.OTPMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

CORS_ORIGIN_ALLOW_ALL = True

CORS_ALLOW_HEADERS = (
    'accept',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
    'access-control-allow-origin'
)

EDIT

Firefox shows me the response for the 504 GATEWAY TIMEOUT of the first POST request:

cf-ray: 4dd82ac15f42cd97-CDG
content-type: text/html; charset=UTF-8
date: Mon, 27 May 2019 13:00:36 GMT
expect-ct: max-age=604800, report-uri="ht….com/cdn-cgi/beacon/expect-ct"
expires: Thu, 01 Jan 1970 00:00:01 GMT
pragma: no-cache
server: cloudflare
set-cookie: __cfduid=d0a3a9ee872171ada14cb…n=.wisly.io; HttpOnly; Secure
set-cookie: cf_use_ob=0; path=/; expires=Mon, 27-May-19 13:01:06 GMT
strict-transport-security: max-age=2592000; includeSubDomains; preload
x-content-type-options: nosniff
X-Firefox-Spdy: h2

The Access-Control-Allow-Origin is missing, but it is part of my backend code. Could anything be happening with Cloudflare?

The expected result would be that, when I POST through the form, receive the 201 back (which would be accepted and read by Chrome) so that I can

Show the user the form has been correctly saved to the database

Not retry the POST, resulting in dual entry.

Thank you!

Body:
You don't need to put access-control-allow-origin in your CORS_ALLOW_HEADERS.

The Django CORS will add automatically on requests based on your configurations.

Some tips you could try:

Use default_headers instead of put all default headers (just to improve the code)

I already had problems with some basic headers that Chrome was sending and my app didn't allow them, so I had to add

from corsheaders.defaults import default_headers

CORS_ALLOW_HEADERS = default_headers + (
    'Cache-Control', 'If-Modified-Since',
)

Try adding "trusted origins"

CSRF_TRUSTED_ORIGINS = (
    '*.yourdomain.com',
)


问:
in ASP.NET MVC3 how can I see the request?
I'm using a simple route as

```<code>routes.MapRoute(
    "Default2", // Route name
    "{cliurl}/{id}", // URL with parameters
    new { cliurl = "none", controller = "ABook", action = "Index", id = "none" } // Parameter defaults
);

routes.MapRoute(
    "Default", // Route name
    "{cliurl}/{controller}/{action}/{id}", // URL with parameters
    new { cliurl = "none", controller = "ABook", action = "Index", id = "none" } // Parameter defaults
);
</code>```

and when I debug the website (VS2010 SP1), I have a breakpoint in my ABook Controller, inside the Index action method witch contains only:

```<code>//
// GET: /ABook/
public ActionResult Index()
{
    if (currentClient == null)
        return RedirectToAction("Empty");

    return View();
}

//
// GET: /Empty/
public ActionResult Empty()
{
    return View();
}
</code>```

The thing is that, when I insert this in the browser:

```<code>http://localhost:14951/client_name/hashed_id
</code>```

I get 3 breaks in that breakpoint.

How can I see what in the world is going on? why 3 times when I just requested 1, what is exactly the browser requesting?

I can only get the Route Parameters and I do get the first correct, but 2nd and 3rd are using the default values, and I tried to navigate through the RequestContext and I can't see anything useful :(

Just want to know if there is a way to really see what's been requested.

答:
As a suggestion, why not hook up the BeginRequest event handler for the application which will allow you to see every request coming through. There is also the HttpContext.Current.Request.Url object which can be inspected

```<code>    // Global.asax
    public MvcApplication()
    {
        BeginRequest += new EventHandler(MvcApplication_BeginRequest);
    }

    void MvcApplication_BeginRequest(object sender, EventArgs e)
    {
         Debug.WriteLine("[Start] Requested Url: " + HttpContext.Current.Request.RawUrl);
    }
</code>```

Body:
I'm using a simple route as

routes.MapRoute(
    "Default2", // Route name
    "{cliurl}/{id}", // URL with parameters
    new { cliurl = "none", controller = "ABook", action = "Index", id = "none" } // Parameter defaults
);

routes.MapRoute(
    "Default", // Route name
    "{cliurl}/{controller}/{action}/{id}", // URL with parameters
    new { cliurl = "none", controller = "ABook", action = "Index", id = "none" } // Parameter defaults
);

and when I debug the website (VS2010 SP1), I have a breakpoint in my ABook Controller, inside the Index action method witch contains only:

//
// GET: /ABook/
public ActionResult Index()
{
    if (currentClient == null)
        return RedirectToAction("Empty");

    return View();
}

//
// GET: /Empty/
public ActionResult Empty()
{
    return View();
}

The thing is that, when I insert this in the browser:

http://localhost:14951/client_name/hashed_id

I get 3 breaks in that breakpoint.

How can I see what in the world is going on? why 3 times when I just requested 1, what is exactly the browser requesting?

I can only get the Route Parameters and I do get the first correct, but 2nd and 3rd are using the default values, and I tried to navigate through the RequestContext and I can't see anything useful :(

Just want to know if there is a way to really see what's been requested.

Body:
As a suggestion, why not hook up the BeginRequest event handler for the application which will allow you to see every request coming through. There is also the HttpContext.Current.Request.Url object which can be inspected

    // Global.asax
    public MvcApplication()
    {
        BeginRequest += new EventHandler(MvcApplication_BeginRequest);
    }

    void MvcApplication_BeginRequest(object sender, EventArgs e)
    {
         Debug.WriteLine("[Start] Requested Url: " + HttpContext.Current.Request.RawUrl);
    }