text:
Q: Avoid Error too many changes at once in directory how to avoid the error of FileSystemWatcher in C#?

too many changes at once in directory

I have to detect all changes on a network share.
The InternalBufferSize is increased to 8192 * 128

A: I think I might have found a pattern that can help improve the the usage of the buffer considerably.
The issue with this class is that until the delegates for the events finish running, it cannot release the memory it uses to hold that information.
For the life of me I don't know why the maximum InternalBufferSize was set to 64Kb, but with this idea you'll use that small buffer much more effectively.
If instead of doing the operations inside the delegates you simply queue them and defer their execution for a background worker, the amount of memory used by it will be considerably smaller.
In fact, I've got no idea why the class in itself doesn't implement something like this in the first place.
The code below is just a sample piece of code for the idea, and shouldn't be used in production environments, but it increased the number of files I could copy and keep track of drastically.
using System;
using System.Collections.Concurrent;
using System.ComponentModel;
using System.IO;
using System.Threading;
using NUnit.Framework;

namespace Soundnet.Synchronisation.FileSystemWatcherTests
{

  /// <summary>
  ///
  /// </summary>
  [TestFixture]
  public class Tests
  {

    static readonly ConcurrentQueue<Change> ChangesQueue = new ConcurrentQueue<Change>();
    const string Destination = @"c:\Destination";
    const string Source = @"c:\Source";

    /// <summary>
    /// Tests this instance.
    /// </summary>
    [Test]
    public void Test()
    {
      var changesBackgroundWorker = new BackgroundWorker();
      changesBackgroundWorker.DoWork += ChangesBackgroundWorkerOnDoWork;
      changesBackgroundWorker.RunWorkerAsync();
      var fileSystemWatcher = new FileSystemWatcher
                                {
                                  Path = Source,
                                  EnableRaisingEvents = true,
                                  IncludeSubdirectories = true,
                                  NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.LastAccess | NotifyFilters.CreationTime | NotifyFilters.FileName | NotifyFilters.DirectoryName,
                                  InternalBufferSize = 65536
                                };
      fileSystemWatcher.Created += FileSystemWatcherOnCreated;
      fileSystemWatcher.Deleted += FileSystemWatcherOnDeleted;
      fileSystemWatcher.Renamed += FileSystemWatcherOnRenamed;
      fileSystemWatcher.Error += FileSystemWatcherOnError;

      while (true)
        Thread.Sleep(1000000);
    }

    /// <summary>
    /// Changeses the background worker configuration document work.
    /// </summary>
    /// <param name="sender">The sender.</param>
    /// <param name="doWorkEventArgs">The <see cref="DoWorkEventArgs"/> instance containing the event data.</param>
    /// <exception cref="System.ArgumentOutOfRangeException"></exception>
    private static void ChangesBackgroundWorkerOnDoWork(object sender, DoWorkEventArgs doWorkEventArgs)
    {
      while (true)
      {
        Change change;
        if (ChangesQueue.TryDequeue(out change))
        {
          var backgroundWorker = new BackgroundWorker();
          switch (change.ChangeType)
          {
            case WatcherChangeTypes.Created:
              backgroundWorker.DoWork += (o, args) =>
                                          {
                                            var fileSystemType = GetFileSystemType(change.FullPath);

                                            var newItem = Path.Combine(Destination, change.Name);
                                            while (true)
                                            {
                                              try
                                              {
                                                switch (fileSystemType)
                                                {
                                                  case FileSystemType.File:
                                                    File.Copy(change.FullPath, newItem, true);
                                                    break;
                                                  case FileSystemType.Directory:
                                                    var directorySecurity =
                                                      Directory.GetAccessControl(change.FullPath);
                                                    Directory.CreateDirectory(newItem, directorySecurity);
                                                    break;
                                                  case FileSystemType.NotExistant:
                                                    break;
                                                }
                                                return;
                                              }
                                              catch (IOException exception)
                                              {
                                                Thread.Sleep(100);
                                                Console.WriteLine(exception.Message);
                                              }
                                            }
                                          };
              break;
            case WatcherChangeTypes.Deleted:
              backgroundWorker.DoWork += (o, args) =>
              {
                var itemToDelete = Path.Combine(Destination, change.Name);
                var fileSystemType = GetFileSystemType(itemToDelete);
                switch (fileSystemType)
                {
                  case FileSystemType.File:
                    File.Delete(itemToDelete);
                    break;
                  case FileSystemType.Directory:
                    Directory.Delete(itemToDelete, true);
                    break;
                }
              };
              break;
            case WatcherChangeTypes.Changed:
              backgroundWorker.DoWork += (o, args) =>
              {
                var fileSystemType = GetFileSystemType(change.FullPath);
                var newItem = Path.Combine(Destination, change.Name);
                switch (fileSystemType)
                {
                  case FileSystemType.File:
                    File.Copy(change.FullPath, newItem, true);
                    break;
                }
              };
              break;
            case WatcherChangeTypes.Renamed:
              backgroundWorker.DoWork += (o, args) =>
              {
                var fileSystemType = GetFileSystemType(change.FullPath);
                var oldItem = Path.Combine(Destination, change.OldName);
                var newItem = Path.Combine(Destination, change.Name);
                switch (fileSystemType)
                {
                  case FileSystemType.File:
                    if (File.Exists(oldItem))
                      File.Move(oldItem, newItem);
                    break;
                  case FileSystemType.Directory:
                    if (Directory.Exists(oldItem))
                      Directory.Move(oldItem, newItem);
                    break;
                }
              };
              break;
            case WatcherChangeTypes.All:
              break;
            default:
              throw new ArgumentOutOfRangeException();
          }
          backgroundWorker.RunWorkerAsync();
        }
      }
    }

    /// <summary>
    /// Files the system watcher configuration created.
    /// </summary>
    /// <param name="sender">The sender.</param>
    /// <param name="fileSystemEventArgs">The <see cref="FileSystemEventArgs"/> instance containing the event data.</param>
    private static void FileSystemWatcherOnCreated(object sender, FileSystemEventArgs fileSystemEventArgs)
    {
      ChangesQueue.Enqueue(new Change
      {
        ChangeType = WatcherChangeTypes.Created,
        FullPath = fileSystemEventArgs.FullPath,
        Name = fileSystemEventArgs.Name
      });
    }

    /// <summary>
    /// Files the system watcher configuration deleted.
    /// </summary>
    /// <param name="sender">The sender.</param>
    /// <param name="fileSystemEventArgs">The <see cref="FileSystemEventArgs"/> instance containing the event data.</param>
    private static void FileSystemWatcherOnDeleted(object sender, FileSystemEventArgs fileSystemEventArgs)
    {
      ChangesQueue.Enqueue(new Change
      {
        ChangeType = WatcherChangeTypes.Deleted,
        FullPath = fileSystemEventArgs.FullPath,
        Name = fileSystemEventArgs.Name
      });
    }

    /// <summary>
    /// Files the system watcher configuration error.
    /// </summary>
    /// <param name="sender">The sender.</param>
    /// <param name="errorEventArgs">The <see cref="ErrorEventArgs"/> instance containing the event data.</param>
    private static void FileSystemWatcherOnError(object sender, ErrorEventArgs errorEventArgs)
    {
      var exception = errorEventArgs.GetException();
      Console.WriteLine(exception.Message);
    }

    /// <summary>
    /// Files the system watcher configuration renamed.
    /// </summary>
    /// <param name="sender">The sender.</param>
    /// <param name="fileSystemEventArgs">The <see cref="RenamedEventArgs"/> instance containing the event data.</param>
    private static void FileSystemWatcherOnRenamed(object sender, RenamedEventArgs fileSystemEventArgs)
    {
      ChangesQueue.Enqueue(new Change
      {
        ChangeType = WatcherChangeTypes.Renamed,
        FullPath = fileSystemEventArgs.FullPath,
        Name = fileSystemEventArgs.Name,
        OldFullPath = fileSystemEventArgs.OldFullPath,
        OldName = fileSystemEventArgs.OldName
      });
    }

    /// <summary>
    /// Gets the type of the file system.
    /// </summary>
    /// <param name="fullPath">The full path.</param>
    /// <returns></returns>
    private static FileSystemType GetFileSystemType(string fullPath)
    {
      if (Directory.Exists(fullPath))
        return FileSystemType.Directory;
      if (File.Exists(fullPath))
        return FileSystemType.File;
      return FileSystemType.NotExistant;
    }
  }

  /// <summary>
  /// Type of file system object
  /// </summary>
  internal enum FileSystemType
  {
    /// <summary>
    /// The file
    /// </summary>
    File,
    /// <summary>
    /// The directory
    /// </summary>
    Directory,
    /// <summary>
    /// The not existant
    /// </summary>
    NotExistant
  }

  /// <summary>
  /// Change information
  /// </summary>
  public class Change
  {
    /// <summary>
    /// Gets or sets the type of the change.
    /// </summary>
    /// <value>
    /// The type of the change.
    /// </value>
    public WatcherChangeTypes ChangeType { get; set; }

    /// <summary>
    /// Gets or sets the full path.
    /// </summary>
    /// <value>
    /// The full path.
    /// </value>
    public string FullPath { get; set; }

    /// <summary>
    /// Gets or sets the name.
    /// </summary>
    /// <value>
    /// The name.
    /// </value>
    public string Name { get; set; }

    /// <summary>
    /// Gets or sets the old full path.
    /// </summary>
    /// <value>
    /// The old full path.
    /// </value>
    public string OldFullPath { get; set; }

    /// <summary>
    /// Gets or sets the old name.
    /// </summary>
    /// <value>
    /// The old name.
    /// </value>
    public string OldName { get; set; }
  }
}

A: From MSDN;

The Windows operating system notifies your component of file changes
  in a buffer created by the FileSystemWatcher. If there are many
  changes in a short time, the buffer can overflow. This causes the
  component to lose track of changes in the directory, and it will only
  provide blanket notification. Increasing the size of the buffer with
  the InternalBufferSize property is expensive, as it comes from
  non-paged memory that cannot be swapped out to disk, so keep the
  buffer as small yet large enough to not miss any file change events.
  To avoid a buffer overflow, use the NotifyFilter and
  IncludeSubdirectories properties so you can filter out unwanted change
  notifications.

A: I have the experience that FileSystemWatcher is not always the most reliable thing to use. You could specify the filter to narrow down the files you are watching (NotifyFilter), or increase the buffer size.
But depending on your requirements you may also want to do it another way, like polling every x seconds to get the list of files. But then you might need to tell us more about your business case.

A: There are two things you should do:

*

*Set InternalBufferSize to the maximum supported value (65536). Your attempt to set it to "8192 * 128" is larger than the maximum supported value listed in the documentation, so you may not have increased the buffer size at all.

*Queue events from the FileSystemWatcher onto a background thread for processing.

It's the second point here that isn't well understood, and really should be documented on MSDN. Internally, FileSystemWatcher is queuing change events into that internal buffer you set the size of above. Critically however, items are only removed from that buffer after your event handler returns. This means every cycle of overhead your event handlers introduce increases the possibility of the buffer filling up. What you should do is clear the limited queue of the FileSystemWatcher as quickly as possible, and move the events into your own infinite queue, to process at the rate you can handle, or discard if you care to do so, but with some intelligence around it.
Here's basically what I do in my code. First, I start my own dispatcher thread:
Dispatcher changeDispatcher = null;
ManualResetEvent changeDispatcherStarted = new ManualResetEvent(false);
Action changeThreadHandler = () =>
{
    changeDispatcher = Dispatcher.CurrentDispatcher;
    changeDispatcherStarted.Set();
    Dispatcher.Run();
};
new Thread(() => changeThreadHandler()) { IsBackground = true }.Start();
changeDispatcherStarted.WaitOne();

Then I create the watcher. Note the buffer size being set. In my case, I only watch changes in the target directory, not subdirectories:
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = path;
watcher.InternalBufferSize = 64 * 1024;
watcher.IncludeSubdirectories = false;

Now I attach my event handlers, but here I invoke them onto my dispatcher rather than running them synchronously in the watcher thread. Yes, the events will be processed in order by the dispatcher:
watcher.Changed += (sender, e) => changeDispatcher.BeginInvoke(new Action(() => OnChanged(sender, e)));
watcher.Created += (sender, e) => changeDispatcher.BeginInvoke(new Action(() => OnCreated(sender, e)));
watcher.Deleted += (sender, e) => changeDispatcher.BeginInvoke(new Action(() => OnDeleted(sender, e)));
watcher.Renamed += (sender, e) => changeDispatcher.BeginInvoke(new Action(() => OnRenamed(sender, e)));

And finally, after disposing of the FileSystemWatcher (you were doing that, right?), you need to shut down your dispatcher:
watcher.Dispose()
changeDispatcher.BeginInvokeShutdown(DispatcherPriority.Normal);

And that's it. I was getting this problem myself, both in network and local scenarios. After using this approach, I wasn't able to generate this error again, even when hammering out empty files to watched directories as fast as possible. If you did ever manage to somehow exhaust the buffer in this case (which I'm not sure is possible, the API upstream is probably slower), there's still further room for optimization here. As long as your dispatcher is over the "tipping point" though, where the sender can't post the events faster than you can dispatch them, you'll never get a backlog, and hence never blow the buffer. I believe this approach puts you into that safe area.

A: SHChangeNotifyRegister can be used to get shell notifications.

A: It should be fixed if you increase the buffer size but its not a practical solution.
Because to make sure it always records everything you would need to make the buffer huge.
And that will effect the performance greatlly.
And i think performance issues could be fixed by implementing multi threading.


text:
Q: Flutter - Size missing error on TextField When using TextField inside a container that is centered by a parent row widget. No parents have a defined width. Container is supposed to take width of the content inside it.
Error -   parentData: offset=Offset(0.0, 0.0); id=_ScaffoldSlot.body (can use size) constraints: BoxConstraints(0.0<=w<=1920.0, 0.0<=h<=924.0) size: MISSING behavior: opaque
My stateless widget:
@override
Widget build(BuildContext context) {
  return MaterialApp(
    home: Scaffold(
      appBar: AppBar(title: Text('Pangea')),
      body: Container(
        color: Colors.black45,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Container(
                height: double.infinity,
                // width: double.infinity,
                child: Column(
                  children: [
                    TextField(
                        // decoration: InputDecoration(
                        //   constraints: BoxConstraints.tightFor(
                        //     width: 300,
                        //   ),
                        // ),
                        ),
                  ],
                )),
          ],
        ),
      ),
    ),
  );
}

If I use InputDecoration inside TextField it works fine. But I would like to keep its size dynamic. May be perhaps I can specify min and max width .

A: I think you might need IntrinsicHeight widget.
It makes its child to wait until its parent has a defined Height and, with that value in its hands, builds the child.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Comparing Operator topologies-norm, strong and weak for a sobolev type linear operator. Another Stanford Qual question that has been bugging me.
Let $\mathcal{L}(L^2(\mathbb{R}))$ be the set of bounded linear operators on $L^2(\mathbb{R})$. Define $\Lambda_sf(\xi)=(1+|\xi|^2)^{is\backslash2}f(\xi)$, for $s \in \mathbb{R}$.
Consider the map $\Lambda:\mathbb{R}\to \mathcal{L}(L^2(\mathbb{R}))$ given by $\Lambda(s)=\Lambda_s$. Prove or disprove the following:
a) $\Lambda$ is continuous when $\mathcal{L}(L^2(\mathbb{R}))$ is given norm topology.
b)$\Lambda$ is continuous when $\mathcal{L}(L^2(\mathbb{R}))$ is given strong(operator) topology.
c)$\Lambda$ is continuous when $\mathcal{L}(L^2(\mathbb{R}))$ is given weak(operator) topology.
$\textbf{Thoughts}$:
1) $\Lambda_s$ is bounded in norm topology since $(1+|\xi|^2)^{is\backslash2}=\exp(\log(1+|\xi|^2)\frac{is}{2})$ which is in turn bounded by 1. Thus $||\Lambda_s f||\leq ||f||_2 $.
2) To prove continuity(or discontinuity) of $\Lambda$ it is enough to consider continuity at 0.
3) $||\Lambda_sf-\Lambda_0f||_2=||\left[\exp(\log(1+|\xi|^2)\frac{is}{2})-1\right]f||_2$
Now for a fixed $s>0$ we can choose $\xi$ so that $\log(1+|\xi|^2)\frac{s}{2}$ is a multiple of $\frac{\pi}{2}$, hence in a neighborhood of these points, $|\exp(\log(1+|\xi|^2)\frac{is}{2})-1| \geq \frac{1}{2}$. And hand wavely speaking, we can choose $f$ so that $f$ is supported on the union of these neighborhoods and $||f||_2=1$.
Thus we have  $||\Lambda_sf-\Lambda_0f||_2=||\left[\exp(\log(1+|\xi|^2)\frac{is}{2})-1\right]f||_2 \geq \frac{1}{2}$. Hence $\Lambda$ is not continuous in strong and norm topologies.
I think that the same type of example can be used to show that $\Lambda$ is not continuous in the weak operator topology.
All of this could be complete BS and I would appreciate if anyone could give me suggestions. Thanks in advance.
PS- The operator looks awful lot like the Fourier definition of Sobolev spaces except there is an $i$ there. Is there any sort of connection there, perhaps like heat and schrodinger's equation?
$\textbf{Edit}:$
As pointed out by amsmath that my counterexample works for the norm but not for strong and weak operator topologies. The reason being that the $f$ I was choosing depends on $s$ and for a fixed $f$ we can use Lebesgue dominated conv. theorem to show that it is actually continuous in the strong toplolgy.


text:
Q: Why the below code is not executing for every value of i in for loop? SetTimeout is not working for each i of for loop. I've tried almost everything, used promise, etc but nothing is working.
animateDijkstra(visitedNodesInOrder) {
  for (let i = 0; i < visitedNodesInOrder.length; i++) {
    // here set timeout is not working for each i :(
    setTimeout(() => {
      const node = visitedNodesInOrder[i];
      const newGrid = this.state.grid.slice();
      const newNode = {
        ...node,
        isVisited: true,
      };
      newGrid[node.row][node.col] = newNode;
      this.setState({ grid: newGrid });
    }, 3000 * (i + 1));
  }
};

A: animateDijkstra(visitedNodesInOrder) {
for (let i = 0; i < visitedNodesInOrder.length; i++) {
    // here set timeout is not working for each i :(

    (function() {
        setTimeout(() => {
            const loopVariable = i;
            const node = visitedNodesInOrder[loopVariable];
            const newGrid = this.state.grid.slice();
            const newNode = {
                ...node,
                isVisited: true,
            };
            newGrid[node.row][node.col] = newNode;
            this.setState({
                grid: newGrid
            });
        }, 3000 * (loopVariable + 1));
    })()
}
};


text:
Q: Paypal Express checkout not working? I have been using Paypal Express checkout for payment in my application.Still its in sandbox mode. It was working fine without any problem till last week.But from this week, the transaction ID not generating.
First of all, I will explain my full flow of transaction.
1.When I checkout, I will call the php file in my server with customer detail and products details.
2.Then this php file will call Paypal API and generate a token and send it back to my application.
3.With transaction ID and device token (generated by libPayPalEC.a library) and loading the sandbox paypal URL with these two parameters.Below is the way I am loading URL in webview if I successfully get token from my server.
NSString *urlAddress = [NSString  stringWithFormat:@"https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout-mobile&useraction=commit&drt=%@&token=%@",_deviceToken,_payPalToken];

4.The webView will be loaded with login page and further transaction is made.
The above process were worked nicely till last week but now its stuck in the second point itself.My php not providing an token.Instead it the response like below.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Pay with a PayPal account - PayPal</title>

<meta name="description" content="PayPal is the safer, easier way to pay online without revealing your credit card number.">

<meta http-equiv="X-UA-Compatible" content="IE=9"><link media="screen" rel="stylesheet" type="text/css" href="https://www.sandbox.paypal.com/MERCHANTPAYMENTWEB-640-20130622-1/css/core/xptdev.css"><link media="screen" rel="stylesheet" type="text/css" href="https://www.sandbox.paypal.com/MERCHANTPAYMENTWEB-640-20130622-1/css/core/global.css"><link rel="stylesheet" type="text/css" href="https://www.sandbox.paypal.com/MERCHANTPAYMENTWEB-640-20130622-1/Checkout/css/checkout.css">

<link rel="stylesheet" type="text/css" href="https://www.sandbox.paypal.com/css/sandbox.css"><link rel="shortcut icon" href="https://www.sandbox.paypal.com/en_US/i/icon/pp_favicon_x.ico"><link rel="apple-touch-icon" href="https://www.sandbox.paypal.com/en_US/i/pui/apple-touch-icon.png">
PayPal requires JavaScript for many of its features. To check out, please turn on Javascript in your internet browser.

Benchmark iPhone's Test Store

Choose a way to pay

<input type="hidden" id="yui-history-field" name="yui-history-field" value=""><form id="historyForm" method="get" class="noAnimation" action="https://www.sandbox.paypal.com/us/cgi-bin/merchantpaymentweb"><input type="hidden" name="cmd" value="_flow"><input id="historyDispatch" type="hidden" name="dispatch" value="50a222a57771920b6a3d7b606239e4d529b525e0b7e69bf0224adecfb0124e9b61f737ba21b081988da7a3c03e3ee25661350b6a36dba24a"><input id="historySession" type="hidden" name="SESSION"><input type="submit" id="historySubmit" name="historySubmit" value="" class="hide parentSubmit noAnimation"><input name="auth" type="hidden" value="ARlB87oxQ9J5V1AHb1z0XwiBtbOHOHDRWmiu.ySH5Pdx06UHFSnnO.ZzwT93TLFLx"><input name="form_charset" type="hidden" value="UTF-8"></form>

<form method="post" id="parentForm" name="login_form" action="https://www.sandbox.paypal.com/us/cgi-bin/merchantpaymentweb?dispatch=50a222a57771920b6a3d7b606239e4d529b525e0b7e69bf0224adecfb0124e9b61f737ba21b081988da7a3c03e3ee25661350b6a36dba24a" class=""><input type="hidden" name="cmd" value="_flow"><input type="hidden" id="myAllTextSubmitID" name="myAllTextSubmitID" value=""><input type="hidden" id="miniPager" name="miniPager" value="">

Your order summary

DescriptionsAmount

Test Product$2.50

Item price: $2.50

Quantity: 1

Item total $2.50

Total $2.50 AUD

Loading ...Updating countryAuthenticating your informationLogging you inAuthenticating your information.Securing your information.Updating your information ...Updating your information ...Updating order total ...

<fieldset id="sliders"><legend class="accessAid">Login</legend><input type="hidden" id="currentSession" name="currentSession" value="hIeXpvxuBcpEkVcO6ac1zxQzgDbkoJ0yBpSa7hB9FsbaJEDJs3mrB2YWy10"><input type="hidden" id="pageState" name="pageState" value="login"><input type="hidden" id="currentDispatch" name="currentDispatch" value="50a222a57771920b6a3d7b606239e4d529b525e0b7e69bf0224adecfb0124e9b61f737ba21b081988da7a3c03e3ee25661350b6a36dba24a"><input type="hidden" id="flag_non_js" name="flag_non_js" value="true">

Choose a way to pay

Pay with my PayPal accountLog in to your account to complete the purchase
<input type="hidden" name="email_recovery" value="false"><input type="hidden" name="password_recovery" value="false">

Email<input type="text" id="login_email" class="confidential large" name="login_email" value="venkatnskns@gmail.com">

PayPal password<input autocomplete="off" type="password" id="login_password" name="login_password" value="" class="restricted large">

<input type="submit" id="submitLogin" name="login.x" value="Log In" class="button primary default parentSubmit">
Forgot your email address or password?

<input type="hidden" id="pageSession" name="SESSION" value="OdkkP9CI6mk-sjRgiWGSF62n-GgAqPqVtZrCPVXBG2V1uX6NmTvvMBEx2_e"><input type="hidden" id="pageDispatch" name="dispatch" value="50a222a57771920b6a3d7b606239e4d529b525e0b7e69bf0224adecfb0124e9b61f737ba21b081988da7a3c03e3ee25661350b6a36dba24a"><input type="hidden" id="CONTEXT_CGI_VAR" name="CONTEXT" value="wtgSziM4C5x0SI-9CmKcv2vkSeTLK5P_g6HqzC__YTYkcqziFNcB84p79Ja">

<input type="submit" value="Don't have a PayPal account?" id="minipageSubmitBtn" name="new_user_button.x" class="parentSubmit noMask noAnimation">
(Optional) Join PayPal for faster future checkout

<input type="hidden" name="cmd" value="_flow"><input type="hidden" name="id" value=""><input type="hidden" name="close_external_flow" value="false"><input type="hidden" name="external_close_account_payment_flow" value="payment_flow">

</fieldset>

<input type="submit" value="Cancel and return to Benchmark iPhone's Test Store." name="cancel_return" class="action">

<input name="auth" type="hidden" value="ARlB87oxQ9J5V1AHb1z0XwiBtbOHOHDRWmiu.ySH5Pdx06UHFSnnO.ZzwT93TLFLx"><input name="form_charset" type="hidden" value="UTF-8"></form>

<input type="hidden" id="XoCountryCode" name="" value="US">

Site Feedback

PayPal. The safer, easier way to pay. For more information, read our User Agreement and Privacy Policy.

Test Site

We didn't made any change in the code(both in app and server). We have three applications like using same sandbox account but using three different severs.In all three applications its not working now.We don't know what is the exact problem. We have been searching in google and paypal site for past two days and came up with no solution.
Please suggest your idea.Really it would be a great help for us now.
Thanks in advance.
NOTE:
In my php code(main part)
   if( $ack == "SUCCESS" ) {
            $token = urldecode($resArray["TOKEN"]);

            //Store the order information the DB and get the last inserted id
            $lastInsertOrderId = storeOrder($token,$comments,$transcation);

            //Store the order items array in the database
            storeOrderItems( $_POST["productArray"],  $lastInsertOrderId);

            //   echo urldecode($resArray["TOKEN"]);
                /* XML Response */
                //$ResponseXML ="<Token><![CDATA[" .$token. "]]></Token>";
                /* JSON Response */
                $ResponseXML ='{"Token":"' .$token. '"}';

               echo $ResponseXML;
                   //If I command the following 4 lines I can get the token but I can't proceed the transaction.
               Redirect to paypal.com here
               $token = urldecode($resArray["TOKEN"]);
               $payPalURL = PAYPAL_URL.$token;
               header("Location: ".$payPalURL);
                  }

In the above php code if I command the last 4 lines I can get the Paypal token but while loading the sandbox login page, its saying the below error.
"This transaction is invalid .Please return to the recipient's website to complete your transaction using their regular checkout flow."
Please share your ideas.
Thank you....


text:
Q: Can't put text in one line if there are more words I can't put my text in one single line if there are more words.  Are there any possible ways to put this text in the block and in one single line? I am using the Bulma framework.

1-9 Klasė

      €
8ak.val.

      Ištisas dėmesys stengiantis patobulėti

      Ištisas dėmesys stengiantis patobulėti

      Ištisas dėmesys stengiantis patobulėti


text:
Q: React app not rendering on home page after adding Header or Home component App.js
import React from "react";
import "./App.css";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import Home from "./Home";
import Header from "./Header";
function App() {
return (

    <Router>
      <Switch>
        <Route path="/checkout">

Checkout

        </Route>
        <Route path="/login">

Login page

        </Route>
        <Route path="/">

          <Home/>

Home page

       </Route>
      </Switch>
      </Router>

  );
}
export default App;

Header.js
import React from "react";
import "./Header.css";
import SearchIcon from "@material-ui/icons/Search";
import ShoppingBasketIcon from "@material-ui/icons/ShoppingBasket";
import { Link } from 'react-router-dom';

function Header() {
  return (

            <ShoppingBasketIcon />

              0

  );
}

export default Header;

index.js
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";

ReactDOM.render(<App />, document.getElementById("root"));

I tried to add Header and Home component in App.js and was expecting the stuffs which I added, but it is showing blank on the home page. In contrast, login page shows texts -"login". Where did I go wrong, I have been searching the same but cannot find any answer anywhere. My react router version is 5.2.0

A: I'm not that familiar with react-router, but It seems you are returning 3 components under 1 Route tag
So maybe put Header, Home and h1 in a div:
<Route>

  <Home />

</Route>


text:
Q: I create simple form using angular template driven form but I got this error,
Object is possibly 'null
You must enter atleast 3 characters
why my error object is always null,minlength is not store in my error object what is the reason for that?
My hero.ts file is,
export class Hero {

  constructor(
    public id: number,
    public name: string,
    public email: string
  ) {  }

}

My formone.component.ts file is,
import { Component, OnInit } from '@angular/core';
import {NgForm} from "@angular/forms";
import {Hero}  from "../../hero"

@Component({
  selector: 'app-formone',
  templateUrl: './formone.component.html',
  styleUrls: ['./formone.component.css']
})
export class FormoneComponent implements OnInit {

  constructor() { }

  ngOnInit(): void {
  }

  model = new Hero(1, 'chamara','chamara@gmail.com');

  submitted = false;

  onSubmit() { this.submitted = true; }

  get diagnostic() { return JSON.stringify(this.model); }

}

My formone.component.html file is,

Template Driven Forms

      <form #formone="ngForm" (ngSubmit)="onSubmit()">

        {{diagnostic}}

          Name
          <input type="text" class="form-control" id="name"
                 required
                 [(ngModel)]="model.name" name="name" #name="ngModel" minlength="3" #x>

          You must enter atleast 3 characters
          This field required

          Email
          <input type="email"  class="form-control" id="alterEgo"
                 [(ngModel)]="model.email" name="alterEgo">

        <button type="submit"   class="btn btn-primary" [disabled]="!formone.form.valid">Submit</button>

      </form>

Plz help me to fix this,

A: Your Approach seems to be fine (at least for me), might you need to take care of few things
Remove extra #X from input code (this is causing issue by misleading error checking) and try to add name?.errors?.minlength just cross check name exists while checking errors.
<input type="text" class="form-control" id="name" required
                [(ngModel)]="model.name" name="name" #name="ngModel" minlength="3">

You must enter atleast 3 characters

You can check more about template driven error handling here:

*

*https://medium.com/swlh/form-validation-with-angular-template-driven-forms-8e0756cbec5
Happy Coding.. :)


text:
Q: In a Reactive scenario what should be better: Reactor Kafka or Kafka Listener I have this scenario chalenging me: Kafka topic with messages that I must consume and expose via SSE to a Webcomponent. I have been done several tentatives in all layers looking for a stable and more reliable approach or at least some I fill more confortable to support.
Now I create a very simple Kafka topic and create two different consumers and both seems to work pretty the same way. One is using org.springframework.kafka.annotation.KafkaListener and other reactor.kafka.receiver.KafkaReceiver.
The final goal is expose via via Spring WebFlux an event posting the message when consumer from topic.
If I am not wrong I have read somewhere that Spring..KafkaListener is blocking code but as far as I can see it isn't. It is just a listener been triggered exactlly as Reactor..KafkaReceiver. Since I am coding a non-blocking code I should avoid blocking code but I can't Spring..KafkaListener blocking anywhere.
Here are the basic comparision resulting in exact same result:
Reactor KafkaReceiver:
ReceiverOptions<Object, Object> consumerOptions = ReceiverOptions.create(consumerProps)
        .subscription(Collections.singleton("test"))
        .addAssignListener(partitions -> logger.debug("onPartitionsAssigned {}", partitions))
        .addRevokeListener(partitions -> logger.debug("onPartitionsRevoked {}", partitions));

kafkaReceiver = KafkaReceiver.create(consumerOptions);

((Flux<ReceiverRecord>) kafkaReceiver.receive()).doOnNext(r -> {
    logger.info(String.format("Consumed Message using KafkaListener -> %s", r.value()));
    r.receiverOffset().acknowledge();
}).subscribe();

Spring Kafka Listener:
@KafkaListener(topics = "test")
public void consume(String message) {
    logger.info(String.format("Consumed Message using KafkaListener -> %s", message));
}

If you want to reproduce the comparision:
1 - clone https://github.com/jimisdrpc/simplest-comparison-kafkaconsumer
2 - create default Kafka topic name test
3 - produce any message to such topic
4 - enable either Reactor Kafka and run again after enable Kafka Listener (I didn't find how make both work in same application at same moment but let's say it isn't that important now)

PS.: I am not asking which is better. I am trying to compare for a very specific scenario (reactive programming aimed to produce events for a webcomponent via Spring WebFlux) and trying to garante that I am not choosing one that might be blocking code somehow.


text:
Q: Use PHP to clean up XML stored in a variable? I'm taking over a previous developer's project. The code is building a large XML document a little at a time, appending new XML to the same variable as it goes along. The problem is the data sometimes has invalid characters.
For example:
$xml .= "<name>Jack & Jill</name>";
$xml .= "<street>123 Mary's Lake Road</street>";

I'm looking for a way to clean up the XML data all at once, like this:
$xml = safeXML($xml);

It seems like building such a function ought to be simple, but so far everything I've found either requires valid XML to start with, or else goofs up the XML tags themselves.
(I know it would be better to format the XML properly before building the document, but this is complex code and as usual the client wants it done yesterday. ;) )


text:
Q: how to store different types of data in flutter secure storage I am new to flutter and I am using flutter secure storage to store user credentials. so I searched on the internet that how can I store different types of data into flutter secure storage as it is allowing me to store only string types of data. I want to store boolean values like login into it, but I did not find any proper answer. Please, someone, confirm me, can I store or not different types of data also into it, instead of String data.

A: Assuming you're talking about the flutter_secure_storage package: it supports strings only.
If you want to store other types of data, you can encode them as a string. The most convenient way to do that is probably JSON. You can use jsonEncode and jsonDecode from the dart:convert library.

A: Yo can use some sort of type parsing.
For bool:

*

*To write to Secure Storage:
await _secureStorage.write(key: _key, value: boolValue.toString());

*To read from Secure Storage:
var value = await _secureStorage.red(key: _key);

Value will be of type String, you can then "cast" it to bool:
bool boolValue = value.toLowerCase() == 'true';

.toLowerCase() just in case, somehow in Secure Storage will be True.
For int you can do:
int i = int.parse('42');

etc.


text:
Q: preserve multiple select values on from submission errors I have a form in which there is a multiple select field along with a lot of other fields. On form submission, if there is any error I'm rendering the same form with the pre filled values that are entered by the user.
The problem is that in case of multiple select, I'm only able to preserve the first value of the selected items.

    <form:label class="control-label col-sm-3 required" path="tags">Tag</form:label>

        <form:select multiple="multiple" name="tags" class="form-control select-search" required="required" type="select" data-placeholder="Select a Tag" path="tags">
            <c:forEach items="${MyConstants.TAGS}" var="tag_element">
                <c:choose>
                    <c:when test="${not empty param.tags}">
                        <c:forEach items="${param.tags}" var="param_tag">
                            <option value="${tag_element}" ${param_tag == tag_element ? 'selected' : ''}>${tag_element}</option>
                        </c:forEach>
                     </c:when>
                     <c:otherwise>
                         <option value="${tag_element}">"${tag_element}"</option>
                     </c:otherwise>
                </c:choose>
             </c:forEach>
        </form:select>

A: Instead of using html's  tag, use  tag which will automatically preserve the values without setting any select. Thanks to this post: Spring MVC selected value in form:selected after form validation error


text:
Q: Is it possible to compile C code to Javascript code? I've found a programming tool called emscripten that can compile c++ code to Javascript code using LLVM. Is it possible to compile C to Javascript using Emscripten (or a similar tool?)

A: Emscripten doesn't know a thing about C++. It operates on LLVM IR, and cares relatively little how that code was created. You can compile just about anything (that has a LLVM-IR-emitting compiler), including C++, to LLVM IR and pass that to Emscripten.
Note that the result is highly unlikely to resemble human-written JavaScript, and will be unfit for maintenance and further development. It also has some inherent restrictions -- JavaScript isn't machine code, and even if it was, it wouldn't necessarily be compatible to the assumptions of some low-level code.


text:
Q: Can you set a column equal to another column in a table using SQLiteDatabse update()? I need to make a column equal to another column in the table. I can't figure it out using the update method of my SQLiteDatabase.
I know the SQL statement is:
UPDATE coolTable SET columnA = columnB;

Do I put it in the ContentValues I pass the function? or the selection string?

A: You can use update() only to set literal values (as bind params), not any other kind of expression supported by sqlite SQL syntax.
Use execSQL() to execute your raw UPDATE query with column name expression.

A: execSQL() with error checking:
SQLiteDatabase db = getReadableDatabase();

try {
    long count = DatabaseUtils.queryNumEntries(db, "pweb");
    db.execSQL("update pweb set h_id = _id;");
    long rows = DatabaseUtils.longForQuery(db, "SELECT changes()", null);
    if(count != rows ) Log.e("wrong count","update failed");
 }
catch(SQLException e){
  Log.e("SQLException","update failed");
}

db.close();

but I was wondering if it is possible to use the database's update()
  function instead of execSQL()

You can use sqlite3 to view and manipulate you data, and test out sql commands.
Create a table:
CREATE TABLE pweb (_id INTEGER PRIMARY KEY,h_id  INTEGER ,sent  INTEGER);

See the original rows:
sqlite> select * from pweb;
1|10|1
2|20|1
3|30|0
4|40|0

execute a column update:
sqlite> update pweb set h_id = _id;

See the changes to all rows:
sqlite> select * from pweb;
1|1|1
2|2|1
3|3|0
4|4|0

Something more complex ?
sqlite>  update pweb set h_id = _id + 1;

result:
sqlite> select * from pweb;
1|2|1
2|3|1
3|4|0
4|5|0

See also Understanding SQLITE DataBase in Android:


text:
Q: How to Change Div Position Dynamically (with Jquery/Javascript) I am doing one R&D and trying to find a answer of one problem. I have 6 divs on page which contains different content. I want to move these six divs place (on live page) by changing jquery or CSS files only. For example :-

1

2

3

4

5

6

I have coded above thing which displays content in below manner (with help of css - float) :
1 2
3 4
5 6
what script or css without changing HTML structure will help me to show content in below structure:-
6 5
3 4
2 1
can any one help me with this please.
Please let me know if I have to give any other information from my end.

A: You could do something like
[].reverse.apply($('div')).appendTo($('body'));

http://jsfiddle.net/EdgzC/1/

A: Here's a quick and dirty way that worked for me. I created a function which takes an array that specifies the new order for the
 tags and uses append to reorder them.
function changeOrder(newOrder) {
    var $divs = $('div'),
        $parent = $divs.eq(0).parent();
    for (var ii = 0; ii < newOrder.length; ii++) {
        $parent.append($divs.eq(newOrder[ii] - 1));
    }
}

$(function() {
    changeOrder([6,5,3,4,2,1]);
});

Working example: http://jsfiddle.net/FishBasketGordo/XK44w/


text:
Q: Is there a way to speed up the game without physics getting wonky? If one uses the "sgtm" (set global time multiplier) console command and sets the global time multiplier too high, resting objects will start to bounce, bounce around the room, and even stretch. Particularly for the purpose of the rate at which one accrues Sneak XP by movement, what way is there to speed up the game without suffering those physics anomalies?
Alternatively, but a different question, what way is there to increase the Sneak XP that is earned by movement?

A: I'm going to assume the physics glitch is a symptom of the game engine and the only way to avoid it would be to speed up the game from outside the game engine.
Regarding leveling Sneak quicker...
The skills all level up at different rates (http://elderscrolls.wikia.com/wiki/Console_Commands_%28Skyrim%29/Skills)
There may be a user mod that changes the rates or it may be possible to make one... But aside from that, with just console commands you're stuck either grinding it or using 'AdvSkill Sneak ###' to advance sneak via console.

A: One could try the "Make clutter items static" option in "Better INI Tweaks for Skyrim" (BITS) mod:

[HAVOK]
[...]
; Makes clutter items static so they can not be moved or picked up in-game.
; WARNING: This tweak will make it so your character can not interact with clutter items at all.
#bPreventHavokAddClutter=0
;bPreventHavokAddClutter=1

; Install to \Skyrim\Data and the tweaks in this file will override any of the same tweaks from
; the Skyrim.ini file, typically found in C:\Users[USERNAME]\Documents\My Games\Skyrim.
;
; Any line in an INI file that begins with a semicolon [;] or a hashtag [#] is interpreted as a
; comment to be read by humans and is ignored by the game.

I suspect that this option will prevent ragdolls from being ragdolls.


text:
Q: How to best find what is writing to the Debug output in .net/c# I have a desktop c# .net app. Visual Studio 2019. 5 million lines of code.
One of them is spamming to the debug output window ( Debug.WriteLine() ).  Is there an easy way to find out (perhaps break on write) where the spam is happening?
I really don't want to have to go through and put in 500 breakpoints...

A: You could add an empty TraceListener and put breakpoints on Write() and WriteLine().
using System;
using System.Diagnostics;

class Program
{
    static void Main(string[] args)
    {
        Trace.Listeners.Add(new MyTraceListener());
        Debug.WriteLine("testing");
    }

    class MyTraceListener : TraceListener
    {
        public override void Write(string message)
        {
            // breakpoint here
        }

        public override void WriteLine(string message)
        {
            // breakpoint here
        }
    }

}

A: The suggestions given will certainly work. This is just another suggestion:
Add this using directive
using System.Runtime.CompilerServices;

Add the following method
    private void showDebug(string message, [CallerLineNumber] int lineNumber = 0)
    {
        Debug.WriteLine(message + " at " + lineNumber.ToString());
    }

Then replace all of "Debug.WriteLine" with "showDebug" (except in the added method)
This will definitely tell you where it is coming from.

A: In situations like this I try to figure out which part of the message doesn't change and then search through the solution for that string.
Depending on you solution you may be able to put a conditional breakpoint in your base Log/Write method.

A: You can use my Runtime Flow extension with filters for your app and the Debug.WriteLine method. In the captured flow you will see what code calls Debug.WriteLine.


text:
Q: What is the grandchild of a parents's siblings called? I know that my parents' siblings' child is my cousin.
But what about the grandchild of my parents' siblings?

A: The naming of different types of cousins is referred to as "ordinals and removals".
If you share the same grandparents, you are "first cousins". If you share the same great grandparents, you are "second cousins". And so on.
The children of your first cousin are your "first cousins once removed". The grandchildren of your first cousin are "first cousins twice removed". The children of your second cousin are your "second cousins once removed". And so on.
Note that most people have no idea how this system works and just use the generic "cousin" for all distant relatives.

A: The grandchild of your parent's sibling is your first cousin once removed. (You are also their first cousin once removed.)
Here's another attempt at a diagram, simply because this form works better for me, maybe it will for you too. The number of "removals" are the extra generations on one side only (shown in orange below), and once those extra generations are removed, the degree indicates how many more generations to get back to siblings (shown in blue below).

A: The child of an aunt or uncle is your

*

*(first) cousin

The grandchild of an aunt or uncle is your

*

*first cousin once removed

Please see the chart at What Is a Second Cousin?

A: The standard family tree chart never made a lot of sense to me, so I drew the following "ladder picture", where first cousins, seconds cousins, third cousins, and so forth, are rungs on a ladder:

This visual might be easier for some folks to understand.  To answer your specific question:

what about the grandchild of my parents' siblings

*

*You are Person 3.

*Your parent's sibling is Person 2.

*The grandchild of Person 2 is Person 6.

Person 3 and Person 6 are first cousins once removed.

A: Wikipedia has some good stuff on this, e.g.

*

*https://commons.wikimedia.org/wiki/File:European_kinship_system_en.svg for English

*https://commons.wikimedia.org/wiki/File:European_kinship_system_de.svg for German.

My German wife had an awful lot of aunts (Tanten) and uncles (Onkel), whereas I have a lot of cousins. It wasn't until I saw these diagrams that I understood why.
See also:

*

*https://commons.wikimedia.org/wiki/File:Table_of_Consanguinity_showing_degrees_of_relationship.png (English)

*https://commons.wikimedia.org/wiki/File:Table_of_Consanguinity_showing_degrees_of_relationship_zh-hans.png (Chinese)

*https://commons.wikimedia.org/wiki/File:Table_of_Consanguinity_showing_degrees_of_relationship_zh-hans.png (Arabic)


text:
Q: Select element inside array let's say I have something like this:
var SucessList = [
 {
  id: 1,
  dedicated: true
 },
 {
  id: 2,
  dedicated: false
 }
];

and I want to make an if function to check if dedicated == true. How do i select dedicated to use like that?

A: let res = SucessList.filter(({dedicated}) => dedicated);


text:
Q: UTF-8 locale in Visual C++ 2010 I am trying to read a UTF-8 text file in Visual C++ 2010 using only the standard library and not Boost or Windows APIs. I define the locale as:
std::locale utf8_locale(std::locale(), new std::codecvt_utf8<wchar_t>);

but this results in the following compiler error:
error C2661: 'std::locale::facet::operator new' : no overloaded function takes 3 arguments
error C2664: 'std::locale::locale(const char *,std::locale::category)' : cannot convert parameter 1 from 'std::locale' to 'const char *'

A: The error is occures in debug mode when the code is used in the file that micrsoft Visual c++ provided below macro is placed.
#ifdef _DEBUG
#define new DEBUG_NEW
#endif

to get rid of this error the #define new DEBUG_NEW should be commented out or the code should be implemented in another file which does not have the above macro.
This bug for Visual c++ 2010 is mentioned here http://connect.microsoft.com/VisualStudio/feedback/details/683483/mfc-c-fails-to-compile-use-of-codecvt-utf8-in-debug-configuration

A: FYI, another work around is to just write
std::locale utf8(std::locale(), ::new std::codecvt_utf8<wchar_t>);

That will force the compiler to use the global new, instead of the locale new


text:
Q: Expressing a vector v as a linear combination of x and y
Express the vector $v = \begin{bmatrix}49\\0\end{bmatrix}$ as a linear combination of $x = \begin{bmatrix}6\\5\end{bmatrix}$ and $y = \begin{bmatrix}-5\\4\end{bmatrix}$
$v = $ ____ $x + $ ______$y$

How exactly can I express this vector as a linear combination of these other two vectors? I've never seen a problem like this before. Nor do I know exactly what a Linear Combination is in "laymans terms"

A: Just put:
$$v = ax+by $$
then solve for $a$ and $b$
\begin{cases}
6a-5b = 49\\
5a+4b = 0
\end{cases}
You will get:
$$v = 4x-5y$$

A: Suppose that you have vectors $x_1,..,x_n \in V$, where $V$ is a vector space over a field $F$ (For example $\mathbb{R}^2$ over $\mathbb{R}$).  Then $z$ is said to be a linear combination of vectors $x_1,..,x_n$ if there exists scalars $a_1,..,a_n \in F$ such that:
\begin{equation}
z = a_1x_1+...+a_nx_n \in V
\end{equation}
In this case you have $V = \mathbb{R}^2$ and $F = \mathbb{R}$. You want to find scalars $a_1,a_2 \in \mathbb{R}$ such that $v = a_1x + a_2y$.
In order to solve this, start from this definition and plug in your information:
\begin{align}
    v = \begin{bmatrix}
           49 \\
           0
         \end{bmatrix} = a_1\begin{bmatrix}
           6 \\
          5
         \end{bmatrix} + a_2\begin{bmatrix}
           -5 \\
          4
         \end{bmatrix}
  \end{align}
Now you can use standard properties of vectors and multiply every component of $x$ by $a_1$, and multiply every component of $y$ by $a_2$. Hence you get a systems of two equations and two unknown, which is consistent.
you have
\begin{equation}
49 = 6a_1-5a_2
\end{equation}
and:
\begin{equation}
0 = 5a_1+4a_2
\end{equation}
You can then solve for $a_1$ and $a_2$. From the second one you get $a_1 = -\frac{4}{5}a_2$, then you substitute into the first one and obtain $49 = -\frac{24}{5}a_2-5a_2$, which then becomes $49 = -\frac{49}{5}a_2$, so $a_2 = -5$, so $a_1 = 4$.
Finally you get $v = 4x-5y$, where $4,-5\in \mathbb{R}$

A: Let the equation be $v=lx+my$. where $l,n\in R$.So now you get two equations ie $6l-5n=49,5l+4n=0$. Now you can solve for $l,n$


text:
Q: Find user's current location(latitude and longitude) when user logged in, through Facebook api? does Facebook api provides user's current location(latitude and longitude) when user logged in ? If yes, then how do I get it ? https://graph.facebook.com/me/ provides only user related data, but not the current location. Please help me to get this.

A: After going through https://developers.facebook.com/docs/reference/fql/user facebook document,I got the current location with latitude and longitude. To get this we need to fire a query which will select current location from user table with user's access token.
FQL(Facebook Query Language) :
https://graph.facebook.com/fql?q=SELECT current_location FROM user WHERE uid=me()& access_token=xxxxx

Response:
{
"data": [
  {
     "current_location": {
        "city": <city name>,
        "state": <state name>,
        "country": <country name >,
        "zip": <zip code>,
        "latitude": <latitude>,
        "longitude": <longitude>,
        "id": <location id>,
        "name": <address>
     }
  }
]
}

A: If you want to find Find user's location(latitude and longitude) on base its profile details when user logged in, through Facebook api? Then Follow this:

*

*Download https://github.com/facebook/facebook-php-sdk
and copy all files from src and put in your project folder and rename it to php-sdk

*Your code file(index.php)
require_once('php-sdk/facebook.php');
$config = array(
  'appId' => 'YOUR_APP_ID',
'secret' => 'YOUR_SECRET_KEY',
'allowSignedRequest' => false // optional but should be set to false for non-canvas apps
);
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
$user_profile = $facebook->api('/me','GET');
$query = 'SELECT current_location FROM user WHERE uid = me()';
$response = $facebook->api(array('method' => 'fql.query', 'query' => $query));
print_r($response);
OutPut:
Array
(
    [0] => Array
        (
            [current_location] => Array
                (
                    [city] => Test
                    [state] => Test
                    [country] => Test
                    [zip] =>
                    [latitude] => 53.0833
                    [longitude] => 92.6667
                    [id] => 4555555878787887
                    [name] => Test
                )

        )

)

A: Yes, it is possible with facebook FQL query.
Please refer below link
https://developers.facebook.com/docs/reference/fql/standard_user_info/


text:
Q: Passing display=touch to Facebook OAuth with Microsoft OWIN I have an ASP.NET MVC5 app which I have configured for Facebook OAuth 2 login using the ASP.NET OWIN authentication model that ships with this version of MVC.
I want to tell Facebook to optimize its login page for touch-based devices. Facebook documentation says I should be able to do this by adding a display=touch parameter to the query string we pass to Facebook when we kick off the OAuth flow. (see https://developers.facebook.com/docs/reference/dialogs/oauth/)
This ought to be a simple thing to do, but I am at a total loss about how to go about customizing the various OWIN middleware classes to add this parameter.
How do I customize the OWIN auth flow to modify the Facebook OAuth URL?

A: Basically: you need to go ahead and create an authentication provider for Facebook. So create a class that inherits from FacebookAuthenticationProvider. Within this class, override the "ApplyRedirect" method. Make it look something like:
public override void ApplyRedirect(FacebookApplyRedirectContext context)
{
    context.Response.Redirect(context.RedirectUri + "&display=popup");
}
Now simply wire this class up with your configuration, like so:

app.UseFacebookAuthentication(new FacebookAuthenticationOptions
{
    Provider = new **<the name of the class that you created>**()
    // the rest of your configuration such as app ID and secret
});

And that should be it!
Answer courtesy of @nlaq here: Facebook PopUp Login with Owin


text:
Q: SELECT AS casting columns implicitly I have a table that contains uuid varchar not null and id integer not null columns.
If I execute this SQL statement
select uuid, id, uuid as id from table;
I get something like
uid                                 |id |id      |
------------------------------------|---|--------|
42e50e73-e673-4dd2-9ef2-d9aa94eece70| 11|      42|
03d92b01-0377-4ce9-8927-d092c6a03232| 12|       3|
96c9e980-2839-45ee-bc7c-456c2beaa589| 13|      96|
878979f5-6a21-465c-bcf3-55f6eb4ec412| 14|  878979|
491d1fbd-4652-42f7-b326-d3876656dc19| 15|     491|
cf00f2ac-d56a-4439-8a4a-8dd6193ca1b8| 16|        |
9cb13097-77ea-4656-8ccb-64420afdc994| 17|       9|

If I replace as id with anything but id, it works as expected.
As is clearly evident from this, Postgres is casting the uuid column into the same type as the id column. This works for all combinations of column1 as column2 where column1 is cast to column2 type.
Why?
I am using Postgres 12.2 on MacOS. I tried the same on MySQL 5.7.28 and it doesn't perform the casting. I am aware this is not a practical query because of name conflicts, but the result is somewhat unexpected.


text:
Q: I want to know the exact concept of virtual address Virtual address is described as linear address in some places, and logical address in others.
I'd like to know which one is right with the clear concept of virtual address.

A: The concept of virtual addresses is that you have a fake/pretend address space and convert/map that somehow to the real/physical address space for one or more reasons (to improve flexibility, to improve portability, to improve security, etc). How this is implemented in practice doesn't really effect the theoretical concept.
For the implementation of the concept on 80x86; virtual addresses are converted into linear addresses using segmentation, then linear addresses are converted into physical addresses using paging. However; segmentation can be configured so that "virtual = linear" (by setting segment bases to zero and segment limits to max., including in 64-bit code if FS and GS are configured so that they do nothing); and paging can be disabled resulting in "linear = physical"; and if neither segmentation nor paging are used you end up with "virtual = linear = physical".
Most operating systems for 80x86 don't use segmentation but do use paging; so virtual addresses can be described as linear addresses for most operating systems (and most applications) on 80x86; but "technically can" isn't a good reason for increasing confusion and almost nobody would call them linear addresses (instead of virtual addresses) without a reason - normally you'd only see the word "linear" used if the difference might matter.
For logical addresses, I have no idea where you saw that, and without context I'd (correctly or incorrectly) assume it's related to storage space and has nothing to do with memory (e.g. "logical block address" as an alternative to "cylinder, head, sector addressing" for old hard disks).

A: The three basic concept you need to know:
Physical - An actual, specific device
Logical - A redirection to a device
Virtual - A simulated device
In ye olde days before large memory system, virtual and logical were often conflated in regard to addresses. In reality, there is no such thing as a virtual address. A logical address can map to a nothing at all, a physical address, or memory that is simulated virtually.
You can have virtual memory that is accessed by logical addresses.


text:
Q: jQuery event on nested future object I have web page which makes some ajax calls and loads the following HTML:

    Delete
    Edit

The following javascript should attach event handlers to the future objects:
$('.actions').live('ready', initFileActions);
var initFileActions = function (options) {
    alert('action called');
    $('.delete', this).click (function (e) {
        alert ('delete called');
    });
   $('.edit', this).click (function (e) {
        alert ('edit called');
    });
    return $(this);
}

The above code calls the first alert ('action called') fine, however it's not calling the second alert ('delete called'), could anyone please help how can I call the second alert in the above code.

A: .live is deprecated and should use .on.
Try:
$(document).on('click','.actions .delete' initFileActions);
var initFileActions = function (options) {
    alert ('delete called');
    return $(this);
}


text:
Q: How to stop Windows 10 switching keyboard layout to default language after sleep How can I stop Windows 10 from switching input language automatically?
It does it when my laptop goes to sleep. On wake up it will switch the keyboard input language to the default language. I don't want this. When I choose an input language, I do so for a reason. I don't need it switched by the OS.


text:
Q: CSS classes not working with svg elements I'm using the vis.js library and most things work. Like when I manually style the elements with the "style" tag however when I use the class attribute the styles are not applied.
The SVG element
const svg = `
<svg xmlns="http://www.w3.org/2000/svg" width="420px" height="165px">
  <foreignObject x="0" y="0" width="100%" height="100%">

   // This doesn't work

Report Id

1

   // This works

Report Name

Medicine-Stock

  </foreignObject>
  </svg>`;

CSS
.testyh1 {
  color: #0481E2;
  margin-top: 0;
  margin-bottom: 3px;
  font-size: 12px;
  line-height: normal;
}

A: I use style tag and update these in HTML page with script tag:


text:
Q: Evaluating the Impact of National Policies Using Panel Data I have a panel data set covering various countries over various years. I have information about the years in which these countries published an entrepreneurship policy - some countries only published one in the past 20 years, while others published a new one every five or ten years. I also have an annual estimate of the level of entrepreneurial activity for each country.
I'd like to evaluate whether the launch of these policy documents resulted in an increase of entrepreneurial activity in these countries. However, I am not sure how to approach this question methodologically, since the policies were introduced in different years and sometimes countries introduced various policies over the time that my data set covers.
I don't think I can use the typical methods for evaluating the impact of treatment (such as difference-in-difference and instrumental variables regression), since the introduction of a treatment, which in my case is the introduction of policies take place across different years and sometimes there are several "treatments" for individual countries.
I would greatly appreciate your help with this question, as I am stuck not having found guidance searching through my books and the existing questions on Cross Validated.

A: Just a partial answer, but maybe it'll help.
You talk about several "treatments" for a single country. One approach to deal with this phenomenon is a
Difference-in-difference-in-differences estimator. There is also a good description of this estimator in  Woolridge's Econometric Analysis of Cross Section and Pannel Data .
Regarding the different points of time of the changes it might be helpful to standardise the data giving t=x for the year of the impact in the measure in a specific country.


text:
Q: Forcing HTTPS with subdomains in .htaccess or httpd.conf I've been unable to get the flow of rewrites in the correct order to force HTTPS and redirect to the 'www' domain by default.
What I'm trying to do is force the 'www' domain if none is provided and at the same time, force to HTTPS, while taking into consideration there are two other subdomains that HTTPS is required for as well.
Scenarios:
http://[domain.com]/* -> https://www.[domain.com]/*
http://assets.[domain.com]/* -> https://assets.[domain.com]/*
http://payloads.[domain.com]/* -> https://payloads.[domain.com]/*

As I understand, this first block check if HTTPS is not on AND if there is no subdomain present, then will redirect to https://www.[domain.com]/
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} !^www\.|assets\.|payloads\. [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

While this checks if HTTPS is not on AND a proper subdomain is found, then redirects to https://[subdomain].[domain.com]/
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} ^www\.|assets\.|payloads\. [NC]
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

Although the first condition/rule set successfully redirects to the default www subdomain, it goes into a loop and nothing displays when going to https://www.[domain.com].
Can someone explain what's wrong with my logic? I've looked at other answers here and either they don't help or there are no answers.
If it's more appropriate to force HTTPS in httpd.conf, and leave the redirects to the .htaccess, I can do that as well.
Thanks in advance.

A: You can accomplish with these 2 rules in httpd.conf or vhost.cong or site root .htaccess:
RewriteEngine On

# for assets or payload subdomains
RewriteCond %{HTTP_HOST} ^(?:assets|payloads)\. [NC]
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NE]

# for rest
RewriteCond %{HTTP_HOST} !^www\. [NC,OR]
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://www.%1%{REQUEST_URI} [R=301,L,NE]


text:
Q: Concatenating Multiple Sequences for a Sample within FASTA file using Perl and REGEX I have over 200 multi-sequence fasta files and inside each fasta file, there are sequences for hundreds of samples for a select gene (i.e.PF3D7_1467550 in the sample input fasta file). Most samples (i.e. sample 303.1 - first sequence in the sample input file) within a fasta file have one sequence but other samples (i.e. IGS-MLW-089sA and IGS-MWI-254sA) have multiple sequences for a gene that need to be concatenated together.
Sample input fasta file
>303.1_assembled_PF3D7_1475500.[1:126].sp.tr
MHHLLFIIWYIILNYYVSGQESATNFYKFIDSFASSTYISEESGSSAYDAKRAIQNNPNY
EEKKTYDEELKESKEKANDLNNKLSLLTSVNVNTLDSDILKLGILPGDSYNFPANDCAVI
KNVQ

>IGS-MLW-089sA_assembled_PF3D7_1475500.[1:61].sp.tr
MHHLLFIIWYIILNYYVSGQESATNFYKFIDSFASSTYISEESGSSAYDAKRAIQNNPNY
>IGS-MLW-089sA_assembled_PF3D7_1475500.[65:126].sp.tr
TYDEELKESKEKANDLNNKLSLLTSVNVNTLDSDILKLGILPGDSYNFPANDCAVIKNVQ

>IGS-MWI-254sA_assembled_PF3D7_1475500.[1:61].sp.tr
MHHLLFIIWYIILNYYVSGQESATNFYKFIDSFASSTYISEESGSSAYDAKRAIQNNPNY
>IGS-MWI-254sA_assembled_PF3D7_1475500.[65:119].sp.tr
TYDEELKESKEKANDLNNKLSLLTSVNVNTLDSDILKLGILPGDSYNFPANDC

Desired output:
 >303.1_assembled_PF3D7_1475500.[1:126].sp.tr
 MHHLLFIIWYIILNYYVSGQESATNFYKFIDSFASSTYISEESGSSAYDAKRAIQNNPNY
 EEKKTYDEELKESKEKANDLNNKLSLLTSVNVNTLDSDILKLGILPGDSYNFPANDCAVI
 KNVQ

 >IGS-MLW-089sA_assembled_PF3D7_1475500.[1:61][65:126].sp.tr
 MHHLLFIIWYIILNYYVSGQESATNFYKFIDSFASSTYISEESGSSAYDAKRAIQNNPNY
 TYDEELKESKEKANDLNNKLSLLTSVNVNTLDSDILKLGILPGDSYNFPANDCAVIKNVQ

 >IGS-MWI-254sA_assembled_PF3D7_1475500.[1:61][65:119].sp.tr
 MHHLLFIIWYIILNYYVSGQESATNFYKFIDSFASSTYISEESGSSAYDAKRAIQNNPNY
 TYDEELKESKEKANDLNNKLSLLTSVNVNTLDSDILKLGILPGDSYNFPANDC

I believe this code from another ticket could be useful.
 %hash;
 while (<DATA>) {
    if (/^>(miRNA\d+)/) {
            $hash{$1}[0] = $_;
            chomp($n = <DATA>);
            unshift @{$hash{$1}[1]}, $n;
    }
}

for $k (sort keys %hash) {
    print $hash{$k}[0], join(',', @{$hash{$k}[1]}), "\n";
 }

Here is the link to the previous ticket:
I need search a pattern in a header line of my file and concatenates the next line with Perl
I am looking for help to modify the following part of code dealing with the selecting the sampleID or alternative suggestions.
 /^>(miRNA\d+)/

Thank you

A: If the samples to be concatenated are adjacent, you can just collect the ranges (e.g. [1:61]) and lines to be printed in two arrays.
#!/usr/bin/perl
use warnings;
use strict;

sub without_ranges {
    my ($header) = @_;
    ( my $without = $header ) =~ s/\[[^\]]+\]//g;
    return $without
}

sub output {
    my ($header, $ranges, $buffer) = @_;
    my $header_with_ranges = $header;
    $header_with_ranges =~ s/(.*\])/$1\[$_]/ for @$ranges;
    print $header_with_ranges, @$buffer;
}

my (@buffer, @ranges);
my $header = "";

while (<>) {
    if (/^>/) {
        my $new_header = $_;
        if (without_ranges($new_header) eq without_ranges($header)) {
            push @ranges, $new_header =~ /\[([^\]]+)\]/;

        } else {
            output($header, \@ranges, \@buffer) if $header;
            $header = $new_header;
            @buffer = @ranges = ();
        }
        last if eof;

    } else {
        push @buffer, $_;
    }
}
output($header, \@ranges, \@buffer);

A: The code from another ticket is not that helpful, and a bit ... inoptimal, frankly.
Here is one of the possible solutions, assuming that you always have ranges [x:y].
use strict; use warnings;

my (%hash,$key,$start
    );
while(<DATA>) {
    chomp;
    if (m{^(>.*?)(?:\[(\d+):(\d+)\]\.sp\.tr)?$}) {
        ($key,$start)=($1,$2);
        next;
    }
    $hash{$key}{$start}.=$_;
}

for my $key (sort keys %hash) {
      my $keyref=$hash{$key};
      printf "%ssp.tr\n%s\n", $key, join (''
                                , map { $keyref->{$_}} sort {$a<=>$b} keys %$keyref
                                );
}

__DATA__
>303.1_assembled_PF3D7_1475500.[1:126].sp.tr
MHHLLFIIWYIILNYYVSGQESATNFYKFIDSFASSTYISEESGSSAYDAKRAIQNNPNY
EEKKTYDEELKESKEKANDLNNKLSLLTSVNVNTLDSDILKLGILPGDSYNFPANDCAVI
KNVQ

>IGS-MLW-089sA_assembled_PF3D7_1475500.[1:61].sp.tr
MHHLLFIIWYIILNYYVSGQESATNFYKFIDSFASSTYISEESGSSAYDAKRAIQNNPNY
>IGS-MLW-089sA_assembled_PF3D7_1475500.[65:126].sp.tr
TYDEELKESKEKANDLNNKLSLLTSVNVNTLDSDILKLGILPGDSYNFPANDCAVIKNVQ

>IGS-MWI-254sA_assembled_PF3D7_1475500.[1:61].sp.tr
MHHLLFIIWYIILNYYVSGQESATNFYKFIDSFASSTYISEESGSSAYDAKRAIQNNPNY
>IGS-MWI-254sA_assembled_PF3D7_1475500.[65:119].sp.tr
TYDEELKESKEKANDLNNKLSLLTSVNVNTLDSDILKLGILPGDSYNFPANDC

>303.1_assembled_PF3D7_1475500.sp.tr
MHHLLFIIWYIILNYYVSGQESATNFYKFIDSFASSTYISEESGSSAYDAKRAIQNNPNYEEKKTYDEELKESKEKANDLNNKLSLLTSVNVNTLDSDILKLGILPGDSYNFPANDCAVIKNVQ
>IGS-MLW-089sA_assembled_PF3D7_1475500.sp.tr
MHHLLFIIWYIILNYYVSGQESATNFYKFIDSFASSTYISEESGSSAYDAKRAIQNNPNYTYDEELKESKEKANDLNNKLSLLTSVNVNTLDSDILKLGILPGDSYNFPANDCAVIKNVQ
>IGS-MWI-254sA_assembled_PF3D7_1475500.sp.tr
MHHLLFIIWYIILNYYVSGQESATNFYKFIDSFASSTYISEESGSSAYDAKRAIQNNPNYTYDEELKESKEKANDLNNKLSLLTSVNVNTLDSDILKLGILPGDSYNFPANDC


text:
Q: Jetty: is it possible to use SPDY/3.1? I run Jetty server using JDK 1.8 and ALPN as described at: How to run Jetty with SPDY using ALPN?
There is line:
ALPNServerConnectionFactory alpn = new ALPNServerConnectionFactory("spdy/3", "http/1.1");

and:
HTTPSPDYServerConnectionFactory spdy = new HTTPSPDYServerConnectionFactory(SPDY.V3, httpConfig, push);

But Chrome 40 uses only "spdy/3.1" and "http/1.1". With ALPN debug enabled it looks like:
[S] ALPN protocols [spdy/3.1, http/1.1] received from client for 1987cc45[SSLEngine[hostname=169.0.1.126 port=59439] SSL_NULL_WITH_NULL_NULL]

Negotiation ends with http/1.1. So I changed that line into:
ALPNServerConnectionFactory alpn = new ALPNServerConnectionFactory("spdy/3.1", "http/1.1");

This gives that spdy/3.1 is selected:
[S] ALPN protocol 'spdy/3.1' selected for 1987cc45[SSLEngine[hostname=169.0.1.126 port=59439] SSL_NULL_WITH_NULL_NULL]

But Chrome does not receive response. I have not found any exception on the server side but it seems that Jetty cannot work with SPDY/3.1.
Can Jetty work with SPDY/3.1? How to set it?
I use JDK 1.8.0_31 and in bootstap alpn-boot-8.1.3.v20150130.jar.

A: Jetty does not support SPDY/3.1, only up to SPDY/3.
In fact, Jetty will never support SPDY/3.1.
SPDY and NPN were just removed from the code tree in the upcoming Jetty 9.3.0 release.
http://git.eclipse.org/c/jetty/org.eclipse.jetty.project.git/commit/?id=2162455b72d5a474bba47d5daf5543d46c2688be


text:
Q: Can an ip based virtual host be followed by an endpoint to point to a different website on Nginx? What I'm wanting to do for testing multiple applications is set up Nginx to have one app at 210.32.45.189/foo and another at 210.32.45.189/bar. Is this possible? I don't know how to configure the server_name directive in my sites-available file.

A: Without more information, this is the best I can think of.
server {
        listen 80;
        server_name 210.32.45.189;

        location /foo {
                ...
        }
        location /bar {
                ...
        }
}


text:
Q: DISTINCT for foreach <?php

$array = array('aaa', 'bbb', 'aaa', 'ccc', 'ddd', 'ccc', 'eee');

foreach($array as $a){
   echo $a;
}

Is possible use some like DISTINCT for foreach? I would like show each values only one, without repeat. How is the best way for this?
http://codepad.org/FZQNEBeK

A: Use array_unique()
$array = array('aaa', 'bbb', 'aaa', 'ccc', 'ddd', 'ccc', 'eee');
$result = array_unique($array);
print_r($result);

Demo

A: Actually array_unique() gets pretty bad when you have large arrays. You would be better off with $uniques =  array_flip(array_flip($array)).


text:
Q: Two child classes that only differ in a static const member I have a class A and two children B and C as follows:
class A {
   private:
     int x;
     template<class T>
     void setX(T &y);

   public:
     A();
};
class B : public A {
  private:
    static const double y;

  public:
      B();
};
class C : public A {
  private:
    static const int y;

  public:
      C();
 };

Both children only differ in the type of their static member y. The implementation of both C and B is the same except on the initialization of the static member:
B::B() : y (1.2) { setX(y) }
C::C() : y (2) { setX(y) }

But the problem with this approach is that in the implementation file I have to write twice the same code for B and C. Is there a proper way to write this such that I do not need to write twice the call to setX?
In the real problem the classes are a little more complicated, but the situation at hand is the same. In particular, initialization of y requires non-trivial constructors and so it has to be in the implementation file.

A: You can write a constructor for A as a function template.
class A {
    //....
public:
    template<typename T>
    explicit A(T& y) {
        setX(y);
    }
};

And call that constructor from child classes:
class B : public A{
    //...
public:
    B() : A(1.2), y(1.2)
    {}
};

Only problem is that base class constructor gets called first, so you need to repeat constant data value twice. You can easily macro it though.


text:
Q: how to get a function from input and apply it on data in python It is normal to get arguments, numbers, and strings from input in python. I am wondering if there is a way to get a user-defined function from the input and apply it in my program.
Suppose I have a program
a = [12,34,2,3,4,23,16,84,3]
print(a)
b = get_function_from_input()
print(b(a))

and if a user inserts something like following in input:
def myfun(X):
   return([max(X),min(X),sum(X)])

then my program outputs:
[84,2,181]

A: You can use a dictionary to link to logic already defined:
a = [12,34,2,3,4,23,16,84,3]

def myfun(X):
    return([max(X),min(X),sum(X)])

dispatcher = {'max_min_sum': myfun}

b = input('Enter a dispatcher key:\n')

print(dispatcher[b](a))

Demo input / output:
Enter a dispatcher key:
max_min_sum
[84, 2, 181]

A: How are you getting the input exactly?
If it helps, just want to point out that functions, like numbers and strings, are objects in python, and can be treated as parameters or return values.
a = [12,34,2,3,4,23,16,84,3]

def dostuff(func):
    return func(a)

def myfun(X):
    return([max(X),min(X),sum(X)])

print(dostuff(myfun))

outputs
[84, 2, 181]


text:
Q: JHipster How to control entitie generation to microservice? or How to do JDL properly to get the entities generated into the right micorservice folder I am trying to prototype a microservice application with JHipster and I have tried to collect all the information what I was able in order to do it properly, but it is not totally clear how to put together a JDL to have the right entities in the right services generated.
What I would expect is to have a directory layout like:
/..
 gateway <- Ideal would be to have only fronted code
 invoice <- Invoice CRUD code with corresponding ms (with below JDL it is empty)
 order <- Order CRUD code with corresponding ms
 usage <- Usage CRUD code with corresponding ms (with below JDL it is empty)

Here is the JDL used:
application {
  config {
    baseName gateway,
    applicationType gateway,
    packageName com.org.myApp.sales,
    serviceDiscoveryType eureka,
    searchEngine elasticsearch,
    authenticationType oauth2,
    prodDatabaseType postgresql,
    cacheProvider hazelcast,
    buildTool gradle,
    clientFramework react,
    testFrameworks [protractor]
  }
  entities *
}

application {
  config {
    baseName invoice,
    applicationType microservice,
    packageName com.org.myApp.invoice,
    serviceDiscoveryType eureka,
    searchEngine elasticsearch,
    authenticationType oauth2,
    prodDatabaseType postgresql,
    devDatabaseType postgresql,
    buildTool gradle,
    serverPort 8081,
    skipUserManagement true
  }
  entities Invoice, Product
}

application {
  config {
    baseName usage,
    applicationType microservice,
    packageName com.org.myApp.usage,
    serviceDiscoveryType eureka,
    searchEngine elasticsearch,
    authenticationType oauth2,
    prodDatabaseType postgresql,
    devDatabaseType postgresql,
    cacheProvider no,
    enableHibernateCache false,
    buildTool gradle,
    serverPort 8082,
    skipUserManagement true
  }
    entities Usage
}

application {
  config {
    baseName order,
    applicationType microservice,
    packageName com.org.myApp.order,
    serviceDiscoveryType eureka,
    searchEngine elasticsearch,
    authenticationType oauth2,
    prodDatabaseType postgresql,
    devDatabaseType postgresql,
    buildTool gradle,
    serverPort 8083,
    skipUserManagement true
  }
entities ProductOrder, OrderItem, ProductCategory, Product
}

entity Product {
    name String required
    description String
    price BigDecimal required min(0)
    size Size required
    image ImageBlob
}

enum Size {
    S, M, L, XL, XXL
}

entity ProductCategory {
    name String required
    description String
}

entity Customer {
    firstName String required
    lastName String required
    gender Gender required
    email String required pattern(/^[^@\s]+@[^@\s]+\.[^@\s]+$/)
    phone String required
    addressLine1 String required
    addressLine2 String
    city String required
    country String required
}

enum Gender {
    MALE, FEMALE, OTHER
}

entity ProductOrder {
    placedDate Instant required
    status OrderStatus required
    code String required
    invoiceId Long
}

enum OrderStatus {
    COMPLETED, PENDING, CANCELLED
}

entity OrderItem {
    quantity Integer required min(0)
    totalPrice BigDecimal required min(0)
    status OrderItemStatus required
}

enum OrderItemStatus {
    AVAILABLE, OUT_OF_STOCK, BACK_ORDER
}

relationship OneToOne {
    Customer{user(login) required} to User
}

relationship ManyToOne {
    OrderItem{product(name) required} to Product
}

relationship OneToMany {
   ProductOrder{orderItem} to OrderItem{order(code) required} ,
   ProductCategory{product} to Product{productCategory(name)}
}

service Product, ProductCategory, Customer, ProductOrder, OrderItem with serviceClass
paginate Product, Customer, ProductOrder, OrderItem with pagination

/* Entities for Invoice microservice */
entity Invoice {
    code String required
    date Instant required
    details String
    status InvoiceStatus required
    paymentMethod PaymentMethod required
    paymentDate Instant required
    paymentAmount BigDecimal required
}

enum InvoiceStatus {
    PAID, ISSUED, CANCELLED
}

enum PaymentMethod {
    CREDIT_CARD, CASH_ON_DELIVERY, PAYPAL
}

entity Usage {
    date Instant required
    details String
    sentDate Instant required
    userId Long required
    productId Long required
}

microservice Invoice with invoice
microservice Usage with usage
microservice Product, ProductCategory, ProductOrder, OrderItem with order
dto * with mapstruct
paginate Invoice with pagination

Environment:
##### **Environment and Tools**

JHipster version: v6.6.0

java version "11.0.5" 2019-10-15 LTS
Java(TM) SE Runtime Environment 18.9 (build 11.0.5+10-LTS)
Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.5+10-LTS, mixed mode)

node: v12.14.0

npm: 6.13.4

yeoman: 3.1.1

INFO! Congratulations, JHipster execution is complete!

So here are my questions:
1. What is exactly controlling where the entities are generated?
        application {
          config {
            baseName gateway,
            applicationType gateway,
            packageName com.org.myApp.sales,
            serviceDiscoveryType eureka,
            searchEngine elasticsearch,
            authenticationType oauth2,
            prodDatabaseType postgresql,
            cacheProvider hazelcast,
            buildTool gradle,
            clientFramework react,
            testFrameworks [protractor]
          }
           entities * <-- What if all entities associated to a different service not to the gateway? (actually when I tried I ended up with an empty folder for gateway)
        }

2. How is microservice <ENTITIES> with <MICROSERVICE_APP_NAME> relates to the above mentioned entities * section?
3. Is the relationship between entities affects where the code is generated?

A: *

*Entities are not generated in a gateway from backend standpoint, only frontend code for these entities is generated

*It's used by the gateway to route to correct microservice

*There can't be any relationship between entities from different microservices because they reside in distinct databases


text:
Q: Legendre symbols So for odd prime $p$, I have Legendre symbol $(\frac{-1}{p}) = (-1)^{(p-1)/2}$, and let $n\geq 3$ be an odd positive integer.
I have to show that for odd positive integers $n_1$ and $n_2$, we have
$\frac{n_1n_2-1}{2}\equiv \frac{n_1-1}{2} + \frac{n_2-1}{2} \pmod{2}$
And from this I have to deduce $(\frac{-1}{n}) = (-1)^{(n-1)/2}$.

So I have manage to show the first part:
$\frac{n_1n_2-1}{2}\equiv \frac{n_1-1}{2} + \frac{n_2-1}{2} \pmod{2}$
$\frac{n_1n_2-n_1-n_2+1}{2} \equiv 0\pmod{2}$
$\frac{(n_1-1)(n_2-1)}{2} \equiv 0\pmod{2}$
$n_1,n_2$ odd $\implies (n_1-1),(n_2-1)$ even $\implies n_1-1=2a, n_2-1=2b; a,b\in \mathbb{Z}$
$\frac{4ab}{2} \equiv 0\pmod{2}$
$2ab \equiv 0\pmod{2}$
$0 \equiv 0\pmod{2}$
So now, I have to somehow use this to deduce $(\frac{-1}{n}) = (-1)^{(n-1)/2}$, but I have no idea what to do. Any suggestions?

A: You already know the result when $n$ is prime, so assume that $n$ is composite and positive. Then there exist positive integers $n_1$ and $n_2$ such that $2\le n_1\le n_2<n$ and $n_1 n_2 = n.$ What determines whether a power of $-1$ is $1$ or $-1$ is the exponent modulo $2.$ By what you have already proven, $$(-1)^{\frac{n-1}{2}}=(-1)^{\frac{n_1 n_2 -1}{2}} = (-1)^{\frac{n_1-1}{2}+\frac{n_2-1}{2}}=(-1)^{\frac{n_1-1}{2}}\cdot (-1)^{\frac{n_2-1}{2}}.$$
You can use strong induction on $n,$ so we get $$(-1)^{\frac{n-1}{2}}=\left(\frac{-1}{n_1}\right)\left(\frac{-1}{n_2}\right).$$ This is equal to $\left(\frac{-1}{n}\right)$ by the complete multiplicativity of the Jacobi symbol (in either entry when the other entry is fixed), assuming that is what you are using for $\left(\frac{-1}{n}\right)$ since the Legendre symbol is defined only for primes in the lower entry.


text:
Q: boto3 read bucket files using concurrency method I am trying to read bucket files without to saving them as a file:
    import boto3
    import botocore
    from io import StringIO
    import pandas as pd

    s3 = boto3.resource('s3',config=botocore.config.Config(signature_version=botocore.UNSIGNED))
    bucket = self.s3.Bucket('deutsche-boerse-xetra-pds')
    objects = self.bucket.objects.filter(Prefix= date)
    file = pd.read_csv(StringIO(self.bucket.Object(key=object.key).get().get('Body').read().decode('utf-8')))

This code works quite well. However, I would like to use concurrency (python asyncio) to speed up the reading process. I did a search into documentation but I could only find something for the download function but not for the get function.
Do you have any suggestion?
Thanks in advance.

A: I found out a solution which works with multiprocessing since my final goal was to reduce the processing time.
As follow the code:
def generate_bucket():
        s3_resoursce = boto3.resource('s3',config=botocore.config.Config(signature_version=botocore.UNSIGNED))
        xetra_bucket = s3_resoursce.Bucket('deutsche-boerse-xetra-pds')

        return s3_resoursce, xetra_bucket

def read_csv(object):
    s3local, bucket_local = self.generate_bucket()

    return pd.read_csv(StringIO(bucket_local.Object(key=object).get().get('Body').read().decode('utf-8')))

def import_raw_data(date: List[str]) -> pd.DataFrame:
        import multiprocessing

        s3local, bucket_local2 = self.generate_bucket()
        objects = [i.key for i in list(bucket_local2.objects.filter(Prefix= date[0]))]

        with multiprocessing.Pool(multiprocessing.cpu_count()) as p:
            df = pd.concat(p.map(self.read_csv, objects))

    return df

For me it works, but I am sure that there could be the possibility to improve this code. I'm open to suggestions.


text:
Q: How many search strings can fgrep handle? I have a text file (about 1.5 gigabytes) that I want to search for occurrences of specific titles.  There are about 10 million titles in my list.
Obviously, not every title in the list will exist in the text file.  That's okay.  I just need to know which titles exist in the text.
Now, if it was just a couple hundred titles, I'd use fgrep and tell it to read the search strings from a file (i.e. fgrep -f patternlist.txt bigtextfile.txt).
But will fgrep choke on that much data?
It's a little bit of work to turn my titles list and the text file into a form that I could use with fgrep, so I'd like some idea of whether this is likely to work before I go to that effort.
Another option would be to split the titles list into multiple files and run fgrep once for each sub-list.  That's not crazy, provided that fgrep can handle a reasonably large number of search strings.  If it can handle 1 million, it's a no-brainer.  If it can't handle 100,000 (requiring over 100 individual runs), then it's a less attractive option.
So, anybody have experience using fgrep to search for a very large number of strings?  If not, is there some other program available?  I could write my own given a day or two, but if I can avoid the work . . .

A: fgrep scale very well using inventions like:

*

*Efficient String: Matching An Aid to Bibliographic Search

*A String Matching Algorithm Fast on the Average

*Update: Fast Cache for Your Text: Accelerating Exact Pattern Matching with Feed-Forward Bloom Filters
Your pattern list is read, compiled and kept in memory, of course. The big input file can be memory mapped with --mmap option for optimal resource usage -- the kernel map the file into a memory region; the application itself do not know how but the whole file is accessible by a simple memory address.


text:
Q: iTunes Connect validation I have an app (v1.0) that I uploaded successfully a couple of weeks ago.
Now we have updated it (v1.1) but when I try to validate it I get "No suitable applications records were found."
I have added the version in iTunes Connect. Targets Bundle version and Bundle version string, short is set to 1.1
In the Organizer, after doing Archive, the two looks the same (except of course for the version number).
Thankful for any help.
PS.
It also doesn't validate the old file that was validated.

A: Did you make sure that the status is "ready for upload".


text:
Q: filename contains Chinese characters unable to be compiled by XeLaTeX windows 10
TeXstudio 2.12.16
texlive2019 default installation
it said:

Could not start Build & View:XeLaTeX: xelatex.exe -synctex=1
  -interaction=nonstopmode "hashujixian-副本".tex

but it can compiles the filename with pure ASCIIcode
how to solve this problem?


text:
Q: Tensorflow Object Detection API 1-channel image Is there any way to use pre-trained models in Object Detection API of Tensorflow, which trained for RGB images, for single channel grayscale images(depth) ?

A: I tried the following approach to perform object detection on Grayscale (1 Channel images) using a pre-trained model (faster_rcnn_resnet101_coco_11_06_2017) in Tensorflow. It did work for me.
The model was trained on RGB Images, So I just had to modify certain code in object_detection_tutorial.ipynb, available in the Tensorflow Repo.
First Change:
Note that exisitng code in the ipynb was written for 3 Channel Images, So change the load_image_into_numpy array function as shown
From
def load_image_into_numpy_array(image):
  (im_width, im_height) = image.size
  return np.array(image.getdata()).reshape(
      (im_height, im_width, 3)).astype(np.uint8)

To
def load_image_into_numpy_array(image):
  (im_width, im_height) = image.size
  channel_dict = {'L':1, 'RGB':3} # 'L' for Grayscale, 'RGB' : for 3 channel images
  return np.array(image.getdata()).reshape(
      (im_height, im_width, channel_dict[image.mode])).astype(np.uint8)

Second Change: Grayscale images have only data in 1 channel. To perform object detection we need 3 channels(the inference code was written for 3 channels)
This can be achieved in two ways.
a) Duplicate the single channel data into two more channels
b) Fill the other two channels with Zeros.
Both of them will work, I used the first method
In the ipynb, go the section where you read the images and convert them into numpy arrays (the forloop at the end of the ipynb).
Change the code From:
for image_path in TEST_IMAGE_PATHS:
  image = Image.open(image_path)
  # the array based representation of the image will be used later in order to prepare the
  # result image with boxes and labels on it.
  image_np = load_image_into_numpy_array(image)
  # Expand dimensions since the model expects images to have shape: [1, None, None, 3]
  image_np_expanded = np.expand_dims(image_np, axis=0)

To this:
for image_path in TEST_IMAGE_PATHS:
  image = Image.open(image_path)
  # the array based representation of the image will be used later in order to prepare the
  # result image with boxes and labels on it.
  image_np = load_image_into_numpy_array(image)
  if image_np.shape[2] != 3:
      image_np = np.broadcast_to(image_np, (image_np.shape[0], image_np.shape[1], 3)).copy() # Duplicating the Content
      ## adding Zeros to other Channels
      ## This adds Red Color stuff in background -- not recommended
      # z = np.zeros(image_np.shape[:-1] + (2,), dtype=image_np.dtype)
      # image_np = np.concatenate((image_np, z), axis=-1)
  # Expand dimensions since the model expects images to have shape: [1, None, None, 3]
  image_np_expanded = np.expand_dims(image_np, axis=0)

That's it, Run the file and you should see the results.
These are my results


text:
Q: Json organization I use JSON for one of my project. For example, I have the JSON structure.
{
    "address":{
        "streetAddress": {
                  "aptnumber" : "21",
                  "building_number" : "2nd",
                  "street" : "Wall Street",
            },
        "city":"New York"
    },
    "phoneNumber":
    [
        {
            "type":"home",
            "number":"212 555-1234"
        }
    ]
}

Now I have a bunch of modules using this structure, and it expects to see certain fields in the received json. For the example above, I have two files: address_manager and phone_number_manager. Each will be passed the relevant information. So address_manager will expect a dict that has keys 'streetAddress' and 'city'.
My question is: Is it possible to set up a constant structure so that every time I change the name of a field in my JSON structure (e.g. I want to change 'streetAddress' to 'address'), I don't have to make change in several places?
My naive approach is to have a bunch of constants (e.g.
ADDRESS = "address"
 ADDRESS_STREET_ADDRESS = "streetAddress"
..etc..
) and so if I want to change the name of one of my fields in JSON structure, I just have to make change in one place. However, this seems to be very inefficient because my constant naming would be terribly long once I reach the third or fourth layer of the JSON structure (e.g. ADDRESS_STREETADDRESS_APTNUMBER, ADDRESS_STREETADDRESS_BUILDINGNUMBER)
I am doing this in python, but any generic answer would be OK.
Thanks.

A: Like Cameron Sparr suggested in a comment, don't have your constant names include all levels of your JSON structure. If you have the same data in multiple places, it will actually be better if you reuse the same constant. For example, suppose your JSON has a phone number included in the address:
{
    "address": {
        "streetAddress": {
            "aptnumber" : "21",
            "building_number" : "2nd",
            "street" : "Wall Street"
        },
        "city":"New York",
        "phoneNumber":
        [
            {
                "type":"home",
                "number":"212 555-1234"
            }
        ]
    },
    "phoneNumber":
    [
        {
            "type":"home",
            "number":"212 555-1234"
        }
    ]
}

Why not have a single constant PHONES = 'phoneNumber' that you use in both places? Your constants will have shorter names, and it is more logically coherent. You would end up using it like this (assuming JSON is stored in person):
person[ADDRESS][PHONES][x] # Phone numbers associated with that address
person[PHONES][x] # Phone numbers associated with the person

Instead of
person[ADDRESS][ADDRESS_PHONES][x]
person[PHONE_NUMBERS][x]

A: You can write a script than when you change the constant, change the structure in all json files.
Example:
import json
CHANGE = ('steet', 'streetAddress')
json_data = None
with open('file.json') as jfile:
    json_data = jfile.load(jfile)
    json_data[CHANGE[1]], json_data[CHANGE[0]] = json_data[CHANGE[0]], None


text:
Q: org.w3c.dom.Node with Android version less than 2.2 getTextContent() is not a recognized function.  getNodeValue() works fine for strings, but anytime I try to parse a number using getNodeValue(), it returns null!
How can I parse a Long from XML using this class?

A: The root cause of this is that the getTextContent() method is a W3C DOM Level 3 method; see the changes section of the DOM level 3 core spec.

The Node interface has two new attributes, Node.baseURI and Node.textContent. ...

and getTextContent() is the getter for the new attribute.
(Presumably, older versions of Android don't implement the DOM level 3 APIs.)
The behavior of getTextContent() is a bit complicated in the general case; see the spec for the textContext attribute.  In the simple case where the target node is an Element with (only) text contents, node.getTextContext() is the same as node.getFirstChild().getNodeValue().

A: You need to navigate down to the text node. For instance, with something like this:
<val>10000</val>

the parsed XML tree has an Element node for the  tag which, in turn, has a child Text node for the "10000". A typical idiom is
valNode.getFirstChild().getNodeValue()

A: If as you say "getNodeValue() works fine for strings", then nothing should prevent from doing the:
Long l = Long.getLong(node.getNodeValue());

Note, getNodeValue() will always return a String that should be then manually converted to a numerical type.
Also - are you sure you are parsing a right node (the one that holds the needed long value)?


text:
Q: Finding fingertip efficient method I am working on detecting the fingertip after hand segmentation.
The research paper I am working on is HandyAR.
Now the paper explains a method based on curvature based detection and fitting an ellipse to detect fingertips.

One other way I found on web is using the convex hull.
Which of the following ways is more accurate and reliable?
Given that this complete process has to be real time , which of the following two ways should be better?


text:
Q: Second menu block not showing children I have installed a theme that has this block region:

In primary menu there was already a menu that works and can show children.
But i wanted to add another menu so i created a menu and placed the block in primary menu region bellow the main navigation menu that was set with the theme.

The first menu has that plus button to show shildren. But the second one doesn't show the plus and test2 is a child of test.
This is my configuration :

Is it a class problem ? Is there a way to edit the second menu html and give it same class as first menu.