text:
Q: SQL Server Trigger loop I would like to know if there is anyway I can add a trigger on two tables that will replicate the data to the other.
For example:

*

*I have a two users tables, users_V1 and users_V2, When a user is updated with one of the V1 app, it activate a trigger updating it in users_V2 as well.

*If I want to add the same trigger on the V2 table in order to update the data in V1 when a user is updated in V2, will it go into an infinite loop? Is there any way to avoid that.

A: I don't recommend explicitly disabling the trigger during processing - this can cause strange side-effects.
The most reliable way to detect (and prevent) cycles in a trigger is to use CONTEXT_INFO().
Example:
CREATE TRIGGER tr_Table1_Update
ON Table1
FOR UPDATE AS

DECLARE @ctx VARBINARY(128)
SELECT @ctx = CONTEXT_INFO()
IF @ctx = 0xFF
    RETURN

SET @ctx = 0xFF

-- Trigger logic goes here

See this link for a more detailed example.

Note on CONTEXT_INFO() in SQL Server 2000:
Context info is supported but apparently the CONTEXT_INFO function is not.  You have to use this instead:
SELECT @ctx = context_info
FROM master.dbo.sysprocesses
WHERE spid = @@SPID

A: *

*Either use TRIGGER_NESTLEVEL() to restrict trigger recursion, or

*check the target table whether an UPDATE is necessary at all:
IF (SELECT COUNT(1)
FROM users_V1
INNER JOIN inserted ON users_V1.ID = inserted.ID
WHERE users_V1.field1 <> inserted.field1
OR users_V1.field2 <> inserted.field2) > 0 BEGIN

UPDATE users_V1 SET ...

A: I had the exact same problem.  I tried using CONTEXT_INFO() but that is a session variable and so it works only the first time!  Then next time a trigger fires during the session, this won't work.  So I ended up with using a variable that returns Nest Level in each of the affected triggers to exit.
Example:
CREATE TRIGGER tr_Table1_Update
ON Table1
FOR UPDATE AS
BEGIN
      --Prevents Second Nested Call
      IF @@NESTLEVEL>1 RETURN

      --Trigger logic goes here
END

Note: Or use @@NESTLEVEL>0 if you want to stop all nested calls
One other note -- There seems to be much confusion in this article about nested calls and recursive calls.  The original poster was referring to a nested trigger where one trigger would cause another trigger to fire, which would cause the first trigger to fire again, and so on.  This is Nested, but according to SQL Server, not recursive because the trigger is not calling/triggering itself directly.  Recursion is NOT where "one trigger [is] calling another".  That is nested, but not necessarily recursive.  You can test this by enabling/disabling recursion and nesting with some settings mentioned here: blog post on nesting

A: I'm with the no triggers camp for this particular design scenario.  Having said that, with the limited knowledge I have about what your app does and why it does it, here's my overall analysis:
Using a trigger on a table has an advantage of being able to act on all actions on the table.  That's it, your main benefit in this case.  But that would mean you have users with direct access to the table or multiple access points to the table.  I tend to avoid that.  Triggers have their place (I use them a lot), but it's one of the last database design tools I use because they tend to not know a lot about their context (generally, a strength) and when used in a place where they do need to know about different contexts and overall use cases, their benefits are weakened.
If both app versions need to trigger the same action, they should both call the same stored proc.  The stored proc can ensure that all the appropriate work is done, and when your app no longer needs to support V1, then that part of the stored proc can be removed.
Calling two stored procs in your client code is a bad idea, because this is an abstraction layer of data services which the database can provide easily and consistently, without your application being worried about it.
I prefer to control the interface to the underlying tables more - with either views or UDFs or SPs.  Users never get direct access to a table.  Another point here is that you could present a single "users" VIEW or UDF coalescing the appropriate underlying tables without the user even knowing about - perhaps getting to the point where there is not even any "synchronization" necessary, since new attributes are in an EAV system if you need that kind of pathological flexibility or in some other different structure which can still be joined - say OUTER APPLY UDF etc.

A: You're going to have to create some sort of loopback detection within your trigger.  Perhaps using an "if exists" statement to see if the record exists before entering it into the next table.  It does sound like it will go into an infinite loop the way it's currently set up.

A: Recursion in triggers, that is, one trigger calling another, is limited to 32 levels
In each trigger, just check if the row you wish to insert already exists.
Example
CREATE TRIGGER Table1_Synchronize_Update ON [Table1] FOR UPDATE AS
BEGIN
  UPDATE  Table2
  SET     LastName = i.LastName
          , FirstName = i.FirstName
          ,  ... -- Every relevant field that needs to stay in sync
  FROM    Table2 t2
          INNER JOIN Inserted i ON i.UserID = t2.UserID
  WHERE   i.LastName <> t2.LastName
          OR i.FirstName <> t2.FirstName
          OR ... -- Every relevant field that needs to stay in sync
END

CREATE TRIGGER Table1_Synchronize_Insert ON [Table1] FOR INSERT AS
BEGIN
  INSERT INTO Table2
  SELECT i.*
  FROM   Inserted i
         LEFT OUTER JOIN Table2 t2 ON t2.UserID = i.UserID
  WHERE  t2.UserID IS NULL
END

CREATE TRIGGER Table2_Synchronize_Update ON [Table2] FOR UPDATE AS
BEGIN
  UPDATE  Table1
  SET     LastName = i.LastName
          , FirstName = i.FirstName
          ,  ... -- Every relevant field that needs to stay in sync
  FROM    Table1 t1
          INNER JOIN Inserted i ON i.UserID = t1.UserID
  WHERE   i.LastName <> t1.LastName
          OR i.FirstName <> t1.FirstName
          OR ... -- Every relevant field that needs to stay in sync
END

CREATE TRIGGER Table2_Synchronize_Insert ON [Table2] FOR INSERT AS
BEGIN
  INSERT INTO Table1
  SELECT i.*
  FROM   Inserted i
         LEFT OUTER JOIN Table1 t1 ON t1.UserID = i.UserID
  WHERE  t1.UserID IS NULL
END

A: Avoid triggers like the plague .... use a stored procedure to add the user. If this requires some design changes then make them. Triggers are the EVIL.

A: Try something like (I didn;t bother with thecreate trigger stuff as you clearly already know how to write that part):
update t
set field1 = i.field1
field2 = i.field2
from inserted i
join table1 t on i.id  = t.id
where field1 <> i.field1 OR field2 <> i.field2


text:
Q: is there a way to pass session variable to a new tab when a link is clicked here is the link used to open  new tab feature

A:

UPDATE Including explanation from comments:
If you need to pass any variable in your URL just add ?<myVariable>=<myValue>.
To open a link in a new tab just add target="_blank" in the anchor tag.

redpajama_set_name: RedPajamaStackExchange


text:
Q: When is it appropriate to use index_scan for getting data already sorted? Is there some rule of thumb? The thing is I just came up with the issue, where index doesn't help to run query faster with its predefined sort. I have the following table tbl:
|  p_id  |   s_id  |  w_id   | amount  | currency_id |          date              |
|integer | integer | integer | numeric |   integer   | timestamp without time zone|

The table contains approximately 500k rows and I need to execute the following query on it:
SELECT p_id, s_id, w_id, amount, currency_id
FROM (
    SELECT p_id, s_id, w_id, amount, currency_id,
    ROW_NUMBER() OVER(PARTITION BY p_id, s_id, w_id ORDER BY date DESC NULLS LAST) rn
    FROM tbl
) sbt
WHERE sbt.rn = 1

Without having any indexes on the table the planner choose the following to do:
Subquery Scan on sbt  (cost=68369.47..90802.76 rows=2991 width=19) (actual time=616.402..958.030 rows=253657 loops=1)
  Filter: (sbt.rn = 1)
  Rows Removed by Filter: 344564
  ->  WindowAgg  (cost=68369.47..83324.99 rows=598221 width=27) (actual time=616.397..909.711 rows=598221 loops=1)
        ->  Sort  (cost=68369.47..69865.02 rows=598221 width=27) (actual time=616.384..642.357 rows=598221 loops=1)
              Sort Key: tbl.p_id, tbl.s_id, tbl.w_id, tbl.date
              Sort Method: quicksort  Memory: 71313kB
              ->  Seq Scan on tbl  (cost=0.00..10969.21 rows=598221 width=27) (actual time=0.038..111.827 rows=598221 loops=1)
Total runtime: 967.421 ms

and on my data it takes 7 secs averagely. I thought, that sorting is a very expensive operation so it's defenitely better to use index scan instead of seq scan + sort. But If I create an appropriate index:
CREATE INDEX text_idx
  ON tbl
  USING btree
  (p_id, s_id, w_id, date DESC NULLS LAST, currency_id, amount);

in order to do Index Only Scan the plan will be the following:
Subquery Scan on sbt  (cost=0.00..56853.58 rows=2991 width=19) (actual time=167.895..747.224 rows=253657 loops=1)
  Filter: (sbt.rn = 1)
  Rows Removed by Filter: 344564
  ->  WindowAgg  (cost=0.00..49375.82 rows=598221 width=27) (actual time=167.889..693.238 rows=598221 loops=1)
        ->  Index Only Scan using test_idx_to_drop on tbl  (cost=0.00..35915.84 rows=598221 width=27) (actual time=167.876..365.174 rows=598221 loops=1)
              Heap Fetches: 598221
Total runtime: 752.713 ms

Looks great, but it didn't help too much to improve performance. The average time of the query execution is now 6.8 secs. I started to look into I/O stats (pg_statio_user_tables, pg_stat_user_table) of the table and what I've figured out is that:
In the case of index scan here is the statistics (cold cache):
idx_scan   idx_tup_fetch   heap_blks_read    idx_blk_read
   1          598221          4987              3819

and sort+seq scan
seq_scan   seq_tup_read   heap_blks_read
   1          598221          4987

QUESTION: Is there a more-or-less short rule where to use index for sorting and where it won't be good. Is in the case of my table using index really inapropriate to avoid sorting?

A: If we compare the output for the EXPLAIN ANALYZE which additionally to the cost provides the actual timings we would see that the query from
Subquery Scan on sbt  <skipped> (actual time=616.402..958.030 rows=253657 loops=1)
<skipped>
Total runtime: 967.421 ms

has improved to
Subquery Scan on sbt  <skipped> (actual time=167.895..747.224 rows=253657 loops=1)
<skipped>
Total runtime: 752.713 ms

Which means that initial query has improved from ~616ms to ~168ms to obtain the first row, and from ~967ms to ~753ms to generate the whole data set.
As of per your observations of 7s and 6.8s to obtain the whole data set on your client is because it takes time to transfer several hundreds of thousands of rows over the network: the latency and bandwidth are finite and limited, hence bring some delays in data delivery.
Additionally to what I said I would suggest you to try to reduce the index to only p_id, s_id, w_id, date DESC NULLS LAST columns and see if the performance is still acceptable. The index-only scans topic is a bit blurry to me so I personally prefer to check it on my data set first.

A: If you are using version >= 9.3, then you can try lateral subquery:
SELECT x.*
FROM (
   SELECT DISTINCT p_id, s_id, w_id FROM tbl
) t,
LATERAL (
   SELECT p_id, s_id, w_id, amount, currency_id
   FROM tbl t1
   WHERE t1.p_id = t.p_id AND t1.s_id = t.s_id AND t1.w_id = t.w_id
   ORDER BY p_id, s_id, w_id, date DESC NULLS LAST
   LIMIT 1
) x
;

with new index only on subset of columns:
CREATE INDEX text_idx_new
  ON tbl
  USING btree
  (p_id, s_id, w_id, date DESC NULLS LAST);

Lateral subqueries are part of SQL Standard,
at the present time - as I know - they are implemented by Oracle 12c, IMB DB2, MS SQL Server and PostgreSQL 9.3.
You can find the documentation here: http://www.postgresql.org/docs/9.3/static/queries-table-expressions.html
Topic named: 7.2.1.5. LATERAL Subqueries

The lateral subquery uses ORDER BY ... LIMIT 1, and PostgreSql can use an index to optimize this kind of queries (unlucky I can't find any documentation on this topic for PostgreSql, their documentation is poor in contrast to Oracle where they have very detailed documentation on how their optimizer works).
Since your query picks only 2991 rows from among 598221, that is 0.4% (very few), so it means that there are only 2991 distinct grops, and the lateral subquery will be performed only 2991 times.
I think it worth to give it a try, because it may perform better.

You are right,  DISTINCT p_id, s_id, w_id requires data to be sorted, however there is index created on these columns, and this index contains already sorted data, so PostgreSql will only scan this index to obtain distinct groups, without sorting.


text:
Q: VLOOKUP issue in Excel I have the following basic VLOOKUP setup, having not used Excel in anger for a while. I am looking up the values a, b and C in a table containing two columns.
                                                    <value returned>     <expected>

a       1   b       =VLOOKUP(A1,C$1:D$1,1,FALSE)    #N/A                 #N/A
b       2   c       =VLOOKUP(A2,C$2:D$2,1,FALSE)    #N/A                 2
c       3   d       =VLOOKUP(A3,C$3:D$3,1,FALSE)    #N/A                 3

I am getting #N/A returned for all rows (as shown to the right), but I would expect the values to the right again to be returned. Can someone please explain what I have done wrong?
Thanks

A: When using VLOOKUP, the column containing the key to be matched has to be the first column on the left of the range.  So change your data layout to this:
A   B   C   D
a       b   1
b       c   2
c       d   3

and use the following formula:
=VLOOKUP(A1, C$1:D$3, 2, FALSE)

and then it should work.  As @Scott mentioned in his comment, if you want to keep your data layout the same, you could look into using INDEX.

A: If you still stick to dataset :
a       1   b
b       2   c
c       3   d

then : =INDEX($C$2:$C$4,MATCH(A1,$D$1:$D$3,0))
So if you re-arrange the data as :
a       2   b
b       3   c
c       4   d

then use : =INDEX($C$1:$C$3,MATCH(A1,$D$1:$D$3,0))
hope that helps. (:


text:
Q: Send Servlet action With href Link and value I'm trying to send a post method to servlet. How it works is it will check the action string which then triggers a command DeleteCommandand object in table is clicked then it takes the Id of the Reg object and deletes it from database..
so this is my servlet:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
     String action = request.getParameter("action");
    System.out.println(action);
    if (action != null) {
        Command command = new CommandFactory().createCommand(action);
        if (command != null) {
            command.execute(request, response);
        }
    }
}

This is my command Factory and the command class it would trigger based on action string:
 public Command createCommand(String actionString) {
    Command command = null;
    System.out.println(actionString);
    //Instantiate the required Command object...
    if (actionString.equalsIgnoreCase("login")) {
        command = new LoginUserCommand();
    } else if (actionString.equalsIgnoreCase("manageRegistrar")) {
        command = new ManageRegistrarCommand();
    } else if (actionString.equalsIgnoreCase("modifyReg")) {
        command = new ModifyRegistrarCommand();
    } else if (actionString.equalsIgnoreCase("logout")) {
        //command = new LogoutUserCommand();
    } else if (actionString.equalsIgnoreCase("something")) {
        //command = new ManageRegistrarCommand();
    } else if (actionString.equalsIgnoreCase("delete")) {
        command = new DeleteRegistrarCommand();
    } else if (actionString.equalsIgnoreCase("changePassword")) {
       // command = new ChangePasswordCommand();
    } else if (actionString.equalsIgnoreCase("verifyEmail")) {
        //command = new VerifyEmailCommand();
    } else if (actionString.equalsIgnoreCase("resendVerificationMail")) {
        //command = new ResendVerificationMailCommand();
    }else if(actionString.equalsIgnoreCase("modify")){
        //command = new ModifyUserCommand();
    }else if(actionString.equalsIgnoreCase("addRegistrar")){
        //command = new CreateUserCommand();
    }
    //Return the instantiated Command object to the calling code...
    return command;// may be null
}

And this is the command I'm currently trying to get the actual parameter value to:
public class DeleteRegistrarCommand implements Command {

@Override
public void execute(HttpServletRequest request, HttpServletResponse response) {
    int userId = Integer.parseInt(request.getParameter("regId"));
    //System.out.println(userIdList.get(0));
    UserServices userservice = new UserServices();
    HttpSession session = request.getSession();
    try {
        if (userId > 0) {
                Registrar registrar = userservice.getRegById(userId);
                if (userservice.delete(registrar.getRegId())) {
                    session.setAttribute("status", 0);
                    session.setAttribute("statusMessage", "Delete Success");
                } else {
                    session.setAttribute("status", 1);
                    session.setAttribute("statusMessage", "Delete Failed");
                }
        } else {
            session.setAttribute("status", 6);
            session.setAttribute("statusMessage", "Ohoooo no.. Nothing to Delete.. ha ha ha");
        }
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/ProcessResult.jsp");
        dispatcher.forward(request, response);
    } catch (ServletException | IOException ex) {
        Logger.getLogger(DeleteUserCommand.class.getName()).log(Level.SEVERE, null, ex);
        session.setAttribute("status", 4);
        session.setAttribute("statusMessage", ex.getMessage());
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/ProcessResult.jsp");
        try {
            dispatcher.forward(request, response);
        } catch (ServletException | IOException ex1) {
            Logger.getLogger(DeleteUserCommand.class.getName()).log(Level.SEVERE, null, ex1);
        }
    }

}

}
OK all of these should be working fine (Hopefully).I just have a problem on the client side (JSP Page). I'm trying to send the action type and the value needed by command to my servlet... this is what i have on my href but doesn't seem to be right.
so This is it :
            <a href="WebActionServlet?action=delete?regId=<%=deleteId%>"><samp class="glyphicon glyphicon-remove"></samp>

but this doesn't seem to be working and when i click on it i just shows me a blank page and the actual action is not performed.. Does anyone know how do perform this using the href link or is they a better way maybe java script or ajax method to be used to perform this and get id and send action based on that table data link ?
Any help is appreciated. Thanks in advance.


text:
Q: Check for undefined in javascript I have the following function :
/**
       * ParkingTime Duration, which is shown by the size of each circle/bubble.
       *
       * @param garage
       * @param res
       * @returns {*}
       */
      function getParkingDuration(garage, res) {
        var parking = res.parking;
        var parking_duration = Array();
        for (var j = 0; j < parking.length; j++) {
          if (typeof parking[j][garage].parkingtime != 'undefined') {
            parking_duration.push(parking[j][garage].parkingtime);
          } else {
            parking_duration.push(0.1);
          }
        }

        return parking_duration;
      }

if there is an undefined variable, i want to push a value to some array.
But when i check my console i still see some errors of parkingtime undefined.
Why the code is not reaching my else statement?

A: My suggestion:
  function getParkingDuration(garage, res) {
    var parking = res.parking || []; // in case res is undefined
    var parking_duration = [];
    for (var j = 0; j < parking.length; j++) {
      parking_duration[j]=0.1; // default
      if (parking[j] &&
          parking[j][garage] &&
          parking[j][garage].parkingtime) {
        parking_duration[j]=parking[j][garage].parkingtime;
      }
    }
    return parking_duration;
  }

A: first of all:
var parking = res.parking; //if res is undefined you'll get an error

second:
for (var j = 0; j < parking.length; j++) { //if parking is undefined you'll get an error

3)
if parking[j][garage] is undefined:
if (typeof parking[j][garage].parkingtime != 'undefined') { //will give error

That's more or less what you need:
function getParkingDuration(garage, res) {
        var parking_duration = Array();
        if(res && res.parking){
          var parking = res.parking;

          for (var j = 0; j < parking.length; j++) {
            if (garage && parking[j][garage] && typeof parking[j][garage].parkingtime != 'undefined') {
              parking_duration.push(parking[j][garage].parkingtime);
            } else {
              parking_duration.push(0.1);
          }
        }
      }

     return parking_duration;
  }

A: Not sure what your object structure is (I mean - whether you are not defining parkingtime or defining it as null or empty), you can try
if ( !isNaN(parking[j][garage].parkingtime) )
{
}

this should work if your parkingtime is supposed to be an Number always.
I am assuming that it always reaches inside if statement since you said

But when i check my console i still see some errors of parkingtime
  undefined.

A: you should use undefined without any string literals. So give like these
(parking[j][garage].parkingtime == undefined).

A: It look like parking[j][garage] itself is undefined.
Can you try this:
 /**
           * ParkingTime Duration, which is shown by the size of each circle/bubble.
           *
           * @param garage
           * @param res
           * @returns {*}
           */
          function getParkingDuration(garage, res) {
            var parking = res.parking;
            var parking_duration = Array();
            for (var j = 0; j < parking.length; j++) {
              if (typeof parking[j] == 'undefined') {
                  parking[j] = {};
              }
              if (typeof parking[j][garage] == 'undefined') {
                 parking[j][garage] = {};
              }
              if (typeof parking[j][garage].parkingtime != 'undefined') {
                parking_duration.push(parking[j][garage].parkingtime);
              } else {
                parking_duration.push(0.1);
              }
            }

            return parking_duration;
          }

A: Here are some things you can check quickly using console.log to see what is going on with your code

*

*Check if res.parking is defined

*Check if parking[j] is defined

*Check if parking[j][garage] is defined

*Check if parking[j][garage] has the attribute `parkingtime'

It will help you see what is defined and what isn't and help you to better address your problem.


text:
Q: Error in Decimal variable to text datatype comparison While comparing  variable with data from ADODB.Recordset  gives results as tabulated below:

*

*AssYear string variable = "2022-2023"

*rs1!FromAY     text column in mssaccess = "2020"

*typename(rs1!FromAY)                    -  Field
 Double(variable in vb6) and text(datatype in mdb)
 val(Mid(AssYear, 1, 4)) >= rs1!FromAY                   TRUE

 Decimal(variable in vb6) and text(datatype in mdb)
 cdec(Mid(AssYear, 1, 4)) >= rs1!FromAY                  FALSE

While comparing Decimal variable and text(datatype in mdb) via ADODB.Recordset  it returns false(incorrect result) but for Double variable and text(datatype in mdb) comparison it returns true.
I can't use Double due to roundoff error.
How to compare Decimal variable to text in ADODB.Recordset ?
The below methods works. what is the reason for the above error?
cdec("2022") >= cdec(rs1!FromAY)                        TRUE
cdec("2022") >= cstr(rs1!FromAY)                        TRUE

A: This works:
CDec(Mid("2022-2023", 1, 4)) >= "2020"

so try with:
CDec(Mid(AssYear, 1, 4)) >= rs1!FromAY.Value

or:
CDec(Mid(AssYear, 1, 4)) >= Val(rs1!FromAY.Value)

But no reason to use CDec here. So, as you wish to compare integer numbers, why not:
Val(Mid(AssYear, 1, 4)) >= Val(rs1!FromAY.Value)


text:
Q: Is it good practice to end coldfusion self-closing tags with "/>"? In HTML, I was always taught to close self-closing with a "/>". For example "
", "<input type='button' value='myButton' />", etc.
In Coldfusion, though, it seems to be standard to just never close these tags. I'm constantly seeing code like:
<cfset myVariable = someValue>
<cfset myOtherVariable = someOtherValue>

etc.
Is this bad code, or is it commonly accepted? I've seen it almost anywhere that I've seen coldfusion code. Is there any benefit to closing these tags, or is it fine to leave it as it is?

A: Because there's no official coding standard for CFML, it's up to you whether to use these. Same as using uppercase/lowercase tags.
Personally I love to have my code beautiful and readable, so I'm always using this syntax for single tags.
But there is at least one techincal difference: custom tags. Let me show this by example.
Consider following custom tag:
<cfif thisTag.ExecutionMode EQ "start">
    started

</cfif>

running

<cfif thisTag.ExecutionMode EQ "end">
    ended

</cfif>

Now these two types of invokation:

<cf_demo>

<cf_demo>

<cf_demo />

<cf_demo />

And here's the output:
<cf_demo>
started
running

<cf_demo />
started
running
running
ended

Second syntax is equivalent of <cf_demo></cf_demo>.
Possibly there are more differences, but I can't remember any at this moment... :)

A: It doesnt matter, it is also not necessary in html unless it is xhtml.

A: I agree with the last comment.
I hate those single tag closes.
It's pointless and not a coding standard for CFML.
It started appearing when xml became popular due to it's strict tag syntax and people assuming it was correct for CFML. CFML isn't HTML. Treating it as such is really in itself lazy coding. I also think it looks more beauiful without the unnecessary closing /> :)
but that's me for you.
I also dislike {} spread on to new lines for each bracket. I guess it's just personal preference.

A: I never used to use the /> until i started using Dreamweaver CC and the auto close only works if you close the tags somehow


text:
Q: Laravel eloquant collection - unable to convert it to valid json I have one laravel eloquant object which i want to convert to JSON to store in MySQL database, i am using below code to convert
Order::create(['product' => json_encode($cart->product, true)]);

I also tried below
Order::create(['product' => $cart->product->toJson()]);

This code is storing perfectly but with seems invalid json format like below
"{\"id\": 5,\"name\": \"CAPSTER CAP\",\"description\": \"This is the\"}"

but it should be like below
{"id": 5,"name": "CAPSTER CAP","description": "This is the"}

A: You should need to create a text or longText datatype column in MySQL database.
Then save JSON as a string like this.
Order::create(['product' => json_encode($cart->product->toArray()) ]);

A: You need to change your migration class's structure. Use json data type for the model class e.g
 Schema::create('orders', function (Blueprint $table) {
     $table->increments('id');
     $table->json('product')->nullable();
     $table->timestamps();
 });


text:
Q: Polya's urn model - limit distribution Let an urn contain $w$ white and $b$ black balls. Draw a ball randomly from the urn and return it together with another ball of the same color. Let $b_n$ be the number of black balls and $w_n$ the number of white balls after the $n$-th draw-and-replacement. Let $X_n$ be the relative proportion of white balls after the $n$-th draw-and-replacement.
I start with $b=w=1$, so the total number of balls after the $n$-th draw-and-replacement is $n+2$.
Now I want to find the limit distribution of $X_n$; I already showed that $X_n$ is a martingale and that it converges a.s.
It is
$$X_n = \dfrac{w_n}{n+2} \quad\text{for}\quad n \in \mathbb{N}_0. $$
I've read that the limit distribution is a beta distribution, but I don't know how to get there.
I could write $w_n$ as the sum of $Y_i$ where $Y_i$ is $0$, if the $i$-th ball is black and $1$, if the $i$-th ball is black. Then I'd have
$$ w_n = 1+\sum_{i=1}^{n} Y_i. $$
Does this help? How can I proceed?
Thanks! :)

A: Suppose that we have started with $w$ white balls and $b$ black balls. Then
\begin{align*}
\mathbb{P}(w_n = w+k)
&= \binom{n}{k} \frac{w(w+1)\dots(w+k-1)b(b+1)\dots(b+n-k-1)}{(w+b)(w+b+1)\dots(w+b+n-1)} \\
&= \frac{1}{B(w, b)} \binom{n}{k} \frac{\Gamma(w+k)\Gamma(b+n-k)}{\Gamma(w+b+n)} \\
&= \frac{1}{B(w, b)} \frac{k^{w-1} (n-k)^{b-1}}{n^{w+b-1}} \frac{E_k(w)E_{n-k}(b)}{E_n(b+w)} ,
\end{align*}
where $\Gamma(\cdot)$ is the gamma function, $B(\alpha, \beta) = \frac{\Gamma(\alpha)\Gamma(\beta)}{\Gamma(\alpha+\beta)}$ is the beta function, and
$$ E_n(z) := \frac{\Gamma(n+z)}{n!n^{z-1}}. $$
Note that $E_n(z) \to 1$ as $n\to\infty$. So, if we write $p_k = k/n$, then the m.g.f. of $X_n$ is explicitly given by
\begin{align*}
\mathbb{E}[e^{\lambda X_n}]
= \frac{1}{B(w, b)} \sum_{k=0}^{n} \exp\biggl( \lambda \frac{p_k + w/n}{1 + (w+b)/n} \biggr) p_k^{w-1}(1 - p_k)^{b-1} \frac{1}{n} \cdot \frac{E_k(w)E_{n-k}(b)}{E_n(b+w)}.
\end{align*}
Letting $n \to \infty$, this converges to
\begin{align*}
\mathbb{E}[e^{\lambda X_{\infty}}]
= \frac{1}{B(w, b)} \int_{0}^{1} e^{\lambda p} p^{w-1}(1 - p)^{b-1} \, \mathrm{d}p.
\end{align*}
From this, we read out that the distribution of $X_{\infty}$ has the density
$$ f(p) = \frac{1}{B(w, b)} p^{w-1}(1 - p)^{b-1} \mathbf{1}_{(0,1)}(p), $$
proving that the limit distribution is $\operatorname{Beta}(w, b)$.

A: Refer to this?

Assuming $B_n$ is uniform on $\{0,1,...,n\}$ (proven by induction):
$$M_{\Theta}(t) = E[\exp(t\Theta)]$$
$$= E[\exp(t\lim \frac{B_n + 1}{n+2})]$$
$$= E[\lim\exp(t \frac{B_n + 1}{n+2})]$$
$$= \lim E[\exp(t \frac{B_n + 1}{n+2})]$$
$$= \lim \frac{1}{n+1}[\exp(t \frac{1}{n+2}) + \exp(t \frac{2}{n+2}) + ... + \exp(t \frac{n+1}{n+2})]$$
Case 1: $t \ne 0$
$$= \lim \frac{a(n)}{(n+1)(1-a(n))} (1-a(n)^{n+1}), \ \text{where} \ a(n) := e^{\frac{t}{n+2}}$$
$$= \lim \frac{a(n)}{(n+1)(1-a(n))} \lim (1-a(n)^{n+1})$$
$$= \lim \frac{a(n)}{(n+1)(1-a(n))} (1-e^t)$$
$$= \frac{1-e^t}{-t}$$
$$= \frac{e^t-1}{t}$$
Case 2: $t = 0$
$$= \lim \frac{1}{n+1}[\exp((0) \frac{1}{n+2}) + \exp((0) \frac{2}{n+2}) + ... + \exp((0) \frac{n+1}{n+2})]$$
$$= \lim \frac{1}{n+1} (1)(n+1) = 1$$
This is the mgf of $Unif(0,1)$


text:
Q: Pattern Search between specific lines and print line numbers I have a file of 20 lines. I want to search for a string between the lines 10 and 15 and print the string along with the line numbers of the original file.
I have tried sed -n 10,15p file | grep -n "pattern"
The problem with the above command is, the output line number 10 of sed will be line number 1 for grep.
Hence it is not printing the line numbers from the original file.

A: When working w/ sed I typically find it easiest to consistently narrow my possible outcome. This is why I sometimes lean on the !negation operator. It is very often more simple to prune uninteresting input away than it is to pointedly select the interesting kind - at least, this is my opinion on the matter.
I find this method more inline with sed's default behavior - which is to auto-print pattern-space at script's end. For simple things such as this it can also more easily result in a robust script - a script that does not depend on certain implementations' syntax extensions in order to operate (as is commonly seen with sed {functions}).
This is why I recommended you do:
sed '10,15!d;/pattern/!d;=' <input

...which first prunes any line not within the range of lines 10 & 15, and from among those that remain prunes any line which does not match pattern. If you find you'd rather have the line number sed prints on the same line as its matched line, I would probably look to paste in that case. Maybe...
sed '10,15!d;/pattern/!d;=' <input |
paste -sd:\\n -

...which will just alternate replacing input \newlines with either a : character or another \newline.
For example:
seq 150 |
sed '10,50!d;/5/!d;=' |
paste -sd:\\n -

...prints...
15:15
25:25
35:35
45:45
50:50

A: Using nl:
nl file | sed -n '10,15{/pattern/p
}'

A: Here is an awk solution:
awk '10<=NR && NR<=15 && /pattern/ {print NR,$0}' file

If we must use only sed, then consider:
sed -n '10,15 {/pattern/ {=;p}}' file | sed 'N;s/\n/ /'

sed's = command will only print the line number on a separate line.  The second instance of sed above is used to combine every two lines so that the line number appears just before its line.


text:
Q: 100% height active link within a td - Responsive table design - IE I am currently making a responsive table with html and css. I have it working perfectly in all browsers except for IE, and this is any version of IE including 10. I only need it to work for IE 8,9 and 10.
The TD's within the table are 100% height in all browsers but the active links within the TD's do not work in IE. If you see the js fiddle below you can see the current day's background colour should fill the TD and it does not in IE. Does anyone know how to fix this? Any help is much appreciated. Below is a link to the js fiddle, the table styles and the active link within the td of the table
.compact_month_view {
    background-color: white;
    border-collapse: collapse;
    height: 100%;
    position: relative;
    table-layout: fixed;
}

.day_cell a {
    background: none repeat scroll 0 0 #FFFFFF;
    color: #CCCCCC;
    display: inline-table;
    height: 100%;
    line-height: 100%;
    overflow: hidden;
    position: relative;
    text-align: center;
    width: 100%;
}

http://jsfiddle.net/LtHFK/

A: Give height for td - .compact_month_view td


text:
Q: How to password protect a file without using software in windows 7 How can I have
important.txt
require the password
1qaz2wsx3edc4rfv
without using software in Windows 7 home premium?

A: You cannot encrypt a text file without using external software such as TrueCrypt etc.
I'd recommend converting it either to a password protected PDF or doc file.
See this link:

The truth is that you really cannot encrypt a .txt file via the file menu or any other sub-menu...

Also, you can make an encrypted disk image and put any file in that container. See this link on how to accomplish that.


text:
Q: How to change the datum description of GeoTIFF in GDAL? I have found coordinate system discrepancies in my raster datasets.
Using gdalinfo 6 out of 500 of my images show the OGC WKT datum definition:
     GEOGCS["ETRS89",
        DATUM["European_Terrestrial_Reference_System_1989",
            SPHEROID["GRS 1980",6378137,298.2572221010042,
        AUTHORITY["EPSG","7019"]],
        AUTHORITY["EPSG","6258"]],

...whereas all the others have the datum defined in the ESRI WKT way, i.e
    PROJCS["ETRS_1989_UTM_Zone_32N",
        GEOGCS["GCS_ETRS_1989",
        DATUM["ETRS_1989",
            SPHEROID["GRS_1980",6378137,298.257222101]],
        PRIMEM["Greenwich",0],
        UNIT["degree",0.0174532925199433]],

In order to do further processing in GDAL I need to create a VRT file. However GDALBUILDVRT fails due to this above discrepancy.
I have tried defining the coordinate system for the 6 files with the ESRI "define coordinate system" Tool and also the "Reproject" tool, but GDALINFO still displays the same datum information.
I have also tried defining and setting the coordinate system with SAFE FME, but to no avail.
GDAL_Edit also has no effect even when with the -unsetgt flag.
SO how can I change the definition?


text:
Q: Simple ASP form validation - swapped? I am trying to do some very simple form validation checking for null or '' (empty) using a conditional, but when I submit my form with ALL BLANK FIELDS, it does the latter section of my code.
And when I fill out all of my fields it does that other part. So when they are blank, tell the user, which is the first section of the conditional, I have pasted my code below. Any suggestions on what I can do? Is it my "OR" or "AND"
if(((f_name <> null) or (f_name <> "")) or ((l_name <> null) or (l_name <> "")) or ((username <> null) or (username <> "")) or ((password <> null) or (password <> ""))) then
    'response.redirect("account_created.asp")
    response.write("You have not filled in all fields.")
else
    Set objConn = ConnectDB()
    query       = "INSERT INTO [user] (username,[password],f_name,l_name) VALUES ('"& username &"','"& password &"','"& f_name &"','"& l_name &"')"
    Set objs    = objConn.Execute(query)
    response.write(query)
    'Response.Redirect ("thankyou.asp")

end if

A: In general it should be sufficient to check for empty string (such as f_name <> "").  I however usually do this with a trim and len. len(trim(f_name)) > 0.  It takes care of all spaces.  You should reconsider your parenthesis since they are not necessary.
if len(trim(f_name)) > 0 or ... then

A: *

*you do not need all the parentheses

*if fname et al are the textboxes, you need fname.Text instead


text:
Q: submit button is not working in simple html form - flask server My Submit Button in HTML/CSS/JS is not working.
Here I attached HTML code
However, I tested my flask server in postman but in simple HTML form submit button is not working!
is it something that is I missed in HTML or in JS ?
Please help me with this problem.

<!DOCTYPE html>

        <title>Banglore Home Price Prediction</title>

        <link rel="stylesheet" href="app.css">

    <form class="form">

Area (Square Feet)

        <input class="area"  type="text" id="uiSqft" class="floatLabel" name="Squareft" value="1000">

BHK

            <input type="radio" id="radio-bhk-1" name="uiBHK" value="1"/>
            1
            <input type="radio" id="radio-bhk-2" name="uiBHK" value="2" checked/>
            2
            <input type="radio" id="radio-bhk-3" name="uiBHK" value="3"/>
            3
            <input type="radio" id="radio-bhk-4" name="uiBHK" value="4"/>
            4
            <input type="radio" id="radio-bhk-5" name="uiBHK" value="5"/>
            5

    </form>
    <form class="form">

Bath

            <input type="radio" id="radio-bath-1" name="uiBathrooms" value="1"/>
            1
            <input type="radio" id="radio-bath-2" name="uiBathrooms" value="2" checked/>
            2
            <input type="radio" id="radio-bath-3" name="uiBathrooms" value="3"/>
            3
            <input type="radio" id="radio-bath-4" name="uiBathrooms" value="4"/>
            4
            <input type="radio" id="radio-bath-5" name="uiBathrooms" value="5"/>
            5

Location

      <select class="location" name="" id="uiLocations">
        <option value="" disabled="disabled" selected="selected">Choose a Location</option>
            <option>Electronic City</option>
            <option>Rajaji Nagar</option>
      </select>

        <button class="submit" onclick="onClickedEstimatePrice()" type="button">Estimate Price</button>

A: you need to add action and method to your form tag like:

<form class="form" method="get" action="/your_url/">
....
</form>

A: If you want to you the default handling of form submitting, you would need to add the method (check your postman call to see the method) and action (the URL you used to test the call in postman) attributes to your form, as well as changing the type of button to submit rather than button.
But since you passed on onclick handler to your button, I assume you want to do  a custom submit handler. Your best bet is to add an onsubmit handler to your form and do the logic there. No need for method and action here.
<form class="form" onsubmit="onFormSubmit(event)">
...
function onFormSubmit(event) {
    event.preventDefault(); // disable default behavior of submitting
    // access form element values
    // replace elementName with the actual value of the "name" attribute
    // remember to assign unique names to the elements
    console.log(event.target.elements.[elementName].value);
}


text:
Q: Can't find 'Master Detail Forms App' option in Xamarin Forms? I'm following a tutorial online on Xamarin Forms, and I was told to select a 'master detail forms app'. The unfortunate thing is, is that I can't find this option for a 'master detail forms' app in the tab below:

Maybe I haven't installed something?
Thanks,

A:
Can't find 'Detail Forms App' option in Xamarin Forms?

For Visual Studio 2019, the old Detail Forms template has been replaced with flyout template, if you do want to make Detail app and contains uwp platform, please try make Xamarin app with Visual Studio 2017.


text:
Q: Git commands with credentials and repo I using this git commands to keep the session open for futures git commands using this
sh "git config --local user.name \"${USER}\""
sh "git config --local user.name \"${USER}@hsbc.uk.co\""
sh "git remote set-url origin \"https://${USER}:${PASS}@${GIT_REPO_NAME_P}\""

Then I can do just
    sh "git checkout master"
    sh "git pull origin master"

But now, since I'm working in parallel with another repo, I need to lock the use of config/remote. I would rather just use the commands
    sh "git checkout master"
    sh "git pull origin master"

Passing the username/password and repo, to avoid the lock if it is possible.
Rehards.


text:
Q: Accepting that $\lim_{x\to\infty}f(x) = +∞$ prove that $\lim_{n\to\infty}\frac{n^\delta}{\ln^\gamma n} = +\infty$ I have the following problem to prove.

Let $\gamma, δ \in \mathbb{R}^\ast_+$ and
  $f\colon \mathbb{R}^\ast_+\to \mathbb{R}$
  defined by $f(x) = \delta x − \gamma\ln x$.
Accepting that $\lim_{x\to+\infty }f(x) = +\infty$ prove that
  $\lim_{n\to\infty} \frac{n^\delta}{\ln^\gamma n}  = +\infty$.

The following substitution is true:
$$n^\delta=e^{\delta\ln n}$$
Any hint, suggestion or solution is welcomed.
Thank you

A: So you must show that $g(n)\stackrel{\rm def}{=}\frac{n^\delta}{(\ln n)^\gamma} \xrightarrow[n\to\infty]{} \infty$, with $\delta,\gamma > 0$.
This is equivalent to showing that $\ln g(n) \xrightarrow[n\to\infty]{} \infty$ (can you see why?).
But $\ln g(n) = \delta \ln n - \gamma\ln \ln n = f(\ln n)$. Use your hypothesis now.

A: Hint: Consider
$$
e^{f(x)}=e^{\delta x-\gamma\ln x}.
$$
Choose $x=\ln n$, then
$$
e^{f(x)}=e^{\delta x-\gamma\ln x}=e^{\delta\ln n-\gamma\ln \ln n}=\frac{e^{\delta\ln n}}{e^{\gamma\ln \ln n}}=\frac{n^\delta}{(\ln n)^\gamma}.
$$
Since $n\rightarrow \infty$, $\ln n\rightarrow\infty$ and so you can relate what you have to $\lim_{x\rightarrow\infty}e^{f(x)}$.


text:
Q: Image not uploaded wrong file I am trying to upload image in backend but i am getting below error in admin.
I am not handling to debug php code and only familiar with html/css + basics js and many modules are already installed in default system  so don't know where the exactly the issue is might be fileuploader.php file.

So if anyone has idea about patch work or quick fix then it would be helpful.I am in windows system. I don't want to fix it in proper way but i need some patch so i can later revert that patch.|
I already tried deleting pub/media gave permission to them but it seems not an issue.
I have checked in console and got below

A: I have temporarily fixed it by changing in magento core Gd2.php file line no 96 by adding one more if condition
private function validateURLScheme(string $filename) : bool
    {
        $allowed_schemes = ['ftp', 'ftps', 'http', 'https'];
        $url = parse_url($filename);
        if ($url && isset($url['scheme']) && !in_array($url['scheme'], $allowed_schemes) && !file_exists($filename)) {
            return false;
        }

        return true;
    }

vendor\magento\framework\Image\Adapter\Gd2.php as suggested in this answer
Wrong file in vendor/magento/framework/Image/Adapter/Gd2.php:64 when i install magento 2.3
I don't know if it is proper way or not but at-least it works and now i am able to upload image in the backend in my windows system.


text:
Q: How to get and compare data type for all the values for similar columns in two dataframes in pyspark I have two files with the same column names. I created two data frames by reading these CSV files. Consider a column named Units Sold. By default, its data type is a string when I checked the schema. Now, I want to iterate through each row of data for this column in both the data frames and check whether the data type is correct or not.
If a column is numeric in one file then it should be the same in the second one if one file is having value as 345 and another is having 345.00 then highlight since the data type is different over here. I tried below thing but this very generic:
types1=[df1.dtypes]
#print(types1)
types2 =[df2.dtypes]
#print(types2)

if(types1==types2):
    print("Data types is equal for both the files..")
else:
    print("Data types is NOT equal for both the files..")

Below is the column and sample data:
Units Sold
8446
3018
1517
3322
9845
9528

I didn't find any relevant posts for my problem. Any help is appreciated.

A: I had the same issue and had to loop over the columns. the problem I had is that some numeric columns were sometimes read as a string because of an NA value indicator.
here is my code chunck to check types (I assume that the 2 dataframes have the same columns with exactly the same names) I also tweaked it to have the same output as you :
df1_types = pd.DataFrame(df1.dtypes,columns=["colname", "type"])
df2_types = pd.DataFrame(df2.dtypes,columns=["colname", "type"])
flag = True
for index, row in df1_types.iterrows():
    if row['type'] != df2_types[df2_types['colname'] == row['colname']]['type'].values[0]:
        # Add numeric check here if needed
        flag = False
        break
if flag:
    print("Data types is equal for both the files..")
else:
    print("Data types is NOT equal for both the files..")

You have to add some custom check for numeric columns in the commented zone.


text:
Q: Add Custom Text Value to BarChart AChartEngine I want to have a different textvalue on top of my barchart. The value is different because i want a logarithmic kind of scaling. How can I achieve this?
Many thanks.
I searched for other questions but all those questions are older than a year and I can't find any up to date information:(
New exception after adding series.addAnnotation(...);
code
public GraphicalView getView(Context context, List<Double> height, List<String> text, List<String> time) {

    XYSeries series = new XYSeries(null);
    for(int i = 0; i < height.size(); i++) {
        series.add(i, height.get(i));
        series.addAnnotation(text.get(i), (double) i, height.get(i));
    }
    XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
    dataset.addSeries(series);

    XYSeriesRenderer renderer = new XYSeriesRenderer();
    //renderer.setDisplayChartValues(true);
    renderer.setColor(Color.parseColor("#3399cc"));

    XYMultipleSeriesRenderer mRenderer = new XYMultipleSeriesRenderer();
    mRenderer.addSeriesRenderer(renderer);

    ...

Exception
    06-11 13:49:49.256: E/AndroidRuntime(18424): FATAL EXCEPTION: main
    06-11 13:49:49.256: E/AndroidRuntime(18424): java.lang.NullPointerException
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at org.achartengine.chart.XYChart.draw(XYChart.java:305)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at org.achartengine.GraphicalView.onDraw(GraphicalView.java:168)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at android.view.View.draw(View.java:13776)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at android.view.View.getDisplayList(View.java:12727)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at android.view.View.getDisplayList(View.java:12771)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at android.view.View.draw(View.java:13500)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at android.view.ViewGroup.drawChild(ViewGroup.java:3171)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3041)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at android.view.View.getDisplayList(View.java:12725)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at android.view.View.getDisplayList(View.java:12771)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at android.view.View.draw(View.java:13500)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at android.view.ViewGroup.drawChild(ViewGroup.java:3171)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3041)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at android.view.View.getDisplayList(View.java:12725)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at android.view.View.getDisplayList(View.java:12771)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at android.view.View.draw(View.java:13500)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at android.view.ViewGroup.drawChild(ViewGroup.java:3171)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3041)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at android.view.View.draw(View.java:13779)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at android.widget.FrameLayout.draw(FrameLayout.java:467)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at android.widget.ScrollView.draw(ScrollView.java:1821)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at android.view.View.getDisplayList(View.java:12727)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at android.view.View.getDisplayList(View.java:12771)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at android.view.View.draw(View.java:13500)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at android.view.ViewGroup.drawChild(ViewGroup.java:3171)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3041)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at android.view.View.draw(View.java:13779)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at android.view.View.getDisplayList(View.java:12727)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at android.view.View.getDisplayList(View.java:12771)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at android.view.View.draw(View.java:13500)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at android.view.ViewGroup.drawChild(ViewGroup.java:3171)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3041)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at android.view.View.draw(View.java:13779)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at android.widget.FrameLayout.draw(FrameLayout.java:467)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at android.view.View.getDisplayList(View.java:12727)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at android.view.View.getDisplayList(View.java:12771)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at android.view.View.draw(View.java:13500)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at android.view.ViewGroup.drawChild(ViewGroup.java:3171)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3041)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at android.view.View.getDisplayList(View.java:12725)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at android.view.View.getDisplayList(View.java:12771)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at android.view.View.draw(View.java:13500)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at android.view.ViewGroup.drawChild(ViewGroup.java:3171)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3041)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at android.view.View.draw(View.java:13779)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at android.widget.FrameLayout.draw(FrameLayout.java:467)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at com.android.internal.policy.impl.PhoneWindow$DecorView.draw(PhoneWindow.java:2420)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at android.view.View.getDisplayList(View.java:12727)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at android.view.View.getDisplayList(View.java:12771)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at android.view.HardwareRenderer$GlRenderer.draw(HardwareRenderer.java:1144)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at android.view.ViewRootImpl.draw(ViewRootImpl.java:2278)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at android.view.ViewRootImpl.performDraw(ViewRootImpl.java:2150)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1961)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1115)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4526)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:725)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at android.view.Choreographer.doCallbacks(Choreographer.java:555)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at android.view.Choreographer.doFrame(Choreographer.java:525)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:711)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at android.os.Handler.handleCallback(Handler.java:615)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at android.os.Handler.dispatchMessage(Handler.java:92)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at android.os.Looper.loop(Looper.java:137)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at android.app.ActivityThread.main(ActivityThread.java:4921)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at java.lang.reflect.Method.invokeNative(Native Method)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at java.lang.reflect.Method.invoke(Method.java:511)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
    06-11 13:49:49.256: E/AndroidRuntime(18424):    at dalvik.system.NativeStart.main(Native Method)

A: The option you have is related to annotations. Add one for each bar, like this:
series.addAnnotation("text", x, y);


text:
Q: small folders icon in my Windows 7 are corrupted Firstly, see the following picture:

As you saw, all those are folders, and this problem happens when changing the icons view to (small icons, list and details), but when change the icons view to the large icons like (tiles, medium icons and large icons) the problem does not occur.
That problem happened after changing the default folders icon from the registry as follows:

But after that, I have retrieved everything as it was, but unfortunately, this problem occurred.
What I have tried:

*

*I have deleted the IconCache.db file.

Now, how can I retrieve all folder icons to the default icon?


text:
Q: react selectors, handle onload state and onclick together I'm trying to understand selectors in react with ReSelect, it's ok for now but i think something wrong with my logic.
1 - After ajax request, i get a list of "categories", with id, name and selected
2 - I'm using this list to create tags, when i click one of them, it change this parameter "selected" (true/false).
3 - Every "categories" are into a "product" which i can select with a dropdown.
Ok until now everything is working perfectly.
onChange from my dropdown, i update my "product" states like that :
{fetching: false, items: [], selected: {}}

*

*with the help of a selector, when the selected product change, i filter my categories to match my selection :

import {
    createSelector
} from 'reselect';

const getSelectedProduct = state => state.products.selected;
const getCategories = state => state.categories;

export const filterByProducts = () => {
    return createSelector(
        getSelectedProduct,
        getCategories,
        (mp, categories) => {

            if (mp && typeof mp === 'object') {
                const mpCategories = mp.categories.split(',');

                categories.items.map(item => {
                    item.selected = mpCategories.indexOf(item.id) >= 0;
                    return item;
                });
            }

            return categories;
        }
    )
}

When i change my product, it will update every selected categories, that's what i want.
But onClick to a tag, i update categories states too :

export const selectCategory = category => {
    return (dispatch, getState) => {
        const state = getState();

        if (state.categories) {
            let categories = state.categories.items;

            categories.map(item => {
                if (item.id === category) {
                    item.selected = !item.selected;
                }
                return item;
            });

            dispatch(receiveCategories(categories));
        }
    }
}

The code is working, but because i changed states onClick, the selector will loop through every categories and make is matching again, but i would like to avoid that.
onChange product, selector will execute (good)
onClick category, because of the new states made in my action.js, selector will run another time (not good).
I was thinking about to merge 2 selectors instead of making an action call, but i'm not sure about it...
If you have some advices, it would be great :)
Thank you !

A: Ok, so i found something simple.
I created a new var called "selection" into my 'categories' actions to handle my selections (onclick tags).
Instead of watching state.categories, i only watch state.categories.items, so my "filterByProduct" will not update every time.
Then i created a new selector called 'updateSelectedCategories', which is watching 'filterByProduct' and state.categories.selection.
So, when i change my product, 'filterByProduct' and 'updateSelectedCategories' will update.
When i change a category, only 'updateSelectedCategories' will update, so i don't love my previous matching.
Here the code :

import {
    createSelector
} from 'reselect';

const getSelectedProduct = state => state.products.selected;
const getCategories = state => state.categories.items;
const getSelection = state => state.categories.selection;

const filterByProduct = createSelector(
    getSelectedProduct,
    getCategories,
    (mp, categories) => {

        if (mp && typeof mp === 'object') {
            const mpCategories = mp.categories.split(',');

            categories.map(item => {
                item.selected = mpCategories.indexOf(item.id) >= 0;
                return item;
            });
        }

        return categories;
    }
);

export const updateSelectedCategories = createSelector(
    filterByProduct,
    getSelection,
    (categories, selection) => {

        if (selection.length > 0 && typeof selection === 'object') {
            categories.map(item => {
                if (selection.indexOf(item) >= 0) {
                    item.selected = true;
                }
                return item;
            });
        }

        return categories;
    }
);


text:
Q: how to terminate rest request gracefully I want to terminate rest request coming to server without further processing if input params are missing.
Currently this is the implementation, which I think is not very good for verify_required_params().
I want to terminate this request without returning any value from verify_required_params() in case of missing params. else flow should continue.
Running this on flask server and open to include any new package for best/ optimized approach.
Can please someone suggest an optimize way for this?
@app.route('/is_registered', methods=['POST'])
def is_registered():
    _json = request.get_json()
    keys = _json.keys()
    customer = Customer()

    if verify_required_params(['mobile'], keys) is True:
        _mobile = _json['mobile']

        validated = validate_mobile(_mobile)
        registered = customer.find(_mobile)

        if not validated:
            response = get_response('MOBILE_NUMBER_NOT_VALID')
            return jsonify(response)

        if not registered:
            response = get_response('MOBILE_NUMBER_NOT_REGISTERED')
            return jsonify(response)

        response = get_response('MOBILE_NUMBER_REGISTERED')
        return jsonify(response)

    else:
        return verify_required_params(['mobile'], keys)

def verify_required_params(required, received):
    required = set(required)
    received = set(received)
    missing = list(sorted(required - received))

    data = {"missing_key(s)": missing}

    # response = app.response_class(
    #     response=json.dumps(data),
    #     status=200,
    #     mimetype='application/json'
    # )

    if missing:
        return jsonify(data)
    return True

A:  You say it works in a RESTful way, then your errors come back as 200 OK
In REST, your URL should encode all the information about your entity. In your case, you are identifying a client by their phone number, and you are getting rather than updating information about them, so your endpoint should look like GET /client/<phonenumber>/registered. That way, a request can't not provide this information without going to a different endpoint.
In short, your code will be replaced with:
@app.route('/client/<mobile>/registered', methods=['GET'])
def is_registered(mobile):
    if not mobile.is_decimal():
        return jsonify({'error': 'mobile is not number'}), 400  # Bad Request
    customer = Customer()
    registered = bool(customer.find(mobile))
    # does it make sense to have a customer who is not registered yet?
    # if not, use:
    if not registered:
        return jsonify({'error': 'client not found'}), 404  # Not Found

    validated = validate_mobile(mobile)
    return jsonify( {'validated': validated, 'registered': registered} )

In addition, it's better to have the validation function be a decorator. That way it gets called before the actual business logic of the function. For your example of checking whether request.get_json() contains the proper fields, this is how it would look like:
import functools

def requires_fields(fields):
    required_fields = set(fields)

    def wrapper(func):
        @functools.wraps(decorated)
        def decorated(*args, **kwargs):
            current_fields = set(request.get_json().keys())
            missing_fields = required_fields
            if missing_fields:
                return jsonify({'error': 'missing fields', 'fields': list(missing_fields)}), 400  # Bad Request
            resp = func(*args, **kwargs)
            return resp
    return wrapper

# usage:

@app.route('/comment', methods=['POST'])
@requires_fields(['author', 'post_id', 'body'])
def create_comment():
    data = request.get_json()
    id = FoobarDB.insert('comment', author=data['author'], post_id=data['post_id'], body=data['body'])
    return jsonify({'new_id': id}), 201  # Created

If you must leave it the way it is now, then in order to not return data from the validation function, you must raise an HTTPException. The default function to do it is flask.abort(code).


text:
Q: My website looks slighty different on my phone compared to my computer I edited css of my website to make it responsive, but it looks completly different on my phone compared to my computer.
This is a screenshot from built-in firefox responsive design view
This one comes from my phone. It looks more stretched, especially when you look at text
CSS code that is responible for page responsibility:
@media screen and (max-width:1300px) {

  .wrapper {
    width: 100%;
  }

  .header {
    width: 100%;
    padding: 40px 0;
  }

  .logo {
    zoom: 0.7;
    -moz-transform: scale(0.7);
    padding: 30
    margin-left: auto;
    margin-right: auto;
  }

  .logo > img {
    margin-left: auto;
    margin-right: auto;
  }

  .nav {
    width: 100%;
    /*font-size: 60px;*/
    padding: 10px 0;
    background-color: #30415d;
    text-align: center;
    border-top: 1px solid #8eaebd;
    border-bottom: 1px solid #8eaebd;
  }

  ol {
    padding: 0;
    margin: 0;
    list-style-type: none;
    font-size: 20px;
    height: auto;
    line-height: 200%;
    display: inline-block;
  }

  ol > li {
    float: left;
    width: 150px;
    /*height: 50px;*/
    border-right: 1px solid #8eaebd;
  }

  .content {
    width: 95%;
    margin-top: 30px;
    margin-bottom: 30px;
    margin-left: auto;
    margin-right: auto;
    text-align: justify;
    padding-top: 10px;
  }

  .socials {
    width: 100%;
    text-align: center;
    background-color: #292929;
  }

  .socialdivs {
    width: 100%;
    margin-left: auto;
    margin-right: auto;
  }

  .fb {
    width: 25%;
    height: 155px;
    float:left;
  }

  .yt {
    width: 25%;
    height: 155px;
    float:left;
  }

  .tw {
    width: 25%;
    height: 155px;
    float:left;
  }

  .gplus {
    width: 25%;
    height: 155px;
    float:left;
  }

  .

}

I tried to increase the font to look bigger on phone screen with no effect. I also tried to add <br> tag to separate this sentence but text still looks to small on phones.

A: Try adding this to your html head
<meta name="viewport" content="width=device-width, initial-scale=1.0">

A meta viewport element gives the browser instructions on how to control the page's dimensions and scaling.
The width=device-width part sets the width of the page to follow the screen-width of the device (which will vary depending on the device).
The  part sets the initial zoom level when the page is first loaded by the browser.


text:
Q: TYPO3 - Error 500 in right panel of Filelist Friend gave me access to TYPO3 CMS of his page to make some changes and I can not open Filelist.
The left panel with directories is displaying but on the right, a have error 500 message in IE or in Chrome just empty frame.
I did some modifications to that page some time ago and everything was working fine then.
Can anyone help me with that ?

A: If a folder contains to much files you might get problems opening it in the file list module, as the gathering of all information and maybe creating of preview thumbnails may take longer than is granted to any php process.
If it's only the preview images you might be able to load the folder after some attempts, as sometime all preview images are generated, but as it also can be other delays because of too much files you need to enhace the runtimelimit
or/and you might need to restructure the files and folders.
Be aware that a moving of files with FTP/SSH might break content in the FE as you might invalidate some FAL (sys_file) records so that used files are not found any more. Better: enhance the timeout (temporarily) and move the files in the backend.
in general: if you only got a blank page you disabled all error-messages (which is ok for FE, but will leave you without hint about errors).
As a first start you could take a look in the webserver-error-log.
If you got no clues: enable errormessages in TYPO3 Install Tool (enable debug mode in "Configuration presets")

A: Ok.
I solved that.
I disabled that extension and then when I looked at maintenance tab on this extension i saw  something like "delete LOCAL installation of this ext".
After deleting local installation and enabling system FileList instance, everything is working just fine :)
Thank You for help.


text:
Q: How to create a function in bashrc to accept arguments? I would like to have an alias in my bashrc file to append the argument passed to it from terminal. For example:
$ lh300

calls:
alias lh3000='open http://localhost:3000'

However, if I type:
$ lh8080
or lh followed by any number:
$ lh####

I would like to call a function that appends the #### into an alias that will
'open http://localhost:####'

How can I do this?

A: A questionable hack involving command_not_found_handle:
command_not_found_handle () {
    if [[ $1 =~ lh([[:digit:]]+) ]]; then
        open "http://localhost:$BASH_REMATCH[1]"
    fi
}

This requires bash 4 or later, I believe.

A: You won't be able to use an alias, but you can create a function:
lh() { open http://localhost:$1; }

Then just call it like lh 3000.


text:
Q: 'ViewController' does not conform to protocol I was learning from techotopia.com tutorial. I have copied all code from there, and I have an problem "Type 'ViewController' does not conform to protocol 'UITableViewDataSource'".
Code and errors are on this screenshot
There was a problem like this on stackoverflow, but in that case the problem was a typo, so I dare to ask.

A: You are not finished implementing the required methods for the TableViewDataSource protocol. You should probably go on with the tutorial until you implemented the cellForRow method


text:
Q: Поменять все вхождения стиля на другой Есть список "легальных" стилей в документе. Надо все вхождения "нелегальных" стилей поменять на некоторый.
Вроде бы простой код, но не работает. В чём ошибка?
Private Sub replaceStyles()
    ' создаю массив допустимых стилей
    Dim validStyles() As String
    Dim strValidStyles As String
    strValidStyles = "АННОТАЦИЯ,ЗАГОЛОВОК ЛИТЕРАТУРА,КЛЮЧЕВЫЕ СЛОВА,НАЗВАНИЕ СТАТЬИ,ОСНОВНОЙ ТЕКСТ,ПОДРАЗДЕЛ,РАЗДЕЛ,РИСУНОК И ТАБЛИЦА,СНОСКА,СПИСОК АВТОРОВ"
    validStyles() = Split(strValidStyles, ",")
Dim i As Integer
Dim v As Integer

' по всем стилям в документе
For i = 1 To ActiveDocument.Styles.count
    ' если они используются
    If ActiveDocument.Styles(i).InUse Then
        valid = False
        ' соответствуют ли они легальным стилям
        For v = LBound(validStyles) To UBound(validStyles)
            If ActiveDocument.Styles(i).NameLocal = validStyles(v) Then
                valid = True
                Exit For
            End If
        Next v
        ' если нет - меняем на "_ОСНОВНОЙ ТЕКСТ_" везде, где встретятся
        If valid = False Then
            With ActiveDocument.Range.Find
                .ClearFormatting
                .Text = ""
                .Style = ActiveDocument.Styles(i)
                .Replacement.Style = "_ОСНОВНОЙ ТЕКСТ_"
                .Execute Replace:=wdReplaceAll
            End With
        End If
    End If
Next i

End Sub


text:
Q: Trying to access a new activity by selecting RadioButton in Android Studio I have a radioGroup with 3 radioButtons. Once you select a radio button it should take you to another activity and access a specific fragment within that second activity. I have no compile or runtime errors. The issue: you can select radioButton but nothing happens. I am new to android studios and java. I would appreciate any help.  Most questions are using a button to access a new activity not a radio button.
package com.example.joseph.ex51_twoactivities;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.RadioButton;

public class MainActivity extends Activity implements View.OnClickListener {
    //EditText etMessage;
    RadioButton profOne;
    RadioButton profTwo;
    RadioButton profThree;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       //etMessage = (EditText)findViewById(R.id.etMessage);
       profOne = (RadioButton)findViewById(R.id.rdProf1);
       profTwo = (RadioButton)findViewById(R.id.rdProf2);
       profThree = (RadioButton)findViewById(R.id.rdProf3);
       if(profOne.isChecked()) {
           profOne.setOnClickListener(this);
       }
       if(profTwo.isChecked()) {
           profTwo.setOnClickListener(this);
       }
       if(profThree.isChecked()) {
           profThree.setOnClickListener(this);
       }
    }

A: I figured it out, I shouldn't have a conditional statement under the onCreate method.


text:
Q: Impedir Autocomplete do navegador na senha Tenho uma tela de bloqueio que desloga o usuario por inatividade, pedindo apenas a senha do mesmo para acessar novamente. Acontece que essa tela não tem serventia nenhuma se autocomplete estiver ligado, já que qualquer um pode mexer nesse pc e entrar na conta desse usuario. Pesquisei muito e vi que o autocomplete="off", por exemplo, já está sendo ignorado pelos navegadores.
Alguém sabe um método funcional para solucionar esse problema? Por JQuery, um plugin qualquer coisa do tipo. Ou realmente só o cliente desabilitando a opção de guarda senha?

A: Os navegadores provavelmente só completam o primeiro campo de senha, tente adicionar um campo de senha invisível (style="opacity: 0;position: absolute") e depois insira no código o que realmente irá usar.

A: Como o atributo autocomplete não é válido pela W3C é comum inserir o autocomplete="off" via javascript:
// Utilizando JQuery
jQuery('campo').attr('autocomplete','off');
// Ou Javascript padrão
campo.setAttribute('autocomplete','off');

Pode-se utilizar a solução do javascript para adicionar esse atributo em campos do ADF e/ou elementos onde não temos acesso direto ao código HTML gerado.


text:
Q: using global variable in node js  app.use(function (req, res, next) {
 res.locals.login = req.isAuthenticated();
 app.locals.userinfo = req.user;
 next();
});

i am using global variables to store user info as i need to display them in my main template.
is it good practice to store user info in variables or is there a workaround?
are there any performance issue in using variables?
i tried creating helpers but that doesnt seems to work.
passing value while rendering is also not possible as user info has to be displaye on nav bar that is part of my main template.

A: You need cookie-session middleware to handle the user information.That is the normal situation in the browser-server architecture.
You can get value from session like
app.get('/', function (req, res, next) {
  res.end(req.session.views + ' views')
})

The session Object is a constant obj in the server, which has a default survival time and can be change also.
And the cookie-session is a common architecture, whatever nodeJs or java or other server-side language.You may can do an analogy, all behavior is similar.


text:
Q: Mongoose connect existing DB I'm trying to understand how MongoDB works.
I created a local MongoDB with the following collection:
 db.user.find().pretty()
{
    "_id" : ObjectId("5a05844833a9b3552ce5cfec"),
    "firstname" : "Emanuel",
    "lastname" : "Mars",
    "username" : "mae",
    "email" : "myEmail@email.ch",
    "passwort" : "mae",
    "role" : 1
}

Now, I want to connect to the DB with Express.
The connection works, but I don't get any data.
This is the model I created:
var userSchema = new mongoose.Schema({
    firstname: { type: String },
    lastname: { type: String },
    username: { type: String },
    email: { type: String },
    passwort: { type: String },
    role: { type: Number }
}, { collection : 'user' });

module.exports = mongoose.model('user', userSchema);

And this is how I want to get all Users in the collection user:
var User = require('../../models/user');

User.find({}, function (err, user) {
 console.log('yes', user);
});

Upon success, it should handle a login process with users from the MongoDB.
Solved:
I forgot to add the DB name at the end of the connect URL.

A: //server.js
var configDB = require('./config/database.js');

mongoose.connect(configDB.url);
const db = mongoose.connection;

db.on('error', () => {
    console.log('DB connection Error');
});
db.once('open', () => {
    console.log('DB is connected');
});

require('./config/passport')(passport);

//user.js
const mongoose = require('mongoose');
const bcrypt   = require('bcrypt-nodejs');

var userSchema = new mongoose.Schema({
    firstname: { type: String },
    lastname: { type: String },
    username: { type: String },
    email: { type: String },
    passwort: { type: String },
    role: { type: Number }
}, { collection : 'user' });

userSchema.methods.generateHash = function(password) {
    return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
};

userSchema.methods.validPassword = function(password) {
    return bcrypt.compareSync(password, this.local.password);
};

module.exports = mongoose.model('user', userSchema);


text:
Q: How do I type a special character on top of a character in java(FX) A dot on top of a variable denotes its derivative with time and A double dot is its second derivative with time.
I want to type this on a JavaFX pane. How do I do that??
PS-essentially the equivalent of \dot{x} in latex.

A: Ok, I figured it out myself. Posting it here for the benefit of others.
This is how you do it.
the Unicode for typing a (.) on top of a Character is \u0307. Append this to any character you want and you will get a (.) on top of it.
Eg:
String pbDot = "P\u0307b";
String omegaDot = "\u03C9\u0307";

Result:


text:
Q: Email to automatically add calendar reminder to their calendars Is there a way to send mass email and automatically add a calendar reminder the users' calendars? I've found you can export an .ics file and link to that where users can import into their program of choice,  but what about something that will do it automatically to any calendar? I've used this article to follow, but nothing for automatically adding to the user's calendar nor do we use that email service.
http://www.whatcounts.com/2013/07/feature-friday-add-calendar-events-in-publicaster-edition/

A: You can not force someone to automatically download the .ics, as you can imagine, auto downloading anything in email would pose a security risk to the reader.
All you can do is host the .ics (or any file really) on the web and hyperlink to it with a 'Save to Calendar' type linkin your email.

A: I believe there is no way to do this automatically. One of the important reason is JavaScript is not allowed by most of the email client.
I think the best way to show user a event and make it easy to add to their calendar is generate a .ics file and attach to the email as an attachment. Many email client, like Gmail, will find it and display it as a part of the email.
Here is a reference of .ics file format http://en.wikipedia.org/wiki/ICalendar


text:
Q: Should we avoid a "double passive"? Does it sound strange to say "An emergency meeting is expected to be held soon." or "The new highway is proposed to be built across the swamp."   Should we avoid this type of construction ?

A: No, there is no reason to avoid those sentences.
It is often simpler and clearer to use the active voice than the passive voice. And the active voice is especially helpful when the agent of the action is important to the message.  Otherwise, the passive voice is alive and well, and there is no reason to fear it blindly.
It's all about deciding what your message is and then finding a clear way to get it across.  And in that quest it is important to consider your audience or readers.  In some contexts they might well expect and appreciate the passive voice.

A: If passive voice does not bother you, you don't need to worry about using this construction.
If passive voice does bother you, don't use it twice in one sentence unless the alternative is more awkward.
The question of doubly passive sentences is essentially the same as the question of any passive sentences. Sometimes passive voice conveys the meaning better, and sometimes it is just needlessly evasive or bland.
The sentences you've posted seem normal enough that they wouldn't stand out in conversation.


text:
Q: Toggle one of two classes with JavaScript So I am creating this button that expands when clicked and hides data when clicked again. I have made it work, but it was working only one time before refresh, then I figured I need to take a different approach, by toggling class on the button itself, not the div where data appears. And my problem is, that to do so I need to toggle only one of two classes the button has with javascript. How do I do that?
const expandMovies = document.querySelector("#btnMovies");
expandMovies.addEventListener("click", toggleMovies)
function toggleMovies() {

if (expandMovies.classList.contains("inactive")) {

getMovies();
expandMovies.classList.toggle("active");

} else {
parentMovies.style.display="none";
expandMovies.classList.toggle("inactive");
}
};

A: You can use second property of toggle method which forces to remove  or add class forcibly. Following is the code snippet which can helpful for you.
const expandMovies = document.querySelector("#btnMovies");
expandMovies.addEventListener("click", toggleMovies)
function toggleMovies() {

if (expandMovies.classList.contains("inactive")) {

getMovies();
expandMovies.classList.toggle("inactive",false);
expandMovies.classList.toggle("active",true);

} else {
parentMovies.style.display="none";
expandMovies.classList.toggle("active",false);
expandMovies.classList.toggle("inactive",true);
}
};


text:
Q: Apache2 Override default Options directive While configuring Apache2 i've got stuck with this problem:
00_default_vhost.conf includes default_vhost.conf

default_vhost.conf
<Directory "/var/www/vhosts">
        AllowOverride None
        Options Indexes, FollowSymLinks
        Order allow,deny
        Allow from all
</Directory>

and after that another vhost.conf where defined
vhost.conf
 <Directory "/var/www/vhosts/vhost">
        AllowOverride All
        Options +Includes +ExecCGI
        Order allow,deny
        Allow from all
 </Directory>

But last include Options directive seems not working at all. Why? Is there a way to let vhost Options override default?


text:
Q: Loop IndexError: list index out of range I have this error
onecheck(sys.argv[1],sys.argv[2],sys.argv[3])
IndexError: list index out of range

I try to make loop a python script .
This is code :
with open(file) as k:
     for line in k:
         aa, bb, cc = line.split(':')
         time.sleep(5)
         os.system("python checkfile.py " + cc + " " + aa + " " + bb)

Last line from file is working

A: Why don't import checkfile directly, don't run via os.system()
If you are looking for a non-blocking way to execute your function in checkfile.py, look at :

*

*https://docs.python.org/2/library/threading.html

*https://www.tutorialspoint.com/python/python_multithreading.htm
:
import checkfile

with open(file) as k:
    for line in k:
        ltab = line.split(':')
        if len(ltab) > 2:
            time.sleep(5)
            checkfile.my_func(ltab[0], ltab[1], ltab[2])

A: Issue: You're getting any of the aa, bb, cc empty at:
aa, bb, cc = line.split(':')

Suggestion: In addition to above comments, you can also put your call in length check:
if len(sys.argv)== 4:  # index 0 - 3
    onecheck(sys.argv[1],sys.argv[2],sys.argv[3])


text:
Q: Operator norm of a matrix Any help here would be appreciated. Very new and rusty to more serious functional analysis.
Compute the operator norm of $ A = \left[
  \begin{array}{ c c }
     a & 0 \\
     0 & b
  \end{array} \right]$
where $A \in  Hom(\mathbb{R}^{2}, \mathbb{R}^{2})$ w.r.t to the $||.||_3$ norm for the domain and the $||.||_2$ norm for the codomain.
Where $ ||x||_2 = \sqrt{\sum_{n \in \mathbb{N}} |x_i|^{2}}$ etc.

A: Let $v=(x,y)$. We want to estimate $\Vert Av\Vert_2=\Vert (ax,by)\Vert_2$ in terms of $\Vert(x,y)\Vert_3$. Using Holder inequality, we get
\begin{align*}
\Vert (ax,by)\Vert_2&=\sqrt{a^2x^2+b^2y^2}=\sqrt{(a^2,b^2)\cdot(x^2,y^2)}\\
&\leq\sqrt{\Vert(a^2,b^2)\Vert_3}\sqrt{\Vert(x^2,y^2)\Vert_{3/2}}=(a^6+b^6)^{\frac{1}{6}}\Vert(x,y)\Vert_3
\end{align*}
Moreover, we can choose $x$ and $y$ (depending on $a$, $b$) such that the Holder inequality becomes an equality.
Hence $$\Vert A\Vert_{(\mathbb{R}^2,\Vert\cdot\Vert_3)\rightarrow(\mathbb{R}^2,\Vert\cdot\Vert_2)}= (a^6+b^6)^{\frac{1}{6}}$$


text:
Q: Why does String.Format work but SqlCommand.Parameters.Add not? I have a Project table with two columns -- ProjectId and ProjectName -- and am writing a function that constructs and executes a SqlCommand to query the database for the ids of a Project with a given name. This command works, but is vulnerable to SQL Injection:
string sqlCommand = String.Format("SELECT {0} FROM {1} WHERE {2} = {3}",
            attributeParam, tableParam, idParam, surroundWithSingleQuotes(idValue));

SqlCommand command = new SqlCommand(sqlCommand, sqlDbConnection);
using (SqlDataAdapter adapter = new SqlDataAdapter(command))
{
    DataTable attributes = new DataTable();
    adapter.Fill(attributes);
    ...
}

attributeParam, tableParam, idParam, and idValue are all strings. For example, they might be "ProjectId", "Project", "ProjectName", and "MyFirstProject", respectively. surroundWithSingleQuotes surrounds a string with '', so surroundWithSingleQuotes(idValue) == "'MyFirstProject'". I am trying to write this function as general as possible since I might want to get all of a given attribute from a table in the future.
Although the above String.Format works, this doesn't:
string sqlCommand = String.Format("SELECT @attributeparam FROM {0} WHERE " +
    "@idparam = @idvalue", tableParam);

command.Parameters.Add(new SqlParameter("@attributeparam", attributeParam));
command.Parameters.Add(new SqlParameter("@idparam", idParam));
command.Parameters.Add(new SqlParameter("@idvalue",
     surroundWithSingleQuotes(idValue)));

SqlCommand command = new SqlCommand(sqlCommand, sqlDbConnection);
using (SqlDataAdapter adapter = new SqlDataAdapter(command))
{
    DataTable attributes = new DataTable();
    adapter.Fill(attributes);
    ...
}

I'm not sure why. I get no error message, but when I fill my DataTable using a SqlDataAdapter, the DataTable contains nothing. Here are various approaches I've taken, to no avail:

*

*Following this answer and Microsoft's documentation, using AddWithValue or using Parameters.Add and SqlParameter.Value.

*Selectively replacing {0}, {1}, {2}, and {3}in String.Format with either the actual value or the parameter string.

In other places in my code, I've used parametrized queries (although with just one parameter) no problem.

A: Basically parameters in SQL only work for values - not identifiers of columns or tables. In your example, only the final parameter represents a value.
If you need to be dynamic in terms of your column and table names, you'll need to build that part of the SQL yourself. Be very careful for all the normal reasons associated with SQL injection attacks. Ideally, only allow a known whitelist of table and column values. If you need to be more general, I'd suggest performing very restrictive validation, and quote the identifiers to avoid conflicts with keywords (or prohibit those entirely, ideally).
Keep using SQL parameters for values, of course.

A: This is a valid statement:
SELECT * FROM SomeTable WHERE SomeColumn=@param
Whereas this is not:
SELECT * FROM @param
This means that you can use parameters for values and not for table names, view names, column names etc.


text:
Q: TaskCanceledException thrown on retrieving a MemoryStream with NPOI workbook When I hit this API, a TaskCanceledException is thrown with an unhelpful stack trace. I'm using this library: https://npoi.codeplex.com/
public class TestController : ApiController
    {
        [HttpGet]
        public HttpResponseMessage Test()
        {
            var templateWorkbook = new XSSFWorkbook();
            var sheet = templateWorkbook.CreateSheet("TestSheet");
            IRow dataRow = sheet.CreateRow(4);
            var cell = dataRow.CreateCell(0);
            cell.SetCellValue(77);

            Stream memoryStream = new MemoryStream();
            templateWorkbook.Write(memoryStream);

            var httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StreamContent(memoryStream)
            };
            httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "test.xlsx" };
            return httpResponseMessage;
        }
    }

What am I doing wrong? This is my stack trace:

[TaskCanceledException: A task was canceled.]
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task) +165
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task) +58
  System.Web.Http.Owin.d__20.MoveNext() +666
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task) +137
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task) +58
  System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task) +25
  System.Web.Http.Owin.d__0.MoveNext() +1814
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task) +137
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task) +58
  Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.d__5.MoveNext()
  +187    System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task) +99
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task) +58
  Microsoft.Owin.Security.Infrastructure.d__0.MoveNext() +561
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task) +137
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task) +58
  Microsoft.Owin.Security.Infrastructure.d__0.MoveNext() +561
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task) +137
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task) +58    Microsoft.Owin.Cors.d__0.MoveNext() +856
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task) +137
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task) +58
  Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.d__5.MoveNext()
  +187    System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task) +99
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task) +58
  Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.d__2.MoveNext()
  +185    Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.StageAsyncResult.End(IAsyncResult
  ar) +69
  Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.EndFinalWork(IAsyncResult
  ar) +64
  System.Web.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
  +380    System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

A: I found a solution.
Copying the memory stream to another one and resetting the seek position to 0 seems to fix it:
MemoryStream memoryStream = new MemoryStream();
templateWorkbook.Write(memoryStream);
MemoryStream copy = new MemoryStream(memoryStream.ToArray());
copy.Seek(0, SeekOrigin.Begin);

Seems like a bug in the NPOI library to me...


text:
Q: How can force python matplotlib to axis to scale linearly? So here is my python code.
import matplotlib.pyplot as plt

M=[]
for i in np.arange(0.01,8,0.01):
    M.append(test(i))
plt.plot(M)
plt.grid(b=True,which="major",color='#666666', linestyle='-',linewidth=0.2)
plt.show()

Where test(x) is some complicated function.
When i try to plot it python for some plots on X-axis from 1 to 800, but i want have scaled it plot from 0.01 to 8. So scaled down without changing graph.
Due to complicated form of test(x) function, i would like to use arrays, and this method of ploting.

A: Add an index to plot against (essentially your x-axis values):
import matplotlib.pyplot as plt

M=[]
indices = []
for i in np.arange(0.01,8,0.01):
    M.append(test(i))
    indices.append(i)
plt.plot(indices, M)
plt.grid(b=True,which="major",color='#666666', linestyle='-',linewidth=0.2)
plt.show()


text:
Q: magento PayPal gateway has rejected request. Security header is not valid (#10002: Security error) PayPal gateway has rejected request. Security header is not valid (#10002: Security error).
how to resolve it

A: Using the same API information for the Sandbox and Live environments. You need to generate separate API information for your Sandbox and Live accounts.

A: Credits : Vimalnath for link
The Security header is not valid error is only caused for two reasons:

*

*Wrong credentials
Make sure that you've put your API Username, API Password and API Signature correctly. Sometimes it happens that during copy and paste there is accidently a space added, this would trigger this error.
Doublecheck this settings in the SDK or in the admin panel of your third party shopping cart.

*Wrong Endpoint
This error would come up if you send the data to the wrong endpoint. Make sure that you sending the live credentials and data to our live endpoint. When you want to test your store make sure that you use our test endpoint and the credentials from your sandbox test account.
If you are using a third party shopping cart, make sure that your store is running in test or live mode, regarding which credentials you are using.
You can check for your credentials here too:
FOR LIVE
https://api-3t.paypal.com/nvp?&user=xxxxxxxxxx&pwd=xxxxxxxxxx&signature=xxxxxxxxxx&version=70.0&METHOD=SetExpressCheckout&RETURNURL=http://www.paypal.com/test.php&CANCELURL=http://www.paypal.com/test.php&PAYMENTACTION=Sale&AMT=50&CURRENCYCODE=USD
Just Substitute the user, pwd and signature and enter in your browser.
You should get ACK = SUCCESS if you have input your credentials correctly.
You can also get your credentials here : https://www.paypal.com/cgi-bin/webscr?cmd=_get-api-signature&generic-flow=true


text:
Q: Cannot use PSQLException.class in @ExceptionHandler I am getting this error:
org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "ix_auth_username"
  Detail: Key (username, authority)=(mike, ROLE_USER) already exists.

And this is how I try to handle this exception:
@RestControllerAdvice
public class RestExceptionHandler {
    @ExceptionHandler({IllegalArgumentException.class, PSQLException.class})
    private ResponseEntity<Object> handleIllegalArgumentException(HttpServletRequest request, IllegalArgumentException exception) {
        HttpStatus status;
        switch (exception.getClass().getName()) {
            case "IllegalArgumentException":
                status = HttpStatus.BAD_REQUEST;
                break;
            default:
                status = HttpStatus.INTERNAL_SERVER_ERROR;
                break;
        }
        ErrorResponse errorResponse = new ErrorResponse(status, LocalDateTime.now(), exception.getMessage());
        return ResponseEntity.badRequest().body(errorResponse);
    }
}

But IntelliJ gives me this error:

Cannot resolve symbol 'PSQLException'

Why? PostgreSQL works fine for me. This is how I use the dependency:
<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <scope>runtime</scope>
</dependency>

A: Simply replace
<scope>runtime</scope>

with
<version>42.5.4</version>

That should make it work.


text:
Q: Filtering/erasing duplicate entries using fluid i'm trying to find a way to erase duplicate entries using fluid. The idea was to use f:alias and then counting the items with the same title.
But my results are ridiculous. The counting is totally wrong.
Is it possible overall to do something like that in fluid?
I tried like this:
    <f:alias map="{client: '{newsItem->f:count()}'}">
        <f:if condition="{client -> f:count()}==1">
            <f:then>
                <f:if condition="{newsItem.teaser}">

                    <f:then>
                        {newsItem.teaser -> f:format.crop(maxCharacters: '{settings.cropMaxCharacters}', respectWordBoundaries:'1') -> f:format.html()}
                    </f:then>
                    <f:else>

There are {newsItem} records in database

{newsItem.txPblcexpandnewsClient}

                    </f:else>
                </f:if>
            </f:then>
            <f:else>
                else 1
            </f:else>
        </f:if>
    </f:alias>

Beste regards
blue

A: Fluid should not to use to heavy for logical context. If it to complex it belongs in the controller.
But try to use the group ViewHelper grouped by title.

A: as Rene already said: avoid this kind of logic in fluid!
but if you really can not do it in another way one solution could be:
use ext:vhs to define and change variables on the fly in fluid.
So you can do 'Gruppenverarbeitung' (I don't know a translation of this german term):

<v:variable.set name="lastitem" value="" />
<f:for each="items" as="item" iteration="iterator">
  <f:if condition="{lastitem}">
    <f:then>
      <f:if condition="{lastitem.title} == {item.title}">
        <f:then>
          <f:comment>just one item more</f:comment>
          <v:variable.set name="counter">
            <f:cObject typoscriptObjectPath="lib.calc">{counter}+1</f:cObject>
          </v:variable.set>
        </f:then>
        <f:else>
          <f:comment>output last item</f:comment>
          <f:render partial="showItem" arguments="{item:lastitem, counter:counter}" />
          <f:comment>store new item, reset counter</f:comment>
          <v:variable.set name="lastitem" value="{item}" />
          <v:variable.set name="counter" value="1" />
        </f:else>
      </f:if>
    </f:then>
    <f:else>
      <f:comment>init variables</f:comment>
      <v:variable.set name="lastitem" value="{item}" />
      <v:variable.set name="counter" value="1" />
    </f:else>
  </f:if>
</f:for>
<f:if condition="{lastitem}">
  <f:comment>output last item, if any</f:comment>
  <f:render partial="showItem" arguments="{item:lastitem, counter:counter}" />
</f:if>