text:
Q: Simple code - error driving me crazy... float to 2 bytes and back Don't know how I finished school not being able to solve that little problem...
Following code produces unexpected output:
 public Color getPixel(int x, int y){
     return img.getPixelReader().getColor(x, y);
 }
 public float colorToHeight(Color c){
     int b =(int)(c.getBlue()*256);
     int r =(int)(c.getRed()*256*256);
     float h = (b+r)/2;
     h-=10000;
     return h;
 }
 public Color heightToColor(float h){
     h+=10000;
     h*=2;
     double r= (int)(h/(256));
     double b = h-(r*256);
     return new Color(r/256,0,b/256,1f);
 }
public void debugPixel(int x, int z){

    System.out.println("test 424->Color:  "+heightToColor(424f));
    System.out.println("test Color->424:  "+colorToHeight(heightToColor(424f)));
    System.out.println("test Color->424->Color:  "+heightToColor(colorToHeight(heightToColor(424f))));
    System.out.println("check A: "+getPixel(x,z) + " Height: "+colorToHeight(getPixel(x,z)));
    System.out.println("check B: "+heightToColor(colorToHeight(getPixel(x,z))));
    System.out.println("check C: "+getPixel(x,z));
}

Output:
test 424->Color:  0x510070ff
test Color->424:  424.0
test Color->424->Color:  0x510070ff
check A: 0x5200cbff Height: 638.0
check B: 0x53001cff
check C: 0x5200cbff

I absolutely do not find the reason why [check B] != [check A]....Thanks!

A: It can't be sure at all that you get the same values, because the back & forth operations (colorToHeight or heightToColor) involve floating point operations, hence loss of precision which happens there.
You can rewrite your methods without using floating point, not even divisions since all can be done with shifts.
 public int colorToHeight(Color c){
     int b = c.getBlue()>>8;
     int r = c.getRed()>>16;
     int h = (b+r)/2;  // will be an integer, b and r are even
     h-=10000;
     return h;
 }
 public Color heightToColor(int h){
     h+=10000;
     h*=2;
     int r= h>>8;
     int b = h-(r<<8);
     return new Color(r>>8,0,b>>8,1f);
 }

A: First, fix the division to:
float h = (b + r) / 2f;

The original code performs the integer division first, then it converts to float, e.g. (1 + 2) / 2 == 1.0. After the fix, it evaluates as (1 + 2) / 2.0 == 1.5.
Thus, in your second test case the height should be:
red = 83
blue = 29
height = 638.5

While with the incorrect integer division:
height = 638.0 // 0.5 truncated off
red = 83
blue = 28 // while 29 is expected

Regarding the RGB bounds, if the Color class operates on the range 0..255, take care when fixing that, since you need 2 distinct constants — an RGB upper LIMIT, and the composition SHIFT:
private static final int LIMIT = 255;
private static final int SHIFT = 256; // or whatever > LIMIT, e.g. 1000

public float colorToHeight(Color c){
    int b = (int) Math.round(c.getBlue() * LIMIT);
    int r = (int) Math.round(c.getRed() * LIMIT);
    float h = (b + r * SHIFT) / 2f;
    h -= 10000;
    return h;
}

public Color heightToColor(float h){
    h += 10000;
    h *= 2;
    double r = (int) (h / SHIFT);
    double b = h - (r * SHIFT);
    return new Color(r / LIMIT, 0, b / LIMIT, 1f);
}


text:
Q: Time interval postgres I have a table which contains id (unique), system id, timestamp and status.
When status 1 it means, system unavailable, when 0 - available:
CREATE temp TABLE temp_data_test (
       id int8 NULL,
       system_id int8 NULL,
       time timestamptz NULL,
       status int4 NULL
);

INSERT INTO temp_data_test (id, system, time, status) VALUES
       (53,1,'2022-04-02 13:57:07.000',1),
       (54,1,'2022-04-02 14:10:26.000',0),
       (55,1,'2022-04-02 14:28:45.000',1),
       (56,1,'2022-04-02 14:32:19.000',0),
       (57,1,'2022-04-05 03:20:18.000',1),
       (58,3,'2022-04-05 03:21:18.000',1),
       (59,2,'2022-04-05 03:21:22.000',1),
       (60,2,'2022-04-06 02:27:15.000',0),
       (61,3,'2022-04-06 02:27:15.000',0),
       (62,1,'2022-04-06 02:28:17.000',0);

It works like when system become unavailable we get 1, when become available -> 0.
I need to get a result table when can see how much hours each day each system was unavailable.
For this table result should be
date          system                 available                             unavailable
2022-04-02      1      13:57:07+00:18:19+09:27:40 =23:43:06         23:59:59-23:43:06=..
2022-04-02      2                        24                                     0
2022-04-02      3                        24                                     0

2022-04-03      1                        24                                     0
2022-04-03      2                        24                                     0
2022-04-03      3                        24                                     0
...
2022-04-05      1                     03:20:18                     23:59:59-03:20:18=..
2022-04-05      3                     03:21:18                     23:59:59-03:21:18=..
2022-04-05      2                     03:21:22                     23:59:59-03:21:22=..

2022-04-06      1               23:59:59-02:28:17=..                       02:28:17
2022-04-06      3               23:59:59-02:27:15=..                       02:27:15
2022-04-06      2               23:59:59-02:27:15=..                       02:27:15

I try do it with over partition by and recursion, but get more interval, than I need.

A: I wrote a sample query for calculating intervals and showing intervals as hours using your table structure:
with d_test as (
    select
        row_number() over (order by system_id, time) as r_num,
        "time"::date as "onlydate",
        "time",
        system_id,
        status
    from temp_data_test
    order by system_id, time
)
select avi.*, unavi."unavialible", unavi."unavialible_hours" from (
    select
        d1.system_id,
        d1.onlydate,
        sum(d2.time - d1.time) as "avialible",
        (extract(day from sum(d2.time - d1.time) )*24 + extract(hour from sum(d2.time - d1.time)))::text || ' hours' as "avialible_hours"
    from d_test d1
    inner join d_test d2 on d1.r_num+1 = d2.r_num and d1.system_id = d2.system_id
    where d1.status = 1
    group by d1.system_id, d1.onlydate
    order by d1.system_id
) avi
left join (
    select
        d1.system_id,
        d1.onlydate,
        sum(d2.time - d1.time) as "unavialible",
        (extract(day from sum(d2.time - d1.time) )*24 + extract(hour from sum(d2.time - d1.time)))::text || ' hours' as "unavialible_hours"
    from d_test d1
    inner join d_test d2 on d1.r_num+1 = d2.r_num and d1.system_id = d2.system_id
    where d1.status = 0
    group by d1.system_id, d1.onlydate
    order by d1.system_id
) unavi on avi.system_id = unavi.system_id and avi.onlydate = unavi.onlydate

Result of this query:

system_id
onlydate
avialible
avialible_hours
unavialible
unavialible_hours

1
2022-04-02
00:16:53
0 hours
2 days 13:06:18
61 hours

1
2022-04-05
23:07:59
23 hours

2
2022-04-05
23:05:53
23 hours

3
2022-04-05
1 day 02:05:57
26 hours

redpajama_set_name: RedPajamaStackExchange


text:
Q: imagejpeg() this function not working in Cpanel cron job I have created cronjob which copies image from one to another site. But imagejpeg() function is not working. I have tested it by direct call it works normal? Can anyone explain it for me?

A: please give chmod 777 or 766 to your path/script.php and in the script change the directory path to full path beginning from the path of the php fpm
/usr/bin/php ../../../var/www/html/script.php


text:
Q: How does increasing the tension on a string affect the density? Consider a string under tension, for example, a string on a guitar. When a guitar string is plucked, it vibrates at a certain frequency. When the tension on the string is increased by twisting the tuning peg at the end of the neck, the frequency of the string increases. According to this video, increasing the tension on a string also increases the speed of the wave moving through it. According to this article, the speed of a wave is higher in a more dense medium.
Does this mean that increasing the tension also increases the density?
This does not seem very logical to me, since density is the "compactness" of a substance, or how close together the individual molecules are. By twisting the tuning peg on a guitar, you rotate the cylinder that the string is fixed to, wrapping it around more tightly. This pulls more of the string around that cylinder, similarly to when you reel in a fishing rod. Since more of the string's molecules are now wrapped around the peg, there should be fewer molecules over the same distance between the bridge and the nut (the two ends of the vibrating portion of the string), therefore bringing the density down.

A: Your intuition is right: the density of the string goes down a little bit when you increase the tension.
HOWEVER: the wave in a string is a transverse wave which depends on the tension and the mass per unit length. If you double the tension the mass per unit length goes down by a small amount (the string gets a bit "thinner" because it gets longer) . Both these things increase the velocity of the transverse wave which is given by
$$v = \sqrt{\frac{T}{\rho}}$$
Where T is the tension and $\rho$ the mass per unit length. Finally, the fundamental frequency is determined as the reciprocal of the round trip time of the wave along the string:
$$T = \frac{2 \ell}{v}$$
so that
$$f = \frac{1}{T} = \frac{v}{2\ell} = \frac{\sqrt{\frac{T}{\rho}}}{2\ell}$$
So to raise the frequency by an octave you need four times the tension (don't try this - you might break the neck) or a string that's half the diameter (one quarter of the area - so one quarter of the mass per unit length). This explains why different strings on the guitar have different gage - you would need too much tension to get the high range from a long thick string.

A: The article you refer to is talking about the speed of sound (or speed of longitudinal wave vibrations) within a material and how that relates to volumetric mass density.  If you were transmitting sound from one end of a guitar string to another, this would be relevant.
But the sound produced from a string is not related to the speed that it travels within the material.  Instead, it only depends on the speed of vibration, which is mainly dependent on the linear mass density and tension.

A: The characteristic speed, $S$ of transverse waves on a taut string or wire with tension $T$ and density per unit length, $\rho$ is
$$S=\sqrt \frac T\rho$$
So indeed as you remove wire from play by wrapping it around the capstan, you decrease the wires density and increase tension. This increases velocity.
and since
$$\omega=\frac v\lambda$$
frequency (pitch) is increased

A: For linear deformations, when a material is compressed/stretched in one direction, it usually tends to expand/contract in the other two directions perpendicular to the direction of compression/stretching. This is called the Poisson effect, and the Poisson ratio is a measure of this effect. For some materials the Poisson ratio can be close to 0.5 (rubber) which means that the material tends to behave as incompressible under this type of deformation. So for a rubber string there is no change of the mass density (per volume) as it is being stretched. But for the stainless steel the Poisson's ratio is about 0.3 which means that the mass density decreases as the string is being stretched. For most string instruments it is the transverse modes that produce the main sound, and it is the mass density per length rather than per volume what matters. However, in some musical instruments the string longitudinal modes can be audible too. Unlike the transverse modes that depend on the string tension, for the longitudinal modes the propagation speed is given by $\sqrt{Y/\rho}$, where $Y$ is the Young modulus and $\rho$ is the mass density per volume, so the change of $\rho$ can be in principle a detectable effect.


text:
Q: Authorize an entire security group to perform an Action in ASP.Net MVC I'd like to authorize users to perform specific actions within my controllers.  I've found the ASP.NET tutorial which explains how to allow individual users to perform specific actions but can this be extended to security groups?  For example, would everyone belonging to the "domain\group" security group have access to the GetSecrets action if the code looked like this:
[Authorize(Users="domain\group")]
public ActionResult GetSecrets()
{ return View(); }

If not, how would I do this?

A: You want to use the Roles property.  Note that this can be a comma-separated list of roles.
 [Authorize(Roles=@"domain\group")]


text:
Q: How to scale out image hosting/serving? I'm building a website where users can upload photos and I'd also convert uploaded photos into thumbnails.
Planning ahead, if the website gets popular, how do I scale it out so that the images (both original and thumbnails) will be stored in and served from multiple servers? Maybe a cluster? Is there any open source software that would help me in this?
Thanks.

A: An interesting question.
I think that the most solid and easily scaled solution would be to use something like MogileFS which is a distributed HTTP based file-system.
Another approach which might be simpler to build is to just make sure you're aware of how you would scale out your image hosting should you need to. Possible approaches could be:
 - Use Amazon S3
 - Implement the sharding/partitioning of images manually in your application, store the images on different backend servers (with slower/large storage) and then put a reverse proxy in front of it.
In my opinion MogileFS would be a great solution to this problem. To scale out should be trivial but the initial implementation might take a bit longer.

A: Buy it don't build it. Akamai and Amazon CloudFront and their ilk commoditize this. Don't reinvent the wheel, it's really a specialist function that is easily and reliably outsourced much more cheaply than it is built in-house.

A: Well one way of approaching this is to convert the image file into binary format and save the binary into a database.
I have used php to convert the images into blob format and store these blobs on a mysql database.  When the files are in the database you can use php scripts to convert the blob back into the mime type like jpeg or gif and display then on the webpage.
So your files are then centrally stored on a database, you can place the scripts which convert the blobs into images on any number of servers.
I have never found any open source software to use this method of storage but it is fairly straight forward to create the scripts.


text:
Q: High windowServer CPU usage on Yosemite Since upgrading from Mountain-Lion to Yosemite, my MacBookPro5,5 (13", 2.26GHz C2D, GeForce 9400m) is (almost always) showing bad performance while working with native windows like Finder, System Preferences and Application Switcher. Even simple things like scrolling a folder in Finder spikes the CPU up. 'WindowServer' process shows high cpu usage (above 50%) while doing these and always tops the 'Total cpu usage' in Activity Monitor.
Updating to 10.10.2, erasing the disk and making a fresh install, following any recommendations about transparency/display/... settings I can found on the web (summarized mostly in WindowServer high CPU on Yosemite and its follow ups), even applying combinations of them did not have any significant effect. This is a clean install (not an update) and I only have Google Chrome as an external/installed app. I don't have an external monitor, although I even tried the recommendations including one...
I have installed Mavericks and this problem is not present now, but I will have to upgrade to Yosemite soon... Has anyone found a working solution yet?


text:
Q: Regular Expression to find all SupressMessage in solution I am looking for a regular expression to match all references to SuppressMessage in a solution that took over.
example:
[SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")]

I tried this to find the SuppressMessage with the beginning and ending square brackets but it does not observe line feeds and when multiple matches are with the same file, it will return the bulk of the file.
\[(SuppressMessage)\((.*)\)\]

A: \[(SuppressMessage\((?:.*?)\))\]

make your expression non greedy.In fact try
\[(SuppressMessage\((?:[^)]*)\))\]

or
\[(SuppressMessage[^)]*\)))

to make it fail proof.

A: [(SuppressMessage)((.*?))]
try it

A: Thanks vks - That got me closer but that finds two groups.
SupressMessage
"Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0"
What I found that works (without multiple SuppressMessages in the same square brace) is:
\[(SuppressMessage.*?)\]


text:
Q: Oracle APEX : How to refresh the page after submit - before Branching I have an APEX page, with a interactive report with Check boxes and a Button on top.
On click of button, It is performing some PLSQL process (on selected rows that are checked) and in a branch I'm invoking a Report Query which downloads a report in the pdf format.
But even after downloading the report, the report is not automatically getting refreshed.
Ideally I want to remove the processed rows from the report so as to avoid multiple processing by clicking the button continuously.
But since I have a branch that goes to download the report, it is not going to other branches that comes after in sequence to refresh the page.
Can anyone tell me how to refresh the page/or just that region after the processing? Thanks.


text:
Q: как правильно воспользоватся методом .reshape() Пытаюсь разобраться но не получается корректно воспользоватся функцией reshape()
Есть звуковой сигнал который переведен в вектор (1990000, )
Что необходимо сделать:
Разделите сигнал на равные части (длину каждой части возьмите равной 1000) и соберите из них "датасет", который будет представлять из себя двухмерный массив - "матрицу", в которой каждая часть сигнала длины 1000 находится в отдельной строке).
То есть первая часть содержит первые 1000 чисел сигнала и находится в первой строке матрицы, вторая часть следующие 1000 чисел сигнала и находится во второй строке матрицы и так далее.
На текущий момент разделил
X_mono = mono_sound.reshape((2, 995, 1000))
print(X_mono.shape)
(2, 995, 1000)

Но как разделить по строкам?


text:
Q: Make a git alias to remove all local merged branches I have a command to delete local copies of branches that have been merged into develop:
git for-each-ref --format='%(refname:short)' refs/heads/ | grep -v develop | xargs -L1 -I '{}' sh -c "git merge-base --is-ancestor {} develop && git branch -d {}"

I'd like to add an alias to my .gitconfig but I cannot get one to work - I think I'm messing up the escaping.  How can I get this command working, or a command that accomplishes the same thing?

A: Regarding how to create an alias for a compound command or script, this should do:
[alias]
  branch-clear = !git for-each-ref ... | ...

Or via a function:
[alias]
  branch-clear = "!f() { git for-each-ref ... | ...; }; f"


text:
Q: Postgresql's pg_dump and pg_restore across different major versions? Recently I came across a (maybe known problem) when Postgre's versions differ in major number (always upgrade, no downgrade), for example with field types.
In my case, there was very little conflicting data so I changed it by hand, but wanted to know more, in case I come across this problem again with more data.
In this concrete case (but can be extended to other possible problems in the future), I created the backup using only data inserts, as I had already the table structure saved.
The problem came when upgrading from 8.x to 9.x with the money type, I got errors because the inserts had a value something like
INSERT INTO foo(...) VALUES (...,'EUR300',...);

So postgres was refusing to insert that in 9.1
My idea, and what I tried is to convert that field to DECIMAL and redoing the dump, that worked, but in a future, is there another mechanism, like using newer pg_dump connecting to old database, instead of current one? (Did not tested this)

A: When going etween different versions, you should always use the new version of pg_dump. Meaning when you go from 8.x to 9.1, you should use pg_dump version 9.1. It should normally take care of any conversions necessary.


text:
Q: Makefile: ...is up to date I have made a makefile for some c files. I have seen too many ways on the internet but i had always the same problem: make: `q_a' is up to date.
q_a:
gcc -o q_a quick_sort_i.c

q_g:
gcc -o q_g quick_sort_g.c

s_a:
gcc -o s_a shell_sort_i.c

s_g:
gcc -o s_g shell_sort_g.c

fork:
gcc -o fork fork.c

I have not files with the same name in my folder and I can compile them when I write in terminal. Can you help? Thanks in advance!

A: You have not specified dependencies for your targets.
What make does, is first checking if your target (q_a) exists as a file, and if it does, if its dependencies are newer (as in, have more recent modification time) as your target. Only if it needs to be updated (it does not exist or dependencies are newer) the rule is executed.
That means, if you need q_a to be recompiled every time quick_sort_i.c is changed, you need to add it as a dependency to q_a, like this:
q_a: quick_sort_i.c
    gcc -o q_a quick_sort_i.c

With that, make will recompile q_a if necessary.


text:
Q: Probability of winning specified amount of money We play a game in which we toss a coin - if we have head we get 1\$ otherwise, we lose 1\$. Let's say we do it 50000 times. What's the probability of losing at least 10\$?
I started by calculating the excepted value of one time:
$$
x_{1} = 1
\\ x_{2} = -1
\\EX= \frac{1}{2}\cdot1 - \frac{1}{2}\cdot 1 = 0
$$
So the excepted value in the whole game is $0$.
Now I don't really know what to do. Do I need to use Chebyshev's inequality? Is it OK if $EX=0$?

A: The key word here is the binomial distribution. The standard presentation is that if you flip a $p$-coin $N$ times, and count the number $X$ of heads, then the distribution is
$$\mathbb P(X=k)=\binom{N}{k}p^k(1-p)^{N-k}.$$
We write $X\sim\operatorname{Bin}(N,p)$ to indicatte that $X$ has this distribution.
Your profit $X$ after $50000$ tosses isn't quite $\operatorname{Bin}(50000,1/2)$ though, since we subtract when the coin comes up tails. If $Y\sim\operatorname{Bin}(50000,1/2)$, then it should be clear that $X=2Y-50000$.
So then $X\leq-10\iff Y\leq24995$. Then
$$\mathbb P(Y\leq24995)=\sum_{k=0}^{24995}\mathbb P(Y=k)=\sum_{k=0}^{24995}\binom{50000}{k}\cdot\left(\frac{1}{2}\right)^{50000}.$$
This sum is obviously not tractable by hand. Most scientific calculators would have some kind of function that computes the CDF for a binomial random variable. You should get $0.484$ as the probability, which seems reasonable -- just a smidgen under half.

A: We model the coin tosses as a binomial distribution.
Let X be the number of heads, then
$$\text{X} \sim Bn( 50000, p=0.5)$$
Then we know the net value of the whole game is
$$\text{net value} = 1(\text{X}) - 1(50000-\text{X})=2\text{X} - 50000$$
To know the probability of loosing at least \$10:
$$\mathbf{P}(\text{net value} \leq -10) = \mathbf{P}(2\text{X} - 50000 \leq -10)=
\mathbf{P}(\text{X} \leq 24995)  ≈ 0.483947$$
Various methods can be used to calculate this final value. I chose to use wolfram alpha as a calculator but for a more laborious method  you could approximate to the normal distribution and then use a table.


text:
Q: Is it possible to merge two teams of final rankings with one team having 7 members, and the second team having 24 members? Is it possible to merge two teams of final rankings with one team having 7 members, and the second team having 24 members? Is there a formula to provide one total overall ranking between the groups?
Team 1 has 7 people
Team 2 has 24 people
both teams have their own set of rankings
We rank using relative reference for both groups containing 4 categories each. Each category is scored among the teams (7 & 24) using a relative reference scoring scale (0-100; highest ranked receives 100 points). For each team, we rank the weighted score among the 4 categories.
We would like to combine these two groups to have one final, overall rank.
Is there a formula to provide one total overall ranking between the groups?
Thank you

A: There are lots of formulas.  Whether they are "fair" or what you want is up to you.  You can just place one team above the other.  You can merge the two lists based on individual total score, or scores in one category.  You can rank the players based on the percentage of the team they beat, so you flip a coin between the two bottoms, but the next three to bottom of 24 come below the next to bottom of 7.


text:
Q: Ugly Number - Mathematical intuition for dp I am trying find the "ugly" numbers, which is a series of numbers whose only prime factors are [2,3,5].
I found dynamic programming solution and wanted to understand how it works and what is the mathematical intuition behind the logic.

*

*The algorithm is to keep three different counter variable for a multiple of 2, 3 and 5. Let's assume i2,i3, and i5.

*Declare ugly array and initialize 0 index to 1 as the first ugly number is 1.

*Initialize i2=i3=i4=0;

*ugly[i] = min(ugly[i2]*2, ugly[i3]*3, ugly[i5]*5) and increment i2 or i3 or i5 which ever index was chosen.
Dry run:
ugly = |1|

  i2=0;
  i3=0;
  i5=0;

ugly[1] = min(ugly[0]*2, ugly[0]*3, ugly[0]*5) = 2

---------------------------------------------------

ugly = |1|2|

  i2=1;
  i3=0;
  i5=0;

ugly[2] = min(ugly[1]*2, ugly[0]*3, ugly[0]*5) = 3

---------------------------------------------------

ugly = |1|2|3|

  i2=1;
  i3=1;
  i5=0;

ugly[3] = min(ugly[1]*2, ugly[1]*3, ugly[0]*5) = 4

---------------------------------------------------

ugly = |1|2|3|4|

  i2=2;
  i3=1;
  i5=0;

ugly[4] = min(ugly[2]*2, ugly[1]*3, ugly[0]*5) = 5

---------------------------------------------------

ugly = |1|2|3|4|5|

  i2=2;
  i3=1;
  i5=1;

ugly[4] = min(ugly[2]*2, ugly[1]*3, ugly[0]*5) = 6

---------------------------------------------------

ugly = |1|2|3|4|5|6|

I am getting lost how six is getting formed from 2's index. Can someone explain in an easy way?

A: The intuition is the following:

*

*any ugly number can be written as the product between 2, 3 or 5 and another (smaller) ugly number.

With that in mind, the solution that is mentioned in the question keeps track of i2, i3 and i5, the indices of the smallest ugly numbers generated so far, which multiplied by 2, 3, respectively 5 lead to a number that was not already generated. The smallest of these products is the smallest ugly number that was not already generated.
To state this differently, I believe that the following statement from the question might be the source of some confusion:

The algorithm is to keep three different counter variable for a
  multiple of 2, 3 and 5. Let's assume i2,i3, and i5.

Note, for example, that ugly[i2] is not necessarily a multiple of 2. It is simply the smallest ugly number for which 2 * ugly[i2] is greater than ugly[i] (the largest ugly number known so far).

Regarding how the number 6 is generated in the next step, the procedure is shown below:
ugly = |1|2|3|4|5

  i2 = 2;
  i3 = 1;
  i5 = 1;

ugly[5] = min(ugly[2]*2, ugly[1]*3, ugly[1]*5) = min(3*2, 2*3, 2*5) = 6

---------------------------------------------------

ugly = |1|2|3|4|5|6

  i2 = 3
  i3 = 2
  i5 = 1

Note that here both i2 and i3 need to be incremented after generating the number 6, because both i2*2, as well as i3*3 produced the same next smallest ugly number.

A: Every "ugly" number (except 1) can be formed by multiplying a smaller ugly number by 2, 3, or 5.
So let's say that the ugly numbers found so far are [1,2,3,4,5]. Based on that list we can generate three sequences of ugly numbers:
Multiplying by 2, the possible ugly numbers are [2,4,6,8,10]
Multiplying by 3, the possible ugly numbers are [3,6,9,12,15]
Multiplying by 5, the possible ugly numbers are [5,10,15,20,25]
But we already have 2,3,4, and 5 in the list, so we don't care about values less than or equal to 5. Let's mark those entries with a - to indicate that we don't care about them
Multiplying by 2, the possible ugly numbers are [-,-,6,8,10]
Multiplying by 3, the possible ugly numbers are [-,6,9,12,15]
Multiplying by 5, the possible ugly numbers are [-,10,15,20,25]
And in fact, all we really care about is the smallest number in each sequence
Multiplying by 2, the smallest number greater than 5 is 6
Multiplying by 3, the smallest number greater than 5 is 6
Multiplying by 5, the smallest number greater than 5 is 10
After adding 6 to the list of ugly numbers, each sequence has one additional element:
Multiplying by 2, the possible ugly numbers are [-,-,-,8,10,12]
Multiplying by 3, the possible ugly numbers are [-,-,9,12,15,18]
Multiplying by 5, the possible ugly numbers are [-,10,15,20,25,30]
But the elements from each sequence that are useful are:
Multiplying by 2, the smallest number greater than 6 is 8
Multiplying by 3, the smallest number greater than 6 is 9
Multiplying by 5, the smallest number greater than 6 is 10
So you can see that what the algorithm is doing is creating three sequences of ugly numbers. Each sequence is formed by multiplying all of the existing ugly numbers by one of the three factors.
But all we care about is the smallest number in each sequence (larger than the largest ugly number found so far).
So the indexes i2, i3, and i5 are the indexes into the corresponding sequences. When you use a number from a sequence, you update the index to point to the next number in that sequence.


text:
Q: Swift TableView multiple Custom cells, inrease number of row in from cell lead to crash I have problem which trying to solve for hours.
I have tableView with multiple cells.
I don't use StoryBoard.
My problem is this:
Number of cells in tableView depends on size of array. When app start, tableView and its cells loads perfectly. Even when i insert into ViewDidLoad this:
arrayOfCategory.append(Category(nameOfCategory: "Example", ColorOfCategory: .white))
tableView.reloadData()

it works. But when i try insert voids into button's target
@objc func handle(sender: UIButton)  {
    arrayOfCategory.append(Category(nameOfCategory: "Sdsdd", ColorOfCategory: .white))
    tableView.reloadData()
}

my app will crash with error:
TaskList[59513:1886772] Could not cast value of type 'TaskList.SwitchCell' (0x1073bd808) to 'TaskList.CategoryShowCell' (0x1073bd500).

Here is cellForRow:
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    switch indexPath.section {
    case 0:
        tableView.register(CategoryShowCell.self, forCellReuseIdentifier: categoryShowID)
        let cell = tableView.dequeueReusableCell(withIdentifier: categoryShowID, for: indexPath) as! CategoryShowCell
          cell.setCell(category: Category(nameOfCategory: "sdsd", ColorOfCategory: .white))
        return cell

    case 1:
        tableView.register(SwitchCell.self, forCellReuseIdentifier: swichCellID)
        let cell = tableView.dequeueReusableCell(withIdentifier: swichCellID, for: indexPath) as! SwitchCell
        return cell
    default:
        tableView.register(SwitchCell.self, forCellReuseIdentifier: swichCellID)
        let cell = tableView.dequeueReusableCell(withIdentifier: swichCellID, for: indexPath) as! SwitchCell

        return cell
    }

}

Does anyone know where is problem?
Xcode point into this line:
let cell = tableView.dequeueReusableCell(withIdentifier: categoryShowID, for: indexPath) as! CategoryShowCell

in cellForRow bude one line above i register right cell.

A: Your problem is in different types of registered cell and type you're trying to force cast it to. Like Xcode says you - TaskList.SwitchCell to TaskList.CategoryShowCell. Force casting happens at as! CategoryShowCell this place.
I suspect, that you are reregistering SwitchCell.self for categoryShowID. It can happen if your categoryShowID is equal to swichCellID.
Check this out and keep in mind, that registering one cell multiple times in cellForRow is a bad idea


text:
Q: Primary Key Duplication Exception I am working on a project in C# using sql server as a data base. So the problem is there is a algo in my project which returns a single value every time; which is saved to the database (as my project requirement). If the algo repeats a value, that will also save to the database which is not required (duplication) and cause some problems. I need help to overcome the problem that a unique value saves only once when it occurs; no repetition in database. I tried to make that column a primary key, but then I found primary key violation exception.

A: Just use an EXISTS query either in-line or in a stored procedure
Your query procedure can check if the row already exists
Edit: Aha sorry forgot the NOT, that would be stupid :D
IF NOT EXISTS(SELECT UniqueValue FROM UniqueValuesTable WHERE UniqueValue = @NewValue)
  INSERT INTO UniqueValuesTable VALUES (@NewValue)

Edit: here is a SQL fiddle to show it working
http://sqlfiddle.com/#!3/b87f9/3
As dems pointed out, the operation isn't atomic, so in a multi session situation there could be a PK violation still
Alternative is:
INSERT INTO UniqueValuesTable SELECT @NewValue WHERE NOT EXISTS (SELECT UniqueValue FROM UniqueValuesTable WHERE UniqueValue = @NewValue)


text:
Q: JSON in uri request What if I pass my searching params in uri request in json-format like this:
http://example.com/?search={"title":"Some+Title","category":12}

instead of
http://example.com/?title=Some+Title&category=12

Before decode json-request I can filter it with some functions like strip_tags(), strpslashes(), etc... But I can do the same with $_SERVER['QUERY_STRING'] with serialize()/unserialize(). Or apply string-filters to N string-params of request, not once to whole request.
Which way do you think will be better, usable and faster to process?
With json
$request = $_GET['search'];
$request = stripslaches(strip_tags($request));
$params  = json_decode($request);

A: The characters { and } are unsafe according to RFC 1738 2.2. They must therefore be encoded before being transferred over a network.
The character : is reserved according to RFC 1738 2.2. It must therefore be encoded before being transferred over a network unless it is used for the purpose for which it was reserved.
Don't use $request = striplashes(strip_tags($request)). If $_GET['search'] does not json_decode sucessfully, treat it as faulty input; don't try to fix it.

A: Sending an encoded JSON string is possible, as any string (you should urlencode and urldecode it though, no stripping needed) but it's not really a good way to do it - use the standard way of passing data in request - if you have only simple data to send, just translate it into traditional GET variables (it's really easy, e.g. with http_build_query as Tomasz suggests). You may also run into difficulities with the request URI length (see What is the maximum length of a URL in different browsers?) if you pack too much data into the JSON object.

A: Isn't it better to use http_build_query instead of passing JSON throw URL? HTTP_build_query is specially designed to pass data throw url params.
Applying this filter to whole param_str of URL may cause unexpected behaviour, besides fact that is actually little bit faster.
I think that you should pass every one parameter throw your filter functions.

A: Why don't you just represent everything with JSON?
http://www.example.com/{"article":"something","page":12,"fragment":"#menu"}

Query strings are already used to represent flat lists of key-value pairs, so what problem does your JSON solution solve? You'll just be adding a new layer of complexity without any benefits.


text:
Q: Combine two texture2d to one texture2d using shader Hi,all i can use unity c# code to do combine two texture2d to one texture2d,but it is not efficient,i want to use shader to do it,but i little knowage about the shader.  for example i have texture2d as A,A size is 1024*1024,then i scale it to 100 *100 as B,and put b to the right_up of the A.How to finish it using shader

A: This's topic may help you but i'm not sure about scale texture, just take a look:
http://catlikecoding.com/unity/tutorials/rendering/part-3/


text:
Q: How to exchange files between docker container and local filesystem? I have a TypeScript code that reads the contents of a directory and has to delete them one by one at some intervals.

Everything works fine locally. I made a docker container for my code and wanted to achieve the same purpose, however, I realized that the directory contents are the same ones existed at the time of building the container.
As for my understanding, the connection between the docker container and the local file system is missing.

I have been wandering around bind and volume options, and I came across the following simple tutorial:
How To Share Data Between the Docker Container and the Host
According to the previous tutorial, theoretically, I would be able to achieve my goal:

If you make any changes to the ~/nginxlogs folder, you'll be able to see them from inside the Docker container in real-time as well.

However, I followed exactly the same steps but still couldn't see the changes made locally reflected in the docker container, or vice versa.

My question is: How can I access my local file system from a docker container to read/write/delete files?
Update

This is my dockerfile
FROM ampervue/ffmpeg
RUN curl -sL https://deb.nodesource.com/setup_10.x | sudo -E bash -
RUN apt-get update -qq && apt-get install -y --force-yes \
    nodejs; \
    apt-get clean
RUN npm install -g fluent-ffmpeg
RUN rm -rf /usr/local/src
RUN apt-get autoremove -y; apt-get clean -y
WORKDIR /work
COPY package.json .
COPY . .

CMD ["node", "sizeCalculator.js"]

A: Easy way to volume mount on docker run command
docker run -it -v /<Source Dir>/:/<Destination Dir> <container_name> bash
Another way is using docker-compose.
Let's try it with docker-compose
put your dockerfile and docker-compose at the same location or dir
main focus
volumes:
  - E:\dirToMap:/work

docker-compose.yaml

version: "3"
services:
  ampervue:
    build:
      context: ./
    image: <Image Name>
    container_name: ampervueservice
    volumes:
      - E:\dirToMap:/vol1
    ports:
      - 8080:8080

And add volume in dockerfile
FROM ampervue/ffmpeg
RUN curl -sL https://deb.nodesource.com/setup_10.x | sudo -E bash -
RUN apt-get update -qq && apt-get install -y --force-yes \
    nodejs; \
    apt-get clean
RUN npm install -g fluent-ffmpeg
RUN rm -rf /usr/local/src
RUN apt-get autoremove -y; apt-get clean -y
WORKDIR /work
VOLUME /vol1
COPY package.json .
COPY . .

CMD ["node", "sizeCalculator.js"]

and run following command to up the container
docker-compose -f "docker-compose-sr.yml" up -d --build

A: At the examples below which come directly from the docs:

The --mount and -v examples below produce the same result. You can't run them both unless you remove the devtest container after running the first one.

*

*with -v:
docker run -d -it --name devtest -v "$(pwd)"/target:/app nginx:latest

*with --mount:
docker run -d -it --name devtest --mount type=bind,source="$(pwd)"/target,target=/app nginx:latest

This is where you have to type your 2 different paths:
-v /path/from/your/host:/path/inside/the/container
   <-------host------->:<--------container------->

--mount type=bind,source=/path/from/your/host,target=/path/inside/the/container
                         <-------host------->        <--------container------->


text:
Q: google maps api java i have a console application, needs to find the distance and route between two places using the google maps api. that means i do not have a browser and hence no javascript. is it possible to do it using java using a HTTP request or something. i have tried geocoding and can find the latitude and longitude of a given address using HTTP requests. how to find distance and routes using java.

A: Rhino provides a javascript engine for Java applications. You can play around with it.

A: Google only provides this in javascript.
However, there is a request to provide it in java also. So possibly, it will be there in the near future.
The fact that there is no out-of-the-box solution from google, doesn't mean that you can not create one for yourselve of course...
[EDIT]
For example, you could read the sourcecode of your directions in html to find the distance and the route.


text:
Q: How to disable button event on JavaFX 8 until http response Using JavaFx8 i have a button that send a http request. I want to disable this button until i received the answer from the server. My situation is the following:
HBox boxRep = new HBox();
...
boxRep.setOnMousePressed((event) ->{
      String responseHttpCode = "";
      responseHttpCode = MySendHttp(ip, port, request);
      ...
      });

My method (MySendhttp) return the String with the http code status (200,404...). I dont't want to send another request until the server answer.
Thanks

A: Run it in a task, on a background thread, and process the response in the onSucceeded handler:
boxRep.setOnMousePressed(event -> {
    Task<String> httpTask = new Task<String>() {
        @Override
        public String call() throws Exception {
            return MySendHttp(ip, port, request);
        }
    };

    Thread thread = new Thread(httpTask);

    httpTask.setOnSucceeded(e -> {
        boxRep.setDisable(false);
        String responseCode = httpTask.getValue();
        // process...
    });

    boxRep.setDisable(true);

    thread.start();
});


text:
Q: Simple for loop, if statement and output message I think this one is pretty simple, but I am new to this, so I am not sure where to go from here :)
I have a Google Sheet, with some data (pretty large sheet). I want a script that check whether the number in a cell (column I) is larger than the number in the same row, but another column (column D).
Imagine two columns with 5 rows: Column D = (3, 3, 3, 3, 3) and Column I = (2, 2, 7, 2, 2)
SO in this example, I want that the script to tell me that I have problem in "Row 3", because the number in Column I, Row 3 is larger than the number in Column D, Row 3 :)
This is what I have:
    function Check() {

      var spreadsheet = SpreadsheetApp.getActive();
      var sheet = spreadsheet.getActiveSheet();
      var lr = sheet.getLastRow();
      var Summary;

      for (var i=6; i<lr; i++) {
        if (sheet.getRange(i,9) > sheet.getRange(i,4)){
          summary.setvalue("Problem")

         }
      }

    }

I want it to start in row 6, because my data starts here. I am only checking column I (therefore 9) and column D (therefore 4)
I am not sure what to do with my for loop and If statement from here? SO now the code is checking every row in column 4 (D) and column I (9), but how do I store store the value, whenever the number in column 9 is larger than the number in column 4? And I also want an output, with all rows where we have a problem, when the code is done? If we don't have any problem, I want a message saying: "no problem"
Can anybody guide me from here?

A: If your output can be set in the sheet (let say in column "J"), you can use this:
function Check() {
  var spreadsheet = SpreadsheetApp.getActive();
  var sheet       = spreadsheet.getActiveSheet();
  var maxRows     = sheet.getMaxRows(); // get the number of rows
  var startRow    = 6;
  var diffCol1    = 'D';
  var diffCol2    = 'I';
  var outputCol   = 'J';
  var outputStrOK = 'no problem';
  var outputStrKO = 'problem';
  var outputRange = []; // stored values
  for (var i = startRow; i <= maxRows; i++) {
    var valueA = sheet.getRange(diffCol2+i).getValue();
    var valueB = sheet.getRange(diffCol1+i).getValue();
    // add controls on values then
    if (valueA > valueB) {
      outputRange.push([outputStrKO]);
    } else {
      outputRange.push([outputStrOK]);
    }
  }
  // setting a range of values is much faster than fulfilling cell by cell in loop
  sheet.getRange(outputCol+startRow+':'+outputCol+maxRows).setValues(outputRange);
}

you should have this as a result:
#|D|I|J
6|9|4|problem
7|4|9|no problem


text:
Q: How to install yugabyte-2.0.6.0/2.0.8.0 on centos7? environment:
os: centos7.6
kernel: 3.10.0-957.el7.x86_64
gcc version 4.8.5
Python 2.7.5
ip:10.1.2.3
host name: srvr0
fqdn:srvr0.example.org
I am trying to install yugabyte, as follows:
a) downloaded yugabyte-2.0.6.0-linux.tar.gz
b) extracted to /opt/yugabyte
c) added loopback addresses 127.0.0.2/8, 127.0.0.3/8, 127.0.0.4/8, 127.0.0.5/8, 127.0.0.6/8, 127.0.0.7/8 to interface lo
d) opened ports 7000, 9000, 7100, 5433,  9042, 6379
e) run /opt/yugabyte/yugabyte-2.0.6.0/bin/post_install.sh
f) run /opt/yugabyte/yugabyte-2.0.6.0/bin/yb-ctl --data_dir "/opt/yugabyte/data" create
but getting error:
INFO: Waiting for master and tserver processes to comeup.
INFO: Waiting for master leader election and tablet server registration.
INFO: PIDs found:{'tserver': [None], 'master': [None]}
ERROR: Atleast one master or tserver is down.
^^^Encontered Errors^^^

Update1:
the ports are free ie.not used up by any service and the log files are empty:
/opt/yugabyte/data/node-1/disk-1/tserver.err
/opt/yugabyte/data/node-1/disk-1/tserver.out
/opt/yugabyte/data/node-1/disk-1/master.err
/opt/yugabyte/data/node-1/disk-1/master.out
/tmp/tmp098oCG

and status logfiles are not created:
/opt/yugabyte/data/node-1/disk-1/tserver.INFO
/opt/yugabyte/data/node-1/disk-1/master.INFO

Update2:
both ps -ef | grep {yb-master pid} and ps -ef | grep {tserver pid} has error:
[1]+ Illegal instruction (core dumped)

Update3:
earlier versions work.
Update 4:
[root@srvr0 ~]# grep "invalid opcode" /var/log/messages
Nov 29 15:28:18 srvr0 kernel: traps: yb-tserver[12192] trap invalid opcode ip:7fa69e2f4b8a sp:7fff91e8dd00 error:0 in ld.so[7fa69e2ec000+1b000]
Nov 29 15:28:18 srvr0 kernel: traps: yb-admin[12199] trap invalid opcode ip:7f2476ebbb8a sp:7fffeaa0cfb0 error:0 in ld.so[7f2476eb3000+1b000]

[root@srvr0 ~]# lscpu
Architecture:          x86_64
CPU op-mode(s):        32-bit, 64-bit
Byte Order:            Little Endian
CPU(s):                4
On-line CPU(s) list:   0-3
Thread(s) per core:    2
Core(s) per socket:    2
Socket(s):             1
NUMA node(s):          1
Vendor ID:             GenuineIntel
CPU family:            6
Model:                 37
Model name:            Intel(R) Core(TM) i7 CPU       M 620  @ 2.67GHz
Stepping:              5
CPU MHz:               1199.000
CPU max MHz:           2667.0000
CPU min MHz:           1199.0000
BogoMIPS:              5320.11
Virtualization:        VT-x
L1d cache:             32K
L1i cache:             32K
L2 cache:              256K
L3 cache:              4096K
NUMA node0 CPU(s):     0-3
Flags:                 fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf eagerfpu pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 cx16 xtpr pdcm pcid sse4_1 sse4_2 popcnt aes lahf_lm ssbd ibrs ibpb stibp tpr_shadow vnmi flexpriority ept vpid dtherm ida arat spec_ctrl intel_stibp flush_l1d

[root@srvr0 ~]# uname -a
Linux srvr0 3.10.0-957.el7.x86_64 #1 SMP Thu Nov 8 23:39:32 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux

Update5 for yugabyte-2.0.8.0 (as on 22-Dec-2019):
Dec 21 19:14:54 srvr0 kernel: perf: interrupt took too long (3197 > 3181), lowering kernel.perf_event_max_sample_rate to 62000
Dec 21 19:14:54 srvr0 journal: g_simple_action_set_enabled: assertion 'G_IS_SIMPLE_ACTION (simple)' failed
Dec 21 19:14:54 srvr0 journal: g_simple_action_set_enabled: assertion 'G_IS_SIMPLE_ACTION (simple)' failed
Dec 21 19:14:54 srvr0 journal: g_simple_action_set_enabled: assertion 'G_IS_SIMPLE_ACTION (simple)' failed
Dec 21 19:14:54 srvr0 journal: g_simple_action_set_enabled: assertion 'G_IS_SIMPLE_ACTION (simple)' failed
Dec 21 19:15:03 srvr0 journal: g_simple_action_set_enabled: assertion 'G_IS_SIMPLE_ACTION (simple)' failed
Dec 21 19:15:03 srvr0 journal: g_simple_action_set_enabled: assertion 'G_IS_SIMPLE_ACTION (simple)' failed
Dec 21 19:15:03 srvr0 journal: g_simple_action_set_enabled: assertion 'G_IS_SIMPLE_ACTION (simple)' failed
Dec 21 19:15:03 srvr0 journal: g_simple_action_set_enabled: assertion 'G_IS_SIMPLE_ACTION (simple)' failed
Dec 21 19:15:03 srvr0 journal: g_simple_action_set_enabled: assertion 'G_IS_SIMPLE_ACTION (simple)' failed
Dec 21 19:15:07 srvr0 journal: g_simple_action_set_enabled: assertion 'G_IS_SIMPLE_ACTION (simple)' failed
Dec 21 19:15:07 srvr0 journal: g_simple_action_set_enabled: assertion 'G_IS_SIMPLE_ACTION (simple)' failed
Dec 21 19:15:07 srvr0 journal: g_simple_action_set_enabled: assertion 'G_IS_SIMPLE_ACTION (simple)' failed
Dec 21 19:15:07 srvr0 journal: g_simple_action_set_enabled: assertion 'G_IS_SIMPLE_ACTION (simple)' failed
Dec 21 19:15:10 srvr0 journal: g_simple_action_set_enabled: assertion 'G_IS_SIMPLE_ACTION (simple)' failed
Dec 21 19:15:13 srvr0 journal: g_simple_action_set_enabled: assertion 'G_IS_SIMPLE_ACTION (simple)' failed
Dec 21 19:15:13 srvr0 journal: g_simple_action_set_enabled: assertion 'G_IS_SIMPLE_ACTION (simple)' failed
Dec 21 19:15:16 srvr0 journal: g_simple_action_set_enabled: assertion 'G_IS_SIMPLE_ACTION (simple)' failed
Dec 21 19:15:16 srvr0 journal: g_simple_action_set_enabled: assertion 'G_IS_SIMPLE_ACTION (simple)' failed
Dec 21 19:15:19 srvr0 journal: g_simple_action_set_enabled: assertion 'G_IS_SIMPLE_ACTION (simple)' failed
Dec 21 19:15:19 srvr0 journal: g_simple_action_set_enabled: assertion 'G_IS_SIMPLE_ACTION (simple)' failed
Dec 21 19:15:47 srvr0 journal: unable to create file '/run/user/0/dconf/user': Permission denied.  dconf will not work properly.
Dec 21 19:15:49 srvr0 journal: g_simple_action_set_enabled: assertion 'G_IS_SIMPLE_ACTION (simple)' failed
Dec 21 19:15:49 srvr0 journal: g_simple_action_set_enabled: assertion 'G_IS_SIMPLE_ACTION (simple)' failed
Dec 21 19:16:01 srvr0 kernel: brcmsmac bcma0:1: wl0: brcms_c_d11hdrs_mac80211:  txop exceeded phylen 153/256 dur 1730/1504
Dec 21 19:16:03 srvr0 journal: g_simple_action_set_enabled: assertion 'G_IS_SIMPLE_ACTION (simple)' failed
Dec 21 19:16:03 srvr0 journal: g_simple_action_set_enabled: assertion 'G_IS_SIMPLE_ACTION (simple)' failed
Dec 21 19:16:23 srvr0 journal: g_simple_action_set_enabled: assertion 'G_IS_SIMPLE_ACTION (simple)' failed
Dec 21 19:16:23 srvr0 journal: g_simple_action_set_enabled: assertion 'G_IS_SIMPLE_ACTION (simple)' failed
Dec 21 19:16:53 srvr0 journal: g_simple_action_set_enabled: assertion 'G_IS_SIMPLE_ACTION (simple)' failed
Dec 21 19:16:53 srvr0 journal: g_simple_action_set_enabled: assertion 'G_IS_SIMPLE_ACTION (simple)' failed
Dec 21 19:18:32 srvr0 journal: g_simple_action_set_enabled: assertion 'G_IS_SIMPLE_ACTION (simple)' failed
Dec 21 19:18:32 srvr0 journal: g_simple_action_set_enabled: assertion 'G_IS_SIMPLE_ACTION (simple)' failed
Dec 21 19:18:44 srvr0 journal: g_simple_action_set_enabled: assertion 'G_IS_SIMPLE_ACTION (simple)' failed
Dec 21 19:18:44 srvr0 journal: g_simple_action_set_enabled: assertion 'G_IS_SIMPLE_ACTION (simple)' failed
Dec 21 19:19:35 srvr0 python: detected unhandled Python exception in '/opt/yugabyte/yugabyte-2.0.8.0/bin/yb-ctl'
Dec 21 19:19:36 srvr0 abrt-server: Executable '/opt/yugabyte/yugabyte-2.0.8.0/bin/yb-ctl' doesn't belong to any package and ProcessUnpackaged is set to 'no'
Dec 21 19:19:36 srvr0 abrt-server: 'post-create' on '/var/spool/abrt/Python-2019-12-21-19:19:36-15790' exited with 1
Dec 21 19:19:36 srvr0 abrt-server: Deleting problem directory '/var/spool/abrt/Python-2019-12-21-19:19:36-15790'
Dec 21 19:20:02 srvr0 systemd: Started Session 8 of user root.
[root@srvr0 ~]#

Please help me in installing and configuring yugabyte properly.

A: Update:
This issue was addressed by https://github.com/yugabyte/yugabyte-db/issues/3044. Some versions of YugabyteDB that were using newer linuxbrew
packages were affected by this issue. The 2.0.8 version of YugabyteDB fixes this issue.
Old:
It is possible that something else is running on one of the ports.
Can you please look at logs in the /opt/yugabyte/data directory for clues.?
For yb-master, look for master.err/master.out/yb-master.INFO files.
Similar, for yb-tserver look for tserver.err/tserver.out/yb-tserver.INFO files.
For example, use this to find the location of the err file.
  find . -name "master.err" -print


text:
Q: Real-time DOM display of multiple javascript subroutines I have an HTML table which I must fill with some javascript function calculations. The javascript function has some subroutines that each make some calculations and fill the HTML table with the results. The problem is that even if the subroutines spend some time to make the calculations and results are expected to appear successive in time, in fact the results are displayed at once. I really want the results to be displayed as they are calculated, at a few seconds pace.

A: add a delay using setTimeout function before calling next subroutine calculation, else the browser will update the DOM only  after all javascript code has been executed

A: Well, if your updates are asynchronous they may be fast and appear to happen at the same time.
You could chain the calculations, so the next starts only after each before it ends.


text:
Q: Finding the matrix of a linear transformation in a basis Let $C$ be a basis for $\mathbb{R}^3$. $$C = \{c_1 = \begin{bmatrix} 1 \cr 2 \cr 3 \end{bmatrix}, c_2 = \begin{bmatrix} 0 \cr 1 \cr -1 \end{bmatrix}, c_3 = \begin{bmatrix} 0 \cr 0 \cr 1 \end{bmatrix}\}$$
L is a linear transformation satisfying $$L(c_1)=c_1+c_2+c_3\\ L(c_2)=-3c_1+2c_2 \\ L(c_3)=c_1+c_2+c_3$$
I'm trying to find the matrix of $L$ with respect to $C$. So my first thought is that the columns of $L$ are $\begin{bmatrix} L(c_1)
L(c_2) L(c_3) \end{bmatrix}$. So now I calculate and I get, and so on that I find L to be $$L = \begin{bmatrix} 1 & -3 & 1 \\ 3 & -4 & 3 \\ 3 & -11 & 3\end{bmatrix}$$
Which I found by adding up and scaling the vectors in C. Is this right? Or am I instead looking for something like $$L = \begin{bmatrix} 1 & 1 & 1 \\ -3 & 2 & 0 \\ 1 & 1 & 1\end{bmatrix}$$ by simply taking the numbers before each $c$ in that description of $L$ above? Am I overthinking this?

A: The matrix representation for $L$ respect to the ordered base $C=\{c_1,c_2,c_3\}$ of ${\bf R}^3$ is given by
$$[L]_{C}^{C}:=\begin{pmatrix} \uparrow&\uparrow&\uparrow\\ [L(c_1)]_{C}&[L(c_2)]_{C}&[L(c_3)]_{C}\\\downarrow&\downarrow&\downarrow \end{pmatrix}\in M_{3\times 3}({\bf R})$$where each column $[T(c_j)]_{C}$ is the coordinate respect to the ordered base $C$.
In your case you know directly $L(c_1),L(c_2)$ and $L(c_3)$ and noticing  for example that $L(c_1)=1\cdot c_1+1\cdot c_2+1\cdot c_3$, thus by definition of coordinates we have $$[L(c_1)]_{C}=\begin{pmatrix}1\\1\\1\\\end{pmatrix}.$$
Similarly with the other coordinates and we have the matrix representation for $L$ respect to $C$ is given by
$$[L]_{C}^{C}=\begin{pmatrix}1&-3&1\\1&2&1\\1&0&1\end{pmatrix}$$


text:
Q: Display configurable product's price and options several times on the same page? Is there a native (strong and simple as a bonus) way to repeat the product prices and options (like sizes, colors, etc.) display on the same page ?
Same question shorter (but maybe there is an other way ?) : can I display both "container1" and "container2" blocks on the same page ?
I tried to echo several times the wanted blocks, but I'm experimenting js conflicts because of duplicate input ids : only the last drop-down list (of each option) is functional, others are empty...
I also tried to use both "container1" and "container2" blocks (removing the unsetCallChild calls in layout) but problem is the same : container1's option drop-down lists are populated, but not container2's lists.

A: Sadly there is no easy way :(
I ran into the same issue when I enhanced my Gifts module[1] to the ability to gift configurables, and display them as selectable items in the cart.
I had to extend the core product.js object to allow passing of a unique id (which I assign to each product as a value using php's uniqueid[2] command.
This then allowed each configurable's dropdowns to be unique and not clash.
Here is my ext-product.js
Object.extend(Product.Config.prototype, {
       initialize: function(config,uniqueid){
        this.config     = config;
        this.taxConfig  = this.config.taxConfig;
        this.settings   = $$('.super-attribute-select-'+uniqueid);
        this.state      = new Hash();
        this.priceTemplate = new Template(this.config.template);
        this.prices     = config.prices;

        this.settings.each(function(element){
            Event.observe(element, 'change', this.configure.bind(this))
        }.bind(this));

        // fill state
        this.settings.each(function(element){
            var attributeId = element.id.replace(/[a-z]*/, '');
            if(attributeId && this.config.attributes[attributeId]) {
                element.config = this.config.attributes[attributeId];
                element.attributeId = attributeId;
                this.state[attributeId] = false;
            }
        }.bind(this))

        // Init settings dropdown
        var childSettings = [];
        for(var i=this.settings.length-1;i>=0;i--){
            var prevSetting = this.settings[i-1] ? this.settings[i-1] : false;
            var nextSetting = this.settings[i+1] ? this.settings[i+1] : false;
            if(i==0){
                this.fillSelect(this.settings[i])
            }
            else {
                this.settings[i].disabled=true;
            }
            $(this.settings[i]).childSettings = childSettings.clone();
            $(this.settings[i]).prevSetting   = prevSetting;
            $(this.settings[i]).nextSetting   = nextSetting;
            childSettings.push(this.settings[i]);
        }

        // Set default values - from config and overwrite them by url values
        if (config.defaultValues) {
            this.values = config.defaultValues;
        }

        var separatorIndex = window.location.href.indexOf('#');
        if (separatorIndex != -1) {
            var paramsStr = window.location.href.substr(separatorIndex+1);
            var urlValues = paramsStr.toQueryParams();
            if (!this.values) {
                this.values = {};
            }
            for (var i in urlValues) {
                this.values[i] = urlValues[i];
            }
        }

        this.configureForValues();
        document.observe("dom:loaded", this.configureForValues.bind(this));
    }
});

and in the templates I output the unique id for the generation of the dropdown templates.
It was not a simple task and took a few days, and is spread over a few template and layout files. If I get time this weekend, I will try and explain all I did.
[1] Gift module
[2] php uniqueid
as an example of the adjustment demo product showing multiple configurables dropdowns and add to cart
Yes, not exactly the same as you want, but the principle is the same. (I am using core blocks via layout in the cart)


text:
Q: Autodetect 'random_page_cost' vs 'seq_page_cost' I read this article about PostgreSQL performance on SSD:
https://amplitude.engineering/how-a-single-postgresql-config-change-improved-slow-query-performance-by-50x-85593b8991b0
These two configurations seem to be important random_page_cost vs seq_page_cost
Since both parameters need to match the particular hardware I wonder if it is possible to automatically detect the matching values?
Update
I have these steps on my mind:

*

*Script creates some dummy tables

*Scripts inserts data to the tables

*Script does some queries

*Script shows matching values for random_page_cost and seq_page_cost

*Human or an automated system takes these values and updates the config. This step is not part of the question.

A:
Since both parameters need to match the particular hardware I wonder if it is possible to automatically detect the matching values?

It's certainly possible to set the parameters automatically, but no one has submitted a patch to do it.
You need to know the sequential and non-sequential read speeds of the drive. There are a ton of ways to get this, but you may just as well use Google because it likely doesn't matter that much. For instance, a quick google search for the sequential and non-sequential read performance of the Samsung SSD 840 Pro (256GB) shows this from AnandTech, with

*

*Random Read 101.4/mbps

*Sequential Read 510.7/mbps

That's roughly a ratio of 1:5, so
SET random_page_cost = 5;
SET seq_page_cost = 1;

Warning, random_page_cost takes into account the cache,

Random access to mechanical disk storage is normally much more expensive than four times sequential access. However, a lower default is used (4.0) because the majority of random accesses to disk, such as indexed reads, are assumed to be in cache. The default value can be thought of as modeling random access as 40 times slower than sequential, while expecting 90% of random reads to be cached.
If you believe a 90% cache rate is an incorrect assumption for your workload, you can increase random_page_cost to better reflect the true cost of random storage reads. Correspondingly, if your data is likely to be completely in cache, such as when the database is smaller than the total server memory, decreasing random_page_cost can be appropriate. Storage that has a low random read cost relative to sequential, e.g. solid-state drives, might also be better modeled with a lower value for random_page_cost.

I've shown my random_page_cost to be 5 times slower than sequential. It's still a wildcard how much of the random_page_cost is already cached. Alas, these values don't really matter much unless the Index scan and the Sequential were so close that you could reasonably pick the Sequential scan by accident. That's seldom the case. It's not uncommon for an Index to speed things up by thousands of times over.
For example, my cpu_index_tuple_cost is 0.005. AFAIK, that means scanning 1000 entries in the index is the same in the planner's eyes as going to the heap once to fetch a block.


text:
Q: Usage of "come" Can I exchange the sentence " How do they come packaged" with "How do they packaged"?
What is the function of the word "come"?

A:
"How do they come packaged?"

Because of the word packaged, the verb come in this context aligns with Definition #5 in NOAD:

come (v.) be sold, available, or found in a specified form : the cars come with a variety of extras | they come in three

Your suggested alternate wording is close:

How are they packaged?

means essentially the same thing (you need to use are, instead of do).

Had you not used the word packaged, though, the situation would change slightly:

"How do they come?"

could be changed to:

"How will they arrive?"

This aligns with Definition #1 in NOAD:

come (v.) arrive at a specified place : my trunk hasn't come yet

A: Most often the usage they come packaged complete with batteries and manual is used to indicate additional items that are included while they are packed in sets of three is used to indicate groupings and they will arrive packed in plain brown paper indicates the style of packaging.  Note that the last of these implies that the content would cause embarrassment if identifiable from the packaging.


text:
Q: density function estimation using neural network I firstly generate data from a bivariate normal distribution with mean (0,0) and var cov (2, 0.5; 0.5, 2).
Here is my code for it:
n <- 10000
set.seed(123) #for reproducible results
dat <- MASS::mvrnorm(n=n,
               mu=c(0, 0),
               Sigma= matrix(c(2, 0.5, 0.5, 2), byrow=T, ncol=2)
)

Now what I want to do is ignore that I know the data is normal.
I would like to approximate the density function using a neural network and compare the estimated model and the true one.
I try to search the literature and I found "Density estimation addresses one of the most fundamental problems in machine learning, the
problem of discovering structure from data in an unsupervised manner". in https://arxiv.org/pdf/1910.13233.pdf
I am wondering can the Neural Density Estimation be implemented on this problem?


text:
Q: using cURL to auto fill and submit the form I am trying to auto fill and submit the form using cURL, the code is here but it is doing absolutely nothing,
<?php
$post_data['countryID'] = '162';
$post_data['autocomplete'] = 'Assam, Karimganj';
$post_data['state'] = '3007';
$post_data['city'] = '60695';
$post_data['countryStateCityCase'] = '2';
$post_data['usesAutoComplete'] = '1';
$post_data['categoryParent'] = '185';
$post_data['categoryChild'] = '219';
$post_data['listing_type'] = '2';
$post_data['title'] = 'Title goes here';
$post_data['currency_typeC'] = '13';
$post_data['priceC'] = '2500';
$post_data['description']= 'Descriptio goes hereDescriptio goes hereDescriptio goes hereDescriptio goes here';
$post_data['email']= 'olx@test.com';
$post_data['ad_language_id']= '1';
$post_data['identity']= '1';
$post_data['imageQty']= '0';
$post_data['phone']= '03311234567';
$post_data['bddisclaimer']= '0';
$post_data['security_code']= 'undefined';
$post_data['captchaKey']= 'undefined';
foreach ( $post_data as $key => $value) {
    $post_items[] = $key . '=' . $value;
}
$post_string = implode ('&', $post_items);
echo $post_string;
$curl_connection =
  curl_init('http://www.olx.in/posting.php?src=8');

curl_setopt($curl_connection, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($curl_connection, CURLOPT_USERAGENT,
  "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
curl_setopt($curl_connection, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_connection, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl_connection, CURLOPT_FOLLOWLOCATION, 1);

curl_setopt($curl_connection, CURLOPT_POSTFIELDS, $post_string);

$result = curl_exec($curl_connection);
echo $result;
print_r(curl_getinfo($curl_connection));
echo curl_errno($curl_connection) . '-' .
                curl_error($curl_connection);

curl_close($curl_connection);
?>

all the fields are properly filled but the nothing is output and i am receiving no confirmation email at all but manually it is working fine, could somebody help me out ?

A: The first reason that hits my head is that you are not doing a percent-encoding while building the content of the HTTP POST request. You can use urlencode(..) function to encode the value of the key-value pair.
Replace
$post_items[] = $key . '=' . $value;

with:
$post_items[] = $key . '=' . urlencode($value);


text:
Q: KDE Splash Screen doesn't disappear Whenever I boot OpenSUSE, The KDE splash screen appears, which is normal. What is not normal, however, is that it never disappears again ! The previous session's windows just appear. KDE is functioning absolutely normal, but this is really annoying, because I can't use the taskbar and I have to use Alt+F2 whenever I want to launch anything. This also makes me lose desktop features, like folders, wallpapers, the clock and themes.
I am using KDE 5.
What can I do to:

*

*Make KDE start a new session every time, not just continue the previous one.

*Make the splash screen disappear so that I can get my desktop again.

Thanks, in advance.


text:
Q: How to retrieve the filename of an image with keras flow_from_directory shuffled method? If I don't shuffle my files, I can get the file names with generator.filenames. But when the generator shuffles the images, filenames isn't shuffled, so I don't know how to get the file names back.

A: Internally, the DirectoryIterator will iterate over an index_arrray which is shuffled when you ask it to.
You just need to index the filename array using the current indexes of the batch:
it = ImageDataGenerator().flow_from_directory(shuffle=True,...)
for img in it:
    idx = (it.batch_index - 1) * it.batch_size
    fnames = [it.filenames[it.index_array[i]] for i in range(idx, idx + it.batch_size)]

A: I think the only option here is to NOT shuffle the files. I have been wondering this myself and this is the only thing I could find in the docs. Seems odd and not correct...


text:
Q: Set a dropdown option to selected based on get variable in url in Razor MVC I have a dropdown menu in a GET form. When the user hits submit, they are directed to the same page and shown the form again. I would like to have the dropdown option the user displayed in the last page already selected. So for example:
 @Html.DropDownList("Type", null, "Type", new { @class = "sbox-input" } )

website.com/Search?Type="Beef"
<select name="Type">
   <option value="Fish" >Fish</option>
   <option value="Chicken" >Chicken</option>
   <option value="Beef" selected="selected">Beef</option>
</select>

A jQuery solution would work just as well.

A: I don't think you need javascript to do this as long as you have type parameter in you Action. I assume that you have something like this:
public ActionResult Search(string type, [other parameters])
{
    ....
    ViewBag.SearchType = type; // put the selected type to the ViewBag
}

SelectList takes selectedValue as fourth parameter to it's constructor, so you can easy create DropDownList in the View with the selected value:
@Html.DropDownList("Type", new SelectList(new Dictionary<string, string> { { "Fish", "Fish" }, { "Chicken", "Chicken" }, { "Beef", "Beef" } }, "Key", "Value", ViewBag.SearchType))

Of course you can create the SelectList in the Action and pass it to the View:
public ActionResult Search(string type, [other parameters])
{
    ....
    ViewBag.SearchTypeList = new SelectList(new Dictionary<string, string> { { "Fish", "Fish" }, { "Chicken", "Chicken" }, { "Beef", "Beef" } }, "Key", "Value", type); // you can assign this to the property of your ViewModel if you have one
}

and then in the View
@Html.DropDownList("Type", ViewBag.SearchTypeList)


text:
Q: BLAS routine to compute diagonal elements only of a matrix product? Say I have two matrices A and B. I want to compute the diagonal elements of the matrix product A * B and place them in a pre-allocated vector result.
Is there a BLAS (or similar) routine to do this as fast as possible?

A: There is no specific routine for that. However, you can use the following definition of matrix multiplication.
Consider C = AB, and aij, bij, cij to denote the (i,j)th element of the corresponding matrices. Without loss of generality, I will assume that all A,B,C are N x N dense matrices.
Then,
cij = sumk=0N-1 (aik, bkj)
Since you are interested only in the diagonal entries:
cii = sumk=0N-1 (aik, bki), for i=1,...,N
In other words, to calculate the ith diagonal matrix of matrix C you need to find a dot product between the ith row of matrix A and ith column of matrix B. That can be achieved by using a dot product BLAS level-1 function ?dot.
res = ?dot(n, x, incx, y, incy)
Let's assume that matrices A and B are stored column-wise and are accessible via pointers *A and *B (which hold N*N values), while *C is a preallocated storage for diagonal entries of matrix C (which holds N values).
The following loop should give you the diagonal:
for (int i=0;i<N;i++)
{
    C[i] = ?dot(N,A[i],N,B[i*N],1);
}

Notice, that we are accessing the ith row of matrix A by passing the first element of the ith row: A[i], and using increment (incx) of N. In contrast, to access the ith column of matrix B we pass the first element of the ith column: B[i*N] and use increment of 1.

Notes:

*

*if A,B, and C have different (but consistent with matrix multiplication) dimensions, only slight modifications will have to be applied.

*if matrices are stored row-wise, the call to ?dot should be slightly changed

*the pseudocode above uses a general ?dot function. In practice, it will be sdot or ddot for single- or double precision real numbers, and versions of ?dotu: cdotu and zdotu for complex numbers of single and double precision, respectively.

*is it the most efficient, cache-friendly, etc-etc implementation? probably not, but it would surprise me if that becomes a bottleneck in an algorithm where NxN matrices A and B have been explicitly calculated anyway.


text:
Q: Updates are not installing When I try to update any programs, it does not work, error message says files are missing. I have not tried anything to fix this issue.

A: 1-check your internet connectivity
2-ensure you dont need any proxy to use internet(or you must set the proxy)
3-open terminal and type sudo apt-get update
4-now you can update your programs.
--if you meet any error, tell about the exact error messages and other appropriate settings you have.


text:
Q: Paypal JAVA REST API examples for recurring payments Does the Paypal JAVA REST API support recurring payment? like getting payment $20 on the 1st day of every month.
Any examples? I could not find such examples.
Thanks for help.

A: In the REST API, classic recurring payments are know as billing plans and billing agreements.
You can find more information here:
https://developer.paypal.com/docs/integration/direct/create-billing-plan/
This would be, roughly, the flow:

*

*Create a Billing Plan with the subscription/recurring payment properties and activate it.

*Create a Billing Agreement passing the ID of the plan you want to use for that particular customer.

*Redirect buyer to PayPal for approval of the agreement.

*Execute the agreement after buyer has approved it and returned back to your site.


text:
Q: R Looping through columns of data frame, filtering by each column I have a data frame looking at errors in data entry.
It has two sets of variables:

*

*One set is error flags (their names will contain 'Error').

*One set is information about the cases which were flagged (for this example, the column 'values').

I would like to loop through the error flag variables, filter the data frame by a value of 1 in each column, and then print.
My problem is that I can't get R to recognize the names of the columns as names to filter by.
I've looked for other examples, and I haven't hit what I need.
In this example, I have a data frame 'test_df', with four variables:  error_1-error_3, and values.
I'd like to loop through those three error variables, and filter test_df for rows having a value of 1.
# set up libraries:
library(tidyverse)
library(magrittr)

# Create the data set 'test_df':
test_df <- structure(list(error_1 = c(0, 0, 1, 1), error_2 = c(0, 0, 1,
1), error_3 = c(0, 0, 1, 1), values = c(1, 2, 3, 4)), class = "data.frame", row.names = c(NA,
-4L))

#  Pull the column names from test_df, retaining only those with 'error' in their name, and print:

names_test_df <- test_df %>%
  dplyr::select(.,contains("error")) %>%
  names()

test_df

names_test_df

> test_df
  error_1 error_2 error_3 values
1       0       0       0      1
2       0       0       0      2
3       1       1       1      3
4       1       1       1      4

> names_test_df
[1] "error_1" "error_2" "error_3"

Here is where the trouble starts - I can't figure out how to feed the elements of names_test_df into functions so that they are recognized as column names in test_df:
test_df %>% dplyr::filter(.,error_1==1)
test_df %>% dplyr::filter(.,as.character(names_test_df[1])==1)
test_df %>% dplyr::filter(.,noquote(names_test_df[1])==1)

> test_df %>% dplyr::filter(.,error_1==1)
  error_1 error_2 error_3 values
1       1       1       1      3
2       1       1       1      4
> test_df %>% dplyr::filter(.,as.character(names_test_df[1])==1)
[1] error_1 error_2 error_3 values
<0 rows> (or 0-length row.names)
> test_df %>% dplyr::filter(.,noquote(names_test_df[1])==1)
[1] error_1 error_2 error_3 values
<0 rows> (or 0-length row.names)

I've also played with looping through 'item' in colnames(test_df), and I get the same result.
Could anybody give some guidance on how to do this?

A: We can convert the string to symbol and evaluate (!!)
library(dplyr)
test_df %>%
     dplyr::filter(., !! rlang::sym(names_test_df[1])==1)
#  error_1 error_2 error_3 values
#1       1       1       1      3
#2       1       1       1      4

Or another option with across
test_df %>%
     filter(across(all_of(names_test_df[1]), ~ . == 1))
#  error_1 error_2 error_3 values
#1       1       1       1      3
#2       1       1       1      4

A: In base R, you can subset the columns with [. For one column you can do :
test_df[test_df[names_test_df[1]] == 1, ]

#  error_1 error_2 error_3 values
#3       1       1       1      3
#4       1       1       1      4

For more than one column where we want to select rows where any of the column has 1 in it.
test_df[rowSums(test_df[names_test_df] == 1) > 0, ]


text:
Q: .NET DependencyInjection and Serilog without using IHost (for console app) When you look at solutions for Dependency Injection and Serilog on .NET projects, most documentation and blogs refers to the IHost model. It does not matter much if for current .NET 6 or other versions of .NET Core.
This is my favorite way for applications providing REST APIs since .NET Core 2.1.
I first defined a BuildLogger() method to configure Serilog with min log level and add all my enrichers/sinks I need.
So my Program.Main method used to look like:
Log.Logger = LoggerBuilder.BuildLogger();
var builder = Host.CreateDefaultBuilder(args).UseSerilog();  // serilog injected in Host.
builder.ConfigureServices(services => services.AddMyServices());
using var source = new CancellationTokenSource();
await builder.Build().RunAsync(source.Token).ConfigureAwait(false);

All fine.
Question is: how to do reuse DI and Serilog without using the IHost model from .NET 6?
My today's user case if for a console app which is only running a few tests and then close, and still reusing some parts I wrote for my previous apps.

A: So instead of the above, I defined that
Log.Logger = LoggerBuilder.BuildLogger();
await using var serviceProvider = new ServiceCollection()
       .AddMyServices()
       .AddLogging(logBuilder => logBuilder.AddSerilog()) // attach serilog.
       .BuildServiceProvider()

RunTests(serviceProvider);

This seems to work as expected.
The trick with AddLogging/AddSerilog() instead of UseSerilog() might be helpful for others!


text:
Q: Comprehensive list of differencies between versions of DirectX, shaders: features, incompatibilities, requirements etc Is there a comprehensive comparison of different versions of DirectX, different versions of shaders?
There's an article on Wikipedia about HLSL with comparison of different versions of shaders. It is useful, but only if you already know a lot of details about shaders (what is instruction predication? what are gradient instructions?). Another problem is that given one source code, different versions of pixel shaders produce different results. It would be much more useful if the article gave some basic idea what is being compared and what are its usages. It would give information about what you really need, what are requirements for your application, what you need to learn.
There're a lot of articles on the Internet about specific features of DirectX (like "Hardware tesselation is supported now, yay!"), but I couldn't find full lists of changes. There're lists of breaking changes between different versions of DirectX on MSDN, but they provide information only on breaking changes, not new features, and are focused on API. There're lists like API features, but they are neither detailed nor comprehensive.
What I want is a comprehensive detailed list of differences between versions of DirectX, versions of shaders, preferably with short exlanations of features for those who only start learning DirectX, HLSL etc.

A: New features for DX10: http://msdn.microsoft.com/en-us/library/bb172268(v=VS.85).aspx
New features for DX11: http://msdn.microsoft.com/en-us/library/ff476342(v=VS.85).aspx
They ALWAYS write a document telling you what is introduced in each new DX version ...
The real skill comes from reading the new list of features and then researching them in the help system.  Its waaaaaay too detailed a thing to put in one document.  So they point you int he right direction and leave you to work out the rest by reading the REST of the documentation.  Sure maybe they could make life easier by putting it all linked from one document but if you actually read the "Programming Guide" its ALL there in more detail than you could ever hope for ...


text:
Q: Equivalence definitions of limits of a sequence Let $(a_n)_{n\geq 1}$ be a sequence of complex numbers, and let $a\in \mathbb{C}$. It is well-known that, if the following statement
$$\forall \epsilon>0\exists N\in \mathbb{N}:(n\geq N\implies |a_n-a|<\epsilon)$$
is satisfied, then $\lim_{n\to \infty}a_n=a$, as a definition. I have seen a lot of proofs that contains something with limits. My experience says that the following statements are equivalent, which I'd like to confirm,
$$\forall \epsilon>0\exists N\in \mathbb{N}:(n\geq N\implies |a_n-a|<\epsilon)\tag{a}$$
$$\forall K>0\forall \epsilon>0\exists N\in \mathbb{N}:(n\geq N\implies |a_n-a|<K\epsilon)\tag{b}$$
$$\exists\alpha>0\forall \epsilon\in (0,\alpha)\exists N\in \mathbb{N}:(n\geq N\implies |a_n-a|<\epsilon)\tag{c}$$
I have seen a lot of proofs that indirecly use $(b)\implies (a)$, and $(c)+(b)$ mixed implies $(a)$.
My short proof of equivalences is:
$(a)\implies (b)$: Assume $K>0$, then putting $\epsilon=K\epsilon'>0$, it implies $\epsilon'>0$.
$(b)\implies (a)$: If $K,\epsilon>0$, then put $\epsilon'=K\epsilon>0$.
$(a)\iff (c)$: It is obvious. (The $\impliedby$ can be seen in this LINK).

A: You are correct that all of these statements are equivalent. For $(a)\iff (c)$, you may want to put your reasoning into notation, although it is fairly obvious. To show complete equivalence, we can say something like $|a_n|-a<\epsilon<\alpha \leq E\in [\alpha,\infty)$, and we already have that this is true $\forall\epsilon \in (0,\alpha)$ and finally $\forall\epsilon' \in(0,\alpha) \cup [\alpha,\infty) \iff \forall \epsilon'>0$.
EDIT:
I wrote this before Hopeless added the link. For all interested, the link, as it addresses the specific question on $(a) \iff (c)$, has more succinct arguments.


text:
Q: How to include dynamically added table rows from javascript when using asp.net after button click i dynamically added rows depending on the number selected, but i just cant seem to pick data in these rows after trying to submit it to the database. On Button Click it only returns the header row that was predefined in the html file. Is there a way i can have these dynamically created rows read because i really need the data generated from them.

function OptionCount(start, cnt) {

  var elems = ['A', 'B', 'C', 'D', 'E', 'F', 'G'];

  var x = cnt;
  var y = start;
  var i;

  for (i = start; i < x; i++) {

    $('.ObjectiveGen').append($('
<input type="checkbox" style="position:relative;" class="ia">	' + elems[i] + '	<input type="text" style="width:100%;"/>	<input type="radio" name="answerradio" />
'))

    $('tr td:not(#inp)').addClass("mitu_center");

  }

}

      <input type="checkbox" id="mainchk" />

    Option Value

    Answer

    Is Answer

The asp.net code shown here
  protected void mn_ServerClick(object sender, EventArgs e)
{

    HtmlTableRowCollection htr = objtable.Rows;

    i = htr.Count;

    foreach (HtmlTableCell tablecell in htr)
    {
        answer = tablecell.InnerText;
    }

     qt.InnerHtml ="Qtn: " + i.ToString() + htr[0].Cells[1].InnerText;

}

enter code here

A: Everytime the page is posted back to the server the page get's re-constructed and the values can be evaluated. Because you added the controls on the client side(through javascript) you will not be able to use them on the server side because the server doesn't know anything about those new controls and how to handle them.
As an alternative you can use the ASP.NET Repeater control.This control is very flexible and can be styled to look and feel just like a native HTML table and you will be able to access the TextBox values on the server after the post back!
Code behind:
public partial class TableRepeaterExample : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            var answer1 = new Answer { Option = "A", AnswerText = "" };
            var answer2 = new Answer { Option = "B", AnswerText = "" };
            var answer3 = new Answer { Option = "C", AnswerText = "" };

            Repeater1.DataSource = new List<Answer> { answer1, answer2, answer3 };
            Repeater1.DataBind();
        }
    }
    protected void mn_ServerClick(object sender, EventArgs e)
    {
        foreach(RepeaterItem item in Repeater1.Items)
        {
            TextBox txtAnswer = item.FindControl("txtAnswer") as TextBox;
            if(txtAnswer != null)
            {
                string answer = txtAnswer.Text;
            }
        }
    }
}

public class Answer
{
    public string Option { get; set; }
    public string AnswerText { get; set; }
}

.ASPX:

    <form id="form1" runat="server">

                    Option
                    Answer

                <asp:Repeater ID="Repeater1" runat="server">
                    <ItemTemplate>

                            <%# Eval("Option") %>

                                <asp:TextBox ID="txtAnswer" runat="server" Text='<%# Eval("AnswerText") %>'></asp:TextBox>

                    </ItemTemplate>
                </asp:Repeater>

        <asp:Button ID="Button1" runat="server" Text="Button" OnClick="mn_ServerClick" />
    </form>


text:
Q: React SVG Render issue I'm trying to import an SVG file as follows:
import ExampleIcon from './icons/example.svg';
But I'm getting a render error:
Uncaught (in promise) DOMException: Failed to execute 'createElement' on 'Document': The tag name provided ('/static/media/example.edcd2c8d.svg') is not a valid name.
How can I use a simple import without needing to cast ExampleIcon as a React Component as follows?
import { ReactComponent as ExampleIcon } from './icons/example.svg';
I'm trying to keep my code standardized within the code base, so I would prefer to avoid using the ReactComponent method where possible.

A: I realised I needed to use react-svg-loader to achieve the result I want, as React disallows SVG imports otherwise.


text:
Q: Functional testing automation tools for iPad/iPhone? There doesn't seem to be many choices out there for running functional tests on the iPad/iPhone.  A quick search brought up a few options: FoneMonkey, Frank, UI Automation.
Does anyone have experience with any of these or have suggestions for better solutions?

A: I'm the FoneMonkey project founder, so admittedly a bit biased, but I would strongly recommend you give FoneMonkey a try. It provides robust recording and playback for native iPhone and iPad apps, and you can easily extend custom scripts with Objective-C logic to automate virtually any UI scenario.
The next release (due out later this week) generates UIAutomation-based tests in JavaScript, as well as ready-to-run OCunit tests.
Stu Stern

A: I also found these:
UISpec: http://code.google.com/p/uispec/
Squish: http://www.froglogic.com/products/editions.php
Are there some more?

A: This is another tool that could be used for UI testing.
Debugging with console environment.
libcat : interactive iPhone application development
https://github.com/wookay/libcat

A: There is also one more app in app store. Name of app is TestStudio from Telerik. (http://www.telerik.com/)
It is good but you require Mac Book to install their extension where you can register your app and then use that app on iPad to test.
Hope this will help.


text:
Q: What is the URI for a Sharepoint Document Library? What happened to the "Get Email Reminder" template? It seems to have disappeared from the Sharepoint menu AND Power Automate. Very inconvenient!
I am trying to do exactly what it used to do for a document library and don't know enough to figure out how to set up the "send http request to sharepoint" bit. How do I figure out the URI? That's my last missing piece.
Edit taken from comment:  I want to set an email reminder for when a document has been on file for 6 months that says that the document is due for review. It feels like a super easy thing (and it was with the little power automate drop down that was there a few weeks ago), but I've been struggling to do it from scratch

A: I'm not aware that there ever was a SharePoint or Flow template for such a specific situation.
Conceptually, you need to create a scheduled flow, not one that triggered by something happening in a library. Filter the library to return only the documents that meet the criteria and then use a loop to send an email for each of the documents.
It might be easier to have a SharePoint library column with the due date and then build a SharePoint view that shows only documents due in the next xx days. The the reminder can be built from the "Get daily reminders in Email" template to go and check the view.


text:
Q: How to display log data on ASP.net MVC4 site with AJAX I am new to webdesign(using ASP.net MVC4/Razor) and sometimes the information on the internet is too much, I have been googleing for 2 hours and I found plenty different answsers for my problem but I got no clue which one is best, so I ll ask it here:
I got a Database (EF code first) and it has a log table that gets inserted from different places. However I want to make a page and on that page it should always show the last 20 rows.
So I googled, and found:

*

*Micorosoft ajax?

*Jquery Ajax?

*unobtrusive Ajax?

*SignalR with Jquery?

*Websockets?

*Using ajax with templates?
I am sure, there will be some options that are better then others or maybe an option I have not mentioned yet. Could someone please tell me what direction should I dig into to get the thing I want. (I don't want to get all the code, I just need some guidance since I am a bit lost in the too many options +-)
EDIT:
I'll specify some more, I know I'll have to make a API to get JSON something like
public JsonResult GetLast20LogRows()
{
  ...
  return listoflast20rows; //(as List<DatabaseLog>())
}

I just don't know the HTML/Javascript/ajax par and how to let it refresh the HTML without refreshing whole the page.(Ajax)
EDIT2:
Serverside code:
ChatBotLog.cs (EF Code First):
  public class ChatBotLog
    {
        [Key]
        public int Id { get; set; }
        public DateTime? Date { get; set; }
        public ServerRegion Region { get; set; }
        public string Text { get; set; }
    }

And now I want a .cshtml (razor page) to fetch a method that display the last 20 rows, I' ll make the method fast to get the last 20 rows:
public JsonResult GetLastLogRows()
{
     using (var db = new MyDb())
     {
         var listlog = db.ChatBotLogs.OrderByDescending(x => x.Date).Take(20);
         return Json(listlog);
     }
}

I think that is a method I should make according to what I have read, anyway please tell me if I am wrong, and I still looking for a way to show it on the view, what type of ajax should I use, it does not have to be "real time live" but like refresh data every 5 sec.
Hope you understand better now, where I am stuck.

A: I think your problem can be solved with a so-simple approach:
1- create a jQuery function that will pull the data from your web server
Example:
function GetLatestLogEntries()
{
    var latestLogEntries;

    $.ajax({
                 type: "GET",
                 url: "/{RootFolder}/GetLast20LogRows",
                 dataType: "json",
                 success: function (e) {
                     latestLogENtries = e.data;

                     // here you will need to format the log entries according to your needs, for example
                     $("#divLogContainer").html(latestLogENtries);

                 }
          });
    }

2- Put the following code inside your script tag to ensure that it will get executed after all the page elements are loaded
$(function(){
       setInterval(GetLatestLogEntries(),5000);
})

3- Smile :)
This will execute the GetLatestLogEntries function every 5 seconds and your page will get updated by the latest 20 entries
if you need further explanations, feel free to comment over this answer
Hope this helps :)


text:
Q: I need to apply update and delete in asp.net MVC 4 Basically i have created a mvc application that will be performing CRUD operations on the database data using entity framework generated from database edmx.So in this after adding EDM and configuring database settings i've added a controller named CRUD with scaffolding enabled to read/write action views and attached model and DB conttext to it.Now everything works as desired upto the point of adding new employee ie Create.The problem comes when i run the index page of crud controller and in which when i press the actionlink edit or delete for any specific employee data it doesn't find that Edit and Delete cshtml pages at all and instead shows the error 404 resource not found.Please help me figure out what's wrong,i'm posting my whole code below:
public class CRUDController : Controller
{
    private TestDBEntities2 db = new TestDBEntities2();
    public ActionResult Index()
    {
        return View(db.Emps.ToList());
    }
    public ActionResult Details(int id = 0)
    {
        Emp emp = db.Emps.Find(id);
        if (emp == null)
        {
            return HttpNotFound();
        }
        return View(emp);
    }
    public ActionResult Create()
    {
        return View();
    }
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(Emp emp)
    {
        if (ModelState.IsValid)
        {
            db.Emps.Add(emp);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(emp);
    }
    public ActionResult Edit(int id = 0)
    {
        Emp emp = db.Emps.Find(id);
        if (emp == null)
        {
            return HttpNotFound();
        }
        return View(emp);
    }
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(Emp emp)
    {
        if (ModelState.IsValid)
        {
            db.Entry(emp).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(emp);
    }
    public ActionResult Delete(int id = 0)
    {
        Emp emp = db.Emps.Find(id);
        if (emp == null)
        {
            return HttpNotFound();
        }
        return View(emp);
    }
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public ActionResult DeleteConfirmed(int id)
    {
        Emp emp = db.Emps.Find(id);
        db.Emps.Remove(emp);
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    protected override void Dispose(bool disposing)
    {
        db.Dispose();
        base.Dispose(disposing);
    }
}

Index.cshtml
@model IEnumerable<MvcApplication2.Emp>
@{
    ViewBag.Title = "Index";
}

Index

    @Html.ActionLink("Create New", "Create")

            @Html.DisplayNameFor(model => model.EmployeeID)

            @Html.DisplayNameFor(model => model.Firstname)

            @Html.DisplayNameFor(model => model.Lastname)

            @Html.DisplayNameFor(model => model.Age)

            @Html.DisplayNameFor(model => model.Project)

            @Html.DisplayNameFor(model => model.Address)

@foreach (var item in Model) {

            @Html.DisplayFor(modelItem => item.EmployeeID)

            @Html.DisplayFor(modelItem => item.Firstname)

            @Html.DisplayFor(modelItem => item.Lastname)

            @Html.DisplayFor(modelItem => item.Age)

            @Html.DisplayFor(modelItem => item.Project)

            @Html.DisplayFor(modelItem => item.Address)

            @Html.ActionLink("Edit", "Edit", new {  /*id=item.PrimaryKey */ }) |
            @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
            @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })

}

Create.cshtml
@model MvcApplication2.Emp
@{
    ViewBag.Title = "Create";
}

Create

@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Emp</legend>

            @Html.LabelFor(model => model.EmployeeID)

            @Html.EditorFor(model => model.EmployeeID)
            @Html.ValidationMessageFor(model => model.EmployeeID)

            @Html.LabelFor(model => model.Firstname)

            @Html.EditorFor(model => model.Firstname)
            @Html.ValidationMessageFor(model => model.Firstname)

            @Html.LabelFor(model => model.Lastname)

            @Html.EditorFor(model => model.Lastname)
            @Html.ValidationMessageFor(model => model.Lastname)

            @Html.LabelFor(model => model.Age)

            @Html.EditorFor(model => model.Age)
            @Html.ValidationMessageFor(model => model.Age)

            @Html.LabelFor(model => model.Project)

            @Html.EditorFor(model => model.Project)
            @Html.ValidationMessageFor(model => model.Project)

            @Html.LabelFor(model => model.Address)

            @Html.EditorFor(model => model.Address)
            @Html.ValidationMessageFor(model => model.Address)

            <input type="submit" value="Create" />

    </fieldset>
}

    @Html.ActionLink("Back to List", "Index")

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Edit.cshtml
@model MvcApplication2.Emp
@{
    ViewBag.Title = "Edit";
}

Edit

@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Emp</legend>

            @Html.LabelFor(model => model.EmployeeID)

            @Html.EditorFor(model => model.EmployeeID)
            @Html.ValidationMessageFor(model => model.EmployeeID)

            @Html.LabelFor(model => model.Firstname)

            @Html.EditorFor(model => model.Firstname)
            @Html.ValidationMessageFor(model => model.Firstname)

            @Html.LabelFor(model => model.Lastname)

            @Html.EditorFor(model => model.Lastname)
            @Html.ValidationMessageFor(model => model.Lastname)

            @Html.LabelFor(model => model.Age)

            @Html.EditorFor(model => model.Age)
            @Html.ValidationMessageFor(model => model.Age)

            @Html.LabelFor(model => model.Project)

            @Html.EditorFor(model => model.Project)
            @Html.ValidationMessageFor(model => model.Project)

            @Html.LabelFor(model => model.Address)

            @Html.EditorFor(model => model.Address)
            @Html.ValidationMessageFor(model => model.Address)

            <input type="submit" value="Save" />

    </fieldset>
}

    @Html.ActionLink("Back to List", "Index")

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Image of Solution Explorer:

A: pass EmployeeID in your ActionLinks:
@Html.ActionLink("Edit", "Edit", new {id=item.EmployeeID }) |
@Html.ActionLink("Details", "Details", new {id=item.EmployeeID }) |
@Html.ActionLink("Delete", "Delete", new {id=item.EmployeeID })

A: try to add the Controller Name
 @Html.ActionLink("Edit", "Edit", "CRUD", new {/*id=item.PrimaryKey */ }) |
 @Html.ActionLink("Details", "Details", "CRUD", new { /*id=item.PrimaryKey */ }) |
 @Html.ActionLink("Delete", "Delete", "CRUD", new { /*id=item.PrimaryKey */ })