text:
Q: TortoiseSVN never checks if working copy is updated to latest revision Since we upgraded to TortoiseSVN 1.7, I noticed that TortoiseSVN never showed me the message that I need to update my working copy, it is never out of date.
I was at an earlier revision, I made some changes, used Commit and it went in without question.
While I was modifying, my colleague modified another file and committed it. I checked the log, and I saw the changes, but the modified file wasn't on my computer, yet my Subversion tab showed that I am on the latest revision.
I UPDATED my so called latest revision and the changes from the previous revison was downloaded (though I was on the latest revision).
How is it possible? What if my modification is dependent on what my colleague modified? I don't get it, how I was allowed to upload a modification when I am not on the latest revision. Any ideas what to check?

A: That has always be the case, with all versions of SVN (and TortoiseSVN). SVN will only reject a commit if one of the modified files in the commit has been modified by someone else. since the last update of the file. It worked file by file, and not on the whole project. That's one of the well-known weaknesses of SVN.
If you want the behavior you describe, use Git.


text:
Q: how to pass params to action#new (in a nested has_many association) via link_to I have a cinema system where you can select a session and buy a ticket for that
so I have a link_to:
<%= link_to 'Buy', new_offer_path(:session_id => session.id) %>

I have a model called offer and a model ticket, when the user press Buy it generates a Offer. this offer has a nested Ticket and the info that i need is the session_ID to create a ticket id in the offer.
Here is my offer controller #new action:
def new
    @offer = Offer.new
    @offer.ticket = params[:session_id]

    respond_with(@offer)
end

but it wont work, i need the params i have passed by link to fill the ticket fields in the offer how i do that?
other maybe usefull
Offer model
class Offer < ActiveRecord::Base
     belongs_to :ticket
end

Ticket model
class Ticket < ActiveRecord::Base
  belongs_to :session
  belongs_to :seat

  has_many :offers
end

A: Add the following in your form:
<%= f.hidden_field :session_id, :value => params[:session_id] %>

So that the session_id persists till the create action.

redpajama_set_name: RedPajamaStackExchange


text:
Q: ExceptionHandling in JSF 2.x, access SessionScoped managed bean from another and redirect I did some research on how to get this done, I found some isolated solutions, but I was not able to figure out, how to combine them and what way is consisted as best practice. I am using tomcat and jsf 2.x.
Scenario:
I have a session scoped bean, mycontrollerA. The controller relates to myviewa.xhtml. After hitting a commandLink on viewA, the action mycontrollerA.doThis() got triggered. In this method I want to use try-catch and if an exception occurs, I want to redirect to my exception report view 'exception.xhtml'. The related controller ExceptionController has an attribute 'message' and I want to set the corresponding value in myControllerA.
Problems: I got an error if I try to grab my exceptionController bean. I guess, that it is just not there, because it never got initialized. I hope that there is a common way to grab a SessionScoped bean from another SessionScoped bean, which handles this 'create if necessary'behaviour out of the box. Moreover I think there my redirection-code could be improved.
Thanks in advance.
public String doThis() {
    try {
        throw new RuntimeException("TestExc");
} catch (RuntimeException e) {
    //ExceptionController exceptionController = (ExceptionController) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("exceptionController");
    //exceptionController.setMessage("Fehlerinfo: " + e.getMessage());
    try {
        FacesContext.getCurrentInstance().getExternalContext().redirect("exception.xhtml");
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }
    return null;
}

@ManagedBean(name = "exceptionController")
@SessionScoped
public class ExceptionController { ... }

A: You could try to resolve the bean via ELResolver:
FacesContext fc = FacesContext.getCurrentInstance();
ELContext el = fc.getELContext();
ExceptionController exCtrl = (ExceptionController) el.getELResolver()
    .getValue(el, null, "exceptionController");

Your problem probably is, that the bean was not created before and therefore it is not yet in the session. With the ELResolver approach it should be created.


text:
Q: PLS-00103: Encountered the symbol "ACCEPT" : The task is to get the maximum salary for employees holding the same position from a department. The position and department number are parameters of the function. here is the code
CREATE OR REPLACE FUNCTION getMaxSalary
(jobId in employees.job_id%TYPE,
 dep_id in employees.department_id%TYPE
)
RETURN NUMBER IS
  result NUMBER := 0;
BEGIN
    SELECT MAX(salary)INTO result
    FROM employees
    WHERE job_id = jobId AND department_id = dep_id;
    IF result IS NULL THEN
      RAISE_APPLICATION_ERROR(-20201, 'This is not a valid department');
    END IF;
    RETURN result;
END;

ACCEPT x CHAR PROMPT 'Please enter Job ID:'
DECLARE
  jobId employees.job_id%TYPE;
  maxSalary NUMBER;
BEGIN
  jobId:= '&x';
  maxSalary:= getMaxSalary(jobId);
    DBMS_OUTPUT.PUT_LINE('The max salary for job id: '|| maxSalary);
END;

A: ACCEPT works in SQL*Plus. You tagged the question with plsqldevelper tag which is related to Allround Automations GUI tool. What do you really use?
Anyway: try to add a slash to terminate PL/SQL block, here:
    ...
    RETURN result;
END;
/                            --> here

ACCEPT x CHAR PROMPT 'Please enter Job ID:'
DECLARE
...


text:
Q: Working of fork() in linux gcc
fork() creates a new process and the child process starts to execute from the current state of the parent process.

This is the thing I know about fork() in Linux.
So, accordingly the following code:
int main() {
  printf("Hi");
  fork();
  return 0;
}

needs to print "Hi" only once as per the above.
But on executing the above in Linux, compiled with gcc, it prints "Hi" twice.
Can someone explain to me what is happening actually on using fork() and if I have understood the working of fork() properly?

A: In general, it's very unsafe to have open handles / objects in use by libraries on either side of fork().
This includes the C standard library.
fork() makes two processes out of one, and no library can detect it happening. Therefore, if both processes continue to run with the same file descriptors / sockets etc, they now have differing states but share the same file handles (technically they have copies, but the same underlying files). This makes bad things happen.
Examples of cases where fork() causes this problem

*

*stdio e.g. tty input/output, pipes, disc files

*Sockets used by e.g. a database client library

*Sockets in use by a server process - which can get strange effects when a child to service one socket happens to inherit a file handle for anohter - getting this kind of programming right is tricky, see Apache's source code for examples.

How to fix this in the general case:
Either
a) Immediately after fork(), call exec(), possibly on the same binary (with necessary parameters to achieve whatever work you intended to do). This is very easy.
b) after forking, don't use any existing open handles or library objects which depend on them (opening new ones is ok); finish your work as quickly as possible, then call _exit() (not exit() ). Do not return from the subroutine that calls fork, as that risks calling C++ destructors etc which may do bad things to the parent process's file descriptors. This is moderately easy.
c) After forking, somehow clear up all the objects and make them all in a sane state before having the child continue. e.g. close underlying file descriptors without flushing data which are in a buffer which is duplicated in the parent. This is tricky.
c) is approximately what Apache does.

A: (Incorporating some explanation from a comment by user @Jack)
When you print something to the "Standard Output" stdout (computer monitor usually, although you can redirect it to a file), it gets stored in temporary buffer initially.
Both sides of the fork inherit the unflushed buffer, so when each side of the fork hits the return statement and ends, it gets flushed twice.
Before you fork, you should fflush(stdout); which will flush the buffer so that the child doesn't inherit it.
stdout to the screen (as opposed to when you're redirecting it to a file) is actually buffered by line ends, so if you'd done printf("Hi\n"); you wouldn't have had this problem because it would have flushed the buffer itself.

A: printf() does buffering. Have you tried printing to stderr?

A: printf("Hi"); doesn't actually immediately print the word "Hi" to your screen. What it does do is fill the stdout buffer with the word "Hi", which will then be shown once the buffer is 'flushed'. In this case, stdout is pointing to your monitor (assumedly). In that case, the buffer will be flushed when it is full, when you force it to flush, or (most commonly) when you print out a newline ("\n") character. Since the buffer is still full when fork() is called, both parent and child process inherit it and therefore they both will print out "Hi" when they flush the buffer. If you call fflush(stout); before calling fork it should work:
int main() {
  printf("Hi");
  fflush(stdout);
  fork();
  return 0;
}

Alternatively, as I said, if you include a newline in your printf it should work as well:
int main() {
  printf("Hi\n");
  fork();
  return 0;
}

A: Technical answer:
when using fork() you need to make sure that exit() is not called twice (falling off of main is the same as calling exit()). The child (or rarely the parent) needs to call _exit instead. Also, don't use stdio in the child. That's just asking for trouble.
Some libraries have a fflushall() you can call before fork() that makes stdio in the child safe. In this particular case it would also make exit() safe but that is not true in the general case.


text:
Q: What's best way to show external text when JavaScript disabled I used scripts to load .txt files into a div on my site.  The text files contain html's  <p> <b> and <br>'s  to control they way they look.  I have been racking my brain but have nothing... What's the cleanest/best way to show the data without scripts so visitors can read the file when javascript is disabled.  FYI: I am trying to avoid duplicating the data on additional pages; so ideas other than that would be preferred. Thanks!

A: you could include the texts as an IFRAME and replace that with your DIV via Javascript.  The iframe gets displayed no matter what, but if javascript is enabled, you can replace it with more shiny stuff.


text:
Q: Multiple installation in a single database I would like to ask, can I install multiple wordpress in one single database? Will the new installation automatically get new table names that differentiate it with the existing ones? Or will it overwrite the existing one?

A: Yes, multiple installations can share a single database.
When you edit the wp-config.php file for each installation, you must give each install a unique table prefix.
The process is also explained in Installing Multiple Blogs: Single Database in Codex.

A: Yes, you can install multiple WordPress instances into one database. You just need to change the database prefix for each install when installing.
In wp-config.php you need to change $table_prefix = 'wp_'; to something else, like $table_prefix = 'xy_';

A: yes its possible, just give different table prefix

A: Multiple WordPress Installation into a single database is possible and it's not so difficult.

*

*The first of all you must install WordPress manually.

*During the installation in your wp-config.php phase, you need to change the prefix "wp_" in order to allow multiple installations.For example, the first can be "wpblog1_" and the next can one be "wpblog2_".

You can use different prefix and use them to create as many installations as you need.


text:
Q: A regular expression to accept URL path with condition I have a regular expression as follows:
listing/(.+?)/([^\/.]+)/?(reviews/?(.+?)?/?)?/?$

it accepts following URLs:
listing/united-states/postname1/

listing/united-states/california/postname2/

listing/united-states/california/chino/postname3/

listing/united-states/california/chino/postname4/reviews/testreview/

What I can do in order it does not accept:
listing/united-states/california/chino/postname1/reviews/

listing/united-states/california/chino/postname2/add-review/

A: You can use a negative look ahead to reject strings that end with /reviews/ or add-review using this regex,
(?!.*/(add-)?reviews?/$)listing/(.+?)/([^\/.]+)/?(reviews/?(.+?)?/?)?/?$
^^^^^^^^^^^^^^^^^^^^^^^^ This negative look ahead will reject strings
                         that end with review or reviews or add-review or add-reviews

Regex Demo
However, if you strictly want the strings to be reject that only end with add-review or reviews, you will have to use this regex,
(?!.*/(?:add-review|reviews)/$)listing/(.+?)/([^\/.]+)/?(reviews/?(.+?)?/?)?/?$

Regex Demo strictly discarding your specified strings


text:
Q: Is it possible to use certificate based authentication for the rabbitmq-management plugin? We are using the rabbitmq-management REST API for different operations on the rabbitmq's entities (queues/exchanges). The standart authentication by login/password works fine, but for some reasons we would like to use password-less authentication (based on ssl certificates). According to the documentation (https://www.rabbitmq.com/management.html) it looks like there is that possibility.
But if we try to configure the plugin:
advanced.config
{rabbitmq_management,
  [{listener, [{port,     15671},
               {ssl,      true},
               {ssl_opts, [{cacertfile, "c:/Services/certs/cacert.pem"},
                           {certfile,   "c:/Services/certs/cert.pem"},
                           {keyfile,    "c:/Services/certs/key.pem"}]}
              ]}
  ]
}

Our client's .NET app
public Foo(string url, X509Certificate clientCert)
{
    var handler = new HttpClientHandler();
    handler.ClientCertificates.Add(clientCert);

    _httpClient = new HttpClient(handler);

    var result = await _httpClient.GetAsync(uri)
 }

We get the following (Fiddler session):

*

*| Tunnel to | HTTP/1.1 200 Connection Established (A SSLv3-compatible ClientHello handshake was found)

*| HostName  | HTTP/1.1 401 Unauthorized

Is it possible to use certificate based authentication for the rabbitmq-management plugin? If Yes, could someone give any samples or a documentation link what we have to do?

A: I recently answered this question on the rabbitmq-users mailing list: link.
The short answer is that you can configure the server to require a client certificate and validate that it was signed by a trusted root cert, but you will still have to provide a username and password - the user won't be extracted from the certificate.

NOTE: the RabbitMQ team monitors the rabbitmq-users mailing list and only sometimes answers questions on StackOverflow.


text:
Q: My Canvas App keeps refreshing I'm using this code for my App to allow the users to login as well as get the app permissions to create and edit the user's events, and it was working fine, but when I tried it today the page keeps refreshing infinity as well as changes the auth code each time. I can't tell what is going on.
<?php
   // Include facebook php api
   require_once("lib/facebook.php");

    // Setup app configuration
    $config = array();
    $config['appId'] = 'APP_ID';
    $config['secret'] = 'APP_SECRET';
    $config['cookie'] = true;
    $config['fileUpload'] = true;

    // set app id & canvas page for location variable
    $app_id = 'APP_ID';
    $canvas_page = "https://apps.facebook.com/mixityhc/";

      $location = "https://www.facebook.com/dialog/oauth?client_id="
         . $app_id . "&redirect_uri=" . urlencode($canvas_page) . "&scope=publish_stream,email,create_event,rsvp_event,user_events,friends_events";

  // create new instance of facebook object
  $facebook = new Facebook($config);

    // Get user id
    $fbID = $facebook->getUser();

    // Get the current access token
    $access_token = $facebook->getAccessToken();

    // check if we have valid user
 if ($fbID) {
     try {
          // Proceed knowing you have a logged in user who's authenticated.
         $fb_user_profile = $facebook->api('/me');

      } catch (FacebookApiException $e) {
          $fbID = NULL;
          // seems we don't have enough permissions
          // we use javascript to redirect user instead of header() due to Facebook bug
          print '<script language="javascript" type="text/javascript"> top.location.href="'. $location .'"; </script>';

         // kill the code so nothing else will happen before user gives us permissions
         die();
      }

  } else {
      // seems our user hasn't logged in, redirect him to a FB login page

     print '<script language="javascript" type="text/javascript"> top.location.href="'. $location .'"; </script>';

     // kill the code so nothing else will happen before user gives us permissions
     die();
 }

 // Get user email address
 $email = $fb_user_profile['email'];

Any help would be much appreciated thank you

A: Okay, I figured it out. The Facebook API was updated to fix an apparent bug in Facebook. So I uploaded the new files (specifically the cert) and it worked. Just in case some one else is having the same problem.
Thanks


text:
Q: Add Css Class to ActionLink of ASP.NET MVC In ASP.NET MVC3 This is a regular actionlink at Razor view :

@Html.ActionLink("Home", "Index", "Home")

and related html dom is:

Home

So my css work correctly if I add css class to the  element like the following:

Home

Does any one know how can I do this?

A: You can do this to pass in html attributes.
@Html.ActionLink("Home", "Index", "Home", new { @class = "MyCssClass" })

You can pass other html attributes as well.
@Html.ActionLink("Home", "Index", "Home", new { @class = "MyCssClass", otherAttributeName = 1 })

hope this helps

A:
@Html.ActionLink("Home", "Index", "Home", new { @class = "myclass" })

A: If you are using a newer version of the ASP.NET MVC framework, you will have to pass an extra parameter for the routeValues. There's no method signature overload that accepts htmlAttributes as the 4th parameter any more, so if you are not passing in routeValues, just pass in a null like this:
@Html.ActionLink("Home", "Index", "Home", null, new { @class = "MyCssClass" })

A: Use another overload:

@Html.ActionLink("Home", "Index", "Home", new { @class="YourClass" })


text:
Q: Remove expired data from Superfeedr We use Superfeedr to load current internal job postings from our cloud recruitment software (Newton).  It was just brought to my attention yesterday that positions that are no longer active are still being loaded in our feed.
The raw feed from Newton is correct and it does not have the non-active positions listed.  When I access the feed via Superfeedr the inactive positions are being returned.  When looking at their documentation, it sounds like this behavior may be by design.
Does anyone know if I am correct or if there is a workaround for this?

Updates
If an entry is updated, they are not propagated by default. This is
  because we want to avoid creating numerous false positives.
There is, however, one exception: if a new entry contains a valid,
  updated element, and the update is very recent (within three minutes),
  you will receive a notification. This means that we will usually
  propagate updates for feeds if we receive a ping from the publisher.

https://documentation.superfeedr.com/subscribers.html


text:
Q: Question on Change of Variables I have to calculate $\lambda^3(Z)$ with $Z=\{(x,y,z) \in \Bbb R^3\mid  \frac{x^2}{a^2}+\frac{y^2}{b^2} \le1,\:\:\: 0\le z\le h\}$ via the transformation $$\phi(\mu, \nu, z) = (k\cdot cosh(\mu)\cdot cos(\nu),\:\:\: k\cdot sinh(\mu)\cdot sin(\nu),\:\:\: z)^T $$
(I also have to determine $k\gt 0$.)
I've already calculated the Jacobi-determinant of $\phi$: $D\phi = k^2sinh^2(\mu) cos^2(\nu) +k^2cosh^2(\mu)sin^2(\nu)$ but now I'm lost on how to continue. (I know i have to apply the Theoreme on Change of Variables but I don't know how to do it). Any tipps would be greatly appreciated. Thanks in advance!

A: The new coordinates are elliptical cylindrical. The curves for $\mu$ constant are ellipses. Note that the region to calculate its volume it's a cylinder of base an ellipse centered in the origin and with semiaxes $a$ and $b$. It's possible to choose $k$ and some value of $\mu$ to fit that ellipse into a constant value of $\mu$. It can be done as follows. Can easily be checked that:
$$\frac{x^2}{k^2\cosh^2\mu}+\frac{y^2}{k^2\sinh^2\mu}=1$$
For every value of $x,y$ and $\mu$. So, for constant $\mu=\mu_0$ the points $(x,y)$ satisfying the equation form an ellipse. This can be well the edge of the cylinder base:
$$\frac{x^2}{k^2\cosh^2\mu_0}+\frac{y^2}{k^2\sinh^2\mu_0}=\frac{x^2}{a^2}+\frac{y^2}{b^2}=1$$
With
$$\begin{cases}
  k^2\cosh^2\mu_0=a^2 \\
  k^2\sinh^2\mu_0=b^2
\end{cases}$$
$$\begin{cases}
  k^2=a^2-b^2\\
  \mu_0=\text{arctanh}(b/a)
\end{cases}$$
Now $Z=\{\mu\in[0+\infty),\nu\in[0,2\pi),z\in\mathbb R\mid  \mu \le\mu_0,\:\:\: 0\le z\le h\}$ (Notice that the jacobian can be expressed as $k^2(\sinh^2\mu+\sin^2\nu)$)
$$Volume(Z)=\int_0^h\int_0^{2\pi}\int_0^{\mu_0}k^2(\sinh^2\mu+\sin^2\nu)\mathbb d\mu\mathbb d\nu\mathbb dz=$$
$$=h\int_0^{2\pi}\int_0^{\mu_0}k^2(\sinh^2\mu+\sin^2\nu)\mathbb d\mu\mathbb d\nu=$$
$$=hk^2\int_0^{2\pi}\int_0^{\mu_0}\sinh^2\mu\mathbb d\mu\mathbb d\nu+hk^2\int_0^{2\pi}\int_0^{\mu_0}\sin^2\nu\mathbb d\mu\mathbb d\nu=$$
$$=hk^22\pi(1/4)(\sinh(2\mu_0)-2\mu_0)+hk^2\pi\mu_0=hk^2\pi(1/2)\sinh(2\mu_0)$$
Substituting $k$ and $\mu_0$ by their values leads to:
$$Volume(Z)=h(a^2-b^2)\pi(1/2)\sinh(2\text{arctanh}(a/b))=h(a^2-b^2)\pi(1/2)\frac{2ab}{a^2-b^2}$$
$$Volume(Z)=\pi abh$$
For a cylinder can be calculated $Volume=Area\_of\_Base·Height$ With $Area\_of\_Base=\pi ab$ as corresponds to an ellipse. Then $Volume=\pi abh$. It works!!


text:
Q: What environment variables are needed for react-native? I was editing my Path variables and somehow I must've got the Path(environment variable) for react-native lost. When I try to use react-native run-android I get the following error 'react-native' is not recognized as an internal or external command, operable program or batch file.
I assume this must be an environment variable issue.
I tried uninstalling and reinstalling but that didn't help.
I've googled about my issue but that didn't help.
If anyone can share the environment variables , or he suspects something else to be the issue I would really appreciate to be pointed at some direction.

A: Found the path that was missing. It was the C:\Users\<user>\AppData\Roaming\npm for anyone that might be concerned.


text:
Q: Using the timer to check a condition inside a if I have to develop an application where it does following things,

*

*Switch is used to initiate the accelerometer

*Then accelerometer data is inserted to an array of size 5

*Then use those accelerometer data to calculate a output value using a equation

*Every times a new reading comes, i delete the last element of the array and add it to the array( array remains dynamic through out the loop

*Then i want to compare whether the output calculated is greater than a specified value and update a global counter?

I implemented this by using a if condition
if(output>10){
[[shared sharedInstance].counter++;
}

(all above are implemented and they work perfectly)
BUT the problem is.....................
I want to check this if condition, used to update to be active for 5ms and deactivate for 10ms but it's also important to "NOT" to stop the accelerometer data process and calculating output.
So i thought that i can implement two global variables and set their values as shown below
1. var_x - set it's value for 1 for 5ms after that set it to 10ms and this process should repeat continuously and it should start after the user activate accelerometer,
So by using this inside my if condition i can make sure it check the condition after 10ms and keep on checking for 5ms
like this.........
if(output>10 && [[shared sharedInstance].var_x >1){
[[shared sharedInstance].counter++;
}

can anyone help me to code this timing function inside the global variable to set the variable value to 1 and 0 ? (

A: - (void)turnCheckOn {
    doCheck = YES;
    [self performSelector:@selector(turnCheckOff) withObject:nil afterDelay:0.005];
}

- (void)turnCheckOff {
    doCheck = NO;
    [self performSelector:@selector(turnCheckOn) withObject:nil afterDelay:0.010];
}

Then call turnCheckOn once.


text:
Q: Counting matching ratings grouped by ID without using table joins? Is it possible? MYSQL? I have an intermediate table called ratingsPerId that is produced from a stored procedure shown here:
Id   Rating
'1', 'low'
'1', 'low'
'1', 'low'
'1', 'low'
'1', 'low'
'2', 'medium'
'2', 'medium'
'2', 'medium'
'2', 'high'
'2', 'high'
'4', 'high'
'4', 'high'
'4', 'high'
'4', 'high'
'4', 'high'
'9', 'high'
'9', 'high'
'9', 'high'
'9', 'high'
'9', 'high'
'9', 'high'
'9', 'high'
'9', 'high'
'9', 'high'

What I want is for Id 1, count up all the lows, mediums, highs. And do the same for all the following Id 2, 4, 9, etc...
Right now what I have is a table join that counts the Highs and Lows per ID:
drop temporary table if exists t1, t2;
create temporary table t1(ruleid int, high INT);
INSERT into t1(
    SELECT ruleid, count(*) AS High from ratingsPerRuleId  WHERE rating='high' group by ruleid);
create temporary table t2(ruleid int, low int);
INSERT into t2(
    SELECT ruleid, count(*) AS Low from ratingsPerRuleId WHERE rating='low' group by ruleid);

SELECT t1.RuleID, t1.high, t2.low from t1 left join t2 on t1.ruleid=t2.ruleid ;

ID   High  Low
1    NULL   5
2     2    NULL
4     5    NULL
9     9    NULL

As you can see, I will need to create a third table for Medium and do a join of that to get the Medium column.
Is there an easier way to do this in MYSQL? I feel like there is a simple statement that can accomplish this, and my messy table joins of small tables aren't necessary but I don't know enough of MYSQL to get the answer.
I looked into Count(distinct) and Select Distinct but haven't found the answer.
Thanks!

A: I guess you need to use CASE WHEN expression.
SELECT
 Id,
 COUNT(CASE WHEN Rating ='high' THEN 1 END) AS high,
 COUNT(CASE WHEN Rating ='medium' THEN 1 END) AS medium,
 COUNT(CASE WHEN Rating ='low' THEN 1 END) AS low
FROM your_table
GROUP BY Id;

Working Demo
OR you can use SUM along with MySQL boolean expression if you don't want to use CASE WHEN.
SELECT
 Id,
 SUM(Rating ='high') AS high,
 SUM(Rating ='medium') AS medium,
 SUM(Rating ='low') AS low
FROM your_table
GROUP BY Id;

Working Demo
Note: SELECT SUM(a=b) returns 1 only if a=b;
NB: The following sample input is used in the working demos
| Id | Rating |
|----|--------|
|  1 |    low |
|  1 |    low |
|  1 | medium |
|  1 |   high |
|  2 |   high |

A: This should work (COUNT excludes null values):
SELECT ruleid
  , COUNT(IF(rating = 'high', 1, NULL)) AS High
  , COUNT(IF(rating = 'medium', 1, NULL)) AS Medium
  , COUNT(IF(rating = 'low', 1, NULL)) AS Low
FROM ratingsPerRuleId
GROUP BY ruleid
;

Also, if you prefer you can replace COUNT(..., NULL)) with SUM(..., 0)).
Note: 1000111's answer is more portable, as older versions of MS SQL do not support IF(...)


text:
Q: Can I use a single custom cell for multiple different cells? I have created a single prototype cell which has two labels (mainLabel and subLabel) and an uiimageview. In the uitableview I'd like to have several cells which reuse the prototype and when needed the subLabel is hidden and the uiimageview is changed with different one or with a uiswitch. The two labels have different text for each cell. Do you have any suggestions/hints in order to do it? possibly in a mvvm architecture?
I'll describe what I am doing:
I have a struct (the Model) with two properties: label and sublabel. This is then instantiate by a viewModel which provides text for each cell, done by a method called getModel(_ indexPath: IndexPath) -> cellModel { ... }. Finally in UIViewController, in tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) { ... } I am calling getModel(), using dequeueReusableCell and setting up each cell.
In getModel() there is a huuuuge switch which I use to know which cell is which
Then in uitableviewcell I have some method that hides sublabel and changes uiimageview.
It kind of works, however I have some issues with while scrolling. For example, sometimes a uiimageview is drawn in another cell, or a subLabel is hidden, even if it is not supposed to. I guess this is due because it is reusing the cell, and I am not resetting it.
Anyway, any suggestions or ideas?
I know this is overkilling...

A: No need for any pattern. Yes, you can use that single cell design for all cells. Just hide/empty label(s) and image view as you like per cell.

A: First of all you have to set default value to both the labels and imageview
i.e. (consider a title label, a sub label and a imageview)
lblTitle.isHidden = false
      lblSubLabel.isHidden = false
      imgViewIcon.image = nil

Then just show labels in specific condition that you want to match and set image in imageview
i.e. (consider your condition to hide sub label)
if needToHide == true {
      lblSubLabel.isHidden = true
}


text:
Q: How to validate form using HTML, PHP and jQuery? I am trying to make a form using HTML, PHP, and jQuery AJAX for a website but I don't know how to validate it. Where should I write the code to validate it, in PHP or jQuery?

A: I would suggest using javascript and html than any other language
The following code is for browser validation
<input required> // info
<input required> // more info
<button type="submit">Press to validate</button>
</form>

When you click the button the form will be validated
For js validation
<button onclick ="myfunction()">Press to validate</button>
<script>
function myfunction(){
var x =document.getElementById('validate');
if (x.value.length < 1){
alert("Empty input box.Form validated")
}
}
</script>

Hope this helps


text:
Q: How to merge multi array of object in python? I have two list of array, I don't know How I can merge multi array of object in python?
[{'name': 'James'}, {'name': 'Abhinay'}, {'name': 'Peter'}]

[{'age': 1}, {'age': 2}, {'age': 3}]

what I want
[{'name': 'James','age':1}, {'name': 'Abhinay','age':2}, {'name': 'Peter','age':3}]

A: Here's one approach that can work:
L1 = [{'name': 'James'}, {'name': 'Abhinay'}, {'name': 'Peter'}]
L2 = [{'age': 1}, {'age': 2}, {'age': 3}]

result = [dict(**x, **y) for x, y in zip(L1, L2)]

print(result)
# [{'name': 'James', 'age': 1}, {'name': 'Abhinay', 'age': 2}, {'name': 'Peter', 'age': 3}]

Using the dict union | operator in Python 3.9 or higher:
result = [x | y for x, y in zip(L1, L2)]


text:
Q: Simple regex to get a twitter username from a string Given a simple string like "@dasweo where you at?" i would like to write a regular expression to extract the "dasweo".
What I have so far is:
print re.findall(r"@\w{*}", "@dasweo where you at?")

This does not work though. Can anyone help me with this?

A: Drop the {..} curly braces, they are not used with *:
>>> re.findall(r"@\w*", "@dasweo where you at?")
['@dasweo']

Only use {..} quantifiers with fixed numbers:
\w{3}

matches exactly 3 letters, for example.

A: Use this pattern:
print re.findall(r"@\w+", "@dasweo where you at?")

The \w means any word character, while the + means one or more.

A: You can use this:
print re.findall(r"(?<=@)\w+", "@dasweo where you at?")

Where (?<=..) is a lookbehind that means: "preceded by" that performs only a check but doesn't capture.

A: Since you don't want the @ to be included in the match, you can use a positive lookbehind:
>>> import re
>>> re.findall(r"(?<=@)\w+", "@dasweo where you at?")
['dasweo']

In general, a regex of the form (?<=X)Y matches Y that is preceded by X, but does not include X in the actual match. In your case, X is @ and Y is \w+, one or more word characters. A word character is either an alphanumeric character or an underscore.
By the way, there is more than one way to do this. You can also use capturing groups:
>>> [m.group(1) for m in re.finditer(r"@(\w+)", "@dasweo where you at?")]
['dasweo']

m.group(1) returns the value of the first capturing group. In this case, that's whatever was matched by \w+.


text:
Q: read() and write() using spi device driver I would use the read() and write() for the /dev/spiB.C which is created by the user mode spi device driver (spidev.c). Now, the SPI ransaction message follows a certain format (e.g., 24 bits, with some bits for address and some bits for data) which is defined by the chip-vendor-specific spi controller driver. How is the message format fit into the read() and write() transaction? Where and how should I define the format in the code before or after the write() or read()?
Thanks!

A: You need to call spidev_ioctl() mentioned in spidev.c
E.g. Just check switch case :SPI_IOC_RD_BITS_PER_WORD which sets the bits/word (line 410).
Then finally it writes to the bits_per_word member in the spi device structure (line 415).
This spi pointer is the pointer of the spi device which you are communicating to and has been allocated during spidev_probe().
Definitely you need to set the configuration before r/w.You also need to set speed and mode of SPI.
I have refered to the below link for spidev.c file:
http://lxr.free-electrons.com/source/drivers/spi/spidev.c


text:
Q: How to map Fixed Versions of a java bug to release? I am looking at some java bugs.
For example, one below is fixed by 7(b14).  How can I find the JDK (Oracle or OpenJDK) version matching it?
http://bugs.java.com/view_bug.do?bug_id=6533413

A: To solve this problem, it's better to use the OpenJDK bug system. You can find there the equivalent page for your bug.
There you can click on the Fix Version label and obtain the page corresponding to the JDK 7 without updates
If you look in the mercurial repository, you will see that the tags for build numbers are from jdk7-b24 to jdk7-b147
So it means that the build b14 is already integrated into the initial release of the JDK7.


text:
Q: Newtonsoft.Json skip invalid objects, continue deserializing How to skip/ignore/handle invalid json objects in Newtonsoft JSON?
Let's say we have string like:
[{
    "$id": "xc1",
    "sdfdsgds0sdfsadgdxc,sfgsagdfgdsfdm",
    "gxcgdfs"
}, {
    "$id": "2",
    "Property1": "Value",
    "Property2": "Value2"
}]

While doing
JsonConvert.DeserializeObject<T>(jsonString);

So the first object is invalid but I would like to read second valid one, but I've got JsonReaderException, is there a way to achieve ignoring/skipping invalid objects in array and go further with deserialization?

A: I have use JsonSerializerSettings class for determine errors while getting serialize JSON string.
var settings = new JsonSerializerSettings
{
    Error = (obj, args) =>
    {
        var contextErrors = args.ErrorContext;
        contextErrors.Handled = true;
    }
};
var result = streamReader.ReadToEnd();
List<ViewModel> viewModel = JsonConvert.DeserializeObject<List<viewModel>>(result, settings);


text:
Q: Proving $\tan x$ is surjective I'm trying to make sure that I understand the argument that $f(x) = \tan x$ is surjective. It should follow from the following these facts: (1) intermediate value theorem ($\tan x$ is continuous on $\mathbb{R}$); (2) $f(x)$ approaches $+\infty$ as $x \to - \frac{\pi}{2}$ from the right; and (3) $f(x)$ approaches $-\infty$ as $x \to \frac{\pi}{2}$ from the left.
My understanding of the argument is this. Let's pick $y \in \mathbb{R}$. Since $\lim\limits_{x \to \frac{\pi}{2}^{-}} f(x) = + \infty$, there exists a $\delta > 0$ so that $x > \delta$ implies $f(x) > y$. Since $\lim\limits_{x \to - \frac{\pi}{2}^{+}} f(x) = -\infty$, there exists $\eta > 0$ so that $x < \eta$ implies $f(x) < \eta$. $\tan(x)$ is defined and continuous on these intervals, so might block out an interval $\left[\eta - \epsilon, \delta + \epsilon\right]$ for some $\epsilon > 0$. At $\delta + \epsilon$, $f(x) > y$. At $\eta - \epsilon$, $f(x) < y$. By the intermediate value theorem, there is some $x$ in the interval satisfying $f(x) = y$. As $y$ was arbitrary, we can repeat this for any $y$.
How does this look?

A: While you may have the right idea, given the corrections coffeemath pointed out, your write-up of it makes several mistakes. Some of these may just be typos, but others appear to be deeper.

($\tan x$ is continuous on $\Bbb R$)

No it isn't. It is not even defined on all of $\Bbb R$. But it is continuous on $\left(-\frac \pi 2, \frac \pi 2\right)$

Let's pick $y \in \mathbb{R}$. Since $\lim\limits_{x \to
\frac{\pi}{2}^{-}} f(x) = + \infty$, there exists a $\delta > 0$ so
that $x > \delta$ implies $f(x) > y$.

You are taking the limit at $x \to \frac \pi2 -$, not as $x \to \infty$. There is $\delta > 0$ such that if $\frac \pi2 - \delta < x < \frac \pi2$, then $f(x) > y$.

Since $\lim\limits_{x \to -
\frac{\pi}{2}^{+}} f(x) = -\infty$, there exists $\eta > 0$ so that $x
< \eta$ implies $f(x) < \eta$.

Again, the limit is as $x \to -\frac \pi 2+$, not as $x \to -\infty$ (and of course it is $f(x) < y$, not $\eta$). There is $\eta > 0$ such that if $-\frac \pi2 < x < -\frac \pi2 + \eta$, then $f(x) < y$.

$\tan(x)$ is defined and continuous on these intervals, so might block out an interval $\left[\eta -
\epsilon, \delta + \epsilon\right]$ for some $\epsilon > 0$. At
$\delta + \epsilon$, $f(x) > y$. At $\eta - \epsilon$, $f(x) < y$. By
the intermediate value theorem, there is some $x$ in the interval
satisfying $f(x) = y$. As $y$ was arbitrary, we can repeat this for
any $y$.

Obviously, the interval needs corrected to $\left[-\frac \pi 2 + \epsilon, \frac \pi 2 - \epsilon\right]$, where $0 < \epsilon < \delta, \eta$. Otherwise, it is correct. However it could be stated more cleanly as

*

*Let $-\frac\pi 2 < a < -\frac\pi 2 + \eta, \frac\pi 2 - \delta < b < \frac\pi 2$, then $f(a) < y < f(b)$ and by the intermediate value theorem, there is an $x \in [a,b]$ with $f(x) = y$. As $y$ was arbitrary, we can repeat this for
any $y$.


text:
Q: Python - Exception "No template named index" in lpthw.web framework I am going through a short Python tutorial, but I can't get the last exercise to work.
This is the source code of app.py
import web

urls = (
    '/', 'Index'
)

app = web.application(urls, globals())

render = web.template.render('templates/')

class Index(object):
    def GET(self):
        greeting = "Hello World"
        return render.index(greeting = greeting)

if __name__ == "__main__":
    app.run()

and this is the view, index.html
$def with (greeting)

        <title>Gothons of Planet Percal #25</title>

$if greeting:
    I just wanted to say
    greeting.

$else:
    Hello, world!

The file app.py is under this directory: C:\Users\Lucas\Desktop\Learn Python The Hard Way\ex50\gothonweb\bin
and index.html is at: C:\Users\Lucas\Desktop\Learn Python The Hard Way\ex50\gothonweb\templates
So, when I want to run the sample code, I type this in the command prompt:
C:\Python26\python.exe "C:\Users\Lucas\Desktop\Learn Python The Hard Way\ex50\gothonweb\bin\app.py"

After that, "http://0.0.0:8080" is displayed on the console, so I go to http://localhost:8080/ in my browser
but I get back a long traceback starting with
<type 'exceptions.AttributeError'> at /
No template named index
Python  C:\Python26\lib\site-packages\web\template.py in _load_template, line 992
Web     GET http://localhost:8080/

What is going on and how do I fix it?
Thanks in advance!

A: I had this problem as well but running on OSX. Ultimately Zed Shaw saw my pleas for help and saw the mistake I was making.
I was running
~/projects/gothonweb/bin $ python app.py

Zed reminded me that I needed to be running this:
~/projects/gothonweb $ python bin/app.py

to allow the templates folder to be found. After I did that it worked like a charm.

A: in windows ,the folder'name must write like this "c:\" not "c/",and you must use full path.
so the right code is  render = web.template.render('d:\\documents\\python\\templates\\')
(app.py is in d:\documents\python)

A: You have a few typos, you need to refer to your view as Index when you use render (needs to be the same as the class name for your route):
return render.Index(greeting = greeting)

And your urls tuple needs a trailing comma:
urls = (
    '/', 'Index',
)

Also make sure your template is named Index.html. Although, looking at the web.py tutorial, it looks like by convention you'd use lowercase for your route class.

A: Well, I suffered from the same problem, and I must say the error message is right, which indicates "you" cannot find the file, simply because you are not in the right path. So @davidheller @shellfly are right.
I use PyCharm as IDE to write python, so here is my solution:
Since I run the app.py, which is under the bin directory, thus render = web.template.render('../templates/')
which .. goes up and then found the file.
To conclude, we must be sure about the current path(even in windows), and both relative path or absolute path can be used in Windows environment, as shown below:

*

*Absolute path.
Absolute path. Since Windows accepts both "/" and "\", we can write
render = web.template.render('C:/Users/Lucas/Desktop/Learn Python The Hard Way/ex50/gothonweb/templates/')

or
render = web.template.render('C:\\Users\\Lucas\\Desktop\\Learn Python The Hard Way\\ex50\\gothonweb\\templates\\')

Note, python interpreter interprets "\\" as "\"

*Relative path.
render = web.template.render('../templates/')

A: You may need to compile the template like so
python web/template.py --compile templates
anyone using web.py with the Google app engine you will need to.

A: I am doing the same exercise and I simply go on cmd , cd to my lpthw directory which contains the folders of the project skeleton inside and do:
> python bin/app.py

I think you have to put all your files from the project skeleton in one folder and run your app from there. Hope this helps. :)


text:
Q: can I use WCF interface as a MVVM Model? My WPF application should receive data from pipe via WCF:
I'm new to MVVM and I can't understand where to put some stuff. It's clear for me what is View but it not clear what is ViewModel and especially what is Model in my case (in case when WCF involved) The questions are:

*

*what is Model? Do I need special class to represent model? Or Model is WCF server application? What is valid worflow "WCF Server application ----named pipe-----> ViewModel <--Data binding--> View" or "WCF Server application ----named pipe-----> Model<--->ViewModel <--Data binding--> View"

*how to refactor code below? where to put all this initialization? to ViewModel? to Model class (if I need it), to special "initialization" class?
public MainWindow()
{
ChannelFactory<IManagementConsole> pipeFactory =
new ChannelFactory<IManagementConsole>(
    new NetNamedPipeBinding(),
    new EndpointAddress(
        "net.pipe://localhost/PipeMBClientManagementConsole"));

    IManagementConsole pipeProxy =
      pipeFactory.CreateChannel();

    List<ConsoleData> datas = new List<ConsoleData>();
    foreach (StrategyDescriptor sd in pipeProxy.GetStrategies())
    {
        datas.Add(pipeProxy.GetData(sd.Id));
    }
    this.DataContext = datas;
}

Can I assume that this is my MVVM Model? :
[ServiceContract]
public interface IManagementConsole
{
    [OperationContract]
    ConsoleData GetData(int strategyId);

    [OperationContract]
    List<StrategyDescriptor> GetStrategies();
}

A: A Model is a class that describes data from backend data source.  They can be the actual classes from the source (like EF or WCF Proxies) or they can be simple DTOs.  It really depends on your preference.
A ViewModel is a class that describes data for display in the View.  Frequently, but not necessarily, the data comes from Model classes.
The ViewModel is responsible for managing the Model classes: exposing their information to the View and doing something with/to them based on input from the View.  That being said, I prefer not to see the actual communications work in the ViewModel.  Instead, I abstract the communications into another layer (I call mine the Service layer, but that can be confusing in this context).
In essence, I have the ViewModel make requests to the Service layer which communicates with the backend to retrieve/create Model objects that are then returned to the ViewModel.  This gets complicated if the service calls are Asynchronous but can still be done.
For a simple example of this, download the code sample from practicalmvvm.com.

A:
Can I assume that this [IManagementConsole] is my MVVM Model? :

Yes it is (can be) the Model. But it's very unlikely it is usable as the ViewModel.
A ViewModel 'wraps' the Model and makes it suitable to support the UI-content and UI-logic.
In your case you'll want a class ManagementConsoleViewModel and a class StrategyDescriptorViewModel.
The ViewModels implement INotifyPropertyChanged and may provide Commands and extra properties for databinding.
Best thing is to look into some basic MVVM samples (it's really very basic, just add BaseViewModel and RelayCommand  classes to your project) and then decide on a (small) Framework. Like Caliburn-micro or MVVM-light.

A: You could use your WCF service client as the MVVM "Model".  However often an actual Model class is made that then uses the WCF services, since often times there isn't a single WCF service for a single View and/or ViewModel.
For example:
public class MyModel
{
    IUsersService usersSrv;
    ICompaniesService compSrv;

    public MyModel(IUsersService usersSrv, ICompaniesService compSrv)
    {
        this.usersSrv = usersSrv;
        this.compSrv = compSrv;
    }

    public string GetUserAndCompanyName()
    {
        return usersSrv.GetUserName() + " belongs to " + compSrv.GetCompanyName();
    }
}

In other words, your Model will typically contain the members that correspond with your View, whereas your WCF services will usually contain members that logically go together.


text:
Q: Extract Data from Returned JSON String (C#, WinForms) I am trying to get the address using the postcode using the Google Mapping API. So far I can get the JSON data back from the response and store it in a 'var'.
However I can't extract the fields such as street, town and county -> ideally into a separate string variable for each.
Here is my code so far.
string postcode = Convert.ToString(tbPostcode.Text);

string searchCode = "http://maps.googleapis.com/maps/api/geocode/json?address=" + postcode + "&sensor=false";
var result = "";

var httpWebRequest = (HttpWebRequest)WebRequest.Create(searchCode);
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";

using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
    streamWriter.Write("");
    streamWriter.Flush();
    streamWriter.Close();

    var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();

    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
    {
        result = streamReader.ReadToEnd();
    }
}

MessageBox.Show(result);

Hope someone can help, thanks!
Adam

A: Have a look at something like
How to: Serialize and Deserialize JSON Data
Which makes use of DataContractJsonSerializer Class

Serializes objects to the JavaScript Object Notation (JSON) and
  deserializes JSON data to objects.

This should help you to create tyhe C# classes you need
json2csharp : generate c# classes from json


text:
Q: Unpivot (or alternative) all columns into rows I have the following data:
create table test(c1 number,
                  c2 number,
                  c3 number,
                  c4 number,
                  c5 number);

insert into test (c1,c2,c3,c4,c5) values(2000,1844054,50.03,922030,25.01);
insert into test (c1,c2,c3,c4,c5) values(2001,1850861,49.86,937391,25.25);
insert into test (c1,c2,c3,c4,c5) values(2002,1841519,50.32,907995,24.81);
insert into test (c1,c2,c3,c4,c5) values(2003,1804163,49.84,902838,24.94);

I need to translate the data from:
c1   | c2      | c3    | c4     | c5
2000 | 1844054 | 50.03 | 922030 | 25.01
2001 | 1850861 | 49.86 | 937391 | 25.25
2002 | 1841519 | 50.32 | 907995 | 24.81
2003 | 1804163 | 49.84 | 902838 | 24.94

to:
c1 | 2000    | 2001    | 2002    | 2003
c2 | 1844054 | 1850861 | 1841519 | 1804163
c3 | 50.03   | 49.86   | 50.32   | 49.84
c4 | 922030  | 937391  | 907995  | 902838
c5 | 25.01   | 25.25   | 24.81   | 24.94

I didn't succeed with a regular PIVOT, so I ask you for help, thank you.

A: You are transposing, not just pivoting. You need to UNPIVOT, then PIVOT.
select * from test
unpivot(c for col in(c2,c3,c4,c5))
pivot(max(c) for c1 in(2000,2001,2002,2003))
order by col;

CO       2000       2001       2002       2003
-- ---------- ---------- ---------- ----------
C2    1844054    1850861    1841519    1804163
C3      50.03      49.86      50.32      49.84
C4     922030     937391     907995     902838
C5      25.01      25.25      24.81      24.94

A: This is a pain.  You can unpivot and the re-aggregate.  Here is one method:
select which,
       max(case when year = 2000 then c end) as val_2000,
       max(case when year = 2001 then c end) as val_2001,
       max(case when year = 2002 then c end) as val_2002,
       max(case when year = 2003 then c end) as val_2003
from ((select c1 as year, 'c2' as which, c2 as c from test) union all
      (select c1 as year, 'c3' as which, c3 as c from test) union all
      (select c1 as year, 'c4' as which, c4 as c from test) union all
      (select c1 as year, 'c5' as which, c5 as c from test)
     ) x
group by which
order by which;

Here is a db<>fiddle.

A:  SELECT * FROM test
 unPIVOT(
    quantity -- unpivot_clause
    FOR product_code --  unpivot_for_clause
    IN ( c2,c3,c4,c5))

pivot(max(quantity) for
c1 in(2000,2001,2002,2003))
order by product_code;


text:
Q: Confusing C# Constructor I ran across some code today that is a little confusing to me.  I have a class called Operator.  Help me understand what is happening in the constructor of the class.  I do not understand why it has the UsedImplicity attribute and I do not know what "this(r => { })" is accomplishing.
public class Operator
{
[NotNull] readonly IUnityContainer _container;
[NotNull] readonly ServerWrapper _server;

[UsedImplicitly]
public Operator()
  : this(r => { })
{
}

UPDATE - The other constructor:
public Operator([NotNull] Action<IUnityContainer> register)
{
  _container = new UnityContainer()
    .RegisterType<ISettingsReader, MessageBusSettingsReader>(
      new ContainerControlledLifetimeManager())
    .RegisterType<IImpersonationStrategyFactory, ImpersonationStrategyFactory>();

  register(_container);

  _operator= new OperatorWrapper(_container.Resolve<ISettingsReader>());
}

A: The constructor provides a callback mechanism: On instantiating an Operator, you as the caller may pass in a method pointer (lambda or not) with the Action<IUnityContainer> signature, that would be a void Callback(IUnityContainer c) for example, or a c => { do_something_with_c(c); }.
The default constructor, that is the one without arguments, chains the constructor with an empty method body, it basically ignores (throws away) the container callback. It does so because it needs to execute the initialization code in that second constructor, but cannot call it without its required argument.
Second subquestion: UsedImplicitly is to get rid of warnings when a symbol is never referenced but meant to be used by reflection or called externally, is well documented here.


text:
Q: Deleting repeated characters in a string bash script I have this code to delete repeated characters in a string:
awk -v FS="" '{
    for(i=1;i<=NF;i++)str=(++a[$i]==1?str $i:str)
}
END {print str}' <<< "AABBCC"

The result is:

ABC

Which is exactly what I want; but the problem is when I pass a variable it removes the repeated letters but it doesn't update the value of the variable. For example:
KEY=AABBCC
awk -v FS="" '{
    for(i=1;i<=NF;i++)str=(++a[$i]==1?str $i:str)
}
END {print str}' <<< "$KEY"
echo the new key is: $KEY

The result is:

ABC
the new key is: AABBCC

How can I get the updated version of the KEY?

A: Try this:
KEY=AABBCC
KEY=$(awk -v FS="" '{ for(i=1;i<=NF;i++)str=(++a[$i]==1?str $i:str) } END {print str}' <<< "$KEY")
echo $KEY

Output:
ABC

A: You need to assign the output of the awk command to the variable like so:
KEY=AABBCC
KEY=$(awk -v FS="" '{
    for(i=1;i<=NF;i++)str=(++a[$i]==1?str $i:str)
}
END {print str}' <<< "$KEY")
echo the new key is: $KEY

will result in
the new key is: ABC


text:
Q: SPARQL query to get several informations from a given wiki-ID I have the information from several authors in a table. In this table, a column contains the wiki-id for each author. I want to use the wiki-ids to get further information, such as gender, place of birth, place of death, etc. My plan is to use a Python script to loop over the table and run for each author a SPARQL query, get their data and add it to the table.
The problem is that I don't know how to query "get information from author that has wiki-id QXXXX". For example, let us take the author Almudena Grandes (Wiki-id Q274348, https://www.wikidata.org/wiki/Q274348). How do I make a SPARQL query that get her gender, place and date of birth?
I have been writing other queries about Spanish authors, like this: https://w.wiki/468x

A: Add
bind(wd:Q274348 as ?person)

to your query about Spanish authors. With this change, you will not get the results of all Spanish authors but only of Almudena Grandes.
A bit simplified, the query looks then like
SELECT distinct ?person ?personLabel ?nationalityLabel ?databirth ?placebirthLabel ?genderLabel
WHERE
{
  bind(wd:Q274348 as ?person)
  ?person wdt:P27 ?nationality.
  optional {?person wdt:P569 ?databirth}.
  optional {?person wdt:P19 ?placebirth}.
  optional {?person wdt:P21 ?gender}.
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
}


text:
Q: How to disable the new element picker in Firefox? Recently when pressing Alt + Z in Firefox an element picker show up. If I click on it the element is temporarily hidden, until the page is reloaded:

This has never happened to me before. This new feature isn't listed in the Release Note for Firefox 54 or its sister page for web developer. It is different to the element picker from uBlock Origin addon:

What is this, and how to disable it?

A: It's from uBlock Origin. Fixed in 1.13.4, see Release notes.


text:
Q: Custom Data Types for DataFrame columns when using Spark JDBC I know I can use a custom dialect for having a correct mapping between my db and spark but how can I create a custom table schema with specific field data types and lengths when I use spark's jdbc.write options? I would like to have granular control over my table schemas when I load a table from spark.

A: There is a minimal flexibility for writes, implemented by

*

*SPARK-10101 - Spark JDBC writer mapping String to TEXT or VARCHAR

*SPARK-10849 - Allow user to specify database column type for data frame fields when writing data to jdbc data sources
but if you want

to have granular control over my table schemas when I load a table from spark.

you might have to implement your own JdbcDialect. It is internal developer API and as far as I can tell it is not plugable so you may need customized Spark binaries (it might be possible to registerDialect but I haven't tried this).

A: https://spark.apache.org/docs/latest/sql-data-sources-jdbc.html
You can use the createTableColumnTypes option.
Here is the example from the documentation.
Specifying create table column data types on write
jdbcDF.write \
    .option("createTableColumnTypes", "name CHAR(64), comments VARCHAR(1024)") \
    .jdbc("jdbc:postgresql:dbserver", "schema.tablename",
          properties={"user": "username", "password": "password"})


text:
Q: Exception block in pl/sql 'Function' not catching error condition I have the following function which i call from another procedure within the same pl/sql package.
Function lf_get_query(p_table in varchar2) return varchar2
Is
    v_where_clause  varchar2(500);
Begin
    Case upper(p_table)
        When 'TABLEA'   then
            v_where_clause := ' Where trunc(x.purchase_dtm) < ' || '''' || trunc(v_check_Date) || '''';
        When 'TABLEB'   then
            v_where_clause := ' Where trunc(x.purchase_dtm) < ' || '''' || trunc(v_check_Date) || ''''
                                || ' And product_type='ABC'
                                || ' And customer_type='XXX'
                                || ' And contract_type='YYY';
        Else
            raise ex_unknown_table_type;
    End case;
    return v_where_clause;
Exception
    When ex_unknown_table_type then
        [[Log to file that table is urecognised. ]]
        raise;
    When others then
        [[Log to file that table is urecognised and include sqlerrm ]]
        raise;
End;

When i call the function, it generates the following error:
ORA-06502: PL/SQL: numeric or value error: character string buffer too small

The error is generated because the variable v_where_clause is not large enough for some of the strings i am trying to store in the variable. What i don't understand is when the error occurs, it is not caught by any of the two exception clauses shown above. Instead  the error is being caught on the exception block for the procedure that is calling this function.
The reason i know it is not being caught by the exception clauses in the function is that both exception clauses are supposed to log the error condition to a file but they are not.
Is there any reason for this? Shouldn't the exception be caught by the 'WHEN OTHERS' exception block?
Also, is there any way i can declare the v_where_clause variable without specifying a size?
Thanks

A: Is the exception block of the calling procedure issuing a rollback? If so, it will rollback your logging along with everything else. The way you get around this is to use a procedure that is defined with PRAGMA AUTONOMOUS_TRANSACTION, which will allow your logging to occur outside of the current transaction.


text:
Q: Averageifs in Excel I need help with a formula that will provide answers for the yellow shaded cells below.  I think it's an average ifs function.  I keep getting DIV/0
In the example below, I'm trying to get the average test score for Techs and Apprentices by state:
       A          B           C         D
1    Name       Title       Location   Test score
2    Joe        Tech          NY       76%
3    Mary       Apprentice    NY       88%
4    Steve      Tech          NJ       63%
5    Harry      Installer     MA       98%
6    Manfred    Tech          IA       77%
7    Sam        Installer     NY       84%
8    Steve      Apprentice    CT       85%
9    Paul       Apprentice    CT       86%
10   Jenn       Installer     IA       88%

Desired result:
Average test score for Techs and Apprentices by state:

    NY      ?
    NJ      ?
    MA      ?
    IA      ?
    CT      ?

A: This can be done with a pivot table without hurting any formulas.
Click a cell in the data table, then Insert > Pivot Table. Drag the Location into the Rows area and the Test Score into the values area. Right click the Test Score field in the values area, change the Value Field Settings to Average. The screenshot shows the pivot table in columns F and G.
Or, manually create a list of locations and use a formula. In the following screenshot, the values in column F are used with this formula starting in cell H3 and copied down:
=AVERAGEIF($C$2:$C$10,F3,$D$2:$D$10)


text:
Q: node-postgres query not firing on redirect to home page after registering a user I'm making a very simple authenticated website for learning giving users the ability to create an account log in and view content.
The issue is not seeing the registered users on the home page (as a test) after a successful post registration. After the post, I am redirecting the user back to the home page and the get route runs a postgres function using node-postgres module to retrieve all of the users in the database and returns them. That doesn't seem to be firing.  Yet, when I run the same function in my database, I do see the new user.
What's weird is that when I hit enter on the home route in the browser afterwards, the new user does pop up. So I'm really not sure if this is a caching thing or not understanding promises correctly (I've just started getting into this) or something else.
I have tried using callbacks instead of promises as shown on here: https://node-postgres.com/features/queries to see if it makes a difference. Other than that, I've added log statements to see if the promise actually resolves or rejects. But it seems to always resolve so I'm really unsure what's going on here.

<%- include('partials/header') %>

Register

          <form action="/register" method="POST">

              Email
              <input type="email" class="form-control" name="username">

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

            <button type="submit" class="btn btn-dark">Register</button>
          </form>

<%- include('partials/header') %>

\\index.js (in ./db)
const {
    Pool
} = require('pg');

const pool = new Pool({
    database: 'secrets'
});

module.exports = {
    query: (text, params, callback) => {
        return pool.query(text, params, callback)
    }
};

//jshint esversion:6

/* Imports
 * ================================================================================ */
const express = require('express');
const bodyParser = require('body-parser');
const db = require('./db');
const util = require('util');

/* App setup
 * ================================================================================ */
const app = express();
app.disable('etag');
const port = 3000;

app.use(express.static(util.format("%s/%s", __dirname, 'public')));
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({
    extended: true
}));

/* Routes
 * ================================================================================ */

// Get request
app.get("/", function (req, res, next) {
    db.query('SELECT * FROM dbo.usp_SelectUsers()')
        .then(function(dbResult) {
            console.log(dbResult.rows);
            res.send(dbResult.rows);
        }, (reason) => {
            console.log("Not fulfilled :(");
        }).catch(_err => next(_err));
});

// Post request for registration
app.post("/register", function (req, res, next) {
    const queryText = 'SELECT dbo.usp_CreateUser($1, $2)';
    const queryValues = [req.body.username, req.body.password];
    db.query(queryText, queryValues)
        .then(res.redirect("/"))
        .catch(err => next(err))
});

CREATE OR REPLACE FUNCTION dbo.usp_SelectUsers()
  RETURNS TABLE (User_ID INTEGER, User_Name VARCHAR(100)) AS
$func$
BEGIN
    RETURN QUERY
    SELECT u.User_ID
        ,u.User_Name
    FROM dbo.User u
    ;
END
$func$  LANGUAGE plpgsql;

Expected result is to see new users in database and displayed on home page ("/") after successful post without having to refresh the page again.

A: I have updated my registration code to use async / await as follows and this fixed everything for me. I realized that the issue I was having previously is that the post did not fully complete before the database call to retrieve the the list of users were made (ie: database did not yet have the new user when calling dbo.usp_SelectUsers).
app.post("/register", async (req, res, next) => {
    try {
        const queryText = 'SELECT dbo.usp_CreateUser($1, $2)';
        const queryValues = [req.body.username, req.body.password];
        const results = await db.query(queryText, queryValues);
        res.redirect("/login");
    } catch (err) {
        throw err;
    }
});

As a side note, I have read that async / await is also much better to use nowadays and this fix added onto the pluses. Please see the following article for reference:
https://hackernoon.com/6-reasons-why-javascripts-async-await-blows-promises-away-tutorial-c7ec10518dd9


text:
Q: How to save a property to a mongoose document post save I'm using Mongoose's timestamps schema option to make a createdAt and updatedAt property on a user schema (calling them "applicants"). The only reason I need this is to figure out how long it takes a user to get through the signup process. When they click the "Let's get started" button, it creates the user on the backend and sets the createdAt and updatedAt properties (at this point, they are equal). Then when they finish the signup process, I want to send another call to the db and force the document to save again, thus updating the updatedAt property. Once that occurs, I want to find the time difference between the two timestamp properties to see how long it took them to finish the process, then save that value to a timeTaken property.
Problem is, the only way I'm seeing to do this is to trigger the save, then in the promise that's returned, save the document again after a "post save" hook runs to update the applicant's document.
Probably will make more sense with the code:
Applicant's Schema
var applicantSchema = new Schema({
    name: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true,
        lowercase: true
    },
    timeTaken: String
}, {timestamps: true});

applicantSchema.post("save", function () {
    this.setTimeTaken();
});

applicantSchema.methods.setTimeTaken = function () {
    var applicant = this;
    var ms = this.updatedAt - this.createdAt;
    var x = ms / 1000;
    var seconds = Math.floor(x % 60);
    x /= 60;
    var minutes = Math.floor(x % 60);
    x /= 60;
    var hours = Math.floor(x % 24);
    applicant.timeTaken = hours + "h:" + minutes + "m:" + seconds + "s";
};

Applicant Router
applicantRouter.put("/:applicantId", function (req, res) {
    Applicant.findById(req.params.applicantId, function (err, applicant) {
        applicant.save().then(function () {
            applicant.save(function (err, applicant) {
                //console.log(applicant.timeTaken);
                if (err) {
                    res.status(500).send(err)
                } else {
                    res.send({success: true, timeTaken: applicant.timeTaken})
                }
            });
        });
    });
});

How this works:
PUT request comes in, mongoose searches mongodb for the document with the given id, then triggers a "save" event. It's caught by the schema's "post save" hook, which calls the document's setTimeTaken method. This method updates the property on the document, but since this happens post save, I need to save it again to get it to persist.
I can't use a pre-save hook, because it won't have updated the updatedAt property yet.
The code above actually works, but I kinda hate myself for writing it this way. I feel like an infomercial actor: "There's got to be a better way!"
Or maybe there isn't? Someone who knows this stuff better ?
Thanks in advance

A: After stepping away from the computer for a few hours I realized I was adding too much complexity and trying too hard to use the built-in timestamps option. I just changed my math to include Date.now() - this.createdAt, changed the post save to a pre save, and got rid of the extra applicant.save():
Applicant's Schema:
var applicantSchema = new Schema({
    name: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true,
        lowercase: true
    },
    timeTaken: String
}, {timestamps: true});

applicantSchema.pre("save", function (next) {
    this.setTimeTaken();
    next();
});

applicantSchema.methods.setTimeTaken = function () {
    var applicant = this;
    var ms = Date.now() - this.createdAt;
    var x = ms / 1000;
    var seconds = Math.floor(x % 60);
    x /= 60;
    var minutes = Math.floor(x % 60);
    x /= 60;
    var hours = Math.floor(x % 24);
    applicant.timeTaken = hours + "h:" + minutes + "m:" + seconds + "s";
};

Applicant Router:
applicantRouter.put("/:applicantId", function (req, res) {
    Applicant.findById(req.params.applicantId, function (err, applicant) {
        applicant.save(function (err, applicant) {
            if (err) {
                res.status(500).send(err)
            } else {
                res.send({success: true, timeTaken: applicant.timeTaken})
            }
        });
    });
});

Works like a charm.


text:
Q: Api rate limiting on azure functions I am trying to rate limit my azure functions wrt IP address of the user. I am trying to use AspNetCoreRateLimit package used for .Net core 3.1 for WebAPI but it doesnt work for Azure function which are HTTP triggered.
I know it can be done with API management but that will incur some cost with it. I was wondering if there are any alternatives to this package or any other method to IP rate limit the calls.
Any help would be appreciated


text:
Q: SQL Database - Using cPanel Here are my database relations:
shows(showID, title, premiere_year, network, creator, category)
episode(showID, episodeID, airdate, title)

*

*showID is a foreign key to shows

actor(actID, fname, lname)
main_cast(showID, actID, role)

*

*showID is a foreign key to shows actID is a foreign key to actor

recurring_cast(showID, episodeID, actID, role)

*

*showID is a foreign key to shows episodeID is a foreign key to
episode

*actID is a foreign key to actor

customer(custID, fname, lname, email, creditcard,membersince,renewaldate, password, username)
cust_queue(custID, showID, datequeued)

*

*custID is a foreign key to customer showID is a foreign key to shows

watched(custID, showID, episodeID, datewatched)

*

*custID is a foreign key to customer

*showID is a foreign key to shows

*(showID, episodeID) is a foreign key to episode

*(custID, showID) is a foreign key to cust_queue

All the 'IDs' are primary keys
I have queries I was given and for some, I don't know how to go about it. Such as:
Find all shows that have more than 5 seasons.  Display the title of the show, and the number of seasons.  Sort the result by the number of seasons.  Note that the first digit of each episode number represents the season number.
I don't really know how to solve this. Please help!


text:
Q: What is the filling of the stapler called in English? (picture attached) What is the filling of the stapler called in English? (you can see it in red circle in the attached picture).
I looked for this word in my native dictionary but I didn't find this word.

A: I'd just call them "staples".
A set of staples joined together like this can be referred to as a "staple strip" or a "strip of staples", as in Eran's answer, but English speakers don't use this term very often.  Instead, most speakers simply refer to them as "staples" in normal speech.
That doesn't mean you can't talk about strips of staples.  You can talk about whether a stapler takes half strips or full strips, for example – the shorter ones take half strips.  But in common speech, it's usually most natural to just say "staples".

A: They are called staples.
Definition from Merriam Webster dictionary here

A: In our office we call them staple sticks or staple cartridges. But usually when you ask someone to give you those, you never mean to ask for singles, so even if you ask for just "staples", I'm sure you'll get a stick of them.

A: I have always said "a row of staples" for the actual staples stuck together that you put into a stapler.
In the US, Swingline is the most known brand of stapler and here is the usage for row of staples

A: In India, I have heard them called "stapler pins" most often. See, for example, listings on various shopping sites:

*

*eBay India

*Stationery Hut (seems to be an Indian site)

*Flipkart (Indian site)

Or various news articles:

*

*FSSAI bans stapler pins in tea bags from January 2018 - The Hindu Business Line, July 24 2017.

*'Indecent obsessions': A peek into life as a kleptomaniac, compulsive liar - The Hindustan Times, August 20, 2017 (emphasis mine):

Pencils, erasers, sharpeners, notepads, paper clips, even stapler
  pins – over the next nine years, Dandekar would stockpile stationery
  he never really wanted, and certainly did not need.

*29 stapler pins removed from 10-month-old baby's oral cavity - Daily News & Analysis, May 6, 2015.

A: They're staples
Just wanted to point out that one of the world's largest office supplies companies based its name on these little things:
https://en.wikipedia.org/wiki/Staples_Inc.
From a marketing perspective, it has a dual meaning - a "staple" is typically a basic ingredient or material so widely used or consumed that it's considered essential to an everyday process. For example, rice and potatoes are staple foods in many parts of the world, cotton is a staple element of clothing.
By labelling themselves Staples, the office supplies company acquires the linguistic side effect of describing themselves as essential/being sellers of essential things

A: By the previous answers here, I found the following things:
In Wikipedia they're called paper staples.
In Cambridge dictionary they're called simply staples.
Checking in google images shows that the boxes that contains them, call them  simply staples. (See here for example)
Staple strips, by googling I found mainly as a term that can refer to paper staples, but not as name of product title for them but just generally referring to what it is called. I found also that "staple strips" as a product title name refers mainly to the staples that are not for papers, but for example for thicker things than paper or fences etc. For "paper staples strips" there are only 5 results in google.
Stapler needles is a name that less common in English speaking countries (for example, by googling I found 972 results, in which 46 results in the UK or 774 results in the US for "stapler needles"). I think it can tell everything about this usage.

A: a "bolt" of staples is what you call the attached line of staples.

A: As already answered, most people would just say they were "staples":

I need to put some more staples in my stapler.

It may also be called "a block of staples" as they are stuck together.
Another alternative is that they may be referred to as a cartridge. Usually, a "cartridge" is a container with something inside, but the fact that the staples are sort of stuck together with a very fine adhesive makes them more than just "some staples". It is a single, collective object designed to be put into a stapler, and for that reason, I think "cartridge" is acceptible.

A: They are called:

Stapler Needles

or

Staple strips.


text:
Q: There's a way of send pushes from server side to devices by location? There is a way to send pushes from the server code (in a ASP.NET app) according to geographic location (more less than a city) of a mobile device? (any device with an example to me is useful)
Thanks!

A: There is a way to send push notification by location, for this purpose i use PushApps, which is an SDK to manage push notifications.
They are suppose to support this option really soon (according to the support people), and they have a functional web site that supports lots of push actions...
go to http://www.pushapps.mobi/
they were extremely helpful with the implementation etc.

A: You have to store the user's location and also map with his gcm ID to be able to push geographically. There are no API's from google to do this.


text:
Q: How do I sign out form Google Auth from Flutter? I am able to successfully - sign in a user using firebase using both Google and Facebook:
firebase_auth.dart, flutter_facebook_login.dart, google_sign_in.dart
I am able to sign out the firebase user using this function from a different widget:
  Future<void>_signOut() async {
    final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
    return _firebaseAuth.signOut();
  }

Now this is a catch-all for both types of logins, Google and Facebook, how can I determine if the user is a Google auth user in which case I can execute
    final GoogleSignIn _googleSignIn = new GoogleSignIn();
...
    _googleSignIn.signOut();

Additionally, if my sign out function is in a different widget and file how can I pass the GoogleSignIn object to be referenced to sign out?

A: There is bool Future type of method for GoogleSignIn and FacebookSignIn.
final facebookLogin = FacebookLogin();
final GoogleSignIn googleSignIn = new GoogleSignIn();
     googleSignIn.isSignedIn().then((s) {});
      facebookLogin.isLoggedIn.then((b) {});

you will get true or false using this you can use sign out method.
and for your 2nd problem of the solution is to create a global object for GoogleSignIn and facebook as well.
import 'dart:async';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:flutter_facebook_login/flutter_facebook_login.dart';

final facebookLogin = FacebookLogin();
final FirebaseAuth firebaseAuth = FirebaseAuth.instance;
final GoogleSignIn googleSignIn = new GoogleSignIn();

Future<FirebaseUser> signInWithGoogle() async {
  // Attempt to get the currently authenticated user
  GoogleSignInAccount currentUser = _googleSignIn.currentUser;
  if (currentUser == null) {
    // Attempt to sign in without user interaction
    currentUser = await _googleSignIn.signInSilently();
  }
  if (currentUser == null) {
    // Force the user to interactively sign in
    currentUser = await _googleSignIn.signIn();
  }

  final GoogleSignInAuthentication googleAuth =
      await currentUser.authentication;

  // Authenticate with firebase
  final FirebaseUser user = await firebaseAuth.signInWithGoogle(
    idToken: googleAuth.idToken,
    accessToken: googleAuth.accessToken,
  );

  assert(user != null);
  assert(!user.isAnonymous);

  return user;
}

Future<Null> signOutWithGoogle() async {
  // Sign out with firebase
  await firebaseAuth.signOut();
  // Sign out with google
  await googleSignIn.signOut();
}


text:
Q: Changing varchar to nvarchar for all table columns in a database Is there a way to fully traverse all tables in the database and changing all the varchar datatype to nvarchar datatype?
The simple SQL below does not work as intended due to constraints from indexing, unique keys and what not.
ALTER TABLE [CUS].[Customers]
    ALTER COLUMN [CustomerNo] NVARCHAR(500);

I tried changing them from SSMS via the GUI way and the profiler actually shows what it does to truly change the datatype.

*

*Step 1: it creates a temporary table, with nvarchar column changed from varchar

*Step 2: set some lock escalation (no idea what this is)

*Step 3: inserts all data from original table into the temporary table

*Step 4: drops original table

*Step 5: renames temporary table to original table's name

*Step 6: adds the constraints

*Step 7: adds the indexes

This involves a lot of steps and it is quite cumbersome if I were to do it manually.
Can anyone suggest a more flexible solution to my problem?

A: Alternatively you could:

*

*Script whole database without data

*Alter column definitions from VARCHAR to NVARCHAR

*Use either SSIS or SQL to transfer data

Pros:

*

*It could have a less significant impact on the source database

*You could minimize the impact even more if you can run this on separate server

Cons:

*

*You would have to transfer all data, which takes time

*You would have to make sure you have enough disk space on server for database data, index data and log file

Depending on the transfer method you choose and size of your tables, the log file might grow huge even if you are in simple recovery mode. This is the worst case scenario when you transfer a lot of data in one huge transaction.
As a side comment: I agree with @Igor - do not change datatype unless you absolutely have to.


text:
Q: extjs store error handling I am trying to handle an exception in an Ext.data.Store instance when creating a new Ext.data.Record. When the server responds with the following json:
{"success": false, "message": "some text"}

I get an exception of type 'request', even though the server returns an HTTP 200 Response!
To get a 'remote' error I have to create an object with the root property
({
    "success": false,
    "message": "some text",
    "data": {
        "PositionId": "00000000-0000-0000-0000-000000000000",
        "Name": "123"
    }
})

...but I don't want this. Is there any way to change this behaviour?
Also, when I insert a record in the store, it is automatically added to the associated grid, but if an error occurs it remains there, so I need to reload store on every error. Is there any better way to do this?

A: Finally, I've found out that if I send back empty data it works as expected. So I don't need to send back any fictional data, my server response is:
({
    "success": false,
    "message": "some text",
    "data": {}
})

A: You should catch one of the two Store events:

*

*loadexception (deprecated)

*exception
For example you could:
// make the store
var myStore = new Ext.data.Store({...});
// catch loading exceptions
myStore.on('exception',function( store, records, options ){
    // do something about the record exception
},this);
// load store
myStore.load();

You could also just use the success and failure events from the store to take action based on the success flag.

A: when success is false operation doesn't have a response property. This thread explains it very clairly!
http://www.sencha.com/forum/showthread.php?196013-access-operation.response-when-success-false
Example:
Ext.define("SC.store.SegurosCancelacionStore", {
    extend: "Ext.data.Store",
    model: "SC.model.PersonaSeguro",
    proxy: {
        timeout: 90000,
        actionMethods: {
            read   : 'POST'
        },
        type: "ajax",
        url: "../SegurosFinsolCancelacionServlet",
        reader: {
            type: "json",
            root: "seguros",
            messageProperty : 'msjError' //without this, it doesn't work
        }
    },
    autoLoad: false
});

Implementation:
storeSegurosCancelacion.load({
                params: {
                    'sucursal':sucursal,
                    'persona': persona
                },
                callback:function(records, operation, success){
                    msg.hide();
                    if(success == true){
                        if(records.length == 0){
                         Ext.Msg.alert('Resultado', 'No se ha encontrado información');
                        }
                    }
                    if(success == false){
                        try{
                             Ext.Msg.alert('Error', operation.getError()); // way more elegant than ussing rawData etc ...
                        }catch(e){
                                Ext.Msg.alert('Error', 'Error  inesperado en el servidor.');
                        }
                    }
                }
            });

Best regards
@code4jhon


text:
Q: Dynamic Memory and assignment operator overloading of objects If I'm using an assignment operator overload with dynamic memory should I check to see if there's something inside the pointer already?
for example if object A has a dynamic memory allocation in the constructor for an array called "name".
stored in object A is the name "John" with the memory allocated in the constructor through
name = new char[strlen(userinput)+1];

If I wanted to copy object B into object A through an assignment operator overload would I have to write
if(name != null){delete [] name;}
name = new char[strlen(src.name)+1];

To first clear the array out or do I not have to delete name before reallocating memory?

A:
"To first clear the array out or do I not have to delete name before reallocating memory?"

This way, you have to take care about memory management and de-/allocation all the time. You have to obey for copy constructions, assignments also (see What is the Rule of Three?).

if(name != nullptr){delete [] name;}
        // ^^^^^^^ The correct term is nullptr

You have to manage the nullptr value yourself. delete/delete [] don't assign a nullptr value automatically, but leave you with a dangling pointer.

The better solution instead of managing dynamically allocated memory yourself, is to use an appropriate container class like std::vector<char> or std::string:
class A {
    std::string name;
};


text:
Q: Show that if $d_1e_1=d_2e_2,\ and\ \gcd(e_1,e_2)=1\Rightarrow\ lcm(d_1,d_2)=d_1e_1=d_2e_2$ Show that for positive integers if  $d_1e_1=d_2e_2\ and \gcd(e_1,e_2)=1\Rightarrow\ lcm(d_1,d_2)=d_1e_1=d_2e_2$
We know that: $$lcm(d_1,d_2)gcd(d_1,d_2)=d_1d_2$$ but this doesn't help much!
What's the trick?

A: Let $k=\gcd(d_1,d_2)$. Then $d_1=kd_1'$ and $d_2=kd_2'$ where $d_1'$ and $d_2'$ are relatively prime. Thus from the relationship you stated we have $$\text{lcm}(d_1,d_2)k=k^2d_1'd_2',$$
and therefore
$$\text{lcm}(d_1,d_2)=kd_1'd_2'.$$
It remains to show that $kd_1'd_2'=d_1e_1=kd_1'e_1$, or equivalently $d_2'=e_1$.
We were told that $d_1e_1=d_2e_2$, or equivalently that $d_1'e_1=d_2'e_2$. Since $e_1$ and $e_2$ are relatively prime, we have $e_1\mid d_2'$. And because $d_1'$ and $d_2'$ are relatively prime, we have  $d_1'\mid e_2$.
But because $d_1'e_1=d_2'e_2$, it follows that $e_1=d_2'$ and $d_1'=e_2$.


text:
Q: Is there a way to highlight duplicate combinations of values in two columns, regardless of the order? I have a UFC database and I'm looking for rematches. Therefore, I need to find the duplicate combinations of names; the combinations that appear more than once. However, since the winner of the first fight could lose the rematch, I need to find duplicates regardless of the order in which they appear.
This is how my database is structured:
database example.
Fighter 1 is the winner and fighter 2 is the loser.
Here is a link to the database (got it from kaggle): https://docs.google.com/spreadsheets/d/19ISNhYFdGzgLZz1x4h2v_Q5Pq0cofw2rkUtwk3xPXGQ/edit?usp=sharing
Feel free to play around with it.
Any ideas on how to solve this?
Here is an example of the result I'd ideally want:
image example
Just a simple highlight over the duplicates.

A: In order to give you more precise help, it would be helpful if you could give an example of the result you want. As has been said, if there are many duplicates and you mark each group with a different colour, it can be visually confusing.
Anyway, I have written a couple of functions with Apps Script and Spreadsheet Service that you may find useful for your project.
Code 1
With these functions, you will be able to get all fights where two fighters that you previously define have participated:
function main() {
  var name1 = 'Conor McGregor'
  var name2 = 'Nate Diaz'
  var result = findDuplicates(name1, name2)
  console.log(result)
}

function findDuplicates(name1, name2) {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Ark1')
  var lastRow = sheet.getLastRow()
  var lastCol = sheet.getLastColumn()
  var range = sheet.getRange(1, 1, lastRow, lastCol).getValues()
  var result = []
  for (var i = 0; i < range.length; i++) {
    if (range[i].includes(name1) && range[i].includes(name2)) {
      result.push(range[i])
    }
  }
  return result
}

Code 2
With this function, you can add in a third column, the same number for each pair of fighters. This way, it is very easy to change the "add a number" to "paint the cells in a colour".
function findPairs() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Ark2')
  var lastRow = sheet.getLastRow()
  var lastCol = sheet.getLastColumn()
  var range = sheet.getRange(1, 1, lastRow, lastCol).getValues()
  var indexToSkip = []
  var k = 0
  for (var i = 0; i < range.length; i++) {
    if (!indexToSkip.includes(i)) {
      var match = range[i]
      indexToSkip.push(i)
      sheet.getRange(i + 1, 3).setValue(k)

      for (var j = i + 1; j < range.length; j++) {
        if (range[j].includes(match[0]) && range[j].includes(match[1])) {
          indexToSkip.push(j)
          sheet.getRange(j + 1, 3).setValue(k)
        }
      }
      k = k+1
    }
  }
}

References:

*

*Apps Script

*Spreadsheet Service


text:
Q: `JSON.stringify` omits custom keys in array I am storing my array as a mixture of array an array and an object. For example assume this one:
let arrObj = [];
arrObj["x"] = 12;
arrObj.push(12);
arrObj["y"] = 15;
arrObj.push(15);

// result: arrObj = [12, 15, x: 12, y: 15]

so that, I can access the value 12 even using arrObj[0] and arrObj["x"]. And this way, I can do a repeat for on it.
But when I stringify it, the keys x and y get lost:
JSON.stringify(arrObj)
// result: "[12,15]"

How should I maintain those keys and their values?

A: While stringifying convert it to an object using spread syntax and later parse and use Array#reduce method to generate the array.
The array keeps the property since Array is also an object in Javascript.

let arrObj = [];
arrObj["x"] = 12;
arrObj.push(12);
arrObj["y"] = 15;
arrObj.push(15);

let json = JSON.stringify({ ...arrObj });

console.log(json);

let parsed = Object.entries(JSON.parse(json)).reduce((arr, [key, value]) => (arr[key] = value, arr), []);

console.log(parsed);

FYI : But it always better to use an Object or Map for key-value pair data, not better that's the right way in my opinion.

UPDATE 1: Or you can use a main object which keeps all additional property and within it create a property which keeps the array as well.

let arrObj = {
  arr: []
};
arrObj["x"] = 12;
arrObj.arr.push(12);
arrObj["y"] = 15;
arrObj.arr.push(15);

let json = JSON.stringify(arrObj);

console.log(json);

let parsed = JSON.parse(json);

console.log(parsed);

UPDATE 2: The second approach cause issue if you are trying to set property named arr(in my case) so keep object  values in separate property.

let arrObj = {
  arr: [],
  obj: {}
};
arrObj.obj["x"] = 12;
arrObj.arr.push(12);
arrObj.obj["y"] = 15;
arrObj.arr.push(15);

let json = JSON.stringify(arrObj);

console.log(json);

let parsed = JSON.parse(json);

console.log(parsed);

A: Arrays should contain numeric-indexed values only. If you want keys in addition to values, use an object:

const obj = {};
obj.x = 12;
obj[0] = 12;
obj.y = 15;
obj[1] = 15;

console.log(JSON.stringify(obj));

for (let i = 0; i in obj; i++) {
  console.log(obj[i]);
}

You could also consider using an object that contains both an array and your custom key-value pairs, eg:

const arr = [];
const obj = { arr };
obj.x = 12;
obj.y = 15;
arr.push(12);
arr.push(15);

console.log(JSON.stringify(obj));

A: Here is a fancy 1 liner solution:

let arrObj = [];
    arrObj["x"] = 12;
    arrObj.push(12);
    arrObj["y"] = 15;
    arrObj.push(15);

var string = JSON.stringify(Object.keys(arrObj).reduce((acc, cur) => ((acc[cur] = arrObj[cur]), acc), {}));

console.log(string);

P.S: I thought it's worthy to mention that you might encounter an unexpected behaviour because in JS, there is no guarantee that object properties are ordered (as you wanted to).
Does JavaScript Guarantee Object Property Order?


text:
Q: How to select in PostgreSQL table where an attribute is not NULL? I have this PostgreSQL table, test:
 a | b | c | d
---+---+---+---
 5 |   | 5 | 7
 5 | 6 |   |
 1 | 2 | 3 |

I want to query all tuples whose b value is not NULL:
SELECT * FROM test WHERE b != NULL;
SELECT * FROM test WHERE b <> NULL;

The two commands both have no return records:
 a | b | c | d
---+---+---+---
(0 rows)

What command should I use to select all tuples that has a b value?

A: IS NOT NULL
Use this command:
SELECT * FROM test WHERE b IS NOT NULL;

The result is:
 a | b | c | d
---+---+---+---
 5 | 6 |   |
 1 | 2 | 3 |
(2 rows)

Standard SQL
Both predicates IS NULL & IS NOT NULL are standard SQL (Wikipedia). So they work in Postgres as well as other compliant databases.


text:
Q: TS errors not detected by eslint I have a nextJS app that uses typescript. I develop using VSCode. I noticed that VSCode displays TS errors as intended when I open a file with an error but eslint doesn't.
For example, here is my VSCode errors:

But here is my linting results:
▶ yarn lint

yarn run v1.22.10
$ eslint .
(node:83388) ExperimentalWarning: Conditional exports is an experimental feature. This feature could change at any time
(node:83388) ExperimentalWarning: Package name self resolution is an experimental feature. This feature could change at any time
✨  Done in 5.26s.

Here are some files that might be useful to identify the problem:
.eslintrc.js:
module.exports = {
  plugins: [
    '@typescript-eslint',
  ],
  extends: [
    'airbnb-typescript',
    'airbnb/hooks',
    'plugin:@typescript-eslint/recommended',
    'plugin:@typescript-eslint/recommended-requiring-type-checking',
  ],
  ignorePatterns: [
    'app.js',
    '.eslintrc.js',
    'jest.config.js',
    'babel.config.js',
    '/plugins',
  ],
  parser: '@typescript-eslint/parser',
  parserOptions: {
    project: './tsconfig.json',
  },
  rules: {
    'react/require-default-props': ['warn', { ignoreFunctionalComponents: true }],
  },
  overrides: [
    {
      files: ['*.spec.tsx', '*.stories.tsx'],
      rules: {
        'import/no-extraneous-dependencies': 'off',
      }
    }
  ]
};

tsconfig.json:
{
  "compilerOptions": {
    "target": "ES2016",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve"
  },
  "include": [
    "next-env.d.ts",
    "**/*.ts",
    "**/*.tsx"
  ],
  "exclude": [
    "node_modules"
  ]
}

bable.config.js:
const path = require('path');

module.exports = {
  presets: [
    [
      'next/babel',
      {
        'styled-jsx': {
          plugins: [path.join(__dirname, '/plugins/styled-jsx-plugin-sass.js')],
        }
      }
    ]
  ],
  plugins: ['inline-react-svg']
}

package.json scripts:
{
"scripts": {
    "preinstall": "npx only-allow npm",
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "storybook": "start-storybook -s ./public -p 6006",
    "build-storybook": "build-storybook",
    "lint": "eslint .",
    "test": "jest"
  },
}

I'll be more than happy to provide any further information to help fix the problem. Thank you in advance!

A: After more research I found this github issue with the same problem: https://github.com/typescript-eslint/typescript-eslint/issues/352
In which the answer was:

we purposely do not care about errors that should arise as a result of type checking errors.
We only care that the code is syntactically valid (i.e. can be parsed without errors), not about whether it's semantically valid (i.e. don't care if it is type sound)

If you want your code to be typechecked - please use tsc (or one of the tools built for your specific build chain).

So the solution in my case was to edit my lint script to be:
{
  "scripts": {
    "lint": "tsc --noEmit && eslint .",
  },
}

The --noEmit flag tells the command to not generate any files.


text:
Q: evaluate: $ \oint_c w \frac{d}{dw} \left( \frac{\phi (w)^n}{(w-a)^n}\right) dw$ If $\phi(w) $ is analytic in the circle with center $a$ then how to evaluate the integral?
$$ \oint_c w \frac{d}{dw} \left( \frac{(\phi (w))^n}{(w-a)^n}\right) dw$$

In second last line of the above picture, I don't understand how it is evaluated. Can anyone explain? Thanks in advance!!

A: Write
$$\frac{d}{dw} \left [\frac{\phi(w)}{w-a} \right ]^n = n \left [\frac{\phi(w)}{w-a} \right ]^{n-1} \left [\frac{\phi'(w)}{w-a} - \frac{\phi(w)}{(w-a)^2}\right] = n [\phi(w)]^{n-1} \left [\frac{\phi'(w)}{(w-a)^n} - \frac{\phi(w)}{(w-a)^{n+1}} \right ]$$
The integral is then
$$\oint_C dw \, w \frac{d}{dw} \left( \frac{(\phi (w))^n}{(w-a)^n}\right) = i 2 \pi a n! \left [\frac{d^n}{dw^n} [\phi(w)^{n-1} \phi'(w)] \right ]_{w=a} \\+ i 2 \pi a n \cdot n! \left [\frac{d^{n+1}}{dw^{n+1}} \phi(w)^n  \right ]_{w=a}$$


text:
Q: Exact statistics in the Frobenius coin problem The Frobenius coin problem guarantees that if $(a,b)=1$, then
$$ax+by$$ does not represent exactly $\frac{(a-1)(b-1)}2$ numbers all below $g(a,b)=ab-a-b$ if $x,y\geq0$ holds.
Assume $m\in[0,ab-a-b]$ and assume $\max\big(\frac a b,\frac ba\big)<2$.
Approximately what fraction of numbers less than $m$ is represented by $ax+by$? In other words what is a good point-wise approximation to the function
$$f_{a,b}(m)=\big|\{n\in\Bbb N_{\leq m}:\exists x,y\in\Bbb N_{\leq\min(a,b)}\cup\{0\}\mbox{ }\mathsf{ with }\mbox{ }ax+by=n\}\big|?$$
For instance, I am looking for an approximation that will explain the fact that every integer $m\in[1,\min(a,b)]$ is not represented. There seems to be more smaller non-representable numbers than larger ones.  It seems lower the $m$, there are more non-representable numbers and there should be comparatively more representable numbers close to $g(a,b)$ to get upto half the numbers to be representable. What exactly is this distribution?

A: The smallest number with two representations is $ab$, so in the range you're talking about, all representations are unique. You're looking for the number of solutions to $ax+by\le m$ with $x,y\ge 0$; this is the number of integer points in the triangle formed by the intersection of the three half-planes $x\ge 0$, $y\ge 0$, and $ax+by\le m$. Up to low-order terms (which your assumption that $a$ and $b$ are near each other makes insignificant, $O(\sqrt m)$) it will be approximately the same as the area of this triangle, which (as a right triangle with sides $m/a$ and $m/b$) is $$\frac{1}{2}\cdot\frac{m}{a}\cdot\frac{m}{b}=\frac{m^2}{2ab}.$$
This is the number of representable points; the fraction of representable numbers is therefore approximately
$$\frac{m}{2ab}.$$


text:
Q: Is there reactive form in AngularDart? In a official AngularDart guide (https://webdev.dartlang.org/angular/guide/forms)
there is a way how to build forms via templates driven way.
I would like to use reactive forms (https://angular.io/docs/ts/latest/guide/reactive-forms.html) with AngularDart but I even can't find properly reference on FormGroup class (see a screenshot below).

A: Seems added in AngularDart 5
NgFormControl-class