text:
Q: Generate random values to mimic skewness I have a actual set of data where the variables are heavily skewed, both positively and negatively.
I need to generate random sample data for the values going forward. The data needs to be similarly skewed for the variables, so that the covariance and correlation remain reasonably similar.
I had planned to use numpy.random.multivariate_normal(), as I can easily determine the mean, and covariance values for the data set. However, as the data is skewed, it is not normal.
Using numpy, or sklearn, is there a random number package that can produce similarly skewed data?
The skewnesses of the variables, if anybody is interested are as follows:
 rain    2.373325
 temp   -0.286573
 rhum   -0.289834
 sun     1.103147
 vis    -0.303844


text:
Q: Updating value of a subfield in MongoDB with Java driver? I've quite new to MongoDB and it's Java driver.
I need to update the value of a subfield, but I can't find any examples online.
The document:
{
    "_id" : ObjectId("45678942342"),
    "user" : "me",
    "aStruct" : {
        "subfield_1" : true,
        "subfield_2" : true
    }
}

How do I update the value of subfield subfield_1 to false, for every document that has user = me ?

Thank you.

A: You can do it as follows :
db.collection.update({user : "me"},{$set:{"aStruct.subfield_1" : false}}, false, true)

In Java you can do it as follows :
DBCollection coll = // Define your collection here

DBObject query = new BasicDBObject();
query.put("user", "me");

DBObject updateObj = new BasicDBObject();
updateObj.put("aStruct.subfield_1", false);

coll.updateMulti(query, new BasicDBObject("$set", updateObj));

For more information read the following document.

*

*Update document in MongoDB

redpajama_set_name: RedPajamaStackExchange


text:
Q: Redirect to new URL safely using PHP I've got a contact form that currently reloads the root page after sending an email.
header('location: /?message=success');
This works just fine, although I'd now like it to go to the page URL stored in $_POST['contact_page']. However, using something like the following code doesn't seem like good practice:
header('location: http://'.$_POST['contact_page'].'?message=success');
My main concern is that someone could change the URL to something nefarious and then this command would execute it. (Also, with the message argument in the new URL, repeatedly running this code will cause more and more instances of the same argument to be added to the end.)
My question: what's a safe way to redirect the user to $_POST['contact_page'] using header (with an argument or two included, like message above)?
EDIT:
The page variable was originally made using this code, $_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"], and ends up in the form www.mysite.com/whatever-page&maybe_some=leftover_arguments

A: You must make a whitelist of what's allowed in your $_POST variable.
The previous answer by LuckyBurger can be incorrect if your PHP is <5.1.2 since it was allowed to send multiple headers with newline.

A: header('location: /'.$_POST['contact_page'].'?message=success');

to
header('location: http://www.yourdomain.com/'.$_POST['contact_page'].'?message=success');

A: A better solution would be to just send the ID of your blog article in the form, and then translate that into a URL.  Don't actually use this code, it's more an illustration:
HTML
<form>
  <input type='hidden' name='blog_id' value='3'>
</form>

PHP
<?php

// do your form processing

$blogId = $_POST['blog_id'];

// query the database to get the blog post slug/URL
// (this is just an example, don't actually put POST vars directly into queries)
$query = "SELECT p.slug, p.url FROM my_blog_posts p WHERE p.id={$blogId}";
$result = executeMyQuery($query);

$postSlug = $result['slug'];
// OR
$postUrl = $result['url'];

header("location: http://www.yourdomain.com/{$postSlug}?message=success");
// OR
header("location: http://www.yourdomain.com/{$postUrl}");

A: Because these links could either go to posts or pages—anything in the website's domain—and the list of allowable links will always be growing, I've gone with the following approach. It makes sure that the only arguments included in the redirect are of the form "page_id" and trims off anything else.
$page_url=$_POST['contact_page'];     // The URL to redirect to
$url_root=strtok($page_url,"?");    // Everything before the PHP arguments
$url_arg1=strtok("&")."&";          // The first argument
$ok_arg="page_id=";
if (strncmp($ok_arg,$url_arg1,strlen($ok_arg))!=0){ // Ditch first argument if not a page/post ID
    $url_arg1="";
}
header('location: http://'.$url_root.'?'.$url_arg1.'message=success');


text:
Q: MySQL: SUM of two COUNT (by distinct value) My MySQL-table saves citations. Each row is one citation, as in:
A = citer, B = cited (i.e., A cited B).
I know how to obtain numbers on (1) who cited A most often, and on (2) whom did A cite most often:
/* (1) who cited A most often? */
SELECT citer,COUNT(citer) AS citations1 FROM `table` WHERE cited='A' GROUP BY citer ORDER BY citations1 DESC

/* (2) whom did A cite most often? */
SELECT cited,COUNT(cited) AS citations2 FROM `table` WHERE citer='A' GROUP BY cited ORDER BY citations2 DESC

Now what I want is to get a sum of these two statistics (citations1 + citations2) so that I know who has the most total citation linkages to A.
Example: If B cited A five (5) times, and A cited B three (3) times, then the sum of the A-B-linkage is eight (8).
Would that be possible with a MySQL-formula? Thank you for your help!

A: You can write this as:
select person, (sum(citers) + sum(citeds)) as total
from ((select citer as person, count(*) as citers, 0 as citeds
       from citations
       where cited = 'A'
       group by citer
      ) union all
      (select cited, 0, count(*) as citeds
       from citations
       where citer = 'A'
       group by cited
      )
     ) c
group by person
order by total desc;

This question is a little tricky.  If you attempt to use a join, you will exclude the possibility that the person with the most citation linkages is only a "citer" or only a "cited".

A: You can join the results:
select t1.citer as person, t1.citations1 + t2.citations2 as result
from
(
SELECT citer,COUNT(citer) AS citations1 FROM `table` WHERE cited='A' GROUP BY citer ORDER BY citations1 DESC
) t
join
(
SELECT cited,COUNT(cited) AS citations2 FROM `table` WHERE citer='A' GROUP BY cited ORDER BY citations2 DESC
) t2
on t1.citer = t2.cited

A: I used UNION in a sub-query and then the sum of the rows
SELECT other, SUM(citations)
FROM (
   SELECT citer other,COUNT(*) AS citations
   FROM citations
   WHERE cited='A'
   GROUP BY citer
   UNION
   SELECT cited, COUNT(*)
   FROM citations
   WHERE citer='A'
   GROUP BY cited) AS uni
GROUP BY other


text:
Q: Format $_GET variable in url for Zend I'm using Zend Framework and it has a controller formatted to be accessed like this: url/search/Steve where Steve is a $_GET variable(name=keyword). It parses it correctly.
Now, the big question is: how can I have an url like that after the form is submitted? Instead of having ?keyword=Steve.
Thanks

A: I'm unsure of what you really want to have done.
If you have forms then what you should do in your case is to put method="POST" so that the fields don't end up in the URL at all in your case.
Or you need to do some JavaScript trickery to change the action="" of the form whenever the field you mention is changed. However, I've found this to be a bit unreliable as some browsers doesn't really like this for some reason.
Or, perhaps better, you could do a redirect after the form is submitted, where you redirect to the new "prettier" URL.
It all depends on your purpose.

A: have a look at the getParam method for Zend_Controller_Request
Something like this...
$var = Zend_Controller_Request::getParam('keyword');
$url = 'url/search'.$var;

If you var_dump($var) in between the two lines of code above you can test what values your application is returning.
This is all part of Zends Request object
Remember you can still use the $_GET superglobal with zend so the above becomes
$var=$_GET['keyword'];
$url = 'url/search'.$var;


text:
Q: speed python script on command line vs launched in IDLE shell I noticed several times that a simple python script (with some straightforward algebraic computation in a loop) runs considerably faster (up to a factor 6) when launched on a shell command line as compared to a run via IDLE's shell. There is nothing fancy going on in the script. I only print a loop variable to visually follow progress in the loop.
Surely just this print statement cannot be the reason for the speed loss in IDLE, or can it ?
Can someone explain me why this is ?

A: Yes, the print statement really is the main cause of slow-down within idle. The stdout and stderr streams are captured by IDLE, and a whole bunch of Tk commands are executed to render the text appropriately. Removing your output to stdout should speed things up again.
See the idlelib.PyShell, idlelib.OutputWindow, and idlelib.EditorWindow modules for (some of) the extent of the rabbit hole...
I would suggest using the logging module to record progress; you can then set the logging level to something higher when running in IDLE to avoid output in that condition, or log somewhere other than stdout.
Although I really wouldn't recommend it, something like the following probably works most of the time if you really want to be able to configure behaviour differently when running under IDLE. Though you really shouldn't :-)
import sys

running_under_idle = 'idlelib' in sys.modules


text:
Q: Missed Headers folder in OpenCl.framework Mac OS Mojave I am trying to stark work with OpenCl framework on my MacBook, and Mac OS has the framework installed, but there is no needed header cl.hpp I want to work with. I have downloaded the header from Khronos OpenCL Registry, but now I do not know where to paste it since there is no Headers folder in /System/Library/Frameworks/OpenCL.framework/, I've tried to find present headers (cl.h) with find in Terminal, but unsuccessful. What can I do?

A: Now I fixed the problem, I noticed that cmake finds OpenCL at /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/OpenCL.framework. There is folder Headers.


text:
Q: How to get rid of the foriegn key exception in mvc I have a module in my project where in a functionality I have a textbox where I am entering a missing note and saving it with button, but the table where I am saving the data is having a foreign key and I am getting the following exception
My code is as follows
    public ActionResult SetBreakageNote(int id, string MissNote, int charge)
    {
        var Rdetail = new ReservationDetail();
        if (ModelState.IsValid)
        {
            Rdetail.ReservationID = id;
            Rdetail.Description = MissNote;
            Rdetail.ChargeType = charge;
            db.Insert(Rdetail);
        }
        return RedirectToAction("Index");
    }

My View
@model IEnumerable<RoomTypeView>

    @foreach (var item in Model)
    {

                                <textarea class="form-control breakage" placeholder="Enter Breakage Note" rows="1"></textarea>

                            <button type="button" class="btn btn-default breakage" data-brid="@item.ReservationID"></button>

    }

  $('.breakage').click(function () {
            $.post("@Url.Action("SetBreakageNote", "HouseKeeping")", { id: $(this).data('brid'), MissNote: $('.breakage').val(), charge: @((int)ChargeTypeEnum.Breakage) });
        });

Here is the exception I am getting

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_ReservationDetails_Reservation". The conflict occurred in database "CavalaV3DB", table "dbo.Reservation", column 'ReservationID

ReservationID is a foreign key for Reservation table.
Please help me with this

A: You are trying to insert some value into your Rdetail in ReservationID column. But that value is not there in Reservation table.
This is violating Foreign key constraint created in the Rdetail table.
You can avoid this by checking this before inserting data into the table
if (ModelState.IsValid)
        {
           if(db.Reservation.where(a=>a.ReservationId==id).Amy()) //Condition to check if data is there or not
          {
            Rdetail.ReservationID = id;
            Rdetail.Description = MissNote;
            Rdetail.ChargeType = charge;
            db.Insert(Rdetail);
            }
        }

A: Before data can be inserted, the value in the foreign key field must exist in the other table first.You must build the table containing the Primary Key first after that you can populate them in a drop down from where you need to select first to save data.

the best way to deal with foreign key in other table's View Bind them in a Drop Down List and set attribute required


text:
Q: UITextView indentation with text styling I am using selectable UITextview to display my multiline message, i need to output my message in below style.

I can able to add numbering based on the newline character(\n) but the text position is starting from the beginning for remaining text, but i want "address" to be be start from "Verify" position

A: append three blank strings at initial of address this will solve your problem easy way.. :)
NSString *stringA = @"address";
NSString *stringAddress = [NSString stringWithFormat:@"   %@",stringA];


text:
Q: Ideal database choice for storing Wearable data (Fitbit) I'm recently developing an app on Fitbit.
I am considering MongoDB or HBase as it has support for aggregation and support for processing data in Key value format.
Example dataset:
{
    "activities-heart": [
        {
            "customHeartRateZones": [],
            "dateTime": "today",
            "heartRateZones": [
                {
                    "caloriesOut": 2.3246,
                    "max": 94,
                    "min": 30,
                    "minutes": 2,
                    "name": "Out of Range"
                },
                {
                    "caloriesOut": 0,
                    "max": 132,
                    "min": 94,
                    "minutes": 0,
                    "name": "Fat Burn"
                },
                {
                    "caloriesOut": 0,
                    "max": 160,
                    "min": 132,
                    "minutes": 0,
                    "name": "Cardio"
                },
                {
                    "caloriesOut": 0,
                    "max": 220,
                    "min": 160,
                    "minutes": 0,
                    "name": "Peak"
                }
            ],
            "value": "64.2"
        }
    ],
    "activities-heart-intraday": {
        "dataset": [
            {
                "time": "00:00:00",
                "value": 64
            },
            {
                "time": "00:00:10",
                "value": 63
            },
            {
                "time": "00:00:20",
                "value": 64
            },
            {
                "time": "00:00:30",
                "value": 65
            },
            {
                "time": "00:00:45",
                "value": 65
            }
        ],
        "datasetInterval": 1,
        "datasetType": "second"
    }
}

What would be an ideal choice to database to store the Sensor data as I wish to do analysis on this data in my application?
Thanks!

A: One thing to worry about with Mongo: The overhead of storing data is massive. In a typical RDBMS or time-series DB, it only stores your data, not the metadata (field names and types) with every row.
You should look into Time Series databases like Graphite and InfluxDB.  Even Cassandra has some features for this.
On the other hand, as the other poster pointed out, it may be simpler to start with a regular SQL database, and only migrate when you need to. By deferring the choice, you will have a better understanding of the specific trade-offs you want.
One easy DB to get started with is Graphite. It makes a very specific trade-off: The data storage requirement for each graph is constant (i.e. does not get bigger over time, even if you log years of data.) It can also deal with millions of metrics per second. The only downside is that the resolution "ages out" so you can tell it to store 1m resolution for a few days, but then decrease to 10m resolution for a month, then 1h resolution for 1 year, and 1d resolution for 10 years. You can tell it to keep stats (max, min, average, 90th percentile) for each interval.  Getting the graph of any arbitrary time span is basically a single disk seek. There are excellent dashboards to view your data (I recommend Grafana).

A: NoSQL DBs are a good choice when you have no structure in your data. You can emulate (key, value) functionality in RDBMSes too. The sample data you have shown looks like can be easily normalized and stored in MySQL or SQL Server. Why don't you go for that first? It will be very easily manageable too. Most importantly, you data has a structure.
If performance becomes a problem, you have indexes at your disposal. Even de-normalization. You can find the steps to normalize your data here in this SO answer about Normalization in databases. You can perform aggregation and do as well processing of your data in RDBMSes as you can in any NoSQL solution. Do you have any other reason?

A: You can try out Amazon Redshift because,

*

*It has direct json load capabilities using copy commands.

*It supports full ANSI SQL (as it is based on PostgreSQL).

*It has analytic functions buit inside.

*It has support for Python and R if you want to even more "analytics".

*It has direct connectivity with most popular reporting solutions (Microstrategy, Tableau etc.)

*Its completely on the AWS cloud.


text:
Q: Shift data from a row into a column I have a row of data that looks like the below.
IBM RPA|Reading|ATC01789|ATC01790|C4966572|NT018258 etc.

My question is how do i move the the data to look like the following?
IBM RPA|Reading|ATC01789
                ATC01790
                C4966572
                NT018258

Any Help would be greatly appreciated.
Thanks

A: Your are basically looking for Transponse,  something like this:
Dim X() As Variant
Dim XT() As Variant
X = ActiveSheet.Range("RangeOfRow").Value2
XT = Application.Transpose(X)
ActiveSheet.Range("RangeOfColum").Value = XT


text:
Q: Bootstrap - split background container full-width This is my sample code

      sample

      sample

and I have this

But I need this

I can reach result that I want with container-fluid, but I need container...

A: Reading the commentaries of your question, why not use the class container-fluid and create a custom class that helps to limit and center the container-fluid element when the width of the screen is greater than the specified (1170px in your case). For example, with a code like this:
HTML

      sample

      sample

CSS
.custom-class {
  max-width: 1170px;
  margin: 0 auto;
}

Example:
You can play with the width resize on the next example, and check if this is what you are expecting. On this example, max-width was decremented to 900px so you can visualize how it works.
https://jsfiddle.net/8bz97a1u/1/
UPDATE:

Here you have a new example with full-width background (that have two colors) and an inner html with fixed max-width (of 900px in the example):
HTML

      sample

      sample

CSS
.fixed-max-width {
  max-width: 900px; /* Example, but you can replace by the value you need */
  margin: 0 auto;
}

.custom-background {
  background: linear-gradient(90deg, red 50%, yellow 50%);
}

LIVE EXAMPLE
https://jsfiddle.net/8bz97a1u/2/

A: I figured out how to do that without so much code. Similar with Shidersz answer, but dealing more with structure. Mantaining responsivity and using bootstrap classes:
HTML

left split

right split

left content

        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque eget mauris ut enim scelerisque sollicitudin in nec nisl. Quisque arcu arcu, bibendum id nunc sit amet, auctor bibendum tellus. Sed non scelerisque nulla. Sed pharetra lacus sapien, et condimentum
        ante condimentum non. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Fusce magna lorem, lacinia congue varius blandit, facilisis quis nulla. Maecenas eu finibus tortor, sed volutpat justo. Fusce pulvinar

right content

        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque eget mauris ut enim scelerisque sollicitudin in nec nisl. Quisque arcu arcu, bibendum id nunc sit amet, auctor bibendum tellus. diam at placerat consectetur. Aliquam nec nisl luctus, imperdiet
        dolor non, feugiat ligula.

CSS
.background-holder {
  overflow: hidden;
  margin: 0 auto;
  position: absolute;
  height: 100%;
  pointer-events: none;
  z-index: -1;
}

.container {
  border-left: 2px solid red;
  border-right: 2px solid red;
}

jsfiddle DEMO


text:
Q: PostgreSQL - NULL References I have a data model for Tasks and Equipments.
Sometimes a Task needs some Equipment to be completed, sometimes it doesn't.
Task table
create table task (
    id serial primary key
,   task_name varchar(80)
)

Equipment table
 create table equipment (
        id serial primary key
    ,   equipment_name varchar(80)
    )

What I would like to do is add a null reference to the Task table.
create table task (
    id serial primary key
,   task_name varchar(80)
,   equipment_id serial null references equipment(id)
)

I get an error
ERROR:  conflicting NULL/NOT NULL declarations for column "equipment_id" of table "task"
SQL state: 42601

How can I maintain my data integrity while adding a Foreign key to my tables so that it works as expected? I thought you could have null references.

A: You have a potential modeling issue: "Task needs some Equipment" as stated. But does "some" actually mean "one",  Can a Task require 2 or more Equipment? If so and assuming an Equipment can be needed by more that 1 task, you need a resolution table (Task_Equipment perhaps) to resolve the many-to-many this represents. So then
create table equipment (
       id serial primary key
     , equipment_name varchar(80)
     );

create table task (
      id serial primary key
    , task_name varchar(80)
    );

create table task_equipment (
       task_id       int
     , equipment_id  int
     , constraint    te_pk
                     primary key (task_id, equipment_id)
     , constraint    te2task_fk
                     foreign key (task_id)
                     references task(task_id)
     , constraint    te2equipment_fk
                     foreign key (equipment_id)
                     references equipment(equipment_id)
     );

And I agree if your version has it use as identity instead of serial.

A: serial is a data type that is really an integer.  So, you want:
create table task (
    id serial primary key,
    task_name varchar(80),
    equipment_id int references equipment(id)
);

That said, Postgres now recommends using int generated always as identity.  This makes it clearer:
create table task (
    id int generated always as identity primary key,
    task_name varchar(80)
);

create table task (
    id int generated always as identity primary key,
    task_name varchar(80),
    equipment_id int references equipment(id)
);

The reasons for preferring generated always as identity are technical.  But one effect is that the code is more consistent -- both the primary key and foreign key have the same explicit type.


text:
Q: Ubuntu add commands to the bash I am using the Zend Framework. Lately I installed the last version of the ZF. I try to use zend tool from a terminal in ubuntu.
When I do ZF show version I still see version 1.9.6. How can I make sure that the ZF command will use the latest version?
I think I have once added the ZF to my terminal profile but I don't know how to change it.
Can anyone help me?

A: This is not a bash issue.  This sounds like a path issue to me.  You didn't mention how you installed version 1.9.6 or how you installed the newest version.  So I can only take a guess as to what's going on.  But I'm guessing that both versions are still installed to different paths and 1.9.6 is being found first due to how your path is setup.
You can see your current path by running echo $PATH.  And you can tell which ZF command is being run by running which ZF.  So from there if you know the path to the binary you wish to run it's just a matter of fixing your PATH.  I would also suggest un-installing the older version if it's not needed so that it doesn't cause you any more issues.


text:
Q: Converter from SAT to 3-SAT Does anyone know of a good program to convert CNF files with any number of variables per clause to CNF files with exactly 3 variables per clause (3-CNF)? I've seen this algorithm in computer science books but can't find an implementation anywhere and would hate to waste time implementing it myself if others have already done it. Thanks!

A: I didn't know any program to do that either, but the algorithm is really simple so just I wrote the following python script (download) that reads a general CNF in DIMACS format and writes the CNF of an equivalent 3-SAT problem in DIMACS format:
from __future__ import print_function
import fileinput

cnf = list()
cnf.append(list())
maxvar = 0

for line in fileinput.input():
    tokens = line.split()
    if len(tokens) == 0 or tokens[0] == "p" or tokens[0] == "c":
        continue
    for tok in tokens:
        lit = int(tok)
        maxvar = max(maxvar, abs(lit))
        if lit == 0:
            cnf.append(list())
        else:
            cnf[-1].append(lit)

assert len(cnf[-1]) == 0
cnf.pop()

new_cnf = list()
for clause in cnf:
    while len(clause) > 3:
        new_clause = list()
        for i in range(0, len(clause), 2):
            if i+1 < len(clause):
                new_cnf.append(list())
                new_cnf[-1].append(clause[i])
                new_cnf[-1].append(clause[i+1])
                maxvar += 1
                new_cnf[-1].append(-maxvar)
                new_clause.append(maxvar)
            else:
                new_clause.append(clause[i])
        clause = new_clause
    new_cnf.append(clause)

print("p cnf %d %d" % (maxvar, len(new_cnf)))
for clause in new_cnf:
    print(" ".join([ "%d" % lit for lit in clause ]) + " 0")

The interesting bit is of course the for clause in cnf: loop that takes the general sat problem stored in cnf and transforms it into a 3-sat instance stored in new_cnf. It does this by translating a clause such as
(A[1] or A[2] or A[3] or A[4] or A[5] or A[6] or A[7])

into the following set of clauses.
(A[1] or A[2] or ~X[1])
(A[3] or A[4] or ~X[2])
(A[5] or A[6] or ~X[3])

(X[1] or X[2] or X[3] or A[7])

The first three clauses are added to new_cnf. The last clause is not 3-sat so the algorithm is re-run on this last clause, yielding the following new clauses:
(X[1] or X[2] or ~Y[1])
(X[3] or A[7] or ~Y[2])

(Y[1] or Y[2])

This are all 3-sat clauses, so they are added to new_cnf and the algorithm continues with the next clause from cnf. (If the last clause were not 3-sat, the algorithm would keep working on it until only 3-sat clauses are left. The length of the last clause approximately halves with each iteration.)

A: SAT is not solvable in polynomial time (according to the current knowledge).
2-SAT is solvable in polynomial time.
So a conversion from generic SAT to 2-SAT will not be fast (not in polynomial time), otherwise we would find a polynomial-time algorithm for SAT.
In other words, the time needed to convert SAT to 2-SAT is roughly the same as the time to just solve SAT.
Maybe you mean 3-SAT, not 2-SAT?


text: Q: how to reuse LU decomposition in sympy for solving Mx = b for constant M and varying b The easiest way to solve Mx=b for matrices in sympy is M.LUsolve(b). Is there a way to reuse the LU decomposition, if I have a lot of equations with constant M and varying b? I don't see one.


text:
Q: UNIQUE constraint vs checking before INSERT I have a SQL server table RealEstate with columns - Id, Property, Property_Value. This table has about 5-10 million rows and can increase even more in the future. I want to insert a row only if a combination of Id, Property, Property_Value does not exist in this table.
Example Table -
1,Rooms,5
1,Bath,2
1,Address,New York
2,Rooms,2
2,Bath,1
2,Address,Miami

Inserting 2,Address,Miami should NOT be allowed. But, 2,Price,2billion is okay. I am curious to know which is the "best" way to do this and why. The why part is most important to me. The two ways of checking are -

*

*At application level - The app should check if a row exists before it inserts a row.

*At database level - Set unique constraints on all 3 columns and let the database
do the checking instead of person/app.

Is there any scenario where one would be better than the other ?
Thanks.
PS: I know there is a similar question already, but it does not answer my problem -
Unique constraint vs pre checking
Also, I think that UNIQUE is applicable to all databases, so I don't think I should remove the mysql and oracle tags.

A: Dependent on the cost of #1 (doing a lookup) being reasonable, I would do both. At least, in Oracle, which is the database I have the most experience with.
Rationale:

*

*Unique/primary keys should be a core part of your data model design, I can't see any reason to not implement them - if you have so much data that performance suffers from maintaining the unique index:

*

*that's a lot of data

*partition it or archive it away from your OLTP work

*The more constraints you have, the safer your data is against application logic errors.

*If you check that a row exists first, you can easily extract other information from that row to use as part of an error message, or otherwise fork the application logic to cope with the duplication.

*In Oracle, rolling back DML statements is relatively expensive because Oracle expects to succeed (i.e. COMMIT changes that have been written) by default.

A: This does not answer the question directly, but I thought it might be helpful to post it here since its better than wikipedia and the link might just become dead someday.
Link - http://www.celticwolf.com/blog/2010/04/27/what-is-a-race-condition/
Wikipedia has a good description of a race condition, but it's hard to follow if you don't understand the basics of programming.  I'm going to try to explain it in less technical terms, using the example of generating an identifier as described above.  I'll also use analogies to human activities to try to convey the ideas.
A race condition is when two or more programs (or independent parts of a single program) all try to acquire some resource at the same time, resulting in an incorrect answer or conflict.  This resource can be information, like the next available appointment time, or it can be exclusive access to something, like a spreadsheet.  If you've ever used Microsoft Excel to edit a document on a shared drive, you've probably had the experience of being told by Excel that someone else was already editing the spreadsheet.  This error message is Excel's way of handling the potential race condition gracefully and preventing errors.
A common task for programs is to identify the next available value of some sort and then assign it.  This technique is used for invoice numbers, student IDs, etc.  It's an old problem that has been solved before.  One of the most common solutions is to allow the database that is storing the data to generate the number.  There are other solutions, and they all have their strengths and weaknesses.
Unfortunately, programmers who are ignorant of this area or simply bad at programming frequently try to roll their own.  The smart ones discover quickly that it's a much more complex problem than it seems and look for existing solutions.  The bad ones never see the problem or, once they do, insist on making their unworkable solution ever more complex without fixing the error.  Let's take the example of a student ID.  The neophyte programmer says "to know what the next student number should be, we'll just get the last student number and increment it."  Here's what happens under the hood:

*

*Betty, an admin. assistant in the admissions office fires up the student management program.  Note that this is really just a copy of the program that runs on her PC.  It talks to the database server over the school's network, but has no way to talk to other copies of the program running on other PCs.

*Betty creates a new student record for Bob Smith, entering all of the information.

*While Betty is doing her data entry, George, another admin. assistant, fires up the student management program on his PC and begins creating a record for Gina Verde.

*George is a faster typist, so he finishes at the same time as Betty.  They both hit the "Save" button at the same time.

*Betty's program connects to the database server and gets the highest student number in use, 5012.

*George's program, at the same time, gets the same answer to the same question.

*Both programs decide that the new student ID for the record that they're saving should be 5013.  They add that information to the record and then save it in the database.

*Now Bob Smith (Betty's student) and Gina Verde (George's student) have the same student ID.

This student ID will be attached to all sorts of other records, from grades to meal cards for the dining hall.  Eventually this problem will come to light and someone will have to spend a lot of time assigning one of them a new ID and sorting out the mixed-up records.
When I describe this problem to people, the usual reaction is "But how often will that happen in practice?  Never, right?".  Wrong.  First, when data entry is being done by your staff, it's generally done during a relatively small period of time by everyone.  This increases the chances of an overlap.  If the application in question is a web application open to the general public, the chances of two people hitting the "Save" button at the same time are even higher.  I saw this in a production system recently.  It was a web application in public beta.  The usage rate was quite low, with only a few people signing up every day.  Nevertheless, six pairs of people managed to get identical IDs over the space of a few months.  In case you're wondering, no, neither I nor anyone from my team wrote that code.  We were quite surprised, however, at how many times that problem occurred.  In hindsight, we shouldn't have been.  It's really a simple application of Murphy's Law.
How can this problem be avoided?  The easiest way is to use an existing solution to the problem that has been well tested.  All of the major databases (MS SQL Server, Oracle, MySQL, PostgreSQL, etc.) have a way to increment numbers without creating duplicates.  MS SQL server calls it an "identity" column, while MySQL calls it an "auto number" column, but the function is the same.  Whenever you insert a new record, a new identifier is automatically created and is guaranteed to be unique.  This would change the above scenario as follows:

*

*Betty, an admin. assistant in the admissions office fires up the student management program.  Note that this is really just a copy of the program that runs on her PC.  It talks to the database server over the school's network, but has no way to talk to other copies of the program running on other PCs.

*Betty creates a new student record for Bob Smith, entering all of the information.

*While Betty is doing her data entry, George, another admin. assistant, fires up the student management program on his PC and begins creating a record for Gina Verde.

*George is a faster typist, so he finishes at the same time as Betty.  They both hit the "Save" button at the same time.

*Betty's program connects to the database server and hands it the record to be saved.

*George's program, at the same time, hands over the other record to be saved.

*The database server puts both records into a queue and saves them one at a time, assigning the next available number to them.

*Now Bob Smith (Betty's student) gets ID 5013 and Gina Verde (George's student) gets id 5014.

With this solution, there is no problem with duplication.  The code that does this for each database server has been tested repeatedly over the years, both by the manufacturer and by users.  Millions of applications around the world rely on it and continue to stress test it every day.  Can anyone say the same about their homegrown solution?
There is at least one well tested way to create identifiers in the software rather than in the database: uuids (Universally Unique Identifiers).  However, a uuid takes the form of xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx where "x" stands for a hexadecimal digit (0-9 and a-f).  Do you want to use that for an invoice number, student ID or some other identifier seen by the public?  Probably not.
To summarize, a race condition occurs when two programs, or two independent parts of a program, attempt to access some information or access a resource at the same time, resulting in an error, be it an incorrect calculation, a duplicated identifier or conflicting access to a resource.  There are many more types of race conditions than I've presented here and they affect many other areas of software and hardware.

A: I think it most cases the differences between that two are going to be small enough that the choice should mostly be driven by picking the implementation that ends up being most understandable to someone looking at the code for the first time.
However, I think exception handling has a few small advantages:

*

*Exception handling avoids a potential race condition. The 'check, then insert' method might fail if another process inserts a record between your check and your insert. So, even if you're doing 'check then insert' you still want exception handling on the insert and if you're already doing exception handling anyways then you might as well do away with the initial check.

*If your code is not a stored procedure and has to interact with the database via the network (i.e. the application and the db are not on the same box), then you want to avoid having two separate network calls (one for the check and the other for the insert) and doing it via exception handling provides a straightforward way of handling the whole thing with a single network call. Now, there are tons of ways to do the 'check then insert' method while still avoiding the second network call, but simply catching the exception is likely to be the simplest way to go about it.
On the other hand, exception handling requires a unique constraint (which is really a unique index), which comes with a performance tradeoff:

*

*Creating a unique constraint will be slow on very large tables and it will cause a performance hit on every single insert to that table. On truly large databases you also have to budget for the extra disk space consumed by the unique index used to enforce the constraint.

*On the other hand, it might make selecting from the table faster if your queries can take advantage of that index.

I'd also note that if you're in a situation where what you actually want to do is 'update else insert' (i.e. if a record with the unique value already exists then you want to update that record, else you insert a new record) then what you actually want to use is your particular database's UPSERT method, if it has one. For SQL Server and Oracle, this would be a MERGE statement.

A: The description of your problem is exactly why primary keys can be compound, e.g., they consist of multiple fields.  That way, the database will handle the uniqueness for you, and you don't need to care about it.
In your case, the table definition could be something similar to the following like:
 CREATE TABLE `real_estate` (
   `id` int(11) NOT NULL AUTO_INCREMENT,
   `property` varchar(255) DEFAULT NULL,
   `property_value` varchar(255) DEFAULT NULL,
   PRIMARY KEY (`id`),
   UNIQUE KEY `index_id_property_property_value` (`id`, `property`, `property_value`),
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;


text:
Q: Detect referrer source regex I have the following JS with regex:
var ref = document.referrer;
if (ref.match(/^https?:\/\/([^\/]+\.)?sporedev\.ro\:\/index.html(\/|$)/i)) {
  alert("Came from index");
}

What I'm trying to do, is to not display a part of HTML if the referrer is the index page of the website or if the referrer is other than the base domain of the website.
I've been working on this regex, modifying one that I found on SO to add the index.html after the domain name.
This is the initial script:
if (ref.match(/^https?:\/\/([^\/]+\.)?reddit\.com(\/|$)/i)) {
  alert("Came from reddit");
}

How can I correctly add "index.html" in this regex and how can I create another condition to check for different base URL?

A: In situations like these, try to adopt the simplest approach. Instead of using regex you could use includes. For example:
if (ref.includes('index.html') {
  //do something
}

If you really want to use regex then consider something simple like:
if (/index\.html/.test(ref)) {
  //do something
}

Regarding the matching of domains, I think it may be a good approach to put your list of domains in an array so you can do something like:
const domains = ['https://foo.com', 'https://bar.com'];

if (domains.indexOf(ref) > -1) {
  //do something
}

You could then combine these approaches with something like:
const domains = ['https://foo.com', 'https://bar.com'];
const fromIndex = ref.includes('index.html');
const fromDomainList = domains.indexOf(ref) > -1;

if (fromIndex || fromDomainList) {
  //do something
}


text:
Q: Multi-label prediction using LIBLINEAR I am using LIBLINEAR and i need to know whether Multi-Label Prediction in windows is possible or not.I tried google but no luck
I want the output to be produced the following way
I train some 10 documents with three class labels 1,2,3 and now when i feed a test document to the classifier and if the document belongs to label 1 and 2 then it should produce 1,2 or something else which shows that document belongs to 1 and 2 both the class labels
I want an example in windows
Thanks

A: By default neither libSvm nor LibLinear supports multiclass classification.
You need to perform a One against all approach.
You can find help on the libsvm page which provides different tools for multi-label classification that are based on LIBSVM or LIBLINEAR


text:
Q: spark-submit not exiting even after process finishes successfully I have written a simple application and it is running fine but when I am submitting the code via spark-submit even after close() is called the spark-submit session is not finishing and I need to kill the PID.
Below is the code snippet
object FaultApp {

  case class Person(name: String, age: Long)

  def main(args: Array[String]):Unit = {

val spark = SparkSession
  .builder
  .enableHiveSupport()
  .config("spark.scheduler.mode", "FAIR")
  .appName("parjobs")
  .getOrCreate()

import spark.implicits._

val pool = Executors.newFixedThreadPool(5)
 // create the implicit ExecutionContext based on our thread pool
implicit val xc = ExecutionContext.fromExecutorService(pool)

import Function._

val caseClass = Seq(Person("X", 32)
                      ,Person("Y", 37)
                      ,Person("Z", 37)
                      ,Person("A", 6)
                   )

val caseClassDS = caseClass.toDF()

val taskA = write_first(caseClassDS)

Await.result(Future.sequence(Seq(taskA)), Duration(1, MINUTES))

spark.stop()

println("After Spark Stop command")
  }

}

object Function {
  def write_first (ds : DataFrame)(implicit xc: ExecutionContext)  = Future {
   Thread.sleep(10000)
   ds.write.format("orc").mode("overwrite")
     .option("compression", "zlib")
     .saveAsTable("save_1")
  }
}

I am submitting the job using the below command
spark-submit --master yarn --deploy-mode client fault_application-assembly-1.0-SNAPSHOT.jar --executor-memory 1G --executor-cores 2 --driver-memory 1G

Below are the last few lines from the log
18/04/18 15:15:20 INFO SchedulerExtensionServices: Stopping
SchedulerExtensionServices
(serviceOption=None,
 services=List(),
 started=false)
18/04/18 15:15:20 INFO YarnClientSchedulerBackend: Stopped
18/04/18 15:15:20 INFO MapOutputTrackerMasterEndpoint:
  MapOutputTrackerMasterEndpoint stopped!
18/04/18 15:15:20 INFO MemoryStore: MemoryStore cleared
18/04/18 15:15:20 INFO BlockManager: BlockManager stopped
18/04/18 15:15:20 INFO BlockManagerMaster: BlockManagerMaster stopped
18/04/18 15:15:20 INFO OutputCommitCoordinator$OutputCommitCoordinatorEndpoint: OutputCommitCoordinator stopped!
18/04/18 15:15:20 INFO SparkContext: Successfully stopped SparkContext
After Spark Stop command

Any help or advice will be greatly appreciated.

A: That's because you're creating an execution context with a threadpool, so your program won't shut down until that is also shutdown.
After spark.stop(), add
xc.shutdown()
println("After shutdown.")

In alternative, instead of creating a new execution context for your futures, you could just use the global one:
 implicit val executor =  scala.concurrent.ExecutionContext.global


text:
Q: I tried from POSTMAN API working fine but not from my Java code? Please I have gone through all the question from stackoverflow, but those are not applicable to my problem.

Please have look in image request working fine from POSTMAN.
But When I tried from android code it is not working.
My Sample Android code is here.
@Override
        protected String doInBackground(Void... params) {
            HttpURLConnection urlConnection = null;
            BufferedReader reader = null;

            // Will contain the raw JSON response as a string.
            String forecastJsonStr = null;

            try {
                URL url = new URL("sample url");

                String postData = "key1=valu1&key2=valu2";

                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(55000 /* milliseconds */);
                conn.setConnectTimeout(55000 /* milliseconds */);
                conn.setRequestMethod("POST");
                conn.setDoInput(true);
                conn.setDoOutput(true);
                OutputStream os = conn.getOutputStream();
                BufferedWriter writer = new BufferedWriter(
                        new OutputStreamWriter(os));
                writer.write(postData);

                writer.flush();
                writer.close();
                os.close();

                int responseCode=conn.getResponseCode();

                if (responseCode == HttpsURLConnection.HTTP_OK) {

                    BufferedReader in=new BufferedReader(
                            new InputStreamReader(
                                    conn.getInputStream()));
                    StringBuffer sb = new StringBuffer("");
                    String line="";

                    while((line = in.readLine()) != null) {
                        Log.e("response ",line);
                        sb.append(line);
                        break;
                    }

                    in.close();
                    return sb.toString();

                }
                else {
                    return new String("false : "+responseCode);
                }
            } catch (Exception e) {
                Log.e("PlaceholderFragment", "Error ", e);
                // If the code didn't successfully get the weather data, there's no point in attemping
                // to parse it.
                return null;
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (final IOException e) {

                    }
                }
            }
        }

Above  java code return 405 error code. I also tried from OkHttp also.
Please help.

A: Putting a '/' at the end of URL causes the redirect to happen because your server likes urls that end in '/'. POST is fully supported by the URL your server redirects you to, but the client is executing a GET request when it behaves according to your setRedirecting() call (cURL does the same exact thing with the -L switch) The fix is to either put a '/' at the end of URL, or to grab the Location header from the response yourself and then initiate another POST request manually.
This can be observed in wireshark. You can test the theory by trying to perform a GET request with your browser to the URL with a slash appended to it. That will cause the browser to get a 405. Here's the fixed code for Android, this code uses the simple fix of appending a '/' to the URL (not production ready):
Read more from here.
Do let me know if this helps :)
Additionally, try using this piece of code:
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://your URL");

try {
    // Add your data
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
    nameValuePairs.add(new BasicNameValuePair("id", "12345"));
    nameValuePairs.add(new BasicNameValuePair("stringdata", "Hi"));
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    // Execute HTTP Post Request
    HttpResponse response = httpclient.execute(httppost);

} catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
} catch (IOException e) {
    // TODO Auto-generated catch block
}
}

A: Your API call is reciveving data in GET parameter. So data should send along with url as given below
            String postData = Uri.encode("key1=valu1&key2=valu2");
            URL url = new URL("sample url"+"?+postData);

A: I just had a similar problem with the HttpClient in Java. The solution was to specify the HTTP version explicitly:
HttpClient.newBuilder()
            .version(HttpClient.Version.HTTP_1_1)
            .build();

Now my requests returns the same result as through Postman.


text:
Q: Field wise Banded Column style I want to design pivot table with banned column style and I am using Excel 2013
I have set the style and it looks like below.

I want to design it Rank wise. Means there three fields Pre, Post, Exp
per Rank
My expectation is like below

Thanks

A: What you want is a customized style, follow this steps:

*

*Clear all filters in the pivot table
Select any cell in the pivot table then click in the Ribbon tab: Data \ Group Sort & Filter: Clear (see fig. 1)

*Select the Field Items you want to fill with a color
Keep press the [Ctrl] key while selecting the field items

*Once selected them fill them with the color you want (see fig.2)

*Pivot table customized in fig. 3

Be aware that this customizes the interior of each items, so the columns banned is not alternated, it's fix.
To keep it alternated the Pivot Table must show all the Rank items always. To do that, change the settings of the Field Rank in tab Layout & Print flag the option Show items with no data (see Fig. 4)


text:
Q: What is the Main Job of Logical Link Layer in Layer 2 I am curious to know what Logical Link Layer does.  What is its main significance?  Is it part of Software?
I am looking for some details of LLC.

A: The LLC sublayer is primarily concerned with:
* Multiplexing protocols transmitted over the MAC layer (when transmitting) and demultiplexing them (when receiving).
* Providing flow and error control

The protocol used for LLC in IEEE 802 networks and in some non-IEEE 802 networks such as FDDI is specified by the IEEE 802.2 standard.
Some non-IEEE 802 protocols can be thought of as being split into MAC and LLC layers. For example, while HDLC specifies both MAC functions (framing of packets) and LLC functions (protocol multiplexing, flow control, detection, and error control through a retransmission of dropped packets when indicated), some protocols such as Cisco HDLC can use HDLC-like packet framing and their own LLC protocol.
An LLC header tells the Data Link layer what to do with a packet once a frame is received. It works like this: A host will receive a frame and look in the LLC header to find out where the packet is destined for - for example, the IP protocol at the Network layer or IPX.
LLC also does ciphering and deciphering of SN-PDU (SNDCP)packets.
The above details are found on Wikipedia.
http://en.wikipedia.org/wiki/Logical_Link_Control


text:
Q: Making .php not required with .htaccess I'm trying to make my links a little easier to write, without the .php.
My rewrite rule is:
RewriteEngine on
RewriteRule ([a-z]+)$ $1.php

This is the first .htaccess I wrote myself, but it doesn't seem to work.
I'm good with RegExp. And I don't see the issue here.
Thanks for the help.

A: RewriteEngine on
RewriteRule ^(.*)$ $1.php

Start from here: http://www.yourhtmlsource.com/sitemanagement/urlrewriting.html

A: Even though yours works for alphabetic filenames, this is what I've used regardless of the name / path of the file to omit the .php extension:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

It makes sure you're not trying to request a directory, and that the file that was requested is a PHP file.

A: Make sure mod_rewrite is enabled in apache config as well as AllowOverride All
LoadModule rewrite_module modules/mod_rewrite.so
<Directory "c:/wamp/www/">

    AllowOverride all
    Order Deny,Allow
    Deny from all
    Allow from all

</Directory>

To get it workign in wamp
Click on wamp icon in systray
Go to apache
then click on httpd.conf
Search the file for mod_rewrite.so. If that line is commented (#) uncomment it.
It should look like
LoadModule rewrite_module modules/mod_rewrite.so

Then look for something like
<Directory "c:/wamp/www/">

You should find a AllowOverride none Change it to AllowOverride all
Restart your wamp server
Then set your .htaccess to nickb suggestion
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

If it still doesn't work just do a search in the httpd.conf for AllowOverride none and change them all to AllowOverride all, as there may be a couple


text:
Q: Diffusion on a semi-Riemannian manifold? A great deal of literature exists on the heat equation and heat kernel for a Riemannian manifold.  The Laplace-Beltrami operator in the given metric replaces the flat Laplacian in the heat equation, and the heat kernel becomes:
\begin{equation*}
p(t,x,y) = F(t,x,y) \exp \left( - \frac{d(x,y)^2}{ct} \right)
\end{equation*}
where $d(x,y)$ is the geodesic distance between $x$ and $y$ and $F$ is some function depending on the Riemannian spatial geometry, instead of the familiar:
\begin{equation*}
p(t,x,y) = \left( \frac{1}{4 \pi t} \right)^{n/2} \exp \left( - \frac{\lvert x-y \rvert^2}{4t} \right)
\end{equation*}
from Euclidean space.
Thus, even living in a curved space, we can still investigate how an uneven distribution of perfume would diffuse through such a spatial manifold if filled with air.
My question concerns how much we would be able to say about diffusion if we lived in a space which was only semi-Riemannian, so that the metric was nondegenerate but not positive definite.  This changes things fundamentally, since of course the Laplace-Beltrami operator is no longer elliptic but hyperbolic.  But one can still at least intuitively imagine spraying perfume in such a space and seeing where it goes.
Has any analog of the heat equation / heat kernel been studied for a semi-Riemannian manifold?  If so, could anyone suggest search terms or a reference?
Many thanks!!

A: This question has been addressed in some cases through a probabilistic approach. You probably know that the heat equation on a Riemannian manifold is intimately tied with its Brownian motion; one way to generalize the diffusion of heat is thus to generalize the Brownian motion; this has been studied in the case of Lorentzian signature under the name of Relativistic Diffusion.
I am not familiar with this domain, but I know someone who is: Jürgen Angst; checking his first paper's abstract, it seems that the subject was started in the following works:

*

*Debbasch et al. J. Math. Phys. 40, 2891 (2001); Eur. Phys. J. 19, 37 (2001);23, 487 (2001); J. Stat. Phys. 88, 945 (1997);90, 1179 (1998),

*Dunkel and Hänggi Phys. Rev. E 71, 016124 (2005);72, 036106 (2005)

I guess than from there and Angst's page you should find a large number of references.

A: Thanks for asking this question and also thanks to @Benoît Kloeckner for the suggestions. I had the same question too.
In case you haven't already found the appropriate equation you are looking for, here is an one-dimensional relativistic diffusion equation [http://plms.oxfordjournals.org/content/107/6/1395].
$$
u_t = \nu \left(\frac{u u_x}{\sqrt{u^2 +(\nu^2/c^2) (u_x)^2}}\right)_x,  x \in \mathbb{R}, t >0.
$$
Since it relativistic, we are dealing with Lorentzian manifold which is a semi-Riemannian manifold. Hope this helps.


text:
Q: pyautogui.locateOnScreen() Returns... Nothing? I'm trying to use PyAutoGui's image recognition functions. (OS X)
Needless to say, I'm running into some slight issues that I can't seem to solve myself no matter where I look or what I do. I'm attempting to have PyAutoGui click on the Chrome shortcut based off a .png screenshot saved to my desktop.
Here's my code in terminal:
>>>import pyautogui
>>>chrome = pyautogui.locateOnScreen('/Users/ianscalzo/Desktop/chrome.png")
>>>

I get no backfire on my filepath, but it causes my shell/terminal to return nothing but go to a new line. (As shown in the code example above - Just causes terminal to go to a blank ">>>")
I don't really understand why it doesn't do anything but go to a new line, so any insight would be greatly appreciated.
Thank you so much!

A: After struggling with this forever also, finally figured out that you either use command line to take the screenshot or using the screenshot button with windows key. It doesn't work with the snipping tool.
so try:
image = pyautogui.screenshot()
image.save('testing.png')

Go and crop testing.png as small as possible so that locateOnScreen works faster. Then go back to the terminal and type:
pyautogui.locateOnScreen('testing.png')


text:
Q: programmatically determine if an evaluation of a function is being assigned? I would like to do this:
def foo():
    if <a magical condition>:
        return x
    else:
        poof()

# or...
def foo():
    x = <a magical object>
    return x

def poof():
    print 'poof!'

bar = foo()  # bar points to <a magical object> but poof() is not called

foo() # prints 'poof!'

I guess it comes down to what the circumstanses are when the returned object's __del__ method is called.  But maybe there is a better way.  Like if the function itself knew it's returned value was being assigned.  I guess I'm worried about relying on the timing of the garbage collection.  Also I don't like that global at_end_of_program flag.
My solution:
class Magic:
    def __del__(s):
        poof()

def foo():
    x = Magic()
    return x

def poof():
    if not at_end_of_program:
        print 'poof!'

bar = foo()  # No poof.

foo() # prints 'poof!'

A: I'm pretty confused by your question, but I think what you are trying to do is run a function when a value is reassigned.
Instead of doing tricky things with a __del__() method function, I suggest you just put your value into a class instance, and then overload __setattr__().  You could also overload __delattr__() to make sure you catch del(object.x) for your value x.
The very purpose of __setattr__() is to give you a hook to catch when something assigns to a member of your class.  And you won't need any strange end_of_program flag.  At the end of your program, just get rid of your overloaded function for __delattr__() so it doesn't get called for end-of-program cleanup.

A: A function can't tell what its return value is used for.  Your solution will print poof if you re-assign to bar for example.
What's the real problem you are trying to solve?


text:
Q: What's the meaning of '-u' in 'git push -u origin master'? I don't quite understand the meaning of -u in the git push -u origin master command. Can you explain what it's used for?

A: The -u flag adds a reference to the upstream server you are pushing to. This lets you git pull without supplying additional arguments i.e. once you enter git push -u origin master you can then simply type git pull and this command will understand that in the future you mean git pull origin master.


text:
Q: Getting total value from each field? How do I get the Total value of Yes, No, Other fields of each username?
I like to add Total field.
SELECT Username,
  SUM(CASE WHEN type = 'Yes' THEN 1 ELSE NULL END) as Yes,
  SUM(CASE WHEN type = 'No' THEN 1 ELSE NULL END) as No,
  SUM(CASE WHEN type = '' THEN 1 ELSE NULL END) as Other
  //How to get total of Yes/No/Other
  FROM table
WHERE source = 'CompanyName' ";

Also the highest Total goes at the top order.

A: use 0 instead of NULL, add the missing group by and use COUNT(*) to get the total of each group and order the result:
SELECT Username,
  SUM(CASE WHEN type = 'Yes' THEN 1 ELSE 0 END) as Yes,
  SUM(CASE WHEN type = 'No' THEN 1 ELSE 0 END) as No,
  SUM(CASE WHEN type = '' THEN 1 ELSE 0 END) as Other,
  COUNT(*) as TOTAL
  FROM table
WHERE source = 'CompanyName'
group by Username
order by TOTAL desc;

This assumes that type can only be 'Yes', 'No'  or ''.

A: Use a sub query to sum up your results and add a sort:
select yes, no, other, yes + no + other as Total
from (

    SELECT Username,
      SUM(CASE WHEN type = 'Yes' THEN 1 ELSE 0 END) as Yes,
      SUM(CASE WHEN type = 'No' THEN 1 ELSE 0 END) as No,
      SUM(CASE WHEN type = '' THEN 1 ELSE 0 END) as Other
      FROM table
    WHERE source = 'CompanyName'
)
order by (yes + no + other) desc

A: Don't use SUM(null), the SUM of (1,1,1,null) = null, not 3.
SELECT s.*, s.yes+s.no+s.other as all FROM (
  SELECT Username,
     SUM(CASE WHEN type = 'Yes' THEN 1 ELSE 0 END) as Yes,
     SUM(CASE WHEN type = 'No' THEN 1 ELSE 0 END) as No,
     SUM(CASE WHEN type = '' THEN 1 ELSE 0 END) as Other
     FROM table
   WHERE source = 'CompanyName'
   GROUP BY Username
) s
ORDER BY all DESC


text:
Q: Tapestry inject form field after uploading files
Versions :
Tapestry version : 5.3.8
Tapestry-jQuery : 3.4.2
My project consists of uploading multiple files, write them on the filesystem, create an object wrapper for each file in order to add some additional informations. These informations would be created by the user with a form just after the upload.
Unfortunately, I had the exception  "element must be enclosed by a form component" when the zone (inside the form : responsible for handling update when a file was uploaded) was updated.
Index.java

public class Index
{

    @Component
    private FormInjector injector;

    @Component
    private Form uploadForm;

    @InjectComponent
    private Zone uploadResult;

    @Inject
    private Block uploadFields;

    @Persist
    @Property
    private List uploadedFiles;

    @Persist
    @Property
    private List customFiles;

    @Persist
    @Property
    private CustomFile file;

    @Inject
    private AjaxResponseRenderer ajaxResponseRenderer;

    @Environmental
    private JavaScriptSupport jsSupport;

    @Environmental
    private FormSupport formSupport;

    @OnEvent(component = "injector")
    Block loadUploadFields(){
        return  uploadFields;
    }

    @OnEvent(component = "uploadFiles", value = JQueryEventConstants.AJAX_UPLOAD)
    void onDocUpload(UploadedFile uploadedFile) {
        CustomFile file = new CustomFile();
        if (uploadedFile != null) {
            if(uploadedFiles==null) {
                uploadedFiles = new ArrayList();
            }
            uploadedFiles.add(uploadedFile);
            file.setFilename(uploadedFile.getFileName());
            if (customFiles==null) {
                customFiles = new ArrayList();
            }
            customFiles.add(file);
        }
        ajaxResponseRenderer.addRender(uploadResult);
    }

    public void onUploadedFile() {
        jsSupport.addScript("$('#injector').trigger()");
    }

}

Index.tml

<j:ajaxUpload t:id="uploadFiles" t:multiple="true">
</j:ajaxUpload>

Uploaded Files

        Name
        Version
        Reference

    <t:Form t:id="uploadForm">
        <t:zone t:id="uploadResult" id="uploadResult" elementName="tbody">
            <t:if test="uploadedFiles">
                <t:loop source="customFiles" value="file" element="tr"
                    formState="none">

                    ${file.filename}

                    <t:FormInjector t:id="injector" id="injector" />

                    <t:block t:id="uploadFields">

                            <input t:type="TextField" t:value="file.version" t:id="version" />

                            <input t:type="TextField" t:value="file.reference" t:id="reference" />

                    </t:block>

                    <t:Trigger event="uploadedFile" />
                </t:loop>
            </t:if>
        </t:zone>
    </t:Form>

With some help from :
Updating a zone inside a form in Tapestry 5
I tried to use the FormInjector and Trigger components but I can't figure out how it works. Now I have the exception : "No object of type org.apache.tapestry5.services.FormSupport is available from the Environment"
Any suggestions to make this work ?
Thanks for your help !

A: Nest your <t:form> inside your <t:zone>. More info here


text:
Q: XYZ data to 2D plot in R I need to make a 2D plot of distance travelled versus my value at that point ("intensity").
My data is formatted as:
lon lat intensity

 1. -85.01478 37.99030  -68.3167
 2. -85.00752 37.97601  -68.0247
 3. -85.00027 37.96172  -67.9565
 4. -84.99302 37.94743  -67.8917

and it continues for 282 rows like this.  I was looking at a few packages that calculate distance between longitude (lon) and latitude (lat) points (such as geosphere), but I couldn't understand how to get my data into the format that it wanted.  I know the total distance travelled in degrees should be 4.01538, evenly spaced out between the 282 points, but I don't know how I could make a column in R with this in mind.

A: dfrm$dist<- cumsum(c(0, with(dfrm, sqrt( (lat[-1]-lat[-nrow(dfrm)])^2+
                                   (lon[-1]-lon[-nrow(dfrm)])^2
                               )))  )
with(dfrm, plot(dist, intensity, type="b"))

Or choose a more "geographic" distance measure with the lagged column values. But given the increments, I doubt the error from using a naive distance measure can be that much.

A: From here I found some packages to calculate distance between coordinates. Assuming your data is called dtf and using the RSEIS package:
dtf <- data.frame(rbind(c(-85.01478,37.99030,-68.3167),
c(-85.00752,37.97601,-68.0247),c(-85.00027,37.96172,-67.9565),
c(-84.99302,37.94743,-67.8917)))
names(dtf) <- c('lon','lat','int')

library(RSEIS)
travelint <- function(i,data){
ddeg <- GreatDist(dtf$lon[i],dtf$lat[i],dtf$lon[i+1],dtf$lat[i+1])$ddeg;
dint <- dtf$int[i+1] - dtf$int[i]; return(list(ddeg,dint))}
out <- sapply(1:(nrow(dtf)-1),data=dtf,travelint)
out <- data.frame(matrix(as.numeric(out),ncol=2,byrow=T))
out$X1 <- cumsum(out$X1)

This will take your data, calculate the distance traveled between points and the intensity change between them. After that it can be plotted like this:
ggplot(out,aes(X1,X2)) + geom_line() +
      labs(x="Distance (Degrees)",y="Intensity Change")

If instead you want increasing intensity , you can use cumsum again to get the cumulative change in intensity and then add it to the first intensity:
out2 <- out
out2 <- rbind(c(0,0),out2)
out2$X2 <- cumsum(out2$X2) + dtf$int[1]
ggplot(out2,aes(X1,X2)) + geom_line() +
      labs(x="Distance (Degrees)",y="Intensity")

A: As mentioned by DWin you can use naive measure or geographic distance measure. Here I am using gdist function from Imap package calculates Great-circle distance .
library(Imap)
library(lattice)
#Dummy data
longlat <- read.table(text="lon lat intensity
 1. -85.01478 37.99030  -68.3167
 2. -85.00752 37.97601  -68.0247
 3. -85.00027 37.96172  -67.9565
 4. -84.99302 37.94743  -67.8917", header=TRUE)

ll <- lapply(seq(nrow(longlat)-1), function(x){
    start <- longlat[x,]
    end   <- longlat[x+1,]
    cbind(distance = gdist(start$lon, start$lat, end$lon, end$lat,units = "m"),
          intensity = end$intensity - start$intensity)
  })
dd <- as.data.frame(do.call(rbind,ll))
library(lattice)
xyplot(intensity~distance,dd,type= c('p','l'),pch=20,cex=2)


text:
Q: Detect and eliminate existing duplicate accounts, contacts and Opp for Professional Edition I am using SF Professional edition have been Searching a free app to detect and eliminate the duplicates mainly for the Accounts, Contacts and Opportunities. Most of the free apps tends to search duplicates  only during an insert or an update operation, suggest me a free app that detect the duplicates from the existing records.

A: With Professional Edition, you are fairly limited.  Maybe you can have Salesforce enable API access temporarily and utilize something like DemandTools to detect duplicate in mass?  DemandTools is primarily used for mass duplicate detection and cleanup, when other tools like RingLead are used primarily for UI prevention.

A: perhaps this will help: Salesforce Labs Dupe Eliminator

A: I have a similar issue (Im sure all orgs have some duplicates) where I use a passive application like DupeCatcher. This handles de-dupeing on insert and update.
I then created a checkbox field (isDuped) on the SObject in question (account) initially set to false. Using http://Dataloader.io I exported the accounts 10k at a time and upserted with the checkbox isDuped set to true. This then triggered the ded-duplication to run on each account that was upserted.
A poor mans solution :)


text:
Q: Android Java code to set redirect to new activity after login? Hi I have an android app created which is a basic login screen which I want to take you to a new activity screen if logged in correctly. However I am having trouble with the redirect. Here is my code:
package com.example.loginscreen;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

   private EditText  username=null;
   private EditText  password=null;
   private TextView attempts;
   private Button login;
   int counter = 3;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      username = (EditText)findViewById(R.id.editText1);
      password = (EditText)findViewById(R.id.editText2);
      attempts = (TextView)findViewById(R.id.textView5);
      attempts.setText(Integer.toString(counter));
      login = (Button)findViewById(R.id.button1);
   }

   public void login(View view){
      if(username.getText().toString().equals("mara") &&
      password.getText().toString().equals("mara")){
      Toast.makeText(getApplicationContext(), "Login Successful!",
      Toast.LENGTH_LONG).show();
      startActivity(new Intent(MainActivity.this,HomePage.class));
       }
   else{
      Toast.makeText(getApplicationContext(), "Wrong Credentials",
      Toast.LENGTH_SHORT).show();
       attempts.setBackgroundColor(Color.RED);
      counter--;
      attempts.setText(Integer.toString(counter));
      if(counter==0){
         login.setEnabled(false);
      }

   }

}
   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      // Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.main, menu);
      return true;
   }

}

At the moment if you login with the wrong credentials everything works as it should but if you login correctly the app just exits and says that it has stopped working. I know the problem it with my startActivity intent because if I remove
startActivity(new Intent(MainActivity.this,HomePage.class));

it at least puts up the toast to notify you that you have logged in correctly. Thanks!
Here is the code for the HomePage:
package com.example.loginscreen;

import android.widget.ImageView;

public class HomePage extends MainActivity{
ImageView image;

public void addListenerOnButton() {

        image = (ImageView) findViewById(R.id.imageView1);
}
}

A: Firstly,
register HomePage activity in manifest.
And
change
public class HomePage extends MainActivity{
}

to
public class HomePage extends Activity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
    }
}

Hope this helps.


text:
Q: Web Page Execution Internals My question is what is the subject area that covers web page execution/loading.
I am looking to purchase a book by subject area that covers when things execute or load in a web page, whether it's straight html, html and Javascript, or a PHP page.
Is that topic covered by a detailed html book, or should I expect to find information like that in a JavaScript of PHP book?
I understand that PHP and Perl execute on the server and that Javascript is client side, and I know there is a lot of on-line documentation describing <html>, <head>, <body>, and so on. I'm just wondering what subject area a book would be in to cover all that, not a discussion of the best book or someone's favorite book, but the subject area.

A: I'm not entirely sure what you are asking, but here are a few areas that you may want to look at:
Web Servers - Handling and processing requests and replying with the required documents or data
HTTP Protocol - Handles the request and transmission of files and other web requests
Browser Rendering - Drawing of the resulting data of a HTTP Request on the page
You then have each individual technology which will be covered by their own books, such as HTML, CSS, Javascript etc, however most of these will be tutorials on how to code using these technologies rather than descriptions of how they are rendered and processed.
What exactly is it you are trying to achieve? It may be easier to point you in the right direction if you can say what you are trying to achieve.

A: There is a generic sequence of events that happens. You may get a better understanding how page is downloaded and parsed by just looking at F12-Developer tool (which really cool tool in Chrome).
Basic execution flow will have the following stages:

*

*Page Request is sent to server (through url)

*Web server accepts the request and handles it

*On success, server site scripts are executed, and HTML generated for transmission

*All that is done through HTPP request/response

*On HTTP status code 200 - standard response for successful HTTP requests is sent

*Html is downloaded

*Html parsed progressively,

*after HTML is parsed the DOM is rendered

*after the DOM rendered and requests for all resources are downloaded ot timed-out the JavaScript execution from the onload/page complete event fires.

More detailed information with example: - Load and execution sequence of a web page

A:
what is the subject area that covers web page execution/loading.

This is an excellent set of slides illustrating how to scrutinize every aspect of the web page execution and loading process.
Google, Chrome - DevTools.
Those tools are advancing rapidly.
While that is not a "subject area", there are many subject areas discussed, which may help you find what you are looking for.
Hope that helps.


text:
Q: Powershell - Adding a Month to all files in a folder a complete newbie to Powershell here.
What I am attempting to do is using Powershell, adding a month for the creationtime of files in a folder, which is based off the current creation date of the document, as opposed to the get-date system date.
Edit to how I get it to work for single documents:
I managed to get it to work for a specific file using this command:
$(get-item test.txt).creationtime=$(Get-item test.txt).creationtime.AddMonths(1)

Rather than specify each filer individually, I want to do the same as above but for all documents in a folder.

A: If the question is to add 1 month to the LastWriteTime date of each file, instead of setting the LastWriteTime date to a date 1 month away from the current system date, you can do
foreach ($file in (Get-ChildItem -Path 'PathToWhereTheFilesAre' -File)) {
    $file.LastWriteTime = $file.LastWriteTime.AddMonths(1)
}

If it is the current system date plus 1 month you want, you can use any of the answers given already by both Klausen and Venkataraman R

A: You can go for foreach loop to iterate over files and update the lastwritetime
$FolderName = "c:\dev"
foreach($file in (GEt-childitem -Path $FolderName ))
{
$file.lastwritetime=$(Get-Date).AddMonths(1)
}

A: First you need to define which files you want to apply this "addmonths". In the code sample I added two parameters you may want to remove, just in case you need them.
Thanks.
# Folder where your files are located
$folder = 'C:\Temp\'

# Create list of files to go thru.
# -Recurse option will navigate in the folders recursively.
# -File can be used so no folders are picked up in your script
$files = Get-ChildItem -Path $folder -Recurse -File

# Iterate file by file in the results
foreach($file in $files)
{
    $file.lastwritetime=$(Get-Date).AddMonths(1)
}

A: Thanks all for your help!
I've used your guidance and created the following code which does exactly what I want it to do:
$folder = "C:\Users\ajames\Powershell"
$files = Get-ChildItem -Path $folder -Recurse -File
foreach($file in $files)
{$file.creationtime=$($file.CreationTime.AddDays(1)) }

Cheers again.


text:
Q: Div showing a activity indicator rails I'm uploading some text to my rails app. It is then processing it (adding tags, etc ...) and that takes a couple of seconds.
Ideally I'd like to have a "Processing div" similar to what is happens when you submit a query to Orbtiz.
What's the best way to do that?

A: You might use flash notice. For example, on the start of process:
flash.now[:notice] = 'Processing div'
render :action => 'your action'

And then when your process is finished use this:
flash.now[:notice] = 'Successfully finished!!!'
render :action => 'your action'

But to have time animation you should write javascript code on the client side. I assumed that for the first time the simple flash notice will be enough for you.


text:
Q: Cannot modify header information - headers already sent by in wordpress I have created a newsletter plugin. I have coded an export function, but I got this error:

Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\blog\wp-includes\script-loader.php:1005) in C:\xampp\htdocs\blog\wp-content\plugins\newsletter\export.php on line 4.

I tried many ways, but in vain. Please suggest me the best way to solve this issue.


text:
Q: Issue with cancelling an AsyncTask I've done a lot of reading on the subject without finding the correct solution.
I have a program which does a network discovery (using ping). I don't understand how you stop the async task. I am doing a task.cancelled(true) but it seems to do nothing. On top of it I'm doing a while() to check if the task is cancelled which returns true immediately.
The sequence: is start (works fine) I wait 5-10 IP addresses and I click on the button stop. Then I click on start but the discover task is not executed.
Can we really stop an async task? How? What is the delay for it?
EDIT
I'm lost. All the Qs in Stackoverflow state that the cancel(true) needs to come from in the task.

*

*I have an example where I called the cancel(true) inside the doinbackground but it didn't trigger the onCancelled

*Most of the case (at least for loops) the stop must come outside the task. My example below simply plays on the loop counter. That works.
One interisting comment came from wrygiel in the Q Ideal way to cancel an executing AsyncTask
it would be great to have a real example.
Here is my code modified but the onCancelled didn't work so I play on the loop counter.
public class MainActivity extends AppCompatActivity {
    TextView text;
    Discover discover;
    int count;
    private boolean running = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button start = (Button) findViewById(R.id.start);
        Button stop = (Button) findViewById(R.id.stop);
        text = (TextView) findViewById(R.id.txt);

        start.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                discover = new Discover();
                discover.execute();
            }
        });

        stop.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
         //       if(discover != null)
         //           discover.cancel(true);
                count = 255;
            }
        });
    }

    private class Discover extends AsyncTask<Object, String, Void> {

        @Override
        protected Void doInBackground(Object... params) {
            String ip;
            Ping ping = new Ping();

            for(count=1;count<255;count++) {
                if(!running) {
                    count = 255;
                    Log.i("Discover", "task terminated");
                }
                ip = "192.168.1." + count;
                if (!ping.pong(ip))
                    publishProgress(ip+" not alive ");
                else
                    publishProgress(ip+" is alive");
            }
            return null;
        }

        @Override
        protected void onPreExecute() {
            text.setText("Start search...");
            super.onPreExecute();
        }

        @Override
        protected void onProgressUpdate(String... values) {
            super.onProgressUpdate(values);
            text.setText(values[0]);
        }

        @Override
        protected void onPostExecute(Void result) {
            text.setText("Task finished");
            super.onPostExecute(result);
        }

        @Override
        protected void onCancelled() {
            running = false;
            super.onCancelled();
        }

    }
}

A: You can not stop asyncTask this way. You can use discover.cancel(true); whenever you want, but you have to stop it manually - check value discover.isCancelled() in your doInBackground method. Otherwise AsyncTask will call whole doInBackground method, but fo not goes through onPostExecute.

A: Asynctask having inbuilt onCancelled() method like onPostExecute()
  @Override
    protected void onCancelled() {
        super.onCancelled();
    }

and you need to periodically check the status of the asynctask , in background function, when you cancel it , onCancelled() method will be invoke instead of onPostExecute().


text:
Q: FFmpeg not utilizing all the threads properly for transcoding as it used to As I heard about FFmpeg and found it more efficient to Transcode videos, so I started using it for doing 90% transcoding my videos into h.265 for decreasing file size. I installed it and I just started working with it. FFmpeg struggled to utilize all the threads with 1080p or lower resolution files, so what I did was that I started transcoding videos in parallel, meaning doing the simultaneous transcoding in 3 different command windows, which worked perfectly utilizing the thread up to 99%-100%.
For some booting issues that my system had, I had to do a complete new windows 10 install. and by that, after re installing FFMpeg, and running the very same bat file a created for transcoding a folder (simultaneous transcoding), it uses the threads in very inefficient way, by capping 16 of them and not the rest.
You can see them here: https://imgur.com/a/xvEM8
Hardware wise, I am using the very same system as before. I just removed 1x8GB RAM stick out of it, to use on another system. I have 24GB of RAM at the moment, But I don't assume that's the issue.
I asked this question here, because the most of the things I learned about ffmpeg was from here. I'm no expert coder by any means, but I want to know if I missed something.
imgur.com/a/ZzG1S
for %%a in ("*.mp4") do ffmpeg -i "%%a" -c:v libx265 -x265-params crf=26 -c:a copy "newfiles\%%~na.mp4" pause
this is saved in bat file.
Thanks


text:
Q: Angular youtube player not displaying videos when app is deployed guys!
Ran into interesting behaviour when using angular youtube player(ngx-youtube-player
). The video displays perfectly fine when app is running on localhost, but when deployed app is running, video simply doesn't show up in the component. Console shows error Refused to load the script 'https://www.youtube.com/iframe_api' because it violates the following Content Security Policy directive: "script-src-elem 'self' 'unsafe-inline' https://apis.google.com/".
We tried to fix it by adding the following line to our index.html
<meta http-equiv="Content-Security-Policy" content="frame-src youtube.com www.youtube.com;">

but it didn't work. I also noticed that this behaviour is observed only in chrome, in Safari everything is working.
We also tried a different way, by adding script-src 'self' youtube.com to meta tag instead, but it throws Refused to load the script 'https://www.youtube.com/iframe_api' because it violates the following Content Security Policy directive: "script-src 'self' youtube.com". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback.
The code looks like this:

import { Component, OnInit, ViewChild } from "@angular/core";
import { BsModalRef } from "ngx-bootstrap";

@Component({
  selector: "app-video-event",
  templateUrl: "./video-event.component.html",
  styleUrls: ["./video-event.component.css"],
})
export class VideoEventComponent implements OnInit {
  videoId: string;
  link: string;

  constructor(public bsModalRef: BsModalRef) {}

  ngOnInit(): void {
    const tag = document.createElement("script");
    tag.src = "https://www.youtube.com/iframe_api";
    document.body.appendChild(tag);

    const videoUrl = new URL(this.link);

    this.videoId = new URLSearchParams(videoUrl.search.slice(1)).get("v");
  }
}
<div class="modal-body">
    <youtube-player class="youtube-player" [videoId]="videoId"></youtube-player>
 </div>

Any suggestions on how it can be fixed? It appears that it's a problem with CSP and/or iframe, but I can't find anything helpful apart from solutions already tried.

A: Problem is with the way you get that videoid from url parameter. you add that link variable but there is no link.

       const tag = document.createElement('script');
      tag.src = 'https://www.youtube.com/iframe_api';
      document.body.appendChild(tag);

      const params = new URL('https://www.youtube.com/watch?v=A-jw5BXS9SU').searchParams;
      const vid = params.get('v');
      if (vid) {
        this.videoId = vid;
      }
    <youtube-player
          [videoId]="videoId"
          [height]="300"
          [width]="540"
        ></youtube-player>

Problem is that

"link" in ts

this works for me.


text:
Q: How can I use current query value in sequelize? I am new with sequelize and i need to include multiple table, i try belove:
const result = await product.findAll({
        where: {
            isDeleted: false,
            sellerId
        },
        attributes: ["name", "type", "isActive", "subCategoryIds"],
        include: [
            {
                model: category,
                as: 'categories',
                attributes: ["name"],
            },
            {
                model: category,
                as: 'subCategories',
                attributes: ["name"],
                where: {
                    id: _.split(sequelize.col("subCategoryIds"), ",")
                },
            },
        ],
        offset: (page - 1) * limit,
        limit
    });

But it's return error :

SequelizeDatabaseError: operator does not exist: character varying = integer

Product model is:
const product = sequelize.define("products",
{
    id: {
      type: DataTypes.BIGINT.UNSIGNED,
      field: "id",
      primaryKey: true,
      autoIncrement: true,
      index: true,
    },
    name: {
      type: DataTypes.STRING,
      field: "name",
      allowNull: false,
    },
    type: {
      type: DataTypes.STRING,
      field: "type",
      allowNull: false,
    },
    categoryId: {
      type: DataTypes.NUMBER,
      field: "categoryId",
      references: {
        key: "id",
        model: category,
      },
      allowNull: false,
    },
    sellerId: {
      type: DataTypes.NUMBER,
      field: "sellerId",
      references: {
        key: "id",
        model: user,
      },
      allowNull: false,
    },
    subCategoryIds: {
      type: DataTypes.STRING,
      allowNull: false,
      get() {
        const result = _.split(this.getDataValue("subCategoryIds"), ",").map(item => +item);
        return result;
      }
    },
    isDeleted: {
      type: DataTypes.BOOLEAN,
      field: "isDeleted",
      defaultValue: false,
    },
    createdAt: {
      type: DataTypes.DATE,
      field: "createdAt",
      defaultValue: DataTypes.NOW,
    },
    updatedAt: {
      type: DataTypes.DATE,
      field: "updatedAt",
      defaultValue: DataTypes.NOW,
    }
  }, {
  tableName: "products",
  timestamps: false
}
);

product.belongsTo(category, { as: "categories", foreignKey: 'categoryId' });
category.hasMany(product, { as: "products", foreignKey: 'categoryId' });

product.belongsTo(category, { as: "subCategories", foreignKey: 'subCategoryIds' });

I am not getting what's going wrong
is there any solution for this
details in table like

categoryId => 11 subCategoryIds => 11, 12

if i remove
       {
            model: category,
            as: 'subCategories',
            attributes: ["name"],
            where: {
                id: _.split(sequelize.col("subCategoryIds"), ",")
            },
        },

then it's working fine, problem is sequelize.col("subCategoryIds") return string col("subCategoryIds") not the actual value of the subCategories ids 11, 12


text:
Q: How many bit strings of length 8 have a weight of 5 start with 101 OR end with 11. I'm very close to solving this problem but finding the final answer is proving problematic.
A: 101x xxxx  = 32 strings starting with 101
B: xxxx xx11  = 64 strings ending with 11
C: 101x xx11  = 8 strings with both of these.
The number of strings with weight five is equal to 56.
It is also important to note the number of strings starting with 101 with weight five is equal to 10
and the number of strings ending in 11 with weight five is equal to 20.
Therefore I thought the answer would've been 22 i.e. sum of 10 + 20 minus the strings common to both given this is an or problem.

A: Yes, you can use inclusion-exclusion, but the intersection should include the weight five condition.  The correct count is:
$$\binom{5}{3}+\binom{6}{3}-\binom{3}{1}=10+20-3=27$$

A: As you've observed:

*

*There are ${5 \choose 3} = 10$ eight-bit strings of weight five starting with $101$ (your $A$)

*There are ${6 \choose 3} = 20$ eight-bit strings of weight five ending with $11$ (your $B$)

*These two sets overlap, so the answer to your problem is $|A| + |B| - |A \cap B|$.

But the overlap $C = A \cap B$ is the strings of the form $101xyz11$ which have five $1$s.  So exactly one of $x, y, z$ is $1$, and $|C| = 3$.


text:
Q: Unknown framework used in PHP web app The framework has MVC design pattern, but it has some weird lines of code. I'll snip a piece of code, does anyone know this weird framework?
class pjAdmin extends pjAppController
{
    public $defaultUser = 'admin_user';

    public $requireLogin = true;

    public function __construct($requireLogin=null)
    {
        $this->setLayout('pjActionAdmin');

        if (!is_null($requireLogin) && is_bool($requireLogin))
        {
            $this->requireLogin = $requireLogin;
        }

        if ($this->requireLogin)
        {
            if (!$this->isLoged() && !in_array(@$_GET['action'], array('pjActionLogin', 'pjActionForgot', 'pjActionPreview')))
            {
                pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionLogin");
            }
        }
    }

If anyone knows this framework, can they tell me how to configure it to work on a localhost server? I am using Ubuntu.
Thanks in advance!


text:
Q: Use selected item from DropDownList to fill in Textboxes in ASP.NET MVC This was automatically generated

Now i want to get the owners name that paard(horse), but be able to edit the owners name after selecting the horse.

I've tried searching everywhere, but i couldn't find anything similar to what i want. Hopefully you guys can help me out.


text:
Q: Vertically stack components of a cell in Matlab? I have a cell A in Matlab composed by sub-arrays with different number of rows but same number of columns, e.g. A={[1 2 3; 4 5 6] [7 8 9] [10 11 12; 13 14 15; 16 17 18]}. Without using loops, I want to vertically stack each sub-array in a matrix B. In the example,
B=[1 2 3; 4 5 6; 7 8 9; 10 11 12; 13 14 15; 16 17 18]

A: Use vertcat to concatenate subcells vertically:
B = vertcat(A{:})

B =

     1     2     3
     4     5     6
     7     8     9
    10    11    12
    13    14    15
    16    17    18


text:
Q: How do I make sure every glyph has the same width? I've noticed that even at the same font size, there is not a standard width. How can I use these in front of a list of items so the words don't appear jagged?
Screenshot of issue:

This is the code:

 Proposal

 Videos

 Assets

 Payment

 History

A: Are you sure that you haven't got another style defined that is doing this?
This is how your HTML looks placed into a file on a site I have using Font Awesome:

Notice how the icons and the text line up. This is your original image with lines added:

It looks like you have a style defined somewhere that is removing the Font Awesome styling.
You could also try adding in the original Font Awesome style (coming from font-awesome.css) to see if that solves it temporarily:
li [class^="icon-"], .nav li [class^="icon-"],
li [class*=" icon-"], .nav li [class*=" icon-"] {
    display: inline-block;
    width: 1.25em;
    text-align: center;
}

A: For Fontawesome version above 4.X, use fa-fw class in the  tag.
Ref:- https://fontawesome.com/how-to-use/on-the-web/styling/fixed-width-icons

A: Since 3.1.1, you could use the icon-fixed-width class instead of having to edit the CSS.
http://fortawesome.github.io/Font-Awesome/3.2.1/examples/#navigation
Since 4.0, you should use fa-fw:
4.x  https://fontawesome.com/v4.7.0/examples/#fixed-width
5.x https://fontawesome.com/how-to-use/on-the-web/styling/fixed-width-icons
Thanks @kalessin for pointing out.

A: Its simple and easy to scale glyph or any icon using this css
> .fa { transform: scale(1.5,1); }


text:
Q: Is there a word for this geological formation? Is there a word for a very tall, narrow rock formation whose base is on the sea floor and the tip is above sea level?
There is this similar formation above sea level.

A: These are called stacks or seastacks. They are typically a coastal formation, as they form from headland erosion.
Description from the U.S Geological Survey:

Sea stacks are blocks of erosion-resistant rock isolated from the land by sea. Sea stacks begin as part of a headland or sea cliff. Relentless pounding by waves erodes the softer, weaker parts of a rock first, leaving harder, more resistant rock behind.

You may also find more information at Wikipedia.


text:
Q: Video/Frame rotation in android Im extracting frames from a video (using javacv) and those are rotated by 180° because the video was taken with a tablet this way.
How can I get the position (if the head is pointing down or not) of a video/frame? Because some videos are ok and others not.


text:
Q: CSS-only version of com_content in Joomla Has anyone built a version of the com_content Joomla 1.5 component? I've got a table-free design but don't want to now introduce ugly tables from the content. Are there any alternative component that is pure CSS? Thank you.

A: check the com_content in the Beez template, it is tables free.
Also, all (I think) template overrides in that template are tables free; I used it as the base for my templates and made the appropriate changes.