text:
Q: Open html section according to what's in the hash as the title says, I am trying to open a section that matches the url hash.
My code works, but it's bugged and I don't know what to do anymore.
Here, I have the following navbar:

         Sobre Nós

           Serviços

Each 'li' opens a section, and that code is already developed and working, but, I can't open it using the hashes, it works, but it opens the other sections even if I'm calling just one.
Code for opening sections accordingly to hash:

Also If I'm coming from another page, all sections will open and if I close and reopen, all sections will open and reopen.
I hope you understand this and thank you in advance.

A: You can try using Element.scrollIntoView() instead of trying to simulate click.
$(document).ready(function() {
    var hash = window.location.hash;
    $('a[data-page-section="' + hash + '"]').get(0).scrollIntoView(true)
});


text:
Q: Iterating through a list and searching for each element in another list in c++ I have created a list of 4 elements called "worklist." I have another list called "choicelist" which has around 40 elements in it. I want to check if any of the elements in "worklist" are present in "choicelist".
I understand that I'd use "std::find" from  to search, but how would I go about checking for each element IN ORDER from "worklist" in "choicelist"?
Baring in mind that once an element from "worklist" HAS been found in "choicelist" I want the search process to end (and preferably some kind of notification about which element in "worklist" was the first one to match).

A: You have to iterate over elements of first list      and check is it there in second list using find function. if it finds the searching element ,  print it and break the loop.
std::list<int> worklist;
std::list<int> choicelist;
//This loop only works in C++11 and above,
//in case of C++98, you need to use iterators to iterate over list
for( auto &x : worklist)
{
        //auto is also a feature of C++11 and above
        auto y = std::find (std::begin(choicelist),
                            std::end(choicelist), x);

        if( y != choicelist.end())
        {
            std::cout<< *y<<"\n";
            break;
        }
 }

if you just need to find first element of first container  in second container,
auto y= std::find_first_of(std:begin(choicelist), std::end(choicelist),
                           std::begin(worklist), std::end(worklist));
if( y != choicelist.end())
{
                std::cout<< *y<<"\n";
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Use of wildcards in mysql table name The table names in my mysql database are dynamically generated. Is there some way to select data from tables which have a name matching a pattern? I guess it will look like:
select * from 'table_id_%'

A: You can use INFORMATION_SCHEMA TABLES table to find tables you want, here is documentation: http://dev.mysql.com/doc/refman/5.0/en/tables-table.html . TABLES table has column NAME which represents names of tables. After finding table names you can run any sql queries  you like.

A: That's not possible in the way you'd like to do it. However you could probably use prepared statements which are basically query-templates where you specificy the parameters (AFAIK also table names) that get replaced depending on your needs without copy and pasting the same query over and over again for different tables.

A: No, you can't do that with MySQL. Tables in a query can't be dynamically specified - you have to build the list in your application (or do several single-table queries).


text:
Q: Find all numbers $n$ divisible by $a$ whose sum of digitis is $b$. I said to myself that it would be funny to find a natural number whose digits add to $69$ divisible by $420$. At first it might sound really silly but when I tried to find such a number it turned out to be way more difficult that I thought.
At first I tried the following, let $n$ be any number such that $420 \mid n$ and $s(n) = 420$, being $s(n)$ the sum of its digits. So for some $k \in \mathbb{N}$, $s(n) = s(420k) = s(2^2 \cdot 3 \cdot 5 \cdot 7\cdot k) = 69$, but I noticed that this wouldn't take me anywhere since I don't know any way of solving for all possible $k$.
The next thing that I tried was finding a number using the divisibility criteria, so I found the number $777.777.777.420$ since it is clearly divisible by $7$, its digits add to a multiple of $3$, more specifically $69$, and its last two digits are a multiple of $4$ and $5$. So this method proved to be useful but not quite efficient.
My question is:

Given any numbers $a$ and $b$, what is the easiest way to find natural numbers $n$ such that $a \mid n$ and $s(n) = b$?


text:
Q: jquery .change function to populate form fields from database not working with Js dynamically added rows I have a form that  the user inputs a category into form field categories, other fields on the form like rate, tarriff codes, etc are populated with information from the database, so far i have that working fine, my problem is that the form allows the user to dynamically add rows with those fields in it for another category, but after that row is created when i try to input another category nothing happens the other fields are not being populated like in the first row.
This is the code i am using. This works to get the information for one row but nothing happens for the rest

My getTariffcd.php is this
    <?php
          $pdo = new PDO("mysql:host=localhost;dbname=customs;charset=utf8",
              "root", "");

              header("Content-Type:application/json; Charset=utf-8");

                 $st = $pdo->prepare("SELECT tariffcd, sub_heading, rate,
                       elevy FROM lt_products WHERE categories =
                         :categories");
                             $st->execute(array ('categories' =>
                                  $_POST['categories']));
                                     $data = $st->fetch(PDO::FETCH_ASSOC);
                                         echo json_encode(array ('status' =>
                          true, 'tariff' => $data ['tariffcd'], 'subhead' =>
                  $data ['sub_heading'], 'rate' => $data ['rate'], 'elevy'
             => $data ['elevy']));

My Form rows are this

          <?php //connect to mysql database
               $connection =
                    mysqli_connect("localhost","root","","customs")or
                             die("Error " . mysqli_error($connection));
                               //fetch data from database
                       $sql = "select categories from lt_products";
                     $result = mysqli_query($connection, $sql) or die("Error
          " . mysqli_error($connection));?>

         <input type="text" list="productcategories"   name="categories[]"
              class="form-control"  id="categories" placeholder="Type Name
                  of Product" >
                          <datalist id="productcategories">

                              <?php while($row = mysqli_fetch_array($result,
                                           MYSQLI_ASSOC)){ ?>
               <option value="<?php echo $row['categories']; ?>"><?php echo
              $row['categories']; ?></option> <?php } ?>
          </datalist>
    <?php mysqli_close($connection); ?>

        Tariff CD:
        <input type="text" class="form-control" name="tariffcd[]"
              disabled="disabled" id="tariffcd">

        Subheading:
         <input type="text" class="form-control" name="sub_heading[]"
              disabled="disabled" id="sub_heading">

         Rate:
         <input type="text" class="form-control" name="rate[]"
             disabled="disabled" id="rate">

         Environmental:
          <input type="text" class="form-control" name="elevy[]"
              disabled="disabled" id="rate">

$

                      <input type="text" name="cost" class="form-control"
                         id="cost" size="6" maxlength="6" onKeyPress="return
                           isNumberKey1(event)" placeholder="Cost" <?php if
                     (isset($_POST['cost'])) echo "value=\"" .
                  $_POST['cost'] . "\"" ?>>

.00

         <button class="btn btn-success btn-add" type="button">

                    </button>

           Press  to
               add another Item to form :)

The Java Script to add the rows is this
$(function()
 {
   $(document).on('click', '.btn-add', function(e)
  {
    e.preventDefault();

    var controlForm = $('.controls form:first'),
        currentEntry = $(this).parents('.entry:first'),
        newEntry = $(currentEntry.clone()).appendTo(controlForm);

    newEntry.find('input').val('');
    controlForm.find('.entry:not(:last) .btn-add')
        .removeClass('btn-add').addClass('btn-remove')
        .removeClass('btn-success').addClass('btn-danger')
        .html('');
   }).on('click', '.btn-remove', function(e)
  {
    $(this).parents('.entry:first').remove();

       e.preventDefault();
        return false;
    });
 });

Any help would be  very much appreciated.


text:
Q: Using Ninject with a Windows Service Any good examples of using Ninject with a Windows Service? I'm not sure what if any extensions I need. Also, not sure what the Composition Root should be? Any good examples of using Ninject with a Windows service out there?

A: A windows service does not differ much from a regular command line application in regard to dependency injection. The straight-forward composition root is your Main method.
The way I usually have done it is create the StandardKernel there with a module in which my dependencies are resolved. Then use kernel.Get to resolve the top level dependencies - everything else will follow from there:
static void Main(string[] args)
{
    var kernel = new StandardKernel(new FooModule());
    var barDependency = kernel.Get<Bar>();

    System.ServiceProcess.ServiceBase[] ServicesToRun;
    ServicesToRun = new ServiceBase[] { new FooService(barDependency) };
    System.ServiceProcess.ServiceBase.Run(ServicesToRun);
}

A: Using Ninject with TopShelf.. run vs install(start)
I faced a strange issue where > MyService.exe run
works fine with the code  Kernel.Bind(handlers => { var bindings = handlers.From("abc.dll") ... }
But when i start the service after installing using > MyService.exe install
it could not resolve the bindings mentioned in Ninject assembly scanning.
After a few hours of breaking my head...
changing the .From(...) to .FromAssembliesMatching(...) i could start the service successfully.
Hope it helps someone.


text:
Q: SP13 - Deploy and debugging stop work for other developers in project My SharePoint team (back-end and front-end developers) work on project.
Solutions are Visual Web Parts for SharePoint 2013. Where one developer deploy her solution or debug web part from visual studio stopping the work of others developers. How to solve this problem?
Thank you previously!

A: Its common that SharePoint Sites stops working for a while till the deployment completes as it includes IIS Application Pool Recycle retracting/adding solutions and its assemblies into layouts folder.
Similarly for debugging, Visual Studio will attach an IIS worker process(w3wp.exe) to the specific application pool to debug the solution. So the sites will not work until that process hits the break point or while its executing.
To avoid stopping other developers work while debugging, you can create separate web application for each developer. So that each developer will have separate Application Pool and  when they can attach worker process to their own Application Pool(their own Web Application) without affecting others development.
https://social.technet.microsoft.com/Forums/office/en-US/7ee3858f-243c-4f43-a72d-3483ad1506f6/multiple-developers-debugging-on-different-web-apps-on-single-server?forum=sharepointgeneral

A: Arun's solution would work, but another is to give each developer their own dev environment. So, each dev would have their own server to work on. If you haven't thought about this before, then it may seem extreme, but this is the common strategy people use. Create an image that's a single server farm, and let each dev have a copy of it to run on their workstation or on a server via hyper-v. Each dev then gets an environment that is unaffected by anything that other developers do. Then, set up another farm, and set up a process so that any code that gets checked in gets deployed to that server for testing purposes.


text:
Q: How can i link the "UserID" with the "username" so i can update my table? Here is my query:
$query = ("UPDATE users SET username='$username', password='$password', email='$email' WHERE userID = '79'");

$result = mysqli_query($connection, $query);

Instead of updating user 79, I want to update the person who is logged in. Therefore, instead of putting 79, would I put $_SESSION?. If so, the session is linked to the username, not the user ID. So I was wondering, how can I link the username which the person is logged in on, with the userID that associates with it?
Sorry, I am new to this forum.
When they log in, they only type in their username and password. They do not type in their userID. So how can i grab the userID when it isnt being posted through a form? I somehow need to link the username (that they type in), with their userID.

A: Stored the user ID as well when you store the user name in $_SESSION. You just need to write $_SESSION['UserID']='USER_ID_VALUE'
Doing that you'll be able to access the user id while the user has an active session.

A: This is one of the perils of rolling your own session management system. If you've never done it before you will make a lot of mistakes. Some of these mistakes will be very serious. This is why using a development framework to give you a good foundation is almost always a good idea.
In general, when you successfully login you should capture the ID of the user that was logged in. The username can't be presumed to be consistent over time, but the ID will be.
Then you can perform updates vs. this ID.
Keep in mind that with an ORM like Doctrine or Propel this would be extremely easy. The way you're going about it here makes it intentionally difficult.

A:
$identity = new stdClass();
$identity->user_id =123;
$identity->username = 'john';

$_SESSION['identity'] = $identity;

// usage without checks,

$identity = $_SESSION['identity'];
echo $identity->user_id;


text:
Q: Casting from void* to int Hello I'm trying to cast arguments from void* to int using
id=*((int *)x);

But I'm getting different values than the original value of x. I've read about using intptr_t but could not understand how to use it

A: That's not a cast, that's a dereference. You want:
id = (int) x;

A: Your approach is casting void pointer to int pointer, not to int. You can cast void pointer to int directly, like this
int n = (int)p;

However, that is not guaranteed to work for all values of integer.
Instead, you should use intptr_t. Change parameter type from void pointer to intptr_t, and use the cast above. This is guaranteed to be portable.


text:
Q: Opening Ports from Docker on buildroot system I just set up buildroot on my RPi3 with docker. It boots up fine and docker also works, but when I try to run a container (e.g. portainer) that need to open a port, it fails with
docker: Error response from daemon: driver failed programming external connectivity on endpoint portainer (b6130d6ee0d30f867ff0e99349db1567389b18e9f42ca35718e0a5aefcb3976d): Error starting userland proxy: listen tcp [::]:9443: bind: address already in use.

It doesn't matter which port I try, it always fails.
doing a netstat | grep 9443 doesn't give any output, which should mean that ther is no other process using this port.
Any recommendations on how to fix this?
EDIT 1: my buildroot version is 2021.08-rc3 and my config can be found in this pastebin
https://pastebin.com/ttWZ6PpY
I am trying out if the same thing happens on buildroot 2021.08.
EDIT 2: I switched to buildroot 2021.08 and changed as little as possible, so only make raspberrypi3_64_defconfig, changing to glibc as C library, enabling docker-cli, docker-compose, docker-engine, ntp (with ntpd) and openssh as well as setting timezone, rootpassword and filesystem image size to 512M, then flashing the image and extending the root partition. After booting up I directly startet a mimimal container like in the unit test with docker run --rm -p 8888:8888 busybox:latest /bin/true, but I still get the same error.
The new config can be found here:  https://pastebin.com/hrTKf26B
EDIT 3: I also tried the 32bit-version (so make raspberrypi3_defconfig in the beginning), but that results in the same error when trying to start a docker container.
EDIT 4: I also tried going back to buildroot LTS (2021.02.5) and installing dbus, but both didn't help.

A: I solved this issue following this another post which provides a solution to disable userland-proxy for docker-compose.
I struggled with this the whole day. The key was the part of the error message that says 'Error starting userland proxy'.
I'm also in an RPi3 but with Buildroot 2021.02.8. I've had this selection related to docker on the menuconfig:
[*] docker-cli
[ ]   build static client
[*] docker-compose
-*- docker-containerd
[ ]   btrfs snapshot driver
[*] docker-engine
... (rest unselected)
-*- docker-proxy


text:
Q: If I was asked to define what a "file storage block" is, what should my answer be? A question says "Define a file storage block with reference to the physical file system in UNIX".

*

*What is the difference between a file storage block and a storage block?

*What is the answer that I should write for this question?


text:
Q: Alcoholic beverage brought by groom as a gift to bride's family I'm naturally an Estonian and we have a word called "kosjaviin" and it's a noun. In general it is a bottle of strong alcohol (~40%) brought by groom as a gift to the bride's family. The first part of the word means "betroth" and the other part means "vodka". In Estonia it is a traditional gift to the future in-laws on the day the groom pops the question.
My question is: "Does there exist a similar word in English?"
Additional questions are welcome!

A: There is an incredibly archaic word, bridesmead, but it hasn't had any currency (except as a placename) in hundreds of years. (We did keep the mead month, or honeymoon, in the language, but the meaning has changed considerably with changing customs in matrimony.) Distilled spirits weren't "a thing" when the custom was alive; that didn't happen until the 12th century in Europe.


text:
Q: Would a propeller attached to, but inside a sealed box work? I can't find anything online about this, maybe I'm just dumb, but I was wondering, if you put a propeller inside of a air tight, water tight box, and turned it on, would it propel the box? If not, why?

A: No, it wouldn't work. Because when you switch on the propeller, it will propel some stuff(like air or water depending on what you are propelling) backwards. So it seems like the propeller will get some push in forward direction and gain some momentum, but because you have a closed container so the stuff will collide the walls which will decrease the momentum that it gained earlier and will again come back to initial state. Another way to see this is that there are no external forces on the system (box + propeller) so it would not accelerate according to Newton's Second Law $F_{external} = ma $ .
You might think what about the energy that I will supply to the propeller to rotate it, where will it go, who will consume it?
Answer:
The energy you spent in propelling will heat up the stuff you are trying to propel. Your stuff particles will move in random directions after having enough collisions with their neighbors making total momentum to zero but will have some non-zero total randomized kinetic energy which is the measure of temperature.


text:
Q: how do I enforce referential integrity between a many to many table and its parent tables I have 4 tables.

*

*Table 1 stores data for Airlines

*Table 2 stores data for Destinations

*Table 3 stores unique Routes(each route is a unique combination of airline and destination).

*Table 4 records the prices of all flights on the routes in table 3. This is a many to many table as there are many flights by each airline to many destinations.

Table 1 = Airlines
    Airline_ICAO_Code varchar(3) Not NULL Primary key,
    Airline varchar(22) NULL

Table 2 = Destinations
    Airport_ICAO_Code varchar(4) Not NULL Primary key,
    Destination varchar(30) NULL

Table 3 = Airlines2Destinations
    ID int IDENTITY(1,1) NOT NULL,
    Airport_ICAO_Code varchar(4) Not NULL Foreign Key References Destinations(Airport_ICAO_Code),
Destination varchar(30) NULL,
    Airline_ICAO_Code varchar(3) Not NULL Foreign Key References Airlines(Airline_ICAO_Code),
    Airline varchar(22) NULL

Table 4 = Airlines2DestinationsPrices
    ID int IDENTITY(1,1) NOT NULL,
    Airport_ICAO_Code varchar(4) Not NULL Foreign Key References Destinations(Airport_ICAO_Code),
    Destination varchar(30) NULL,
    Airline varchar(22) NULL,
    Airline_ICAO_Code varchar(3) Not NULL Foreign Key References Airlines(Airline_ICAO_Code),
    Departure smalldatetime,
    Price smallmoney

My problem is how do I enforce referential integrity between tables 3 and 4. This is necessary as the routes entered in table 4 must be present in table 3. I need advice as to what way to set up the Primary keys on Table 3 and Table 4 that will enable me to do this.
I am considering using a composite key on table 3 like this:
Primary Key(Airport_ICAO_Code,Airline_ICAO_Code)

or concatenating the Airport_ICAO_Code and Airport_ICAO_Code columns into a new column and dropping the ID columns.
If I use the Identity column as the primary key for both tables there is no guarantee that the ID for a route in Table 4 will match the ID for a route in Table 3.
Because of all these options I'm unsure of the best way forward. If someone could take the time to help out on this it would really be appreciated.
Thanks for any help offered
Edit:
After receiving advice from Marc in the post below I set up Table 4 as follows. However there is no primary key on this table. Would the ID column be better for the Primary key or could I use a Composite Key like this Primary Key (Airlines2DestinationsID,Departure).
Table 4 = Airlines2DestinationsPrices

ID int IDENTITY(1,1) NOT NULL,
Airlines2DestinationsID INT NOT NULL
    FOREIGN KEY REFERENCES dbo.Airlines2Destiations(ID),
Departure smalldatetime,
Price smallmoney

A: Basically, if any one entry in table 4 always belongs to a single entry in table 3, I would just store the Airlines2Destiations.ID as a foreign key into table 4.
That way, each entry of table 4 is always clearly and uniquely connected to a single entry in table 3. Also: drop all the redudancy from table 4 - you only need the reference to table 3 - you don't need to repeat airline or airport codes and names.
Table 3 = Airlines2Destinations
ID int IDENTITY(1,1) NOT NULL,
Airport_ICAO_Code CHAR(4) NOT NULL
     Foreign Key References Destinations(Airport_ICAO_Code),
Destination VARCHAR(30) NULL,
Airline_ICAO_Code CHAR(3) NOT NULL
     Foreign Key References Airlines(Airline_ICAO_Code),
Airline VARCHAR(22) NULL

Table 4 = Airlines2DestinationsPrices
ID int IDENTITY(1,1) NOT NULL,
Airlines2DestinationsID INT NOT NULL
    FOREIGN KEY REFERENCES dbo.Airlines2Destiations(ID),
Departure smalldatetime,
Price smallmoney


text:
Q: What is the processing libraries processing.js can execute? I want to create socket connection with processing.js. But processing.js can't use java library. Can I use processing.net.* ? And What is the processing libraries processing.js can execute? I can't find the list of libraries. Help me!!

A: As far as I know, Processing.JS has no support for Processing libraries. But since it is JavaScript, you can use a framework like jQuery and any libraries for jQuery.
As far as socket connections, take a look at Socket.io (http://socket.io/) to connect to a socket from JavaScript. You can use JavaScript inside Processing.JS.

A: There ARE some libraries which are 'cross-platform', that is, they work with (at least) Java and Javascript. Two examples I know of are Guido and RiTa, but there may well be others...


text:
Q: SQL Group by range and total column With the following function and stored procedure i get a resultset with 2 columns.
What i need additional is a third column total for all open invoices inner score range
It would great for any idea.
  ALTER FUNCTION dbo.OpenOrders
    (
    @MandantId int
    )
  RETURNS TABLE
  AS
  RETURN
  SELECT        SUM(Invoices.Amount - ISNULL(Payment.Amount, 0)) AS Op
  FROM            Invoices INNER JOIN
                           Orders ON Invoices.OrderId = Orders.OrderId LEFT  OUTER JOIN
                           Payment ON Invoices.InvoiceId = Payment.InvoiceId
  WHERE        (Orders.MandantId = @MandantId)
  GROUP BY Invoice.InvoiceId, Invoices.Amount
  HAVING        (SUM(Invoices.Amount - ISNULL(Payment.Amount, 0)) <> 0)

  ALTER PROCEDURE dbo.GetOpRanges
  @MandantId int
  AS
  BEGIN

    SELECT * INTO #tmp_ranges

    FROM

    //wrong in first post -> OPDebitorByMandant(@MandantId)
    OpenOrders(@MandantId)

    SELECT  op AS [score range], COUNT(*) AS [number of occurences]
    FROM
    (SELECT CASE
      WHEN op BETWEEN 0 AND 50 THEN '  0- 50'
      WHEN op BETWEEN 50 AND 100 THEN ' 50-100'
      WHEN op BETWEEN 100 AND 500 THEN '100-500'
      ELSE '500 and >' END AS op
    FROM [#tmp_ranges]) AS t

    GROUP BY op

    RETURN

Result:
score range number of occurences range
------------------+-------------
  0- 50            23
 50-100            4
100-500            4
500 and >          21

What i need additional is a third column total for all open invoices inner score range.

Target result:
score range number of occurences Total
-----------+--------------------+------
  0- 50            23             1.150
 50-100            4                400
100-500            4              2.000
500 and >          21            22.000

      Tables:
    Invoices
    InvoiceId  CustomerId OrderId DateOfInvoice Amount
    ----------+----------+-------+-------------+------
    1          1           20      20160301      1000.00
    2          2           22      20160501      2000.00
    3          1          102      20160601      3000.00
    ...

    Orders
    OrderId MandantId CustomerId DateOfOrder Amount
    -------+---------+----------+-----------+-----------
     20     1         1          20160101     1000.00
     22     1         2          20160101     2000.00
    102     1         1          20160101     3000.00
    ...

    Payment
    PaymentId MandantId CustomerId InvoiceId OrderId DateOfPayment Amount
    ---------+---------+----------+---------+-------+-------------+-------------
    1         1         1          1          20     20160310      1000.00
    2         1         2          2          22     20160505      2000.00
    3         1         1          3         102     20160610      3000.00
    ...

hope it's helpfull and thanks again in advance for any solution


text:
Q: How to add XML tags to an XML document from posted data? I am trying to write a web-based data visualisation app that allows users to load in a txt file, autoparse it to xml, view it on the screen, right-click on the text and assign a tag to all counts of the selected word.
Currently upon right click, I pass to the PHP handler: element name to be added, the attribute name to be added, the value to be added, the files name, and the selected word. I have all of these available in the handler, but after several hours of searching I cannot figure out how to add the tag element/attribute/value to the selected word in the XML file.
php file
<?php

$target_dir = "../UserFiles/Files/";

//$filename = $_POST["filename"];

$filename = "Chretien 1 Erec";

//$element = $_POST["element"];

$element = "Emotion";

//$attribute = $_POST["attribute"];

$attribute = "Type";

//$value = $_POST["value"];

$value = "Positive";

//$selection = $_POST["selection"];

$selection = "vilains";

$target_file = $target_dir . $filename . ".xml";

//if(isset($_POST["submit"])) {

  $xml = file_get_contents($target_file);

  $sxml = simplexml_load_string($xml);

  //get current xml elements

  $docElements = [];

  array_push($docElements, $sxml->getName());

  foreach ($sxml->children() as $child){

      array_push($docElements, $child->getName());

  }

  if (in_array($element, $docElements, true)) {

    echo "It's there!";

  } else {

    echo "It's not there!";

    $result = $sxml->xpath($element);

    print_r($result);

    //$sxe = new SimpleXMLElement($element);

    //$sxe->addAttribute($attribute, $selection)

  }

?php>;

xml file
<?xml version="1.0"?>;

<LiteraryWork Author="Chretian" Title="Erec" Type="Romance">

 Li vilains dit an son respit

que tel chose a l'an an despit

qui mout valt mialz que l'an ne cuide

por ce fet bien qui son estuide

atorne a bien, quel que il l'ait

car qui son estuide antrelait

tost i puet tel chose teisir

<LiteraryWork>


text:
Q: Finding angle between a moving tangent and a fixed point Actually, this is a part of a physics question I was recently solving.
Here's what I've come to.
There's an arbitrary point in a circle of radius (say, r). We need to find the minimum angle the line joining a point on the circumference of the circle makes with the tangent drawn at that point.
Originally, I've come to the point where I need to find the point at which the vector (velocity vector, in this case) has its component maximum along the line joining the point and the initial arbitrary point.
I know that the question might sound a bit confusing, but please try to understand it and hint me the solution. Hints to the solution would be fine.

A: Let your circle be centered at the origin. Let the point on the periphery be $Q=r\pmatrix{\cos \theta \\ \sin \theta}$ and the point inside the circle be $P=\pmatrix{x_0 \\ y_0}$.
A vector parallel to the tangent at $Q$ will then be $r_1=\pmatrix{-\sin \theta \\ \cos \theta}$, and a vector along the line from $P$ to $Q$ will be $r_2=\pmatrix{x_0-r\cos \theta \\y_0- r\sin \theta}$.
The angle $\phi$ between these vectors are given as
$$\cos \phi=\frac{r_1 \cdot r_2}{|r_1||r_2|}=\frac{y_0\cos \theta-x_0\sin\theta}{|r_2|},$$
where $$|r_2|=\sqrt{(x_0-r \cos \theta)^2+(y_0-r\sin\theta)^2}=\sqrt{r^2+x_0^2+y_0^2-2r(x_0 \cos \theta+y_0\sin \theta)},$$
which can then be solved for $\phi$. This unfortunately cannot be simplified any further - for that, we would have to know more about $P$ and $Q$.


text:
Q: Implement inheritance in C I was working with GTK in one of my projects and I noticed that the library supports inheritance. As you can type-cast a child struct to its parent struct and vice versa. Other than GTK I've never seen this used (so flawlessly):
struct parent p = {5};
struct child c;
c = (struct child)p;
c.b = 1;
//c.a = 5, c.b = 1

Does using the parent struct as the first element do this? As this would seem much more neat. But could padding and aligning interfere?
struct parent { int a; }
struct child  { struct parent p; int b; }

Or does rewriting all parent data make it happen?
struct parent { int a; }
struct child  { int a; int b; }

EDIT I am NOT looking to implement all pillars of OOP in C. My question is only involving type-casting the data in parent and child structs. I have found that GTK uses GObject to do this, but what must be done to achieve what GObject is doing as far as type casting?


text:
Q: AWK - Extracting the last syllable of words I have to extract the last syllable of several words.
The words will always end in a consonant.
The possible consonants are these: "b c cs d dz dzs f g gy h j k l ly m n ny p q r s sz t ty v w x y z zs"
The possible vowels are these: "a o u ö ü e i á ó ú ő ű é í"
Given this word, "vélemény" , I have to extract ény
Given this word, "otthion", I have to extract ion
Given this word, "feladat", I have to extract at
I have made this function, which will return the position of the last vowel.But what if two vowels together?
function extrac(arr1,arr2,x1)
{
    # arr1 - array-vowels "a o u ö ü..."
    # arr2 - array-word divided into letters
    # x1 - length-arr2

    for (ix=x1; ix>0; ix--)
    {
        for (jx=1; jx<=14; jx++)
        {
            if (arr1[jx] == arr2[ix])
            {
                return ix;
            }
        }
    }

}

IN
vélemény
otthion
feladat

Desired output:
vélemény    ény
otthion    ion
feladat    at

A: $ awk 'match($0,/[aouöüeiáóúőűéí]+[^aouöüeiáóúőűéí]+$/,a){print $0, a[0]}' file
vélemény ény
otthion ion
feladat at

The above uses GNU awk for the 3rd arg to match(). With other awks it'd be:
$ awk 'match($0,/[aouöüeiáóúőűéí]+[^aouöüeiáóúőűéí]+$/){print $0, substr($0,RSTART,RLENGTH)}' file
vélemény ény
otthion ion
feladat at

With some awks you might be able to use Equivalence Classes instead of listing each possible variation of each vowel:
/[[=a=][=e=][=i=][=o=][=u=]]+[^[=a=][=e=][=i=][=o=][=u=]]+$/

but Equivalence Classes aren't supported in GNU awk.


text:
Q: Install Amazon pay extension from admin panel in magento 2.2.3
Readiness check fails while installing Amazon pay module in Magento CE 2.2.3
for checking cron scripts i have changed the code in

C:\xampp\htdocs\dev\setup\src\Magento\Setup\Controller\Environment.php

Uncomment this
    $setupCheck = $this->cronScriptReadinessCheck->checkSetup();
    $updaterCheck = $this->cronScriptReadinessCheck->checkUpdater();

and add this
    $setupCheck = ['success' => 1];
    $updaterCheck = ['success' => 1];

the above code is to avoid check cron.
PHP settings check and PHP extensions check are failed
XAMPP v3.2.2 php version 7.0.27
How do i fix this and install any extension from admin page ?

A: You should check below links
https://www.magestore.com/magento-2-tutorial/fix-php-settings-check-error-in-magento-2-0-installation-on-localhost/
http://devdocs.magento.com/guides/v2.0/install-gde/trouble/php/tshoot_php-set.html
These links will help you.


text:
Q: Retrieve response and do an action in a HttpWebRespo call, from an IAsyncResult function C# From my class I call another class that makes a call to an API with an IAsyncResult function that listens when the server responds.
My question is how do I go about when the API responds, take that response and do an action.
My code listens, and grabs the answer, but I'm not managing to do anything with it
winForm.cs:
var response = services.postService(payment,url);
//if response Its OK make somthing

service.cs
  public HttpWebRequest request;

  private static ManualResetEvent allDone = new ManualResetEvent(false);

  public void postService(PayModel paymentObject, String url)
    {

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url + "pay");
        request.ContentType = "application/json";
        request.Method = "POST";

        var response = request.BeginGetRequestStream(new AsyncCallback(result => GetRequestStreamCallback(result, paymentObject)), request);
    }

    public void GetRequestStreamCallback(IAsyncResult asynchronousResult,PayModel paymentObject)
    {
        request = (HttpWebRequest)asynchronousResult.AsyncState;

        using (var streamWriter = new StreamWriter(request.EndGetRequestStream(asynchronousResult)))
        {
            string json = new JavaScriptSerializer().Serialize(paymentObject);
            Console.Out.WriteLine(json);
            streamWriter.Write(json);
            streamWriter.Flush();
            streamWriter.Close();
        }

        var response = request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);

    }

    private void GetResponseCallback(IAsyncResult asynchronousResult)
    {
        request = (HttpWebRequest)asynchronousResult.AsyncState;

        HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
        Stream streamResponse = response.GetResponseStream();
        StreamReader streamRead = new StreamReader(streamResponse);
        string responseString = streamRead.ReadToEnd();
        Console.WriteLine(responseString);
        streamResponse.Close();
        streamRead.Close();
        response.Close();
        allDone.Set();
        frmVenta.closeTransaccion();
    }

I tried many things but I can't get the answer, when I put a return on it, it never performs the action, the program continues and does not return
I cant use HttpClient , the program es older.


text:
Q: How do I convert Oracle query to criteria query? select l.city,
       l.street_address,
       c.country_name,
       r.region_name
from HR.locations l join HR.countries c using (country_id)
                    join HR.regions r   using (region_id)

A: Finally I got the answer by using simple logic.
private static void getLocations(Session session){
    Criteria query = session.createCriteria(Locations.class);
    Criteria countries= query.createCriteria("country");
    Criteria regions =countries.createCriteria("region");

    List<Locations> locations = regions.list();

    for(Locations loc: locations){
        System.out.println(loc.getCity() + " "+loc.getStreetAddress()+" "+loc.getCountry().getCountryName()
                +" "+loc.getCountry().getRegion().getRegionName());
    }

}


text:
Q: VScode integrated terminal suddenly throws an error during initialization I'm using the most recent VScode on Ubuntu 22.10 and experiencing the following issues while opening ZSH and BASH shells in the integrated terminal. The standard Ubuntu terminal works without errors.
After starting a ZSH integrated terminal:
compdump:138: command not found: mv
/home/user/.oh-my-zsh/oh-my-zsh.sh:56: command not found: mkdir
/home/user/.oh-my-zsh/tools/check_for_upgrade.sh:29: command not found: git
/home/user/.oh-my-zsh/oh-my-zsh.sh:115: command not found: rm
getent:6: command not found: grep
_p9k_init_cacheable:59: command not found: uname
_p9k_init_cacheable:61: command not found: uname

BASH
Command 'uname' is available in the following places
 * /bin/uname
 * /usr/bin/uname
The command could not be located because '/bin:/usr/bin' is not included in the PATH environment variable.
uname: command not found

Just several hours before, it worked just fine. Then I tried to set up Remote SSH to another Linux machine (Fedora 36, with the same sort of errors I was also unable to resolve by googling).
Using the @modified keyword in Settings, I ensured that no unexpected changes had been made. The PATH is the same as in the fully operational standard terminal.
Wondering what could be the issue.
UPDATES.
PATH variable:
/usr/local/cuda-11.7/bin:/home/user/.conda/envs/env/bin:$PATH
The problem.
Unlike the complete PATH expansion in the standard terminal, PATH was expanded partially (omitting /usr/bin, etc.) in the integrated terminal.

A: Based on this error,
The command could not be located because '/bin:/usr/bin' is not included in the PATH environment variable.
I suggest you run,
export PATH="/usr/bin:$PATH"
To add /bin:/usr/bin to your PATH
Having :$PATH in your PATH means that the sheell will add the variable $PATH to the end of your PATH

A: The cause of the issue the following configuration from the User settings:
terminal.integrated.env.linux": {
    "PYTHONPATH": "/media/user:/media/user/common:$PYTHONPATH",
    "PATH": "/media/user:/media/user/common:$PATH"
}

While the PYTHONPATH variable is expanded properly in the integrated terminal, the PATH is expanded partially to something shown in the UPDATES section of the question. To build on top of the answer by @Orion447, looking for any potential place where PATH could get corrupted is the approach that likely solves the problem.


text:
Q: How to send data param to server using datatables jquery I have this code to draw datatables, so I try to get data from server in JSON format but I need to send data: ajdi variable...
My code:
function drawMeh() {

                $('#Meh').dataTable({
                    "ajax": "track_meh.php",
                    paging: false,
                    //"dom":' <"search"f><"top"l>rt<"bottom"ip><"clear">',
                    // end ,
                    "columns": [{
                            "data": "ID"}, {
                            "data": "datum"}, {
                            "data": "masina"},{
                            "data": "radnih_sati"},{
                            "data": "kolicina"},{
                            "data": "cena"},{
                            "data": "ukupno"},{
                            "data": "akcija"
                        }
                    ],

                    "columnDefs": [
                            {
                        "targets": 7,
                        "data": "akcija",
                        "render": function(data, type, full, meta) {
                            // return data;
                            return '

';
                        }
                            },

                            {
                        "targets": [0],
                        "visible":false
                            }

    ]
                });

            };

How I can send data: ajdi to server to get right JSON data from track_meh.php ?

A: Here is from datatable 1.10:
 "ajax" : {
                "url" :  "track_meh.php",
                "type" : "POST",
                "data" : ajdi
            },

Here is from the legacy:
$(document).ready( function() {
  $('#example').dataTable( {
    "bProcessing": true,
    "bServerSide": true,
    "sAjaxSource": " track_meh.php",
    "fnServerData": function ( sSource, aoData, fnCallback, oSettings ) {
      oSettings.jqXHR = $.ajax( {
        "dataType": 'json',
        "type": "POST",
        "url": sSource,
        "data": ajdi,
        "success": fnCallback
      } );
    }
  } );
} );

A: something like this, http://prototypejs.org/learn/introduction-to-ajax
new Ajax.Request('/some_url', {
  method: 'get',
  parameters: {company: 'example', limit: 12}
});


text:
Q: Merge 2 data frames based on matching rows of 2 columns with Pandas I have a very important problem that needs to be solved for a project!
So I have 2 data frames that look like these ones:
The first Dataframe is:
Date            Winner      Loser         Tournament
2007-01-01      Luczak P.   Hrbaty D.     Grandslam
2007-01-02      Serra F.    Johansson J.  Grandslam
2007-01-02      ......      ......

The second Dataframe is:
Date            Winner      Loser          Tournament
2007-05-28      Federer R.  Russel M.      Grandslam
2007-05-28      Ascione T.  Cilic M.       Grandslam
2007-05-28      ......      ......

The two data frames have the same number of rows corresponding to the same matches from the same period even though the first one starts from 2007-01-01 and the other from 2007-05-28. I checked it by looking at the excel files which I imported to build the two data frames (from different sources).
The problem is that one Dataframe (the first one) gives me the exact date for each match while the other Datframe (second one) sets the date for each row as the starting period of the tournament and not the exact date that match was played. So I cannot merge the two data frames based on Date values.
However, I know for sure that the couples of Winner and Loser for each row are the same so I wanted to merge the two data frames based on the rows in which the winner and the players are the same.
Does anybody knows how I can do this? Thanks in advance!

A: You can do it by merge_asof:
df = pd.merge_asof(df1.sort_values('Date'),
                   df2.sort_values('Date'), on='Date', by=['Winner','Loser'])

A: df= pd.merge(df1,df2,how='inner',left_on=['Winner','Loser'],right_on=['Winner','Loser'])


text:
Q: Getting an error when trying to delete team Django When I try to add delete to my views I receive an error:

Team matching query does not exist.

What am I doing wrong in here? It seems like traceback leads me to context_processor.py. This is my code below:
Views.py
@login_required
def team(request, team_id):
    team = get_object_or_404(Team, pk=team_id, status=Team.ACTIVE, members__in=[request.user])
    invitations = team.invitations.filter(status=Invitation.INVITED)

    return render(request, 'team/team.html', {'team': team, 'invitations': invitations})

@login_required
def activate_team(request, team_id):
    team = get_object_or_404(Team, pk=team_id, status=Team.ACTIVE, members__in=[request.user])
    userprofile = request.user.profile
    userprofile.active_team_id = team.id
    userprofile.save()

    messages.info(request, 'The team was activated')

    return redirect('team:team', team_id=team.id)

@login_required
def add(request):
    profile = request.user.profile
    form = TeamForm()
    if request.method == 'POST':
        form = TeamForm(request.POST, request.FILES)

        if form.is_valid():
            team = form.save(commit=False)
            team.created_by = request.user
            team.save()
            team.members.add(request.user)

            profile.active_team_id = team.id
            profile.save()

            return redirect('account')

    context = {'form': form}
    return render(request, 'team/add.html', context)

@login_required
def edit(request):
    #profile = request.user.profile
    team = get_object_or_404(Team, pk=request.user.profile.active_team_id, status=Team.ACTIVE, members__in=[request.user])
    form = TeamForm(instance=team)
    if request.method == 'POST':
        form = TeamForm(request.POST, request.FILES, instance=team)

        if form.is_valid():
            team.save()

            messages.info(request, 'The changes was saved')

            return redirect('team:team', team_id=team.id)

    context = {'form': form, 'team': team}
    return render(request, 'team/edit.html', context)

@login_required
def delete(request, pk):
    team = Team.objects.get(pk=request.user.profile.active_team_id)
    if request.method == 'POST':
        team.delete()
        return redirect('account')
    context = {'object': team}
    return render(request, 'team/delete.html', context)

urls.py
urlpatterns = [
    path('add/', add, name='add'),
    path('edit/', edit, name='edit'),
    path('delete/', delete, name='delete'),
    path('invite/', invite, name='invite'),
    path('activate_team/<int:team_id>/', activate_team, name='activate_team'),
    path('<int:team_id>/', team, name='team'),
    path('teams_page/<int:team_id>/', teams_page, name='teams_page'),
]

delete.html
{% extends 'main.html' %}

{% block content %}

            <form class="form" action="" method="POST">
                {% csrf_token %}

Are you sure you want to delete "{{object}}"?

                Go Back

                <input class="btn btn--sub btn--lg  my-md" type="submit" value="Confirm" />
            </form>

{% endblock %}

context_processors.py
from .models import Team

def active_team(request):
    if request.user.is_authenticated:
        if request.user.profile.active_team_id:
            team = Team.objects.get(pk=request.user.profile.active_team_id)

            return {'active_team': team}

    return {'active_team': None}

The error traceback:
Traceback Switch to copy-and-paste view
D:\anaconda3\envs\gla-website\lib\site-packages\django\core\handlers\exception.py, line 47, in inner

                    response = get_response(request)

     …
▶ Local vars
D:\anaconda3\envs\gla-website\lib\site-packages\django\core\handlers\base.py, line 181, in _get_response

                    response = wrapped_callback(request, *callback_args, **callback_kwargs)

     …
▶ Local vars
D:\GLA-WEBSITE\gla\index\views.py, line 13, in index

        return render(request, 'index/index.html',context)

     …
▶ Local vars
D:\anaconda3\envs\gla-website\lib\site-packages\django\shortcuts.py, line 19, in render

        content = loader.render_to_string(template_name, context, request, using=using)

     …
▶ Local vars
D:\anaconda3\envs\gla-website\lib\site-packages\django\template\loader.py, line 62, in render_to_string

        return template.render(context, request)

     …
▶ Local vars
D:\anaconda3\envs\gla-website\lib\site-packages\django\template\backends\django.py, line 61, in render

                return self.template.render(context)

     …
▶ Local vars
D:\anaconda3\envs\gla-website\lib\site-packages\django\template\base.py, line 168, in render

                    with context.bind_template(self):

     …
▶ Local vars
D:\anaconda3\envs\gla-website\lib\contextlib.py, line 119, in __enter__

                return next(self.gen)

     …
▶ Local vars
D:\anaconda3\envs\gla-website\lib\site-packages\django\template\context.py, line 244, in bind_template

                updates.update(processor(self.request))

     …
▶ Local vars
D:\GLA-WEBSITE\gla\team\context_processors.py, line 7, in active_team

                team = Team.objects.get(pk=request.user.profile.active_team_id)

     …
▶ Local vars
D:\anaconda3\envs\gla-website\lib\site-packages\django\db\models\manager.py, line 85, in manager_method

                    return getattr(self.get_queryset(), name)(*args, **kwargs)

     …
▶ Local vars
D:\anaconda3\envs\gla-website\lib\site-packages\django\db\models\query.py, line 435, in get

                raise self.model.DoesNotExist(

A: Context processors are executed whenever a template is rendered.
You can't .get() a team after you delete it.

*

*Use .filter() and .first() instead:

def active_team(request):
    if request.user.is_authenticated:
        if request.user.profile.active_team_id:
            # team = Team.objects.get(pk=request.user.profile.active_team_id)           # Change this
            team = Team.objects.filter(pk=request.user.profile.active_team_id).first()  # to this

            return {'active_team': team}

    return {'active_team': None}

*You probably want to unset a user's active team when deleting the team:

@login_required
def delete(request, pk):
    team = Team.objects.get(pk=request.user.profile.active_team_id)
    if request.method == 'POST':
        team.delete()

        # Unset user's active team
        request.user.profile.active_team_id = None
        request.user.save()

        return redirect('account')
    context = {'object': team}
    return render(request, 'team/delete.html', context)

A: I belive that the delete query
team = Team.objects.get(pk=request.user.profile.active_team_id)

is not returning any result and so you can't perform any deletion with team object
try the following:
@login_required
def delete(request, pk):
  try:
      team = Team.objects.get(pk=request.user.profile.active_team_id)
      if request.method == 'POST':
          team.delete()
          return redirect('account')
      context = {'object': team}
      return render(request, 'team/delete.html', context)
  except Team.DoesNotExist:
      raise Http404("No Team found for the user")

or better, using get_object_or_404 like in edit function:
@login_required
def delete(request, pk):
  team = get_object_or_404(Team, pk=request.user.profile.active_team_id)
  if request.method == 'POST':
      team.delete()
      return redirect('account')
  context = {'object': team}
  return render(request, 'team/delete.html', context)


text:
Q: Android-facebook Message I would like to know is there any way to send a message to a friend in facebook from an android app.(Not wall post).Googled a lot about this topic but didn't get any proper solution.Guide me to some reference or blog

A: I am not sure about native application but you can do it from HTML5 application using javascript:-
https://developers.facebook.com/docs/reference/dialogs/send/
If no other solution place the script in an html file and load the same from the native app


text:
Q: Images only shows src with CKeditor After days of searching for my answer, i could not find anything that solved my problem.
I am currently making a custom small 'cms' for a website. I am using CKeditor and KCfinder for it. The problem is that I cannot add images on the webpage. All of the images are shown in the CKeditor, but when I save the changes, only an image src is shown on the front-end.
My currently echo in php is
<?php
    while($row = mysqli_fetch_array($typebox1)){
    echo $row['box1'];
    }
?>`

Where the echoed row is a database TEXT with some text and an image src.
I allowed image tags in the congifure.js file with
config.extraAllowedContent = 'img[src,alt,width,height]';

and add some script to replace the normal textarea
window.onload = function(){
    CKEDITOR.replace( 'box1',
    {
    toolbar : 'basic',
    uiColor : '# 9AB8F3',
    enterMode : CKEDITOR.ENTER_BR
    });

    CKEDITOR.replace( 'box2',
    {
    toolbar : 'basic',
    uiColor : '# 9AB8F3',
    enterMode : CKEDITOR.ENTER_BR
    });
};

But none of this all seems to work. If someone need further code just ask! I would appreciate every little step to the solution.

A: I solved the problem now. I needed to add htmlspecialchars_decode and htmlentities on the echoes to display the image correctly. CKEditor inserted &codes into the database, which made some problems.


text:
Q: Technical Details of Android Lollipop Settings View I am trying to figure out how would you implement something like an Android Settings View for both phones and tablets? It doesn't look like a ListView or RecyclerView utilizing CardView? Which Android class or component would you use to implement/design a similar looking ListView?
Its sort of a 2 column layout on tablets and one column layout on phones:

Any sample code or tips would be appreciated.

A: You can accomplish this by using a combination of RecyclerView and CardView for the General settings (Ex: Wireless and networks or Device), then you can use a GridView inside each card to hold the specific settings (Ex: WiFi or Controller). Then to accomplish the two column trick, use resource qualifiers on an xml file containing an integer for the number of columns you want to display.
I'll give you an overview of the code.
You have an xml file like recycler_layout.xml that holds the frame for everything.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <android.support.v7.widget.RecyclerView
        android:id="@+id/friend_rv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

Then you have the frame for a card with a GridView inside of it.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/settings_card">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal">
            <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Your General Setting Title"
            android:id="@+id/textView3" />
            <GridView
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:id="@+id/setting_content"
                android:numColumns="@integer/yourColumnInteger"/>
        </LinearLayout>
    </android.support.v7.widget.CardView>
</LinearLayout>

Finally you have a file like myIntegers.xml that contains yourColumnInteger where you define the value to be 1 if the user is on a phone (i.e. their screen is X size) and 2 if the user is on a tablet (i.e. their screen is Y size which is bigger than X)
Then all you have to do is wire up all the adapters for the thing. You'll need an adapter that populates the cards and an adapter for the GridView that populates the specific settings. (And I assume you understand that you will probably need another xml layout for the frame that makes of the specific settings like the setting icon and name in a vertical linear layout)


text:
Q: Prove that $\sqrt[5]{5} \notin \mathbb{Q}(e^\frac{2 \pi i}{25})$ I need to prove that $\sqrt[5]{5} \notin \mathbb{Q}(e^\frac{2 \pi i}{25})$. Let's call $\xi = e^\frac{2 \pi i}{25}$. I think I have found a solution using the field trace operator but I am not quite sure it is correct.
Let's call $T$ the field trace operator over $\mathbb{Q}$ and suppose $\sqrt[5]{5} \in \mathbb{Q}(\xi)$. Then there would exist $\alpha_i$ ($i \neq 5, 10, 15, 20$) such that:
$$ \sqrt[5]{5} = \alpha_0 + \alpha_1 \xi + \alpha_2 \xi^2 + \dots \alpha_{24} \xi^{24}$$
The trace of $\sqrt[5]{5}$ is $\sqrt{5} (1 + \xi^5 + \xi^{10} + \xi^{15} + \xi^{20}) = 0$ since it is the sum of the 5th roots of unity. On the other hand all the $\xi^j$ with $j \neq 5,10,15,20$ are conjugates between themselves so the trace of any of them is:
$$ T(\xi^j) = (\xi+\xi^2 + \dots \xi^{24}) = -(1+\xi^5+\xi^{10}+\xi^{15}+\xi^{20})=0$$
so taking traces at the original expression we find that $\alpha_0 = 0$.
Usually I multiply by some suitable expression at both sides and repeat this process so I can remove enough coefficients. In this case, however once i reach:
$$ \sqrt[5]{5} = \xi (\alpha_1 + \alpha_2 \xi + \dots + \alpha_{24} \xi^{23})$$
My only idea is to take norms and deduce that:
$$ \sqrt[5]{5} = |\alpha_1 + \alpha_2 \xi + \dots + \alpha_{24} \xi^{23}|$$
and iterate the process above to remove all coeficients (which would lead to an obvious contradiction). Would that be ok?

A: On one side, ${X^5} - 5$ is an Eisenstein polynomial, hence is irreducible over Q, so K = Q($\sqrt [5]5$) has degree 5 over Q; but K /Q is not galois because K does not contain any 5th root of unity. On the other side, because the given cyclotomic field L/Q is an abelian extension, all its subextensions are galois over Q, hence K is not contained in L .

A: What you mean by "taking the norm" looks like taking the complex absolute value. This however doesn't allow you to take trace anymore.
Usually this can be proved with Galois theory. A sketch of the procedure:

*

*Let $K$ be the field $\Bbb Q(\sqrt[5]5, \zeta_5)$ where $\zeta_5$ is a primitive fifth root of unity. Show that $K/\Bbb Q$ is Galois.

*Show that the two subextensions $\Bbb Q(\sqrt[5]5)/\Bbb Q$ and $\Bbb Q(\zeta_5)/\Bbb Q$ of $K/\Bbb Q$ have degrees $5$ and $4$ respectively.

*Show that $K/\Bbb Q$ has degree $20$ and deduce that its Galois group is isomorphic to a semidirect product $\Bbb Z/5 \Bbb Z \rtimes \Bbb Z/4\Bbb Z$ which is non-commutative.

*Conclude that $\sqrt[5]5$ cannot be contained in $\Bbb Q(\zeta_{25})$ because $\operatorname{Gal}(\Bbb Q(\zeta_{25})/\Bbb Q)$ is commutative.


text:
Q: How to debug | Some times the "Save Draft" button seems to spin but does not actually save I am using wordpress 3.5.1 and lately there seems to be a recurring problem with the save draft function where it seems like the draft was saved (i.e the wheel finishes spinning without an error message) but alas, all edits are lost. This happens both in the regular editor as well as in the distraction free wring space (where it is extremely frustrating, as all edits are lost when returning to the regular editing mode).
I couldn't find a discussion about this problem in the other forums or any instructions on how to debug this or find the source of the problem.
Any help will be much appreciated.

A: In wordpress root directory,open file wp-config.php,and find this code:
define('WP_DEBUG', true);

and just set the value to false somehow like this:
define('WP_DEBUG', false);

so that all errors will display,hope this can be helpful to u!
and also the best way is to resintall wordpress if it's convient to u


text:
Q: How to add third column into staggered grid I'm new in android... and i have find a staggered grid on github of two columns but i need to add another column to my staggered grid .... so how to add?? please help
Main Activity:
package com.grafixartist.masonry;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity {

Toolbar mToolbar;
RecyclerView mRecyclerView;

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

    mToolbar = (Toolbar) findViewById(R.id.toolbar);

    if (mToolbar != null) {
        setSupportActionBar(mToolbar);
        getSupportActionBar().setTitle("Staggered Grid");
    }

    mRecyclerView = (RecyclerView) findViewById(R.id.masonry_grid);
    mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(2,    StaggeredGridLayoutManager.VERTICAL));

    MasonryAdapter adapter = new MasonryAdapter(this);
    mRecyclerView.setAdapter(adapter);
    SpacesItemDecoration decoration = new SpacesItemDecoration(16);
    mRecyclerView.addItemDecoration(decoration);

}

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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
}

Masonary Adaptor:
package com.grafixartist.masonry;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

 /**
  * Created by Suleiman on 26-07-2015.
  */
        public class MasonryAdapter extends     RecyclerView.Adapter<MasonryAdapter.MasonryView> {

private Context context;

int[] imgList = {R.drawable.two, R.drawable.one, R.drawable.three, R.drawable.four,
        R.drawable.five, R.drawable.six, R.drawable.seven, R.drawable.eight,
        R.drawable.nine, R.drawable.ten};

String[] nameList = {"One", "Two", "Three", "Four", "Five", "Six",
        "Seven", "Eight", "Nine", "Ten"};

public MasonryAdapter(Context context) {
    this.context = context;
}

@Override
public MasonryView onCreateViewHolder(ViewGroup parent, int viewType) {
    View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.grid_item, parent, false);
    MasonryView masonryView = new MasonryView(layoutView);
    return masonryView;
}

@Override
public void onBindViewHolder(MasonryView holder, int position) {
    holder.imageView.setImageResource(imgList[position]);
    holder.textView.setText(nameList[position]);
}

@Override
public int getItemCount() {
    return nameList.length;
}

class MasonryView extends RecyclerView.ViewHolder {
    ImageView imageView;
    TextView textView;

    public MasonryView(View itemView) {
        super(itemView);

        imageView = (ImageView) itemView.findViewById(R.id.img);
        textView = (TextView) itemView.findViewById(R.id.img_name);

    }
}
}

SpacesItemDecoration:
package com.grafixartist.masonry;

import android.graphics.Rect;
import android.support.v7.widget.RecyclerView;
import android.view.View;

 /**
  * Created by Suleiman on 26-07-2015.
   */
public class SpacesItemDecoration extends RecyclerView.ItemDecoration {
private final int mSpace;

public SpacesItemDecoration(int space) {
    this.mSpace = space;
}

@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
    outRect.left = mSpace;
    outRect.right = mSpace;
    outRect.bottom = mSpace;

    // Add top margin only for the first item to avoid double space between items
    if (parent.getChildAdapterPosition(view) == 0)
        outRect.top = mSpace;
}
}

activity_main.xml:
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/quickreturn_coordinator"
android:layout_width="match_parent"
android:layout_height="match_parent">

   <android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:layout_scrollFlags="scroll|enterAlways"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

      </android.support.design.widget.AppBarLayout>

      <android.support.v7.widget.RecyclerView
        android:id="@+id/masonry_grid"
       android:layout_width="match_parent"
        android:layout_height="match_parent"
         app:layout_behavior="@string/appbar_scrolling_view_behavior" />

     </android.support.design.widget.CoordinatorLayout>

grid_items.xml:
     <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="wrap_content"
      android:layout_height="wrap_content"
     android:background="@android:color/white"
        android:orientation="vertical">

<ImageView
    android:id="@+id/img"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:adjustViewBounds="true"
    android:scaleType="centerCrop" />

<TextView
    android:id="@+id/img_name"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:padding="8dp" />

    </LinearLayout>

Output:
Output
But i want to add one more column to staggered grid like below:
This is what i want

A: Try This:-
mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(2,    StaggeredGridLayoutManager.VERTICAL));

change to
mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(3,    StaggeredGridLayoutManager.VERTICAL));


text:
Q: Identifying events that have happened between two times in SQL I'm trying to calculate the number of events that have happened between 09:00AM and 10:00AM however instead of bring back all events that have happened between those hours I am only returning the events that have happened at 10:00, i'm new to sql so this seems like it should be an easy query but I've been struggling for hours. My query looks as follows:
SELECT * FROM EVENTS
WHERE TIME BETWEEN '09:00:00AM' AND '10:00:00AM';

I know that there are 30+ events to occur between those two times (because I counted them manually) but for some reason this query only brings back the ones to happen at 10:00:00AM exactly, please help.


text:
Q: Updating a DataGridView when underlying MSAccess Database Changes I'm trying to get a DataGridView control (on tab control of Form1) to update when I write data to the underlying MS Access database from two other Forms.
I've read a vast number of replies to similar questions here on StackOverflow and all around the internet but the usual responses;
    myDataGridView.Update()
and
     myDataGridView.Refresh()
don't work.
Neither does
    myBindingSource.ResetBindings(false)
or changing the
     DataGridView.DataSource
by setting it null and then setting it to myBindingSource.
I've also tried using the
    myTableAdpter.Fill(myDataSet)
approach but again absolutely nothing.
It's a WinForms application in C# using VS2017 and a simple "Refresh" button on the tab in Form1.
I'm absolutely baffled so any help would be greatly appreciated.
Thanks for any help
Regards
Matthew
p.s. Here's the current code I have for the Reset Button but it doesn't do anything.
 private void button1_Click(object sender, EventArgs e)
    {
        RefreshDisplay();
    }

    private void tabControl1_TabIndexChanged(object sender, EventArgs e)
    {
        RefreshDisplay();
    }

    private void RefreshDisplay()
    {
        sacsDataGridView.DataSource = null;
        sacsBindingSource4.ResetBindings(false);
        sacsDataGridView.DataSource = sacsBindingSource4;
        sacsDataGridView.Update();
        sacsDataGridView.Refresh();
    }

Regards
Matthew


text:
Q: A recommendation for books on Lie algebra representation I am looking for a holistic book on lie algebra representation, including the infinite dimensional cases. I heard Humphrey book is standard but it does not seem to include the infinite dimensional Lie algebras
Could anyone please recommend me a book that would fit my interests?

A: Anthony W. Knapp has a book, namely Representation Theory of Semisimple Groups, which includes infinite-dimensional representations of Lie algebras and Lie groups. There are many other books, e.g., Unitary Representations of Reductive Lie Groups by D. Vogan. Which one fits your interests most is of course up to you.

A: VS Varadarajan's Lie Groups,  Lie Algebras, and their Representations  may suit your purposes.


text:
Q: Firebase.auth() is not a function Error REACT NATIVE I am trying to implement firebase authentication in my project. However, I'm getting the error Firebase.auth() is not a function. Does anyone know why this is happening?
App.js
import { initializeApp } from 'firebase/app';
import * as firebase from "firebase/app";
const firebaseConfig = {
  apiKey: "",
  authDomain: "",
  projectId: "",
  storageBucket: "",
  messagingSenderId: "",
  appId: ""
};
firebase.initializeApp(firebaseConfig);

js
import React from "react";
import * as firebase from "firebase/app";
export const loginRequest = (email, password) =>
  firebase.auth().signInWithEmailAndPassword(email, password);

A: use
import auth from '@react-native-firebase/auth';

instead.
or
import * as firebase from '@react-native-firebase';

You are trying to use the App library for everything. It only works as the App library.


text:
Q: Switching power supply: why is the primary current rating 1A off when calculating power? So I bought a couple of switching power supplies for a project of mine and I am currently recalculating my actual power usage out of my wall socket to figure out how to distribute power. I have made sure that my power supplies will never exceed 90% of its capacity, but the normal operating will be around 40-50%.
I tried to calculate the values and compare them with the ratings of my supplies and they are way more off that I anticipated. Example:
I have a 5V power supply that can deliver 20 amps for DC output. My AC input rating for this supply says: 230V (170-264V) 1.5A. However my calculations for 240V is 0.416A. So the theoretical and stated power usage is 1 amp off. I figured there would be some waste but not that much.
So:

*

*Are my calculations way off?

*Are the producer of the power supply
just overly careful?

*Or does the power supply really waste the much
energy in the conversion?

*

*Does the power supply have a poor power factor ?

*Is the part load efficiency poor ?

A: this supply says: 230V (170-264V) 1.5A. However my calculations for 240V is 0.416A.
You are comparing two different things.  The supply spec gives you the absolute maximum current it will ever draw under any conditions of output load, input voltage, temperature, phase of the moon, and what you had for breakfast.
You are calculating actual current for a specific case based on output power.  You are also doing it at significantly higher input voltage than the minimum.  Since this is a switching supply, the highest input current will occur at the minimum input voltage.  That alone accounts for a 40% reduction in input current.
Of course these power supplies aren't 100% efficient.  Look at the datasheet to see how much loss there is at full output power and the worst case input voltage.  That could account for another 15% reduction or so.  Then there is usually a significant cover your butt margin in specifying input current.  The manufacturer doesn't want to get caught with the supply ever drawing more than they said it would.  Since most customer aren't going to care that the supply might draw 1.5 A instead of 1 A, the manufacturer gives the more conservative worst case value.

A: You can't calculate AC power by multiplying effective voltage and effective current as put on the label. The voltage is there so you can pick the right device for an input voltage and the current is there so you don't overload the circuit, power strips etc.
On the label, there may be two addional values, first is ...VA, which is multiplied effective voltage and effective current, and can be used to determine whether a circuit or power strip would be overloaded (similar to the effective current value), and second is power factor = 0.5 (sometimes cos phi = ...) or similar, which is an additional factor to be considered to get from that VA value to the real power consumed by a device.
That factor is determined by taking the wave form of the current and phase shift between voltage and current into account.


text: Q: How to "validate" a Rubik's Cube configuration? Looking at a picture of a Rubik's cube how can I tell if it's in one of its possible configurations (image is not fake)? By "possible configuration" I mean a configuration that can be achieved by simply rotating the cube (no dismantling). I'm aware that colors of opposite sides cannot be on the same side and I'm interested in a more general solution.


text:
Q: NULL Output for writing a code for displaying random string out of the declared array I am writing this as a lambda function which should Display a random string out of the declared array, but upon the time of execution, it displays "NULL".
Please can anyone suggest me the correct code or syntax and tell me whats wrong with this code.
exports.handler = async (event) => {
    let messages = ["AWS","Pranav","Hello World"];
    let response = messages[Math.floor(Math.random()*100)];
    return response;
};

A: Nothing to do with Lambda, error is in the way you take a random array element.
Change it to this:
exports.handler = async (event) => {
    let messages = ["AWS","Pranav","Hello World"];
    let response = messages[Math.floor(Math.random()*messages.length)];
    return response;
};

Instead of multiplying Math.random() by 100, which gives you a random number between 0 and 100, you should multiply it by messages.length.
More examples on generating a random number in JS here: https://stackoverflow.com/a/24152886/2727317


text:
Q: Adjacency matrix graph representation code crashing I wrote the following code for Adjacency matrix graph representation but code is not working. I think there is some problem in line 25 but i am not able to debug it. Please point out the problem in code.
Thanks
#include<iostream>
#include<cstdlib>

using namespace std;

struct Graph{
    int V;
    int E;
    int **adj;
};

struct Graph* adjMatrixForGraph(int vertices,int edges){
    int i,j;
    Graph *G=(struct Graph*) malloc(sizeof(struct Graph));
    //Graph *G=new Graph();
    if(!G){
        cout<<"Memory error";
    }
    G->V=vertices;
    G->E=edges;
    G->adj =(int **) malloc(sizeof(G->V*G->V));
    //G->adj =new int*;
    for(i=0;i<G->V;i++){
        for(j=0;j<G->V;j++){
           *(*(G->adj+j)+j)=0;
        }
    }/*
    for(int u=0;u<G->E;u++){
        cin>>i>>j;
        G->adj[i][j]=1;
        G->adj[j][i]=1;
    }*/
    return G;
}

int main(){
    Graph *G=NULL;
    G=adjMatrixForGraph(4,4);
    return 0;
}

A: You do not allocate a two dim array by
G->adj =(int **) malloc(sizeof(G->V*G->V));

Instead, you should do
G->adj =(int **) malloc(G->V*sizeof(int*));
for (int i = 0; i < G->V; ++i) {
  *(G->adj+i) = (int*) malloc(G->V*sizeof(int));
}

BTW, it might be more efficient for you to use 1-d array to simulate 2-d array because memory access can be slower than index computation. But that can be another story.


text:
Q: Sacar los mayores valores de un count SQLServer tengo esta consulta "Mostrar id y nombre de la/s instalación/es que albergaron más eventos el año pasado.". Como me pide de las instalaciones, refiere a que si la cantidad de eventos máximo fue 10 y hay dos instalaciones que tienen 10 entonces que me muestre ambas dos.
Hasta ahora hice esto pero solo me devuelve el primer valor, con TOP no creo que sea la solución ya que si lo uso debería poner un limite y la idea es que siempre muestre las instalaciones con más eventos sin importar cuantas sean.
Instalacion(idInstalac,nomInstalac)
Eventos(idEvento,idInstalac)

SELECT MAX(idInstalac), MAX(cantidadIns)
FROM  (SELECT E.idInstalac, COUNT(*) as cantidadIns
        FROM Eventos E INNER JOIN Instalacion I ON I.idInstalac = E.idInstalac
        WHERE YEAR(fchEvento) = YEAR(GETDATE())-1
        GROUP BY E.idInstalac) C

A: Puedes utilizar having en el group by para establecer este criterio, a los valores agrupados.
SELECT E.idInstalac
     , COUNT(*) as cantidadIns
FROM Eventos E
     INNER JOIN Instalacion I ON I.idInstalac = E.idInstalac
WHERE YEAR(fchEvento) = YEAR(GETDATE())-1
GROUP BY E.idInstalac
HAVING COUNT(*) > 10

Having

A: Si tu versión de SQL Server lo permite, una forma podría ser usando DENSE_RANK() en una CTE o en su defecto una subconsulta, para numerar cada grupo según la cantidad, y luego simplemente filtramos el grupo 1 (los casos máximos)
;WITH CTE AS (
    SELECT  E.idInstalac,
            COUNT(*) as cantidadIns,
            DENSE_RANK() OVER (ORDER BY count(*) desc) AS RN
            FROM Eventos E
            INNER JOIN Instalacion I
            ON I.idInstalac = E.idInstalac
            WHERE YEAR(fchEvento) = YEAR(GETDATE())-1
            GROUP BY E.idInstalac
)
SELECT *
    FROM CTE
    WHERE RN = 1


text:
Q: rsqlite_query_send: could not execute1: unable to open database file I'm hitting this weird database connection issue with RSQLite that I need to work around somehow.  I have documented how to reproduce this issue at the link below:
https://github.com/rstats-db/RSQLite/issues/101
> dbSendQuery(db, "create table hfp as select * from hfp_pac as a inner join ac as b on a.h_seq = b.ph_seq AND a.ppposold = b.ppposold")
Error in sqliteSendQuery(conn, statement) :
  rsqlite_query_send: could not execute1: unable to open database file

Here is the db connection
> summary(db)
<SQLiteConnection>
  SQLite version:      3.8.6
  Database name:
  Loadable extensions:
  File open flags:
  VFS:
>

I have tried following other SQLite-based stackoverflow questions where users hit the unable to open database file error, but they all say you must explicitly set the full filepath - and this has been no help either.
If anyone could help diagnose why I'm hitting this bug so that I can work around it, I'd appreciate it.


text:
Q: Sending emails with pure Ruby I have problems with sending emails with pure Ruby. Here is how my script looks like:
Mail.defaults do
  delivery_method(
    :smtp,
    address: 'smtp.sendgrid.net',
    port: 587,
    user_name: 'sendgrid_username',
    password: 'sendgrid_password',
    authentication: :login,
    enable_starttls_auto: false,
    openssl_verify_mode:  "none"
  )
end

Mail.deliver do
  from     'Test Email'
  to       'user@example.com'
  subject  'Here is the image you wanted'
  body     "Test Email"
end

This script raise the following error:
/Users/mateuszurbanski/.rubies/ruby-2.7.2/lib/ruby/2.7.0/net/smtp.rb:975:in `check_auth_response': 535 Authentication failed: Bad username / password (Net::SMTPAuthenticationError)

I'm using credentials from one of my Ruby on Rails project and they are fine. Any ideas?

A: Sendgrid recently transitioned to api keys and will reject plain auth, see details here.
Your old credentials while still being valid may not be accepted.
Generate a new api key in sendgrid and use it in place of password. Username will be apikey

A: Instead of using your SendGrid username and password in this config, use the following,
user_name: 'apikey',
password: '<sendgrid_api_key>',

This works for me when defining the smtp settings for ActionMailer, so it should work here as well.


text:
Q: html - correct way to append json to a link Hi I have a code which uses facebook login:
<iframe allowtransparency="true" frameborder="no" height="600" scrolling="auto" src="http://www.facebook.com/plugins/registration.php?
client_id=183620578322567&
redirect_uri=http://example.com/store_user_data.php?&
fields=[
{"name":"name"},
{"name":"email"},
{"name":"password"},
{"name":"gender"},
{"name":"birthday"},
{"name":"captcha"}
]"
scrolling="auto"
frameborder="no"
style="border: none;"
width="500"
height="600">
</iframe>

as you can see the json part(fields) in the src attribute is something wrong with a quote missing possible but I'm unable to attach it, so how would be the correct way? thnks

A: some does and don't regarding your issue:

*

*don't use escape(), its been deprecated since ECMAScript v3.

*Use encodeURI() instead. you can also use decodeURI() in the way round.

*don't use encodeURIComponent() to escape all the url string, since it would ruin your URL, use it just when you want to send a url as a paramter.

*don't use ' for the attributes in your json, use " instead, because the mentioned functions does not encode the ' character.

for instance, you can add your json to the url, and then call encodeURI:
var url = 'http://myhost.com/?{"key", "value"}';
var myEncodedurl = encodeURI(url);
//result-->http://myhost.com/?%7B%22key%22,%20%22value%22%7D

but
encodeURIComponent(url);
//result-->http%3A%2F%2Fmyhost.com%2F%3F%7B%22key%22%2C%20%22value%22%7D

then using encodeURIComponent would help you if you want to send all that url as a parameter, like this:
var myEncodedurl = 'http://myotherhost.com/?myurl=' +
                    encodeURIComponent('http://myhost.com/?{"key", "value"}');
//result-->http://myotherhost.com/?myurl=http%3A%2F%2Fmyhost.com%2F%3F%7B%22key%22%2C%20%22value%22%7D

BTW, for your sample you'd better try:
var url = 'http://www.facebook.com/plugins/registration.php?client_id=183620578322567&redirect_uri=' +
encodeURIComponent('http://example.com/store_user_data.php?&'
+ 'fields=['
+ '{"name":"name"},'
+ '{"name":"email"},'
+ '{"name":"password"},'
+ '{"name":"gender"},'
+ '{"name":"birthday"},'
+ '{"name":"captcha"}'
+ ']&"'
+ 'scrolling="auto"'//extract it from encodeURIComponent if they belong to your original url
+ 'frameborder="no"'//extract it from encodeURIComponent if they belong to your original url
+ 'style="border: none;"'//extract it from encodeURIComponent if they belong to your original url
+ 'width="500"'//extract it from encodeURIComponent if they belong to your original url
+ 'height="600"'/*extract it from encodeURIComponent if they belong to your original url*/);

A: You should properly escape the whole string. Use the JavaScript encodeURIComponent() function.
There are more information about javascript url escaping here: URL encode sees "&" (ampersand) as "&" HTML entity

A: at the basic level, you need to change src="..." to src='...' so that the double quotes inside your JSON aren't used to close the src attribute.   However, you should really url encode all special characters in the url and try to avoid carriage returns in your url.


text:
Q: mysqld_safe does not allow MySQL connection I cannot start mysqld without getting the following error:
[root@alarm ~]# mysqld
140414 16:01:04 [ERROR] Fatal error: Please read "Security" section of the manua l to find out how to run mysqld as root!

140414 16:01:04 [ERROR] Aborting

140414 16:01:04 [Note] mysqld: Shutdown complete

If I try to start mysql, it tell me it cannot connect to the local mysql server through the socket '/run/mysqld/mysqld.sock'. I fixed this by running mysqld_safe instead of mysqld. This has stopped working and I now get the following error:
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/run/mys qld/mysqld.sock' (2)

I use mariadb on the Archlinux distribution. Anyone know how to fix this?
EDIT 1:
Steve, I managed to start the mysqld service by using systemctl as can be seen here:
[root@alarm ~]# ps aux | grep mysql
mysql      880  1.0 10.3 514276 52776 ?        Ssl  09:30   0:01 /usr/bin/mysqld --pid-file=/run/mysqld/mysqld.pid
root      1618  0.0  0.1   4032   936 pts/0    S+   09:31   0:00 grep mysql

When I try to run mysql, I still get the error:
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/run/mysqld/mysqld.sock' (2)

A: ----- ORIGINAL SUGGESTION -----
Try running (as root):
systemctl start mysqld

If this doesn't work please post back to say if the same error returned.
----- FURTHER ADVICE -----
Great that MySQL is now starting at least.
Few things to check:
1) Does the socket file actually exist? If not run touch /run/mysqld/mysqld.sock to create it and see if that helps, you might need to change the file to be owned/writeable by the mysql user;
2) Have you checked your my.cnf file to check the mysql configuration is all correct?
3) If the above don't help I'd suggest trying to start mysql again using the --verbose flag so you get a more detailed error output


text:
Q: how to modify a value in a database (all tables all columns) I have a big Oracle database with more than 1000 tables.
Each table has 1000+ rows and 100+ columns.
I am trying to modify each occurrence of value "red" (or "RED") with value "blue" (or "BLUE") in the whole database.
Each occurrence of red could  possibly be in the middle of a string (%red%)
I was told a stored procedure is the right way. is that correct? which stored procedure would help me?
thanks!

A: One option is to

*

*use nested cursor for loops

*

*one that fetches all tables in your schema

*another that fetches all VARCHAR2 columns in those tables

*replace "red" with "blue" for all rows that contain "row"

Something like this:
SQL> select * from test;

STRING_COL
--------------------------------------------------
this is a red apple
Deep red sea

SQL>     declare
  2        l_str varchar2(200);
  3      begin
  4        for cur_t in (select table_name from user_tables) loop
  5          for cur_c in (select column_name from user_tab_columns
  6                        where table_name = cur_t.table_name
  7                          and data_type = 'VARCHAR2'
  8                       )
  9          loop
 10            l_str := 'update ' || cur_t.table_name || ' set ' ||
 11                      cur_c.column_name  || ' = replace (' ||
 12                      lower(cur_c.column_name) || ', ''red'', ''blue'')' ||
 13                     ' where instr(lower(' || cur_c.column_name ||'), ''red'') > 0';
 14            execute immediate (l_str);
 15          end loop;
 16        end loop;
 17      end;
 18
 19  /

PL/SQL procedure successfully completed.

SQL> select * from test;

STRING_COL
--------------------------------------------------
this is a blue apple
Deep blue sea

SQL>


text:
Q: How to limit input length with scanf In this program I have taken a dimensional character array of size[3][4],
as long as I enter a 3 characters for each row it will work well.
For example: if I enter  abc abd abd I get the same output but if i enter more letters in the first or second or 3rd row I get an error.
How should I check for null character in 2 dimensional?
# include <stdio.h>
#include  <conio.h>
# include <ctype.h>

void main()
{
   int i=0;
   char name[3][4];
   printf("\n enter the names \n");
   for(i=0;i<3;i++)
   {
      scanf( "%s",name[i]);
   }

   printf( "you entered these names\n");
   for(i=0;i<3;i++)
   {
      printf( "%s\n",name[i]);
   }
   getch();
}

A: As pointed out by @SouravGhosh, you can limit your scanf with "%3s", but the problem is still there if you don't flush stdin on each iteration.
You can do this:
printf("\n enter the names \n");
for(i = 0; i < 3; i++) {
    int c;
    scanf("%3s", name[i]);
    while ((c = fgetc(stdin)) != '\n' && c != EOF); /* Flush stdin */
}

A:
How should I chk for null character in 2 dimensional ... [something has eaten the rest part, I guess]

You don't need to, at least not in current context.
The problem is in your approach of allocating memory and putting input into it. Your code has
char name[3][4];

if you enter more that three chars, you'll be overwriting the boundary of allocated memory [considering the space of \0]. You've to limit your scanf() using
scanf("%3s",name[i]);

Note:

*

*change void main() to int main(). add a return 0 at the end.

*always check the return value of scanf() to ensure proper input.

EDIT:
As for the logical part, you need to eat up the remainings of the input words to start scanning from the beginning of the next word.
Check the below code [Under Linux, so removed conio.h and getch()]
# include <stdio.h>
# include <ctype.h>
int main()
{
        int i=0; char name[3][4];
        int c = 0;
        printf("\n enter the names \n");
        for(i=0;i < 3;i++)
        {
                scanf( "%3s",name[i]);
                while(1)   // loop to eat up the rest of unwanted input
                {          // upto a ' ' or `\n` or `EOF`, whichever is earlier
                    c = getchar();
                    if (c == ' ' || c == '\n' || c == EOF) break;
                }
        }
        printf( "you entered these names\n");

        for(i=0;i<3;i++)
        {
                printf( "%s\n",name[i]);
        }
    return 0;
}

A: (Cringing after reading the answers to date.)
First, state the problem clearly. You want to read a line from stdin, and extract three short whitespace separated strings. The stored strings are NUL terminated and at most three characters (excluding the NUL).
#include <stdio.h>

void main(int, char**) {
    char name[3][4];
    printf("\n enter the names \n");
    {
        // Read tbe line of input text.
        char line[80];
        if (0 == fgets(line, sizeof(line), stdin)) {
            printf("Nothing read!\n");
            return 1;
        }
        int n_line = strlen(line);
        if ('\n' != line[n_line - 1]) {
            printf("Input too long!\n");
            return 2;
        }
        // Parse out the three values.
        int v = sscanf(line, "%3s %3s %3s", name[0], name[1], name[2]);
        if (3 != v) {
            printf("Too few values!\n");
            return 3;
        }
    }
    // We now have the three values, with errors checked.
    printf("you entered these names\n%s\n%s\n%s\n",
        name[0], name[1], name[2]
    );
    return 0;
}

A: you might consider something on the order of    scanf( "%3s%*s",name[i]);
which should, if I recall correctly, take the first three characters (up to a whitespace) into name, and then ignore anything else up to the next white space. This will cover your long entries and it does not care what the white space is.
This is not a perfect answer as it will probably eat the middle entry of A B C if single or double character entries are mode. strtok, will separate a line into useful bits and you can then take substrings of the bits into your name[] fields.
Perhaps figuring out the entire requirement before writing code would be the first step in the process.


text:
Q: "react-router-dom " router component does not work I want to use history explicitly. So I know about BrowserRoute but I want to use Route and use history as its property. when I run the program I get this page.enter image description here
This is my AppRouter.js

import React from "react";
import { Router, Route, Switch } from "react-router-dom";
import { createBrowserHistory } from "history";
import LoginPage from "../components/LoginPage";
import ExpenseDashboardPage from "../components/ExpenseDashboardPage";
import AddExpensePage from "../components/AddExpensePage";
import EditExpensePage from "../components/EditExpensePage";
import NotFoundPage from "../components/NotFoundPage";
import PublicRoute from "./PublicRoute";
import PrivateRoute from "./PrivateRoute";

export const history = createBrowserHistory();

const AppRouter = () => (
  <Router history={history}>

      <Switch>
        <PublicRoute path="/" component={LoginPage} exact={true} />
        <PrivateRoute path="/dashboard" component={ExpenseDashboardPage} />
        <PrivateRoute path="/create" component={AddExpensePage} />
        <PrivateRoute path="/edit/:id" component={EditExpensePage} />
        <Route component={NotFoundPage} />
      </Switch>

  </Router>
);

export default AppRouter;

LoginPage.js

import React from "react";
import { connect } from "react-redux";
import { startLogin } from "../actions/auth";

export const LoginPage = ({ startLogin }) => (

    <button onClick={startLogin}>Login with Google</button>
    <button>Amir Hossein Jobeiri</button>

);

const mapDispatchToProps = (dispatch) => ({
  startLogin: () => dispatch(startLogin()),
});

export default connect(undefined, mapDispatchToProps)(LoginPage);

PublicRoute.js

import React from "react";
import { connect } from "react-redux";
import { Route, Redirect } from "react-router-dom";

export const PublicRoute = ({
  isAuthenticated,
  component: Component,
  ...rest
}) => (
  <Route
    {...rest}
    component={(props) =>
      isAuthenticated ? <Redirect to="/dashboard" /> : <Component {...props} />
    }
  />
);

const mapStateToProps = (state) => ({
  isAuthenticated: !!state.auth.uid,
});

export default connect(mapStateToProps)(PublicRoute);

PrivateRoute

import React from "react";
import { connect } from "react-redux";
import { Route, Redirect } from "react-router-dom";
import Header from "../components/Header";

export const PrivateRoute = ({
  isAuthenticated,
  component: Component,
  ...rest
}) => (
  <Route
    {...rest}
    component={(props) =>
      isAuthenticated ? (

          <Component {...props} />

      ) : (
        <Redirect to="/" />
      )
    }
  />
);

const mapStateToProps = (state) => ({
  isAuthenticated: !!state.auth.uid,
});

export default connect(mapStateToProps)(PrivateRoute);

I searched a lot about this problem but I do not get the right answer. Please help if you can.

A: I changed my "history" version to "4.7.2". It works properly.


text:
Q: Mathematica help with NIntegrate I am fairly new to mathematica and I'm trying to generate an SIS s-wave IV plot using the formulae in the attached image. Could I get some help in fixing the issue?

A: Try
Clear[delta,gamma,z,e,beta];
delta=0.01;gamma=0.1;z=e-I*gamma;beta=1;
f[x_]:=1/(1+Exp[beta x]);
sbcs[e_]:=Re[z]/(z^2-delta^2)^(1/2);
s[v_]:=NIntegrate[sbcs[e]f'[e-v],{e,-5,5}];
Plot[ReIm[s[v]],{v,-1.005,1.005}]

See if that plot exactly matches what the textbooks say that it should be.
Then compare that character by character with what you have and try to figure out exactly why the differences are there. If you can't figure out why a change is there then change that single bit back to what you had and try it again and see what happens.
Be very careful to remember that Mathematica keeps a cache of previous assignments and will use that memory until you restart Mathematica or assign a different value or specifically tell it to forget a particular assignment. If you don't keep that in mind you can get results minutes or hours later that you do not realize depends on an assignment you made earlier.


text:
Q: Identify Columns using regex Hi I have a df where the suffix is often the filename.
df   apple_filename_fruit.csv  banan_filename_new fruity.csv  test_col
0     0                               26                       4
1    23                              262                       2
2     23                              2626                     3

How should the regex be ammended since nothing prints?
for col in df.columns:
    if col.endswith("filename_(\w+)") and "new" in col:
         print(col)

A: Use Series.str.contains with $ for end of string and chain with & for bitwise AND:
m = df.columns.str.contains("filename_.*$") & df.columns.str.contains("new")
print (m)
[False False  True False False]

for c in df.columns[m]:
    print (c)
    banan_filename_new

A: you can use filter with the regex argument.
df.filter(regex=r'(?=.*filename)(?=.*new)')

  banan_filename_new
0                  26
1                 262
2                2626

A: I do not think endswith work with regexes; one way to edit your for loop is to use the re module, and nest the if statements:
for col in df:
    if re.search("filename.*$", col):
        if "new" in col:
            print(col)

banan_filename_new


text:
Q: Wix: Which CustomAction is called just before showing the failure screen? I have a requirement wherein I need to execute a custom action if the installer fails (either automatically or manually failed by returning ActionResult.Failure from another custom action).
I tried
<Custom Action="CallMe" After="InstallFinalize"></Custom>
but the CA is not called.
Any help is appreciated.
Edit: Found out from logs that it is "FatalError" custom action. But then doing this <Custom Action="CallMe" Before="FatalError"></Custom> throws
Error  8   Unresolved reference to symbol 'WixAction:InstallExecuteSequence/FatalError' in section 'Product:*'

A: You can use
   <Custom Action="CallMeCancel" OnExit="cancel" />
   <Custom Action="CallMeError" OnExit="error" />

The values for OnExit are success, cancel, error, suspend


text:
Q: Change Field labels in VF page I have below VF page that is look alike of standrad detail page. Now I need to change field labels in the vf page. Can someone suggest a wayout please?
Code:
<apex:page standardController="Account_Plan_vod__c" standardStylesheets="true">
    <apex:pageBlock title="Kol Plan"/>

    <apex:dataTable value="{!Account_Plan_vod__c}"
                var="AP"
                cellPadding="4" border="1">

    <apex:column value="{!AP.Name}"/>
    </apex:dataTable>
    <apex:detail subject="{!Account_Plan_vod__c.Id}"  relatedList="true" title="false">

    </apex:detail>

      </apex:page>

A: If you want to change button label at Object level then for Standard Object go  to

Customize> Tab Names and Labels > Rename Tabs and Labels > Select
  Object > edit > Change the name

For custom Object you can directly change the name.