问:
Find single common element between List of Triples and Flat List
I have a list of triples,

```<code>posPools = [[13, 14, 15], [17, 19, 20], [16, 20, 22], [15, 16, 24], [15, 22, 23], [13, 20, 23], [15, 18, 19], [10, 15, 22], [7, 8, 9], [8, 10, 17], [15, 16, 17], [10, 15, 16], [8, 9, 15], [15, 16, 22], [7, 8, 9], [1, 8, 11], [1, 2, 4], [3, 6, 7], [10, 3, 1], [2, 5, 8]]
</code>```

Each list within posPools represents a contaminated pool with water from 3 wells x,y,z. Only one well (x y or z) needs to be contaminated in order to contaminate the entire pool. There are 24 total wells.

I have a flat list of potentially contaminated wells, and I know for sure that any well # not in this list is not contaminated.

```<code>potPosWell = [4, 6, 8, 9, 15, 18, 20, 23]
</code>```

If one pool, e.g. posPools[0] = [13,14,15] contains only one element in common with potPosWell, e.g. #15, then I know for sure that well #15 is contaminated, and I want to append 15 to a new list posWell.

However, if a pool, e.g.posPools[8] = [7,8,9] contains more than one element in common with potPosWell, e.g. #8 & #9, then I don't want to append either 8 or 9 to posWell. (That is because I wouldn't know for sure whether well #8 or #9 contaminated the pool).

The output should be

```<code>posWell = [4,6,8,15,20]
</code>```

I have no idea how to iterate over posPools to check if each sub-list has only one element in common potPosWell and then append that element to a new list posWell.

My working idea:
First, find which triples in posPools share only one element in common with potPosWell and append those triples into a new nested list.
Second, determine which element within each triple is equivalent to potPosWells and append it to PosWell.
Third, eliminate duplicate elements in posWells.

I'm not even sure if the data structures I have now are optimal for this sort of comparison.

These lists are small enough to do by hand, but it just clicked in my head that this would be something fun to program into Python. Alas, I barely knew enough Python to clean up the data to this stage. I would greatly appreciate if someone gave me examples of how to implement what I'm thinking about.

*Edit: There is one pool in posPools [10,3,1] that contains no wells from potPosWell. This means that it was a false positive when tested for contamination. None of the wells 10,3, or 1 are actually contaminated since none appear in potPosWell.

答:
One way using set.intersection:

```<code>pot = set(potPosWell)

list({i.pop() for pool in posPools if len(i:=pot.intersection(pool)) == 1})
</code>```

In case if you are on less than python 3.8:

```<code>res = []
for pool in posPools:
    i = pot.intersection(pool)
    if len(i) == 1:
        res.append(i.pop())
</code>```

Output:

```<code>[4, 6, 8, 15, 20]
</code>```

Body:
I have a list of triples,

posPools = [[13, 14, 15], [17, 19, 20], [16, 20, 22], [15, 16, 24], [15, 22, 23], [13, 20, 23], [15, 18, 19], [10, 15, 22], [7, 8, 9], [8, 10, 17], [15, 16, 17], [10, 15, 16], [8, 9, 15], [15, 16, 22], [7, 8, 9], [1, 8, 11], [1, 2, 4], [3, 6, 7], [10, 3, 1], [2, 5, 8]]

Each list within posPools represents a contaminated pool with water from 3 wells x,y,z. Only one well (x y or z) needs to be contaminated in order to contaminate the entire pool. There are 24 total wells.

I have a flat list of potentially contaminated wells, and I know for sure that any well # not in this list is not contaminated.

potPosWell = [4, 6, 8, 9, 15, 18, 20, 23]

If one pool, e.g. posPools[0] = [13,14,15] contains only one element in common with potPosWell, e.g. #15, then I know for sure that well #15 is contaminated, and I want to append 15 to a new list posWell.

However, if a pool, e.g.posPools[8] = [7,8,9] contains more than one element in common with potPosWell, e.g. #8 & #9, then I don't want to append either 8 or 9 to posWell. (That is because I wouldn't know for sure whether well #8 or #9 contaminated the pool).

The output should be

posWell = [4,6,8,15,20]

I have no idea how to iterate over posPools to check if each sub-list has only one element in common potPosWell and then append that element to a new list posWell.

My working idea:
First, find which triples in posPools share only one element in common with potPosWell and append those triples into a new nested list.
Second, determine which element within each triple is equivalent to potPosWells and append it to PosWell.
Third, eliminate duplicate elements in posWells.

I'm not even sure if the data structures I have now are optimal for this sort of comparison.

These lists are small enough to do by hand, but it just clicked in my head that this would be something fun to program into Python. Alas, I barely knew enough Python to clean up the data to this stage. I would greatly appreciate if someone gave me examples of how to implement what I'm thinking about.

*Edit: There is one pool in posPools [10,3,1] that contains no wells from potPosWell. This means that it was a false positive when tested for contamination. None of the wells 10,3, or 1 are actually contaminated since none appear in potPosWell.

Body:
One way using set.intersection:

pot = set(potPosWell)

list({i.pop() for pool in posPools if len(i:=pot.intersection(pool)) == 1})

In case if you are on less than python 3.8:

res = []
for pool in posPools:
    i = pot.intersection(pool)
    if len(i) == 1:
        res.append(i.pop())

Output:

[4, 6, 8, 15, 20]


来源: stackexchange

问:
Use Firebase Analytics for User Analytics
Is it possible to use Firebase Analytics for In App Analytics.

I want to track when a person open another user's profile like this:

import { getAnalytics, logEvent } from "firebase/analytics";

const analytics = getAnalytics();
logEvent(analytics, 'open_profile', {
  profileId: '1234'
});
```

So now I want to show the user with id 1234 how many times the open_profile event occurs where the profileId is 1234.

Is this possible with Firebase?

答: Yes, we can track all the events in the application by creating custome events and we can also view each individual events and its count in firebase dashboard.

ContentLicense: CC BY-SA 4.0

Body:
Is it possible to use Firebase Analytics for In App Analytics.

I want to track when a person open another user's profile like this:

import { getAnalytics, logEvent } from "firebase/analytics";

const analytics = getAnalytics();
logEvent(analytics, 'open_profile', {
  profileId: '1234'
});

So now I want to show the user with id 1234 how many times the open_profile event occurs where the profileId is 1234.

Is this possible with Firebase?


问:
Counting the number of items which do not have an entry in a foreign table
I've got two tables. Organisations and ReturnForms.

The ReturnForm structure is:

```<code>| formID | returnMonth | returnYear | orgID |
</code>```

Organisations submit return forms on a monthly basis. returnMonth and returnYear stores what month/year the form is for, orgID is the fk for which organisation submitted the form, formID is the pk for the returnForm table.

I want to count how many organisations do not have a returnForm for a specific month/year combination. For a single month/year, this is easy:

```<code>SELECT count(*)
FROM   `tblOrganisations` AS `Organisation`
       LEFT JOIN `tblReturnForms` AS `NoForm`
         ON ( `NoForm`.`orgID` = `Organisation`.`orgID`
              AND `NoForm`.`returnMonth` = 3
              AND `NoForm`.`returnYear` = 2010 )
WHERE  `NoForm`.`formID` IS NULL
</code>```

The problem I'm having is to count how many forms have not submitted between 12/2005 and the current month. I could calculate it by running the about query for each month/year between 12/2005 and summing them, but I'm certain there is a better, more elegant way of doing it.

答:
You can compute the earliest year and month required like so:

```<code>min_year = current_year;
min_month = current_month - 4;
if min_month < 1 then
    min_month = 12 + min_month;
    min_year = min_year - 1;
end if;

create temp table periods(year integer, month integer);
for month/year in(12/2005 .. min_month/min_year)
    insert into periods values (year, month);
loop;
</code>```

and then use these in your SQL statement like so:

```<code>SELECT
    `periods`.`year`,
    `periods`.`month`,
    count(*),
FROM
    `tblOrganisations` AS `Organisation`
     JOIN periods
     LEFT JOIN `tblReturnForms` AS `NoForm` ON
         (`NoForm`.`orgID` = `Organisation`.`orgID`
          AND
          `NoForm`.`returnYear` = `period`.`year`
          AND
          `NoForm`.`returMonth` <= `periods`.`month`))
WHERE
    `NoForm`.`formID` IS NULL
GROUP BY
    `periods`.`year`,
    `periods.`month`
</code>```

This will give you number of missing returns per return type/month/year - all in one query - then just loop over the results.

ContentLicense: CC BY-SA 3.0

Body:
I've got two tables. Organisations and ReturnForms.

The ReturnForm structure is:

| formID | returnMonth | returnYear | orgID |

Organisations submit return forms on a monthly basis. returnMonth and returnYear stores what month/year the form is for, orgID is the fk for which organisation submitted the form, formID is the pk for the returnForm table.

I want to count how many organisations do not have a returnForm for a specific month/year combination. For a single month/year, this is easy:

SELECT count(*)
FROM   `tblOrganisations` AS `Organisation`
       LEFT JOIN `tblReturnForms` AS `NoForm`
         ON ( `NoForm`.`orgID` = `Organisation`.`orgID`
              AND `NoForm`.`returnMonth` = 3
              AND `NoForm`.`returnYear` = 2010 )
WHERE  `NoForm`.`formID` IS NULL

The problem I'm having is to count how many forms have not submitted between 12/2005 and the current month. I could calculate it by running the about query for each month/year between 12/2005 and summing them, but I'm certain there is a better, more elegant way of doing it.

Body:
You can compute the earliest year and month required like so:

min_year = current_year;
min_month = current_month - 4;
if min_month < 1 then
    min_month = 12 + min_month;
    min_year = min_year - 1;
end if;

create temp table periods(year integer, month integer);
for month/year in(12/2005 .. min_month/min_year)
    insert into periods values (year, month);
loop;

and then use these in your SQL statement like so:

SELECT
    `periods`.`year`,
    `periods`.`month`,
    count(*),
FROM
    `tblOrganisations` AS `Organisation`
     JOIN periods
     LEFT JOIN `tblReturnForms` AS `NoForm` ON
         (`NoForm`.`orgID` = `Organisation`.`orgID`
          AND
          `NoForm`.`returnYear` = `period`.`year`
          AND
          `NoForm`.`returMonth` <= `periods`.`month`))
WHERE
    `NoForm`.`formID` IS NULL
GROUP BY
    `periods`.`year`,
    `periods.`month`

This will give you number of missing returns per return type/month/year - all in one query - then just loop over the results.


问:
SICP Exercise 1.16 ... what does "invariant quantity" hint mean?
I see there are a few other questions around this exercise but none specifically are asking what is meant within the hint... "define the state transition in such a way that the product abn is unchanged from state to state".

They also mention that this idea of using an "invariant quantity" is a powerful idea with respect to "iterative algorithms". By the way, this problem calls for the design of a "logarithmic" exponent algorithm that has a space complexity of O(1).

Mainly I just have no idea what is meant by this hint and am pretty confused. Can anyone give me a nudge in what is meant by this? The only thing I can really find about "invariant quantities" are described using examples in physics which only makes this concept more opaque.

Exercise description in full:

Exercise 1.16: Design a procedure that evolves an iterative exponentiation process that uses successive squaring and uses a logarithmic number of steps, as does fast-expt. (Hint: Using the observation that (bn/2)2 = (b2)n/2, keep, along with the exponent n and the base b, an additional state variable a, and define the state transformation in such a way that the product abn is unchanged from state to state.

At the beginning of the process a is taken to be 1, and the answer is given by the value of a at the end of the process. In general, the technique of defining an invariant quantity that remains unchanged from state to state is a powerful way to think about the design of iterative algorithms.)

Thanks in advance.

答:
This is not about any "logarithmic exponentiation", which is a very vague and confusing terminology.

As the quote you provided says, it is about exponentiation function that takes logarithmic number of steps to get its final result.

So we want to develop a function, exp(b,n), which would take O(log n) time to finish.

The numbers involved are all integers.

So how do we calculate bn? We notice that

```<code>b^n = b * b * b * b *... * b
      `------n times------/        O(n) time process
</code>```

and, when n is even,

```<code>b^n = b * b * b * b * ... * b *
      `------n/2 times-----/
      b * b * b * b * ... * b
      `------n/2 times-----/
    = (b^(n/2))^2                ; viewed from the side
    = (b^2)^(n/2)                ; viewed from above
</code>```

and when n is odd,

```<code>b^n = b * b * b * b * ... * b *
      `------n/2 times-----/
      b * b * b * b * ... * b *
      `------n/2 times-----/
      b
      `--1 time--/
    = (b^(n/2))^2  *  b
    = (b^2)^(n/2)  *  b
</code>```

Note that both expression fall into same category if we write the first one as (b^2)^(n/2) * 1.

Also note that the equation

```<code>  b^n = (b   )^(n  )  *  { a where a = 1   }
      = (b ^2)^(n/2)  *  { a where a = ... }
      = (b'  )^(n' )  *  { a' }
</code>```

means that to calculate b^n * a is the same as to calculate b'^n' * a' with the changed values of { b' = b^2 ; n' = n/2 ; a' = {if {n is even} then {a} else {a * b}} }.

So we don't actually compute either of the sides of that equation. Instead we keep the triples { b, n, a } at each step and transform them according to that rule

```<code> { b, n, a } --> { b', n', a' } --> ...
</code>```

with the initial values of b and n as given to us, and the first a equal to 1; and know that the final result calculated from any of the triples would be the same if we'd actually calculated it somehow. We still don't know how exactly we'd do that; just that it would be the same. That's the "invariant" part.

So what all this is good for? Well, since the chain { n --> n/2 --> ... } will certainly reach a point where n == 1, we know that at that point we can break the chain since

```<code> c^1 * d  ==  c * d
</code>```

and this one simple multiplication of these two numbers will produce the same result as the initial formula.

Which is the final result of the function.

And that's the meaning of the hint: maintain the state of the computation as a (here) triple of numbers (or just three variables named b, n, a), and implement your computation as a chain of state-transforming steps. When the chain is broken according to some test (here, n == 1), we've reached our destination and can calculate the final result according to some simple rule (here, c * d).

This gives us a nice and powerful methodology for problem solving.

Oh, and we also know that the length of that chain of changing states is O(log n), since we halve that n at each step.

Body:
This is not about any "logarithmic exponentiation", which is a very vague and confusing terminology.

As the quote you provided says, it is about exponentiation function that takes logarithmic number of steps to get its final result.

So we want to develop a function, exp(b,n), which would take O(log n) time to finish.

The numbers involved are all integers.

So how do we calculate bn? We notice that

b^n = b * b * b * b *... * b
      `------n times------/        O(n) time process

and, when n is even,

b^n = b * b * b * b * ... * b *
      `------n/2 times-----/
      b * b * b * b * ... * b
      `------n/2 times-----/
    = (b^(n/2))^2                ; viewed from the side
    = (b^2)^(n/2)                ; viewed from above

and when n is odd,

b^n = b * b * b * b * ... * b *
      `------n/2 times-----/
      b * b * b * b * ... * b *
      `------n/2 times-----/
      b
      `--1 time--/
    = (b^(n/2))^2  *  b
    = (b^2)^(n/2)  *  b

Note that both expression fall into same category if we write the first one as (b^2)^(n/2) * 1.

Also note that the equation

  b^n = (b   )^(n  )  *  { a where a = 1   }
      = (b ^2)^(n/2)  *  { a where a = ... }
      = (b'  )^(n' )  *  { a' }

means that to calculate b^n * a is the same as to calculate b'^n' * a' with the changed values of { b' = b^2 ; n' = n/2 ; a' = {if {n is even} then {a} else {a * b}} }.

So we don't actually compute either of the sides of that equation. Instead we keep the triples { b, n, a } at each step and transform them according to that rule

 { b, n, a } --> { b', n', a' } --> ...

with the initial values of b and n as given to us, and the first a equal to 1; and know that the final result calculated from any of the triples would be the same if we'd actually calculated it somehow. We still don't know how exactly we'd do that; just that it would be the same. That's the "invariant" part.

So what all this is good for? Well, since the chain { n --> n/2 --> ... } will certainly reach a point where n == 1, we know that at that point we can break the chain since

 c^1 * d  ==  c * d

and this one simple multiplication of these two numbers will produce the same result as the initial formula.

Which is the final result of the function.

And that's the meaning of the hint: maintain the state of the computation as a (here) triple of numbers (or just three variables named b, n, a), and implement your computation as a chain of state-transforming steps. When the chain is broken according to some test (here, n == 1), we've reached our destination and can calculate the final result according to some simple rule (here, c * d).

This gives us a nice and powerful methodology for problem solving.

Oh, and we also know that the length of that chain of changing states is O(log n), since we halve that n at each step.


问:
C++ compile time ternary conditional
Please, help me to figure out syntax of compile time ternary conditional in C++:

#include <iostream>
#include <type_traits>
int main(void)
{
 //const auto y = constexpr(std::is_null_pointer_v<decltype(nullptr)>) ? 777 : 888.8;
 const auto y = constexpr(std::is_null_pointer_v<decltype(nullptr)> ? 777 : 888.8);
 std::cout<<y<<std::endl;
}
```

Both of the options above give me error: expected primary-expression before ‘constexpr’ (gcc-11.2.0; compiled with g++ -std=c++17).

Thank you very much for your help!

答:
Although one solution is provided while I program it, I suggest other solution:
making your consteval tenary function template, As it can handle different type in it.</p>
```<code>template<bool T,auto A, auto B>
consteval auto tenary() {
    if constexpr (T) {
        return A;
    }
    else {
        return B;
    }
}

#include <iostream>
#include <type_traits>
int main(void)
{
    const auto y = tenary<std::is_null_pointer_v<decltype(nullptr)>,777,888.8>();
    std::cout << y << std::endl;
}
</code>```

Title: C++ compile time ternary conditional

Body:
Please, help me to figure out syntax of compile time ternary conditional in C++:

#include <iostream>
#include <type_traits>
int main(void)
{
 //const auto y = constexpr(std::is_null_pointer_v<decltype(nullptr)>) ? 777 : 888.8;
 const auto y = constexpr(std::is_null_pointer_v<decltype(nullptr)> ? 777 : 888.8);
 std::cout<<y<<std::endl;
}

Both of the options above give me error: expected primary-expression before ‘constexpr’ (gcc-11.2.0; compiled with g++ -std=c++17).

Thank you very much for your help!

Body:
Although one solution is provided while I program it, I suggest other solution:
making your consteval tenary function template, As it can handle different type in it.

template<bool T,auto A, auto B>
consteval auto tenary() {
    if constexpr (T) {
        return A;
    }
    else {
        return B;
    }
}

#include <iostream>
#include <type_traits>
int main(void)
{
    const auto y = tenary<std::is_null_pointer_v<decltype(nullptr)>,777,888.8>();
    std::cout << y << std::endl;
}


问:
Difference in CPU usage statistics
Machine: MacBook

Java 1.8

```<code>➜  [~] sysctl hw.physicalcpu hw.logicalcpu
hw.physicalcpu: 6
hw.logicalcpu: 12
</code>```

I was debugging a java application using VisualVM and was unable to figure out the following. VisualVM reported a usage of 7.8% at one point. During the same time I checked the Mac Activity Monitor and over there a 147% usage was displayed. What's the difference?

The fans on my laptop were causing a lot of noise!

答:
I'm just speculating here because normally I don't use VisualVM and do not use MacBooks. Perhaps the 7.8% is the load per CPU. And 147% is the sum of loads of all CPUs. If you would determine the load per CPU you would get 147/12=12.25% which is pretty close to the 7.8%.

It could also be you have other processes running on your system.

I would definitely look at a more reliable profiler like async-profiler.

Title: Difference in CPU usage statistics

Body:
Machine: MacBook

Java 1.8

➜  [~] sysctl hw.physicalcpu hw.logicalcpu
hw.physicalcpu: 6
hw.logicalcpu: 12

I was debugging a java application using VisualVM and was unable to figure out the following. VisualVM reported a usage of 7.8% at one point. During the same time I checked the Mac Activity Monitor and over there a 147% usage was displayed. What's the difference?

The fans on my laptop were causing a lot of noise!


问:
Code halts unexpectedly on backend of my wix site
I wrote an asynchronous function which is supposed to check if a given url returns a '200' from a get and otherwise wait a few seconds to try again a limited number of times. The code works just fine when I run it in my computer using node but when I transfer it to backend it only checks for the site once and then immediately stops when receiving an error. What am I doing wrong?</p>

```<code>async function wait(url,delay=10000,attp=3){
 let t0 = new Date(Date.now());
 let attempts = 0;
    console.log('starting...');
 async function check(){
 if(attempts<attp){
            console.log('ATTEMPTS: ',attempts);
 return await request.get(url).on('error',
 async function(err){
                console.log('ERROR: ',err);
                attempts+=1;
 return await setTimeout(()=>{check()},delay);
            }).on('response',
 async function(response){
 if(response.statusCode===200){
 let t1 = new Date(Date.now());
                    wixData.insert('pagSeguroTimeStats', { 'time': (t1 - t0) / 1000. });
 return '200';
                }else{
                    attempts+=1;
                    console.log('not 200');
 return await setTimeout(()=>{check()},delay);
                }
            });
        }else{
 return '404';
        }
    }
 return check();
}
</code>```

答:
The 14 second limit only applies to web functions.

Time
Wix allows web modules called from the frontend, HTTP functions, and router hooks to run for up to 14 seconds. This limitation applies to both free and premium sites. Any of these methods that take longer than 14 seconds receives a 504 response code. Note that after 14 seconds the code might still execute, but the connection to the client is closed so the results do not appear in the frontend. This error message appears in your log:
/backend/.js(w)/ timed out because it exceeded the maximum execution time.

I've got a .js function that just stop, and I get no error or anything.

Body:
I wrote an asynchronous function which is supposed to check if a given url returns a '200' from a get and otherwise wait a few seconds to try again a limited number of times. The code works just fine when I run it in my computer using node but when I transfer it to backend it only checks for the site once and then immediately stops when receiving an error. What am I doing wrong?

async function wait(url,delay=10000,attp=3){
 let t0 = new Date(Date.now());
 let attempts = 0;
    console.log('starting...');
 async function check(){
 if(attempts<attp){
            console.log('ATTEMPTS: ',attempts);
 return await request.get(url).on('error',
 async function(err){
                console.log('ERROR: ',err);
                attempts+=1;
 return await setTimeout(()=>{check()},delay);
            }).on('response',
 async function(response){
 if(response.statusCode===200){
 let t1 = new Date(Date.now());
                    wixData.insert('pagSeguroTimeStats', { 'time': (t1 - t0) / 1000. });
 return '200';
                }else{
                    attempts+=1;
                    console.log('not 200');
 return await setTimeout(()=>{check()},delay);
                }
            });
        }else{
 return '404';
        }
    }
 return check();
}


问:
Python concurrent.futures global variables
I have a multiprocessing code, and each process have to analyse same data differently.
The input data is always the same, it is not changeable.
Input data is a data frame 20 columns and 60k rows.

How to efficiently 'put' this data to each process?

On single process application I have used global variable, but in multiprocessing it's not working.

When I try to transfer this as a function argument, I have only the first element of the table

答:
Welcome to Stack Overflow. You need to take the time and give reproducible minimal working examples to get specific answers and help the society in general.

Anyway, you shouldn't use global variables if you need to change them with each iteration/process/etc.

Multiprocessing works like that in rough easily-digestible terms:

import concurrent.futures
import glob

def manipulate_data_function(data):
    result = torture_data(data)
    return result

# ProcessPoolExecutor for CPU bound stuff
with concurrent.futures.ThreadPoolExecutor(max_workers = None) as executor:
    futures = []
    for file in glob.glob('*txt'):
        futures.append(executor.submit(manipulate_data_function, data))
```


问:
How to pass html textbox value to a javascript function
I have a HTML textbox where user will input some string which i want to pass to a JavaScript function:

```<code><input type="text" id="ad_search_query" style="width:295px">
<input type="button" value="<s:text name="button.search"/>" class="p-userButton"
 onClick="ADSEARCHGF.showTable('');"/>
</code>```

Please suggest how can i do it.

答:
In javascript function you can access textbox value like this

var text = document.getElementsByName("textbox1").value;

Body:
I have a HTML textbox where user will input some string which i want to pass to a JavaScript function:

<input type="text" id="ad_search_query" style="width:295px">
<input type="button" value="<s:text name="button.search"/>" class="p-userButton"
 onClick="ADSEARCHGF.showTable('');"/>

Please suggest how can i do it.


问:
Rotation of the array means that each element is shifted right by one index, and the last element of the array is also moved to the first place
For example, the rotation of array A = [3, 8, 9, 7, 6] is [6, 3, 8, 9, 7]. The goal is to rotate array A K times;
that is, each element of A will be shifted to the right by K indexes.

For example, given array A = [3, 8, 9, 7, 6] and K = 3, the function should return [9, 7, 6, 3, 8].

I want this in java.
I have tried this.

```<code>public static int[] rotation(int[] a,int k) {

    int[] newArray = new int[a.length];
    for(int i = 0 ; i < a.length ; i++) {
        int newPosition = (i + k)%a.length;
        newArray[newPosition] = a[i];
    }
    return newArray;
}
</code>```

答:
Here is my answer in JavaScript

function solution(A, K){
let arr = [];
let lastIndex = A.length -1;
        let rotation = K-1;
    for(let i = 0; i < K; i++){
        arr[rotation] = A[lastIndex];
        --lastIndex;
        --rotation;
    }

    for(let j = 0; j <= lastIndex; j++){
        arr.push(A[j]);
    }
    return arr;
}
```

Body:
For example, the rotation of array A = [3, 8, 9, 7, 6] is [6, 3, 8, 9, 7]. The goal is to rotate array A K times;
that is, each element of A will be shifted to the right by K indexes.

For example, given array A = [3, 8, 9, 7, 6] and K = 3, the function should return [9, 7, 6, 3, 8].

I want this in java.
I have tried this.

public static int[] rotation(int[] a,int k) {

    int[] newArray = new int[a.length];
    for(int i = 0 ; i < a.length ; i++) {
        int newPosition = (i + k)%a.length;
        newArray[newPosition] = a[i];
    }
    return newArray;
}


问:
Trying to run "brownie run .\scripts\deploy.py --network rinkeby" but getting a ValueError
Hey guys I am trying to deploy my project on the rinkeby chain using infura, but I am getting a ValueError
Here is my trackback:

```<code>INFO: Could not find files for the given pattern(s).
Brownie v1.17.1 - Python development framework for Ethereum

  File "c:\users\allow\appdata\local\programs\python\python39\lib\site-packages\brownie\_cli\__main__.py", line 64, in main
    importlib.import_module(f"brownie._cli.{cmd}").main()
  File "c:\users\allow\appdata\local\programs\python\python39\lib\site-packages\brownie\_cli\run.py", line 44, in main
    network.connect(CONFIG.argv["network"])
  File "c:\users\allow\appdata\local\programs\python\python39\lib\site-packages\brownie\network\main.py", line 40, in connect
    web3.connect(host, active.get("timeout", 30))
  File "c:\users\allow\appdata\local\programs\python\python39\lib\site-packages\brownie\network\web3.py", line 52, in connect
    uri = _expand_environment_vars(uri)
  File "c:\users\allow\appdata\local\programs\python\python39\lib\site-packages\brownie\network\web3.py", line 183, in _expand_environment_vars
    raise ValueError(f"Unable to expand environment variable in host setting: '{uri}'")
ValueError: Unable to expand environment variable in host setting: 'https://rinkeby.infura.io/v3/$WEB3_INFURA_PROJECT_ID'
</code>```

Here is my deploy.py code

```<code>from brownie import accounts, config, SimpleStorage, network
import os

def deploy_simple_storage():
    account = get_account()
    simple_storage = SimpleStorage.deploy({"from": account})
    stored_value = simple_storage.retrieve()
    print(stored_value)
    transaction = simple_storage.store(15, {"from": account})
    transaction.wait(1)
    updated_stored_value = simple_storage.retrieve()
    print(updated_stored_value)

def get_account():
    if network.show_active() == "development":
        return accounts[0]
    else:
        return accounts.add(config["wallets"]["from_key"])

def main():
    deploy_simple_storage()
</code>```

I have a really little experience in coding. I think the problem is related to .env, but I don't know what I should now. FYI I am using windows n follow this course
https://www.youtube.com/watch?v=M576WGiDBdQ
stuck at 4:48:00

答:
I had the same issue (Mac OS) and I looked at another YouTube around Brownie Deployment and noticed that "network" needs to be defined at import.

This line of code above the from brownie import did the trick in my deploy.py:

import brownie.network as network
```

Body:
Hey guys I am trying to deploy my project on the rinkeby chain using infura, but I am getting a ValueError
Here is my trackback:

INFO: Could not find files for the given pattern(s).
Brownie v1.17.1 - Python development framework for Ethereum

  File "c:\users\allow\appdata\local\programs\python\python39\lib\site-packages\brownie\_cli\__main__.py", line 64, in main
    importlib.import_module(f"brownie._cli.{cmd}").main()
  File "c:\users\allow\appdata\local\programs\python\python39\lib\site-packages\brownie\_cli\run.py", line 44, in main
    network.connect(CONFIG.argv["network"])
  File "c:\users\allow\appdata\local\programs\python\python39\lib\site-packages\brownie\network\main.py", line 40, in connect
    web3.connect(host, active.get("timeout", 30))
  File "c:\users\allow\appdata\local\programs\python\python39\lib\site-packages\brownie\network\web3.py", line 52, in connect
    uri = _expand_environment_vars(uri)
  File "c:\users\allow\appdata\local\programs\python\python39\lib\site-packages\brownie\network\web3.py", line 183, in _expand_environment_vars
    raise ValueError(f"Unable to expand environment variable in host setting: '{uri}'")
ValueError: Unable to expand environment variable in host setting: 'https://rinkeby.infura.io/v3/$WEB3_INFURA_PROJECT_ID'

Here is my deploy.py code

from brownie import accounts, config, SimpleStorage, network
import os

def deploy_simple_storage():
    account = get_account()
    simple_storage = SimpleStorage.deploy({"from": account})
    stored_value = simple_storage.retrieve()
    print(stored_value)
    transaction = simple_storage.store(15, {"from": account})
    transaction.wait(1)
    updated_stored_value = simple_storage.retrieve()
    print(updated_stored_value)

def get_account():
    if network.show_active() == "development":
        return accounts[0]
    else:
        return accounts.add(config["wallets"]["from_key"])

def main():
    deploy_simple_storage()

I have a really little experience in coding. I think the problem is related to .env, but I don't know what I should now. FYI I am using windows n follow this course
https://www.youtube.com/watch?v=M576WGiDBdQ
stuck at 4:48:00


问:
I am changing the state of the REACT component from another component but no refresh
I need a light to see what is missing?.
I am changing the state of the Users REACT component when I add a user to the backend.
The user added with no issues.
And I send the state of the User element in  and I change the state when "onSubmit:" happened
but the Users REACT component didn't reload .
What is wrong with this approach?</p>
```<code>import { v4 as uuidv4 } from 'uuid';
import React, { useState, useEffect }  from 'react';
import { useFormik } from 'formik';
function unique_id() {
    return uuidv4()
}
var PlayersBackend='/players';
const validate = values => {
    const errors = {};
    if (values.firstName === 0 || values.firstName.replace(/^\s+|\s+$/gm, '').length === 0) {
        errors.firstName = 'Required';
    } else if (values.firstName.length === 0) {
        errors.firstName = 'The message must be no empty';
    }

    if (values.lastName === 0 || values.lastName.replace(/^\s+|\s+$/gm, '').length === 0) {
        errors.lastName = 'Required';
    } else if (values.lastName.length === 0) {

        errors.lastName = 'The message must be no empty';
    }
    return errors;
};
const addPlayer = async (firstName, lastName) => {
    await fetch(PlayersBackend, {
        method: 'POST',
        mode: 'cors',
        cache: 'no-cache',
        credentials: 'same-origin',
        headers: {
            "Content-Type":"application/json",
        },
        body: JSON.stringify({ firstName, lastName })
    })

};

const AddPlayerForm=(compUsersState) =>{
    const formik = useFormik(
        {initialValues:{firstName: '',lastName: '',},
            validate,
            onSubmit: (values,{resetForm}) =>
        {  addPlayer(values.firstName,values.lastName).then();
            resetForm();
            console.log(compUsersState.compUsersState)
            compUsersState.compUsersState(p => p+1);

        },
    });
    return (
        <form onSubmit={formik.handleSubmit}>
            <label htmlFor="firstName">First Name</label>
            <input
                id="firstName"
                name="firstName"
                type="text"
                onChange={formik.handleChange}
                value={formik.values.firstName}
            />
            <label htmlFor="lastName">Last Name</label>
            <input
                id="lastName"
                name="lastName"
                type="text"
                onChange={formik.handleChange}
                value={formik.values.lastName}
            />

            <button type="submit">Add user</button>
        </form>
    );
};

export const Users = () => {

    const [error, setError] = useState(null);
    const [isLoaded, setIsLoaded] = useState(false);
    const [users, setPlayers] = useState([]);
    const [,compUsersState] = useState(0);
    useEffect(() => {
        fetch(PlayersBackend).then(response => response.json()).then((data) => { setIsLoaded(true);setPlayers(data);}, (error) => {setIsLoaded(true);setError(error);})},[])
    if (error) {
        return <div>Error: {error.message}</div>;
    } else if (!isLoaded) {
        return <div>Loading...</div>;
    } else {

        if (typeof (users._embedded) !== 'undefined')
        {
            return (

                <ul>
                    <AddPlayerForm compUsersState={compUsersState}/>
                    {users._embedded.players.map(player => (
                        <li className="d-flex justify-content-start" key={unique_id()}>
                            {player.firstName} {player.lastName}
                        </li>
                    ))}

                </ul>
            );

        }
        else return  (<ul> </ul> )

    }

}
</code>```

答:
Try with forceupdate like

```<code>const forceUpdate = React.useReducer(bool => !bool)[1];
</code>```

And call with state update

```<code>forceUpdate();
</code>```

Body:
I need a light to see what is missing?.
I am changing the state of the Users REACT component when I add a user to the backend.
The user added with no issues.
And I send the state of the User element in  and I change the state when "onSubmit:" happened
but the Users REACT component didn't reload .
What is wrong with this approach?

import { v4 as uuidv4 } from 'uuid';
import React, { useState, useEffect }  from 'react';
import { useFormik } from 'formik';
function unique_id() {
    return uuidv4()
}
var PlayersBackend='/players';
const validate = values => {
    const errors = {};
    if (values.firstName === 0 || values.firstName.replace(/^\s+|\s+$/gm, '').length === 0) {
        errors.firstName = 'Required';
    } else if (values.firstName.length === 0) {
        errors.firstName = 'The message must be no empty';
    }

    if (values.lastName === 0 || values.lastName.replace(/^\s+|\s+$/gm, '').length === 0) {
        errors.lastName = 'Required';
    } else if (values.lastName.length === 0) {

        errors.lastName = 'The message must be no empty';
    }
    return errors;
};
const addPlayer = async (firstName, lastName) => {
    await fetch(PlayersBackend, {
        method: 'POST',
        mode: 'cors',
        cache: 'no-cache',
        credentials: 'same-origin',
        headers: {
            "Content-Type":"application/json",
        },
        body: JSON.stringify({ firstName, lastName })
    })

};

const AddPlayerForm=(compUsersState) =>{
    const formik = useFormik(
        {initialValues:{firstName: '',lastName: '',},
            validate,
            onSubmit: (values,{resetForm}) =>
        {  addPlayer(values.firstName,values.lastName).then();
            resetForm();
            console.log(compUsersState.compUsersState)
            compUsersState.compUsersState(p => p+1);

        },
    });
    return (
        <form onSubmit={formik.handleSubmit}>
            First Name
            <input
                id="firstName"
                name="firstName"
                type="text"
                onChange={formik.handleChange}
                value={formik.values.firstName}
            />
            Last Name
            <input
                id="lastName"
                name="lastName"
                type="text"
                onChange={formik.handleChange}
                value={formik.values.lastName}
            />

            <button type="submit">Add user</button>
        </form>
    );
};

export const Users = () => {

    const [error, setError] = useState(null);
    const [isLoaded, setIsLoaded] = useState(false);
    const [users, setPlayers] = useState([]);
    const [,compUsersState] = useState(0);
    useEffect(() => {
        fetch(PlayersBackend).then(response => response.json()).then((data) => { setIsLoaded(true);setPlayers(data);}, (error) => {setIsLoaded(true);setError(error);})},[])
    if (error) {
        return
Error: {error.message}
;
    } else if (!isLoaded) {
        return
Loading...
;
    } else {

        if (typeof (users._embedded) !== 'undefined')
        {
            return (

                    <AddPlayerForm compUsersState={compUsersState}/>
                    {users._embedded.players.map(player => (

                            {player.firstName} {player.lastName}

                    ))}

            );

        }
        else return  (

 )

    }

}

Body:
Try with forceupdate like

const forceUpdate = React.useReducer(bool => !bool)[1];

And call with state update

forceUpdate();


问:
tabEndNewRow deletes value of last cell
Tabulator documentation tells us that

```<code>The tabEndNewRow option will cause the table to create a new
row and add focus on the first editable cell in that row when
you tab out of the last editable cell on the table. You can
set it to one of a number of options to determine the data of
the new row.
</code>```

but in my code the tab pressed on last cell if it is editable it DELETEs the cell's value

```<code>    var cols = [{
        title: "Cell 1",
        field: "c1",
        editor: "input"
      },
      {
        title: "Cell 2",
        field: "c2",
        editor: "input"
      },
      {
        title: "Cell 3",
        field: "c3",
        editor: "input"
      },

    ];

    var row = {
      "c1": "",
      "c2": ""
    }
    var table = new Tabulator('#table', {
      columns: cols,
      data: [row],
      height: "100%",
      tabEndNewRow: row,
    })
</code>```

Working jsFiddle https://jsfiddle.net/radek/xe4qbL5k/6/

would you have any solution for that issue?

答:
I think you found a bug in Tabulator.  In version 5.1.0 if you look at the not-minified version you can see the line

```<code>// cell.getElement().firstChild.blur();
</code>```

commented out on line 13359.  Commenting this line out causes the new row to be added before the changes to the current row are processed.  I checked version 5.0.10 and it did not have that line commented but it shows some other errors.  With 4.9.3 your fiddle works fine.

jsFiddle

Title: tabEndNewRow deletes value of last cell

Body:
Tabulator documentation tells us that

The tabEndNewRow option will cause the table to create a new
row and add focus on the first editable cell in that row when
you tab out of the last editable cell on the table. You can
set it to one of a number of options to determine the data of
the new row.

but in my code the tab pressed on last cell if it is editable it DELETEs the cell's value

    var cols = [{
        title: "Cell 1",
        field: "c1",
        editor: "input"
      },
      {
        title: "Cell 2",
        field: "c2",
        editor: "input"
      },
      {
        title: "Cell 3",
        field: "c3",
        editor: "input"
      },

    ];

    var row = {
      "c1": "",
      "c2": ""
    }
    var table = new Tabulator('#table', {
      columns: cols,
      data: [row],
      height: "100%",
      tabEndNewRow: row,
    })

Working jsFiddle https://jsfiddle.net/radek/xe4qbL5k/6/

would you have any solution for that issue?

Body:
I think you found a bug in Tabulator.  In version 5.1.0 if you look at the not-minified version you can see the line

// cell.getElement().firstChild.blur();

commented out on line 13359.  Commenting this line out causes the new row to be added before the changes to the current row are processed.  I checked version 5.0.10 and it did not have that line commented but it shows some other errors.  With 4.9.3 your fiddle works fine.

jsFiddle


问:
Proper use of new/delete
As a sequel of my previous question, I would like to ask what I am doing wrong in the following code.

The code is, for example

```<code>void myclass1::myfun()
{
myclass2* newVar = new myclass2();
/* other code and stuff */
myvector.push_back(newVar); // myvector is a member of myclass1 and is a std::vector<myclass2*>
delete newVar;
}
</code>```

but when I run it, myvector returns empty, unless I comment out the delete line.

What am I doing wrong?

答:
As already said, you cannot access or change memory when you have freed it already. You must take care of deleting your object in your destructor (or an extra function). Here's a snippet that would do that:</p>

```<code>// this function adds the object
`void MyClass1::AddFun()
{
  myClass2* Ptr = new myClass2();  // create new object via new-operator
  myvector.push_back(Ptr);
}

// this function clears the entire vector
void MyClass1::ClearAllContent()
{
  while (myvector.empty() == false)
  {
    delete myvector[myvectory.size() - 1];  // free the last object in your vector
    myvector.pop_back();                    // pop_back reomves the "empty"-pointer
  }
}
</code>```

Title: Proper use of new/delete

Body:
As a sequel of my previous question, I would like to ask what I am doing wrong in the following code.

The code is, for example

void myclass1::myfun()
{
myclass2* newVar = new myclass2();
/* other code and stuff */
myvector.push_back(newVar); // myvector is a member of myclass1 and is a std::vector<myclass2*>
delete newVar;
}

but when I run it, myvector returns empty, unless I comment out the delete line.

What am I doing wrong?

Body:
As already said, you cannot access or change memory when you have freed it already. You must take care of deleting your object in your destructor (or an extra function). Here's a snippet that would do that:

// this function adds the object
`void MyClass1::AddFun()
{
  myClass2* Ptr = new myClass2();  // create new object via new-operator
  myvector.push_back(Ptr);
}

// this function clears the entire vector
void MyClass1::ClearAllContent()
{
  while (myvector.empty() == false)
  {
    delete myvector[myvectory.size() - 1];  // free the last object in your vector
    myvector.pop_back();                    // pop_back reomves the "empty"-pointer
  }
}


问:
How to get authentication for Using Googles Media Translation API with Springboot
I am trying out Google's Media Translation API. I cloned their test code that can be found here

but I am getting an error
java.io.IOException: The Application Default Credentials are not available. They are available if running in Google Compute Engine. Otherwise, the environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining the credentials. See https://developers.google.com/accounts/docs/application-default-credentials for more information.

However, I already have the JSON file downloaded so I want to know how I can make the library point to that file as the source of authentication.

I have tried export GOOGLE_APPLICATION_CREDENTIALS=/Users/tobilobaowolabi/Downloads/blood-drive-296909-03dad529f7b9.json but it is not working either

答:
You may point your library to your source of authentication through your code.

First you need to update your pom.xml file and add below code inside the <dependencies>

```<code><dependency>
      <groupId>com.google.auth</groupId>
      <artifactId>google-auth-library-oauth2-http</artifactId>
      <version>1.3.0</version>
</dependency>
</code>```

Once done with pom.xml, go to your java code and add below code inside translateFromFile method.

```<code>String jsonPath = "<your_json_file_path>";
    GoogleCredentials credentials = GoogleCredentials.fromStream(new FileInputStream(jsonPath))
    .createScoped(Lists.newArrayList("https://www.googleapis.com/auth/cloud-platform"));

 SpeechTranslationServiceSettings speechTranslationServiceSettings =
     SpeechTranslationServiceSettings.newBuilder()
         .setCredentialsProvider(FixedCredentialsProvider.create(credentials))
         .build();
</code>```

The above code is to call your json path as credentials and then build it through SpeechTranslationServiceSettings.

Lastly, you need to pass SpeechTranslationServiceSettings to the create() of SpeechTranslationServiceClient .

```<code>try (SpeechTranslationServiceClient client = SpeechTranslationServiceClient.create(speechTranslationServiceSettings))
</code>```

You may check this Authentication Sample Code as reference for the authentication of credentials.

Body:
You may point your library to your source of authentication through your code.

First you need to update your pom.xml file and add below code inside the <dependencies>

<dependency>
      <groupId>com.google.auth</groupId>
      <artifactId>google-auth-library-oauth2-http</artifactId>
      <version>1.3.0</version>
</dependency>

Once done with pom.xml, go to your java code and add below code inside translateFromFile method.

String jsonPath = "<your_json_file_path>";
    GoogleCredentials credentials = GoogleCredentials.fromStream(new FileInputStream(jsonPath))
    .createScoped(Lists.newArrayList("https://www.googleapis.com/auth/cloud-platform"));

 SpeechTranslationServiceSettings speechTranslationServiceSettings =
     SpeechTranslationServiceSettings.newBuilder()
         .setCredentialsProvider(FixedCredentialsProvider.create(credentials))
         .build();

The above code is to call your json path as credentials and then build it through SpeechTranslationServiceSettings.

Lastly, you need to pass SpeechTranslationServiceSettings to the create() of SpeechTranslationServiceClient .

try (SpeechTranslationServiceClient client = SpeechTranslationServiceClient.create(speechTranslationServiceSettings))

You may check this Authentication Sample Code as reference for the authentication of credentials.


问:
No Vuex store detected in Vue Dev Tools (vue2/vuex3)
For very specific reasons, I have set the vue dev tools to true in production.

```<code>Vue.config.devtools = true
</code>```

Am using the following versions:

```<code>"vue": "^2.5.2"
"vuex": "^3.0.1"
"vuetify": "^1.0.0"
</code>```

While I can see the components and events, the Vuex store is not detected.

I have tried downgrading the vuex version to 2.3.1 and 2.4.x, but it did not help.
Here's the link I referred to - https://github.com/vuejs/vue-devtools/issues/405

Note - The store works well, its just that I am not able to view it in the Vue dev tools.

Any pointers is appreciated.

答:
I had the exact same problem with Vue 3.
Updating the vuex from 4.0.0 to 4.0.2 did resolve the problem.</p>

Body:
For very specific reasons, I have set the vue dev tools to true in production.

Vue.config.devtools = true

Am using the following versions:

"vue": "^2.5.2"
"vuex": "^3.0.1"
"vuetify": "^1.0.0"

While I can see the components and events, the Vuex store is not detected.

I have tried downgrading the vuex version to 2.3.1 and 2.4.x, but it did not help.
Here's the link I referred to - https://github.com/vuejs/vue-devtools/issues/405

Note - The store works well, its just that I am not able to view it in the Vue dev tools.

Any pointers is appreciated.


问:
SQL Database Mail sudden failure with Exception Message: Cannot send mails to mail server
Trying to send email from database server to internal company mail, used to work properly until recently

Failed with the following error message:

The mail could not be sent to the recipients because of the mail server failure. (Sending Mail using Account 1 . Exception Message: Cannot send mails to mail server. (Failure sending mail.).  )

Tried
restarted the database mail service, still failed

exec msdb.dbo.sysmail_help_status_sp

shows STARTED status

```<code>sp_CONFIGURE 'show advanced', 1
GO
RECONFIGURE
GO
sp_CONFIGURE 'Database Mail XPs', 1
GO
RECONFIGURE
GO
sp_CONFIGURE 'show advanced', 0
GO
RECONFIGURE
GO
</code>```

config updated but still failed to send out mail

Anything else I can check?

答:
Update on issue:

Found that the server the mail profile has been configured to has been decommissioned. Changing that to the new server fixed the issue

Body:
Trying to send email from database server to internal company mail, used to work properly until recently

Failed with the following error message:

The mail could not be sent to the recipients because of the mail server failure. (Sending Mail using Account 1 . Exception Message: Cannot send mails to mail server. (Failure sending mail.).  )

Tried
restarted the database mail service, still failed

exec msdb.dbo.sysmail_help_status_sp

shows STARTED status

sp_CONFIGURE 'show advanced', 1
GO
RECONFIGURE
GO
sp_CONFIGURE 'Database Mail XPs', 1
GO
RECONFIGURE
GO
sp_CONFIGURE 'show advanced', 0
GO
RECONFIGURE
GO

config updated but still failed to send out mail

Anything else I can check?


问:
how to change the color of select text
how to change the color of the dropdown text that I am given red but initially it look like black when we click that it look like red, so how to change that initially it look like red color

<select>
  <option style="color:red">one</option>
  <option style="color:red">two</option>
</select>```

答:
You should apply the style to the select, not to the option.

Setting style="color:red" will set the color of the option to red.

Setting style="color:green" will set the color of select to green

<select style="color:green">
  <option style="color:red">one</option>
  <option style="color:red">two</option>
</select>```
</div>
</div>
</p>
<p>If you dont want the color of options to be updated, use <code>color: initial</code> for the option.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>select {
  color: red;
}

select option {
  color: initial;
}</code>```

<select>
  <option>one</option>
  <option>two</option>
</select>```

Title: how to change the color of select text

Body:
You should apply the style to the select, not to the option.

Setting style="color:red" will set the color of the option to red.

Setting style="color:green" will set the color of select to green

<select style="color:green">
  <option style="color:red">one</option>
  <option style="color:red">two</option>
</select>

If you dont want the color of options to be updated, use color: initial for the option.

select {
  color: red;
}

select option {
  color: initial;
}

<select>
  <option>one</option>
  <option>two</option>
</select>


问:
How to solve the issue of Warning: Each child in a list should have a unique "key" prop even I am using key props
Here is my code

```<code>return (
    <ScrollView>
      <View style={{ padding: 10, flex: 1 }}>
        {listing.map((listing) => (
          <>
            <View style={styles.containerOne} key={listing.snome_id}>
              <View
                id="listing"
                style={styles.containerTwo}
              >
                <Text style={{ margin: 15, marginTop: 20 }}>
                  {listing.header}
                </Text>

                {listing.url.map((url) => (
                  <Image style={styles.pic} source={{ uri: url }} />
                ))}

                <Text style={{ margin: 15, marginTop: 20 }}>
                  {' '}
                  {listing.description}
                </Text>
              </View>
            </View>
          </>
        ))}
      </View>
    </ScrollView>
  );
</code>```

I am trying to view multiple listings and the corresponding image and some text. It seems even though I am using a key prop in the view component it is still throwing error to me and I am not sure about the reason behind that.

I hope that somebody can help me to resolve this issue.

答:
The key always needs to be given to the top-level component created by the map function. In your code, that's the Fragment. You'll need to replace this:

```<code>  <>
            <View style={styles.containerOne} key={listing.snome_id}>
 ...
  </>
</code>```

With this:

```<code>  <React.Fragment key={listing.snome_id}>
            <View style={styles.containerOne}>
  ...
  </React.Fragment>
</code>```

Body:
Here is my code

return (
    <ScrollView>
      <View style={{ padding: 10, flex: 1 }}>
        {listing.map((listing) => (
          <>
            <View style={styles.containerOne} key={listing.snome_id}>
              <View
                id="listing"
                style={styles.containerTwo}
              >
                <Text style={{ margin: 15, marginTop: 20 }}>
                  {listing.header}
                </Text>

                {listing.url.map((url) => (
                  <Image style={styles.pic} source={{ uri: url }} />
                ))}

                <Text style={{ margin: 15, marginTop: 20 }}>
                  {' '}
                  {listing.description}
                </Text>
              </View>
            </View>
          </>
        ))}
      </View>
    </ScrollView>
  );

I am trying to view multiple listings and the corresponding image and some text. It seems even though I am using a key prop in the view component it is still throwing error to me and I am not sure about the reason behind that.

I hope that somebody can help me to resolve this issue.

Body:
The key always needs to be given to the top-level component created by the map function. In your code, that's the Fragment. You'll need to replace this:

  <>
            <View style={styles.containerOne} key={listing.snome_id}>
 ...
  </>

With this:

  <React.Fragment key={listing.snome_id}>
            <View style={styles.containerOne}>
  ...
  </React.Fragment>


问:
Check whether elements in 2d array is ascending or not in java
So I got a problem
Write a program in java to take an 2D array from user and display all elements if array
in ascending order.

Here I took the input from user but am not able to check whether elements in 2d array are ascending or not

```<code>import  java.util.Scanner;
class Q3{
    public static void main(String[] args) {
        int rows, columns;

    Scanner input= new Scanner (System.in);
    System.out.println("Enter size of 2D Array : ");
    rows = input.nextInt();
    columns = input.nextInt();

    System.out.println("Enter array elements: ");
    int [][] arr1 = new int [rows][columns];

    for(int i=0; i<rows;i++)
    {
        for(int j=0;j<columns; j++)
        {
            System.out.print("arr1 ["+ i+"]["+j+"] = " );
            arr1[i][j] = input.nextInt();
        }
    }
     //Checking whether the array is of ascending order or not

      // for(int i=0; i<rows;i++)
      // {
     //     for(int j=0;j<columns; j++)
    //     {
    //         for(int k=0; k<rows;k++)
    //         {
    //             for(int l=0 ;l<columns; l++)
    //             {
    //                 if(arr1[i][j] < arr1[k][l])
    //                 {
    //                     break;
    //                 }
    //             }
    //         }
    //     }
    // }
}
</code>```

}

Here to check for ascending order what should I do ??
I have tried a couple of things but didn't work

答:
Just two for loops are enough to check weather the 2d array is in ascending order or not.

```<code>import  java.util.Scanner;
class Q3{
    public static void main(String[] args) {
        int rows, columns;
        var out = System.out;

        Scanner input= new Scanner (System.in);
        System.out.println("Enter size of 2D Array : ");
        rows = input.nextInt();
        columns = input.nextInt();

        System.out.println("Enter array elements: ");
        int [][] arr1 = new int [rows][columns];

        for(int i=0; i<rows;i++){
            for(int j=0;j<columns; j++){
                System.out.print("arr1 ["+ i+"]["+j+"] = " );
                arr1[i][j] = input.nextInt();
            }
        }
        //Checking whether the array is in ascending order or not
        boolean ascendingOrder = true;
        for(int i=0;i<rows && ascendingOrder;i++){
            for(int j=0;j<columns-1 && ascendingOrder;j++)
                if(arr1[i][j] > arr1[i][j+1])
                    ascendingOrder = false;
        }
        //displaying the 2d array is its in ascendingOrder
        if(ascendingOrder){
            for(int i=0; i<rows;i++){
                for(int j=0;j<columns; j++){
                    out.print(arr1[i][j]+" ");
                }
                out.println();
            }
        }

        // for(int i=0; i<rows;i++)
        // {
        //     for(int j=0;j<columns; j++)
        //     {
        //         for(int k=0; k<rows;k++)
        //         {
        //             for(int l=0 ;l<columns; l++)
        //             {
        //                 if(arr1[i][j] < arr1[k][l])
        //                 {
        //                     break;
        //                 }
        //             }
        //         }
        //     }
        // }
    }
}
</code>```

output:

```<code>$ java Q3
Enter size of 2D Array :
2
2
Enter array elements:
arr1 [0][0] = 1
arr1 [0][1] = 2
arr1 [1][0] = 3
arr1 [1][1] = 4
1 2
3 4

$ java Q3
Enter size of 2D Array :
2
2
Enter array elements:
arr1 [0][0] = 3
arr1 [0][1] = 2
arr1 [1][0] = 1
arr1 [1][1] = 2
</code>```

Body:
So I got a problem
Write a program in java to take an 2D array from user and display all elements if array
in ascending order.

Here I took the input from user but am not able to check whether elements in 2d array are ascending or not

import  java.util.Scanner;
class Q3{
    public static void main(String[] args) {
        int rows, columns;

    Scanner input= new Scanner (System.in);
    System.out.println("Enter size of 2D Array : ");
    rows = input.nextInt();
    columns = input.nextInt();

    System.out.println("Enter array elements: ");
    int [][] arr1 = new int [rows][columns];

    for(int i=0; i<rows;i++)
    {
        for(int j=0;j<columns; j++)
        {
            System.out.print("arr1 ["+ i+"]["+j+"] = " );
            arr1[i][j] = input.nextInt();
        }
    }
     //Checking whether the array is of ascending order or not

      // for(int i=0; i<rows;i++)
      // {
     //     for(int j=0;j<columns; j++)
    //     {
    //         for(int k=0; k<rows;k++)
    //         {
    //             for(int l=0 ;l<columns; l++)
    //             {
    //                 if(arr1[i][j] < arr1[k][l])
    //                 {
    //                     break;
    //                 }
    //             }
    //         }
    //     }
    // }
}

}

Here to check for ascending order what should I do ??
I have tried a couple of things but didn't work

Body:
Just two for loops are enough to check weather the 2d array is in ascending order or not.

import  java.util.Scanner;
class Q3{
    public static void main(String[] args) {
        int rows, columns;
        var out = System.out;

        Scanner input= new Scanner (System.in);
        System.out.println("Enter size of 2D Array : ");
        rows = input.nextInt();
        columns = input.nextInt();

        System.out.println("Enter array elements: ");
        int [][] arr1 = new int [rows][columns];

        for(int i=0; i<rows;i++){
            for(int j=0;j<columns; j++){
                System.out.print("arr1 ["+ i+"]["+j+"] = " );
                arr1[i][j] = input.nextInt();
            }
        }
        //Checking whether the array is in ascending order or not
        boolean ascendingOrder = true;
        for(int i=0;i<rows && ascendingOrder;i++){
            for(int j=0;j<columns-1 && ascendingOrder;j++)
                if(arr1[i][j] > arr1[i][j+1])
                    ascendingOrder = false;
        }
        //displaying the 2d array is its in ascendingOrder
        if(ascendingOrder){
            for(int i=0; i<rows;i++){
                for(int j=0;j<columns; j++){
                    out.print(arr1[i][j]+" ");
                }
                out.println();
            }
        }

        // for(int i=0; i<rows;i++)
        // {
        //     for(int j=0;j<columns; j++)
        //     {
        //         for(int k=0; k<rows;k++)
        //         {
        //             for(int l=0 ;l<columns; l++)
        //             {
        //                 if(arr1[i][j] < arr1[k][l])
        //                 {
        //                     break;
        //                 }
        //             }
        //         }
        //     }
        // }
    }
}

output:

$ java Q3
Enter size of 2D Array :
2
2
Enter array elements:
arr1 [0][0] = 1
arr1 [0][1] = 2
arr1 [1][0] = 3
arr1 [1][1] = 4
1 2
3 4

$ java Q3
Enter size of 2D Array :
2
2
Enter array elements:
arr1 [0][0] = 3
arr1 [0][1] = 2
arr1 [1][0] = 1
arr1 [1][1] = 2


问:
In a Java debugger, how to ignore exceptions never passing through my code
I'm currently using IntelliJ IDEA for Java development, but I'm also interested in answers targeting other IDEs or general concepts for debugging Java code. Because this is a feature I've missed in a number of IDEs, I'm unsure if I've missed a workflow concept when transferring my debug habits from other languages.

Let's say I'm writing some code in myapp.* while using framework classes from somelib.*. A typical stack trace may start in either package and may switch several times between them. Let's also say I'm debugging under the assumption that there are bugs in my code and that there aren't any in the library code. An example stack trace (showing only class names):

```<code>somelib.D (current stack frame)
somelib.C
myapp.Y
myapp.X
somelib.B
somelib.A
</code>```

Normally, I'm not interested in the following types of exceptions and do not want the debugger to break on them:

Thrown in somelib.B and caught in somelib.A. Either the library code is throwing exceptions to handle problematic state inside the library or to stop the application. In the latter case, I'm only interested in the exception message which hopefully tells me what's wrong.

Thrown in somelib.D and caught in somelib.C. The library code may use exceptions as a form of logic where a certain action is tried and an alternative route is taken in the case of a problem or where my code is notified by the problem by other means (e.g. returning a null reference where appropriate).

Types of exceptions I am interested in:

Thrown in somelib.C or somelib.D and not caught in somelib.C or somelib.D. Here I want the debugger to break on the line in myapp.Y where I call the code from somelib.C.

Thrown in myapp.X or myapp.Y, either caught or uncaught. Here I want the debugger to break on the line the exception is thrown.

IntelliJ IDEA gives me the options to select wether I want to break on caught or uncaught exceptions, or both and to restrict the location where the exception is thrown to a set of classes. These options don't help much as I normally want to break on any exception, wether caught or uncaught, as long as code I've written is between the place it's thrown and the place it's caught, eventually.

答:
It seems to be impossible to do exactly what I wanted in a convenient way. At the time of this question I was in the process of learning Java and teaching it to my fellow students, so a simple solution would have been favorable.

But with my current experience it seems reasonable to use the following approach:

Put catch (Trowable t) around each thread body, i.e. at the top level of Runnable.run() and static main(String[]) and log these "uncaught" exceptions to the console.

Care needs to be taken to not accidentally catch checked exceptions with these "catch-all" handlers, but to handle them as part of program logic.

When starting to debug, do not create any exception breakpoints.

As soon as an exception is logged to the console, create an exception breakpoint for it and try to make it get thrown again.

This should only happen unchecked exceptions (i.e. subclasses of RuntimeException) as other exceptions have to be explicitly caught and handled anyway.

As catching and handling unchecked exceptions normally isn't part of a program's logic, creating these exception breakpoints without constraints on the place it's thrown should not catch any "false positives".

An alternative is to skip the last two steps and instead create an exception breakpoint for RuntimeException. But this has a higher change of catching exceptions that are caught as part of the program logic.

Body:
I'm currently using IntelliJ IDEA for Java development, but I'm also interested in answers targeting other IDEs or general concepts for debugging Java code. Because this is a feature I've missed in a number of IDEs, I'm unsure if I've missed a workflow concept when transferring my debug habits from other languages.

Let's say I'm writing some code in myapp.* while using framework classes from somelib.*. A typical stack trace may start in either package and may switch several times between them. Let's also say I'm debugging under the assumption that there are bugs in my code and that there aren't any in the library code. An example stack trace (showing only class names):

somelib.D (current stack frame)
somelib.C
myapp.Y
myapp.X
somelib.B
somelib.A

Normally, I'm not interested in the following types of exceptions and do not want the debugger to break on them:

Thrown in somelib.B and caught in somelib.A. Either the library code is throwing exceptions to handle problematic state inside the library or to stop the application. In the latter case, I'm only interested in the exception message which hopefully tells me what's wrong.

Thrown in somelib.D and caught in somelib.C. The library code may use exceptions as a form of logic where a certain action is tried and an alternative route is taken in the case of a problem or where my code is notified by the problem by other means (e.g. returning a null reference where appropriate).

Types of exceptions I am interested in:

Thrown in somelib.C or somelib.D and not caught in somelib.C or somelib.D. Here I want the debugger to break on the line in myapp.Y where I call the code from somelib.C.

Thrown in myapp.X or myapp.Y, either caught or uncaught. Here I want the debugger to break on the line the exception is thrown.

IntelliJ IDEA gives me the options to select wether I want to break on caught or uncaught exceptions, or both and to restrict the location where the exception is thrown to a set of classes. These options don't help much as I normally want to break on any exception, wether caught or uncaught, as long as code I've written is between the place it's thrown and the place it's caught, eventually.


问:
Timed input in python 3 for Mac and Windows
I need a timed input for python 3 on both Mac and Windows which, if the user runs out of time, automatically chooses one of the options. Every other answer for a question I've seen only terminates after user presses 'Enter'. I need it to terminate regardless of any 'Enter' pressed or not.

For example, in my chess program, if no input is given after 5 seconds, I need it to automatically choose "Q". Also if the input is not in ["Q", "R", "B", "N"] then I also need it to choose "Q".

The following code doesn't work. It'll ask for the input then wait forever; the timer doesn't work at all.

```<code>def countdown():
    global timer
    timer = 5
    for x in range(timer):
        timer -= 1
        time.sleep(1)

countdownThread = threading.Thread(target=countdown)
countdownThread.start()

while timer > 0:
    promotedPiece = input("Promote to Q, R, B or N? >  ").upper()
    if timer == 0:
        break

if timer == 0:
    if promotedPiece not in ["Q", "R", "B", "N"]:  # If not valid input, choose Queen
        promotedPiece = "Q"
        print("Queen auto selected")
</code>```

答:
If you're comfortable with async, it's a very simple solution to this problem, with the aioconsole (pip install aioconsole) library:

import asyncio

from aioconsole import ainput # async version of input()

async def get_choice() -> str:
    try:
        coro = ainput("Promote to Q, R, B or N? >  ")
        choice = await asyncio.wait_for(coro, timeout=5.0)
    except asyncio.TimeoutError:
        print()  # go to next line past ">" of prompt
        choice = "Q"
    return choice.upper()

async def main():
    print("You chose", await get_choice())

asyncio.run(main())
```

Body:
I need a timed input for python 3 on both Mac and Windows which, if the user runs out of time, automatically chooses one of the options. Every other answer for a question I've seen only terminates after user presses 'Enter'. I need it to terminate regardless of any 'Enter' pressed or not.

For example, in my chess program, if no input is given after 5 seconds, I need it to automatically choose "Q". Also if the input is not in ["Q", "R", "B", "N"] then I also need it to choose "Q".

The following code doesn't work. It'll ask for the input then wait forever; the timer doesn't work at all.

def countdown():
    global timer
    timer = 5
    for x in range(timer):
        timer -= 1
        time.sleep(1)

countdownThread = threading.Thread(target=countdown)
countdownThread.start()

while timer > 0:
    promotedPiece = input("Promote to Q, R, B or N? >  ").upper()
    if timer == 0:
        break

if timer == 0:
    if promotedPiece not in ["Q", "R", "B", "N"]:  # If not valid input, choose Queen
        promotedPiece = "Q"
        print("Queen auto selected")


问:
Allow 2 decimal places in <input type="number">
I have a <input type="number"> and I want to restrict the input of the users to purely numbers or numbers with decimals up to 2 decimal places.

Basically, I am asking for a price input.

I wanted to avoid doing regex. Is there a way to do it?

```<code><input type="number" required name="price" min="0" value="0" step="any">
</code>```

答:
I had a strange editing experience with some of these solutions. This seems to work pretty well from a user's perspective (only intervene when necessary):</p>
```<code>function handleNumberChanged (e) {
    const fixed = parseFloat(e.target.value).toFixed(2).toString()
    if (fixed.length < parseFloat(e.target.value).toString().length)
      e.target.value = fixed
}
</code>```

Body:
I have a <input type="number"> and I want to restrict the input of the users to purely numbers or numbers with decimals up to 2 decimal places.

Basically, I am asking for a price input.

I wanted to avoid doing regex. Is there a way to do it?

<input type="number" required name="price" min="0" value="0" step="any">

Body:
I had a strange editing experience with some of these solutions. This seems to work pretty well from a user's perspective (only intervene when necessary):

function handleNumberChanged (e) {
    const fixed = parseFloat(e.target.value).toFixed(2).toString()
    if (fixed.length < parseFloat(e.target.value).toString().length)
      e.target.value = fixed
}


问:
Can Kendo Grid use client side filtering with server side paging/sorting?
I use ServerOperation(true) on my Kendo Grid DataSource to perform server side paging/sorting.  I have some columns declared with the Filterable method, which causes server side requests to populate the type ahead.  I would like these Filterable columns to just work client side with whatever data is available on the current page.  Is there a way to configure this?</p>

答: I use toODataString on the grid's State object on the front end, which queries my OData v4 ASP.NET Web Service running on IIS (server side).


问:
Swift - Button text color won't change with setTitleColor
I can not seem to get the text in two of my buttons to change to white, unless I manually do it through the storyboard. Any ideas?

class AppUIButton: UIButton {

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        backgroundColor = Theme.tintColor
        layer.cornerRadius = frame.height / 2
        setTitleColor(UIColor.white, for: .normal)
    }
}

class AddTripViewController: UIViewController {

    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var tripTextField: UITextField!
    @IBOutlet weak var cencelButton: UIButton!
    @IBOutlet weak var saveButton: UIButton!

    var doneSaving: (() -> ())?

    override func viewDidLoad() {
        super.viewDidLoad()

        titleLabel.font = UIFont(name: Theme.mainFontName, size: 24)

        //I can force the text color to change with the bellow
        //cencelButton.setTitle("Cancel", for: .normal)
        //cencelButton.setTitleColor(UIColor.white, for: .normal)

        //saveButton.setTitle("Add", for: .normal)
        //saveButton.setTitleColor(UIColor.white, for: .normal)

    }

    @IBAction func cancel(_ sender: Any) {
        dismiss(animated: true)
    }

    @IBAction func save(_ sender: Any) {
        TripFunctions.createTrip(tripModel: TripModel(title: tripTextField.text!))
        if let doneSaving = doneSaving {
            doneSaving()
        }
        dismiss(animated: true)
    }
}
```

答:
This should work for you.</p>
```<code>titleLabel.textColor = UIColor.white
</code>```

Body:
This should work for you.

titleLabel.textColor = UIColor.white


问:
Add entry to array inside an Observable object
I have an angular app where on one page I am displaying an object that includes an array of comments as a sub-object.
I load the object into my class as an Observable.
Then I display the object in my html by using the

```<code><div class="container-fluid mt--7" *ngIf="drill | async as item else loading">
</code>```

That way it has a display until the Observable loads.

As part of the page, you have the ability to append a new comment to the Drill object. Saving that object to the DB works fine, but I would like to just append the new comment to the Drill object so that I don't have to requery the Drill object from the DB to have the new comment displayed.

I just can't figure out how to update the Observable from inside the .subscribe method of service call to persist the new comment.

```<code>addComments(): void {
    const comment = new Comment(null, this.commentsForm.get('comment').value, this.commentsForm.get('rating').value);
    this.drillService.addComments(this.id, comment).subscribe(comment => {
     ---- This is where I can't figure out what to do ------
    });

  }
</code>```

答:
You can update observable directly, There are 2 ways you can fix your issue.

Instead of using drill observable store comments in an array and push new comment into this array and use this array to display html side

Create a new observable using Subject (rxjs operater). You can find examples of how you can create observable using subject https://medium.com/globant/rxjs-subjects-the-complete-know-how-3dc1e7e341a0

Body:
I have an angular app where on one page I am displaying an object that includes an array of comments as a sub-object.
I load the object into my class as an Observable.
Then I display the object in my html by using the

That way it has a display until the Observable loads.

As part of the page, you have the ability to append a new comment to the Drill object. Saving that object to the DB works fine, but I would like to just append the new comment to the Drill object so that I don't have to requery the Drill object from the DB to have the new comment displayed.

I just can't figure out how to update the Observable from inside the .subscribe method of service call to persist the new comment.

addComments(): void {
    const comment = new Comment(null, this.commentsForm.get('comment').value, this.commentsForm.get('rating').value);
    this.drillService.addComments(this.id, comment).subscribe(comment => {
     ---- This is where I can't figure out what to do ------
    });

  }


问:
SQL: Have two two columns of old and new SKUS. Need to pull into a single column with new skus if any
I have two columns with data from Table1 that have the SKU number and New SKU Number. My goal is to query this data as a single column as shown in the 'Desired' Table

```<code>+-------+--------+    +---------+
| SKU   | NEW_SKU|    | Desired |
+-------+--------+    |---------+
| null  | 1      |    | 1       |
| null  | 1      |    | 1       |
|  2    | null   |    | 2       |
|  2    | 3      |    | 3       |
|  2    | 5      |    | 5       |
+-------+--------+    +---------+
</code>```

Currently I have:

```<code>SELECT

SKU
CASE WHEN (SKU IS NOT NULL AND NEW_SKU IS NOT NULL) THEN new_sku
WHEN (SKU IS NULL AND NEW_SKU IS NOT NULL) THEN new_sku
ELSE SKU END AS Product_number

FROM Table1
</code>```

答:
Use COALESCE here:

SELECT SKU, NEW_SKU, COALESCE(NEW_SKU, SKU) AS Product_number
FROM Table1;
```

The COALESCE function, as used above, would use the NEW_SKU value if it be non NULL, otherwise would fall back to using the SKU value.

Body:
I have two columns with data from Table1 that have the SKU number and New SKU Number. My goal is to query this data as a single column as shown in the 'Desired' Table

+-------+--------+    +---------+
| SKU   | NEW_SKU|    | Desired |
+-------+--------+    |---------+
| null  | 1      |    | 1       |
| null  | 1      |    | 1       |
|  2    | null   |    | 2       |
|  2    | 3      |    | 3       |
|  2    | 5      |    | 5       |
+-------+--------+    +---------+

Currently I have:

SELECT

SKU
CASE WHEN (SKU IS NOT NULL AND NEW_SKU IS NOT NULL) THEN new_sku
WHEN (SKU IS NULL AND NEW_SKU IS NOT NULL) THEN new_sku
ELSE SKU END AS Product_number

FROM Table1

Body:
Use COALESCE here:

SELECT SKU, NEW_SKU, COALESCE(NEW_SKU, SKU) AS Product_number
FROM Table1;

The COALESCE function, as used above, would use the NEW_SKU value if it be non NULL, otherwise would fall back to using the SKU value.


问:
Base64 binary data in an URL string opening blank page if file too large
I am building a React project where a user needs to be able to preview a document that has been uploaded, converted to a Base64 binary data object and stored in a variable called 'upload'. I use the following code to display it in a new tab when the user clicks on the preview button:

```<code>var newWIndow;
if (upload.includes("data:application/pdf"))
    newWIndow = "<iframe width='100%' height='100%' src='" + upload + "'></iframe>"
else
    newWIndow = "<img width='100%' src='" + upload + "'></img>";
var x = window.open();
x.document.open();
x.document.write(newWIndow);
x.document.close();
</code>```

The uploads are limited to image or pdf files. The preview works great, except when the file is PDF and the file size goes over 1MB. In that case, it simply opens a blank page:

Does anyone perhaps know why the larger files won't open? Is there a better way to approach this? Any advice would be very much appreciated.

答:
You can convert your too big base64 pdf to blob, and then create a new URL from that blob.

Something like this upload is your base64 pdf string:

```<code>var url = 'data:application/pdf;base64,'+ upload ;
var blobUrl;
fetch(URL)
 .then(res => res.blob())
 .then(URL.createObjectURL)
 .then((ret) => {blobUrl=ret; return blobUrl;})
 .then(console.log)
</code>```

This way you get a smaller URL from the same content.

One can test at this jsfiddle at example 2.

Body:
I am building a React project where a user needs to be able to preview a document that has been uploaded, converted to a Base64 binary data object and stored in a variable called 'upload'. I use the following code to display it in a new tab when the user clicks on the preview button:

var newWIndow;
if (upload.includes("data:application/pdf"))
    newWIndow = ""
else
    newWIndow = "";
var x = window.open();
x.document.open();
x.document.write(newWIndow);
x.document.close();

The uploads are limited to image or pdf files. The preview works great, except when the file is PDF and the file size goes over 1MB. In that case, it simply opens a blank page:

Does anyone perhaps know why the larger files won't open? Is there a better way to approach this? Any advice would be very much appreciated.

Body:
You can convert your too big base64 pdf to blob, and then create a new URL from that blob.

Something like this upload is your base64 pdf string:

var url = 'data:application/pdf;base64,'+ upload ;
var blobUrl;
fetch(URL)
 .then(res => res.blob())
 .then(URL.createObjectURL)
 .then((ret) => {blobUrl=ret; return blobUrl;})
 .then(console.log)

This way you get a smaller URL from the same content.

One can test at this jsfiddle at example 2.


问:
Linking an Android library that is on local machine
I have a set of utils and custom widgets that I want to pull out of my project as an Android library so that I can use them in other projects (and possibly share in the future).  I created a new Android Studio project and changed the build.gradle file so that 'com.android.application' was 'com.android.library' and deleted the applicationId.  It all compiles fine and I have a .aar file created.

I now want to use this new library as a module in my original project.  When I do an Import Project, all the files from the library project are copied into my original project.  But I don't want that because if I change the imported library code, it isn't reflected in the library project or vice versa.

I also tried adding this to settings.gradle:

```<code>include ':myutils'
project(':myutils').projectDir = new File(settingsDir, '../../../../Development/MyUtils/')
</code>```

and in the original project app build.gradle:

```<code>dependencies {
    implementation project(':myutils')
...
</code>```

But I get this error:

```<code>ERROR: Unable to resolve dependency for ':app@debugUnitTest/compileClasspath': Could not resolve project :myutils.
Show Details
Affected Modules: app
</code>```

How can I link the library to my project without importing it?  I would prefer not to go through an external maven repo yet.  I'm happy to (and would expect to) recompile my library whenever there is a change there and then rebuild my original project.

Thank you in advance.

答:
I have been using Phgr's above technique for four years. I have three comments -

First, I don't clean the app project each time I change the library - I just do a Sync Project before building and testing the app.

Second, I changed the File-Settings-Keymap-Main Menu-File-Sync to Alt-S for easy of syncing - I hate wasting time using the mouse for selecting the Sync icon.

Third, I have an implementation line in the app's build module file for each app variant such as the following -

```<code>debugImplementation files('c:/Android Studio Projects/PciLibrary/app/build/outputs/aar/PciLibrary-debug.aar')
releaseImplementation files('c:/Android Studio Projects/PciLibrary/app/build/outputs/aar/PciLibrary-release.aar')
</code>```

All of this is working fine with Android Studio 4.2.2 and sdk version 30.

Hope this helps others with this problem

Body:
I have a set of utils and custom widgets that I want to pull out of my project as an Android library so that I can use them in other projects (and possibly share in the future).  I created a new Android Studio project and changed the build.gradle file so that 'com.android.application' was 'com.android.library' and deleted the applicationId.  It all compiles fine and I have a .aar file created.

I now want to use this new library as a module in my original project.  When I do an Import Project, all the files from the library project are copied into my original project.  But I don't want that because if I change the imported library code, it isn't reflected in the library project or vice versa.

I also tried adding this to settings.gradle:

include ':myutils'
project(':myutils').projectDir = new File(settingsDir, '../../../../Development/MyUtils/')

and in the original project app build.gradle:

dependencies {
    implementation project(':myutils')
...

But I get this error:

ERROR: Unable to resolve dependency for ':app@debugUnitTest/compileClasspath': Could not resolve project :myutils.
Show Details
Affected Modules: app

How can I link the library to my project without importing it?  I would prefer not to go through an external maven repo yet.  I'm happy to (and would expect to) recompile my library whenever there is a change there and then rebuild my original project.

Thank you in advance.

Body:
I have been using Phgr's above technique for four years. I have three comments -

First, I don't clean the app project each time I change the library - I just do a Sync Project before building and testing the app.

Second, I changed the File-Settings-Keymap-Main Menu-File-Sync to Alt-S for easy of syncing - I hate wasting time using the mouse for selecting the Sync icon.

Third, I have an implementation line in the app's build module file for each app variant such as the following -

debugImplementation files('c:/Android Studio Projects/PciLibrary/app/build/outputs/aar/PciLibrary-debug.aar')
releaseImplementation files('c:/Android Studio Projects/PciLibrary/app/build/outputs/aar/PciLibrary-release.aar')

All of this is working fine with Android Studio 4.2.2 and sdk version 30.

Hope this helps others with this problem


问:
Make two versions - lite and pro - of the same app
We have an AdWhirl-sponsored version of an app (Moonrise) and would like to offer an ad-free $.99 version.

For maintenance reasons, I'd like to have a single app in which I just change a couple #defines to turn ads on and off.

But how do I compile to two different 'app packages', so to speak, that have different names and bundle identifiers?

I guess I'm just asking for a heads-up before I try it, and if there is a gotcha I should think of. Also, if there is an even easier way of doing it, I'd like to know (as this should be common among devs).

Plan is to

Create a bundle identifier, change it in the -info.plist

Create a new app with a new name, change bundle Display Name and icon

Make a #define or such to not show ads

Upload to App Store

Have I missed anything?

答:
Create new bundle identifier

Create one more .plist file for your app (you may duplicate existing one)

Change application name, bundle identifier and so on in new .plist file

Add another target (you may duplicate existing)

Find in target settings "Info.plist" entrie and change it to new one

Add some user defined flag in targets settings to mark what one of them is LITE and another is not LITE

Configure schemes for different targets

If you will do everything good, you will be able to use single project to build different versions of it.


问:
Laravel 5.5, Queued mail with attachments
I want to send queued mail with attachments. When I test without queueing it works fine.
But when I put mail in the queue the mail contains no attached files.
I see the file-paths in serialized string in the job

I get error Illegal string offset 'file'.

Any clues about whats wrong?

```<code>$attachments = [
    storage_path( 'app/pdf.pdf' ),
    storage_path( 'app/pdf-2.pdf' ),
];
dispatch( new ProcessReports( $this->report, $attachments ) )->delay( now()->addMinutes( 1 ) );
</code>```

I use a mailable to setup mail:

```<code>$mailable = $this->subject( 'Your reports' )
                 ->view( 'email' );

if ( count( $this->attachments ) > 0 ) {
    foreach ( $this->attachments as $attachment ) {
        $mailable->attach( $attachment );
    }

}

return $mailable;
</code>```

and finally the job handler:

```<code>public function __construct( Report $report, $attachments = array() ) {
    $this->report      = $report;
    $this->attachments = $attachments;
}

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle() {

        $email = new ReportSent( $this->report, $this->attachments );
        Mail::to( $this->report->user->email )
            ->send( $email );
    }
</code>```

答:
Controller

```<code>$files = [
    public_path('files/160031367318.pdf'),
    public_path('files/1599882252.png'),
];

$details = [
    'title' => 'Mail from abc',
    'body' => 'hello',
    'email' => 'abc@gmail.com',
    'files' => $files
];

dispatch(new SendEmailJob($details));

</code>```

Job Handler

```<code>public $details;

public function __construct($details)
{
    $this->details = $details;
}

public function handle()
{
  $details = [
    'title' =>  $this->details['title'],
    'body' =>$this->details['body'],
    'files' =>$this->details['files'],
    'email' =>$this->details['email'],
  ];
  Mail::to($this->details['email'])->send(new NotificationMail($details));
 }

</code>```

Mailable

```<code> public $details;

 public function __construct($details)
 {
    $this->details = $details;
 }

 public function build()
 {
   $this->subject('Mail from abc')->markdown('mail.notification-mail');
    foreach ($this->details['files'] as $file){
       $this->attach($file);
    }

  return $this;
 }

</code>```

Body:
I want to send queued mail with attachments. When I test without queueing it works fine.
But when I put mail in the queue the mail contains no attached files.
I see the file-paths in serialized string in the job

I get error Illegal string offset 'file'.

Any clues about whats wrong?

$attachments = [
    storage_path( 'app/pdf.pdf' ),
    storage_path( 'app/pdf-2.pdf' ),
];
dispatch( new ProcessReports( $this->report, $attachments ) )->delay( now()->addMinutes( 1 ) );

I use a mailable to setup mail:

$mailable = $this->subject( 'Your reports' )
                 ->view( 'email' );

if ( count( $this->attachments ) > 0 ) {
    foreach ( $this->attachments as $attachment ) {
        $mailable->attach( $attachment );
    }

}

return $mailable;

and finally the job handler:

public function __construct( Report $report, $attachments = array() ) {
    $this->report      = $report;
    $this->attachments = $attachments;
}

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle() {

        $email = new ReportSent( $this->report, $this->attachments );
        Mail::to( $this->report->user->email )
            ->send( $email );
    }

Body:
Controller

$files = [
    public_path('files/160031367318.pdf'),
    public_path('files/1599882252.png'),
];

$details = [
    'title' => 'Mail from abc',
    'body' => 'hello',
    'email' => 'abc@gmail.com',
    'files' => $files
];

dispatch(new SendEmailJob($details));

Job Handler

public $details;

public function __construct($details)
{
    $this->details = $details;
}

public function handle()
{
  $details = [
    'title' =>  $this->details['title'],
    'body' =>$this->details['body'],
    'files' =>$this->details['files'],
    'email' =>$this->details['email'],
  ];
  Mail::to($this->details['email'])->send(new NotificationMail($details));
 }

Mailable

 public $details;

 public function __construct($details)
 {
    $this->details = $details;
 }

 public function build()
 {
   $this->subject('Mail from abc')->markdown('mail.notification-mail');
    foreach ($this->details['files'] as $file){
       $this->attach($file);
    }

  return $this;
 }


问:
How do I open browser in specific "profile" using BATCH script in Windows?
Here is the shell script I have used to open the specific URL

```<code>   start microsoft-edge: https://stackoverflow.com/questions/ask
</code>```

However, I have multiple Profiles defined in Edge browser.

How do I open a browser based on the Profile name ? How do I pass Profile name or path in script?

答:
I'm on linux so I can't test it but you can test with one of those arguments :

--user-data-dir="C:\ChromeBrowser_profiles\Profile_edge"

or

--profile-directory="Profile 4"

Body:
Here is the shell script I have used to open the specific URL

   start microsoft-edge: https://stackoverflow.com/questions/ask

However, I have multiple Profiles defined in Edge browser.

How do I open a browser based on the Profile name ? How do I pass Profile name or path in script?


问:
"Could not find a part of the path" error message
I am programming in c# and want to copy a folder with subfolders from a flash disk to startup.

Here is my code:

```<code>private void copyBat()
{
    try
    {
        string source_dir = "E:\\Debug\\VipBat";
        string destination_dir = "C:\\Users\\pc\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup";

        if (!System.IO.Directory.Exists(destination_dir))
        {
            System.IO.Directory.CreateDirectory(destination_dir);
        }

        // Create subdirectory structure in destination
        foreach (string dir in Directory.GetDirectories(source_dir, "*", System.IO.SearchOption.AllDirectories))
        {
            Directory.CreateDirectory(destination_dir + dir.Substring(source_dir.Length));
        }

        foreach (string file_name in Directory.GetFiles(source_dir, "*.*", System.IO.SearchOption.AllDirectories))
        {
            File.Copy(file_name, destination_dir + file_name.Substring(source_dir.Length), true);
        }
    }
    catch (Exception e)
    {
        MessageBox.Show(e.Message, "HATA", MessageBoxButtons.OK, MessageBoxIcon.Warning);
    }
}
</code>```

I got an error:

Could not find a part of the path E:\Debug\VipBat

答:
This could also be the issue: Space in the folder name

Example:
Let this be your path:
string source_dir = @"E:\Debug\VipBat";

If you try accessing this location without trying to check if directory exists, and just in case the directory had a space at the end, like :
"VipBat    ", instead of just "VipBat" the space at the end will not be visible when you see in the file explorer.

So make sure you got the correct folder name and dont add spaces to folder names. And a best practice is to check if folder exists before you keep the file there.

Body:
I am programming in c# and want to copy a folder with subfolders from a flash disk to startup.

Here is my code:

private void copyBat()
{
    try
    {
        string source_dir = "E:\\Debug\\VipBat";
        string destination_dir = "C:\\Users\\pc\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup";

        if (!System.IO.Directory.Exists(destination_dir))
        {
            System.IO.Directory.CreateDirectory(destination_dir);
        }

        // Create subdirectory structure in destination
        foreach (string dir in Directory.GetDirectories(source_dir, "*", System.IO.SearchOption.AllDirectories))
        {
            Directory.CreateDirectory(destination_dir + dir.Substring(source_dir.Length));
        }

        foreach (string file_name in Directory.GetFiles(source_dir, "*.*", System.IO.SearchOption.AllDirectories))
        {
            File.Copy(file_name, destination_dir + file_name.Substring(source_dir.Length), true);
        }
    }
    catch (Exception e)
    {
        MessageBox.Show(e.Message, "HATA", MessageBoxButtons.OK, MessageBoxIcon.Warning);
    }
}

I got an error:

Could not find a part of the path E:\Debug\VipBat


问:
How to backup and restore to have full record SQL server
I have a database with

record 1

record 2

record 3
Then I delete

record 1

record 2
Next, I add

record 4

record 5

record 6
How to backup and restore to have full record

record 1

record 2

record 3

record 4

record 5

record 6

答:
SQL Server backups won't solve this issue for you.

However you could use Temporal Tables.
https://learn.microsoft.com/en-us/sql/relational-databases/tables/temporal-tables?view=sql-server-ver15