text:
Q: Finding shortest cycle in undirected graph that includes 2 specified vertices I am given a dataset of philosophers that resembles an undirected graph. The philosophers are stored in a hash map where the key is the name of the philosopher and the value is a list of his neighbors.
The user Gives 2 philosopher names as input and I need to find the shortest cycle (if one exists that is) that includes those 2 philosophers in it.
At first I thought that this problem is quite similar to the traveling salesman problem however in that problem we also have traveling distances and each vertex can only be visited once which doesn't seem to be the case here. The solution to this problem seems to be graph related but I am not quite sure which algorithm to use or even which problem resembles it.
A solution I thought about involved finding all cycles in the given graph, reducing the results to only the cycles that contain the philosophers given by the user and picking only the shortest cycle out of those since I would score the cycles based on how many "jumps" they make which would essentially be a simple counter. The problem with this is that I'm worried it might not be an optimal solution considering how big the dataset is and how many cycles can potentially be formed (a lot).
The output needs to be in this format: {u1, u2, u3, u4, u5, u1} where u is the name of each philosopher that creates the cycle I'm looking for. If such a cycle doesn't exist then I just need to print an appropriate message.

A: You can use a variant of Suurballe's algorithm. As Wikipedia explains (at https://en.wikipedia.org/wiki/Suurballe's_algorithm):

Suurballe's algorithm is an algorithm for finding two disjoint paths in a nonnegatively-weighted directed graph, so that both paths connect the same pair of vertices and have minimum total length. […] The main idea of Suurballe's algorithm is to use Dijkstra's algorithm to find one path, to modify the weights of the graph edges, and then to run Dijkstra's algorithm a second time. The output of the algorithm is formed by combining these two paths, discarding edges that are traversed in opposite directions by the paths, and using the remaining edges to form the two paths to return as the output.

and later:

The version of Suurballe's algorithm as described above finds paths that have disjoint edges, but that may share vertices. It is possible to use the same algorithm to find vertex-disjoint paths, by replacing each vertex by a pair of adjacent vertices, one with all of the incoming adjacencies u-in of the original vertex, and one with all of the outgoing adjacencies u-out. Two edge-disjoint paths in this modified graph necessarily correspond to two vertex-disjoint paths in the original graph, and vice versa, so applying Suurballe's algorithm to the modified graph results in the construction of two vertex-disjoint paths in the original graph.

So you'll need to translate your unweighted, undirected graph of |V| vertices and |E| unweighted, undirected edges to a weighted, directed graph of 2|V| vertices and 2|E| + |V| weighted, directed edges; then apply Suurballe's algorithm; then translate the result back to a cycle on the original graph.


text:
Q: Change empty view of ListView I'm using a ListView with a custom adapter to receive a JSON response and put it into a nice list - works great.
I'm now testing various exceptions and error handling and am catching errors received from my web API within the Android app. This all works great, handles well - but for the life of me I can't work out how to change the 'empty view' of a ListView once it has been set once.
It's within a fragment, if that makes any difference - but the ProgressBar and ListView are defined in an XML layout which is inflated in the Fragment. I have a TextView also inside there which contains some error text - I want to know how to switch the ProgressBar out for the TextView onError()!
Edit: Currently the ListView uses the ProgressBar as the empty view - I want to know how to later change this to another view - XML defined or programmatic.
The UI thread is not being locked as all API calls are carried out on an AsyncTask, so that's not the issue.
ListView.removeAllViews() caused a fairly imminent crash.
Apologies if this is trivial...

A: You could define the empty view to be a FrameLayout and put whatever you want the empty state be inside that view and change it the way you'd change contents of any other view.

A: I have two empty views for my ListView. One is ProgressBar which I shows while I am loading data from database or server. Other is TextView, which I shows when I got error or have no data.
I put my ListView, ProgressBar and TextView in FrameLayout. And set visibility of both ProgressBar and TextView to Gone.
    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">

        <ListView
            android:id="@+id/my_listview"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

        <TextView
            android:id="@+id/empty_textview"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:visibility="gone"
            android:text="@string/no_contacts_found"/>

        <ProgressBar
            android:id="@+id/empty_progressbar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:visibility="gone"
            android:layout_gravity="center"
            android:indeterminate="true"/>

    </FrameLayout>

Before loading data from database or server, I change visibility of ProgressBar to Visible and set it as empty view of my ListView. So my ListView starts showing ProgressBar, indicating user that data is still loading.
If I got error or got no data from database or server, I set visibility of ProgressBar to Gone and change visibility of TextView to Visible. And then set TextView as empty view of my ListView.

A: I just found this code in an old project, should work fine:
View emptyView = inflater.inflate(R.layout.id_of_your_layoout_file, parent, false);
getListView.setEmptyView(emptyView);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why am I seeing no conversations between my desktop and my handheld apps with Wireshark? I've got a Windows app that runs on my desktop and connects to a Windows CE app on a handheld device. The handheld fetches data using the Windows app as its conduit (it downloads tables and then converts them into another format, but that's probably neither here nor there as far as this question goes).
Because of the bizarre anomaly we experience where in certain rare instances the handheld app hangs (if the filesize is a very specific number - see Why would a fetch operation crash when the amount of data is divisible by 1023 or 1024?), I want to see just exactly what is being passed between the two devices.
I've gotten the IP Address for both machines/devices using "ipconfig" at the command line. Running Wireshark while they communicate (activity is taking place) and then poring over the capture afterwards, I see several occasions where the desktop machine's IP Address is involved (both as the Destination and the Source) but never do I see the handheld device's IP Address...Why not?
A lot of the "talking" that the desktop machine is engaged in seems to be with wireshark, too.
So the two devices/apps obviously are communicating, but it's as if Wireshark is blind to it...???

A: If the desktop and handheld are communicating over a Wi-Fi network, and you're running Wireshark on the desktop machine, that should work, if you capture on the Wi-Fi network (leave promiscuous and monitor mode turned off in this case).
If you're running Wireshark on some third machine, you will have to capture in either promiscuous or monitor mode on the third machine, and monitor mode won't work on Windows.  If the network is protected (WEP, WPA, WPA2, etc.), you will need to configure Wireshark to decrypt packets on the network.
If the desktop and handheld are communicating over a mobile phone network, you might be able to run Wireshark on the desktop and capture the traffic (but probably not on Windows), but you won't be able to run it on a third machine.


text:
Q: cannot format HDD in OSX I have a new 4TB external drive. If the device is on, my mac will fail to boot (blank white screen) and when the drive is turned off, reboot immediately resumes. I cannot boot to safe mode, single user or verbose when the drive is on.
After boot and I turn on the drive, disk utility does not recognize the drive, but system profiler does see the HDD as an unknown device. After about 20 minutes Disk utility finally sees the drive
/dev/disk2
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:                                                   *4.0 TB     disk2

Disk Utility (GUI) does not allow me to verify, repair or partition the disk and it appears as unformatted and read only.
OSX 10.6.6 -
Drive IOMEGA UltraMAX Plus 4TB (2 bay stripe set) -
Connected via firewire
If I cannot erase or partition the drive, what is my next step?

A: Try running OSX off your install disk and using Disk Utility there, if that doesn't work use a linux livecd if you have one.

A: Can you connect the drive via USB or via the network?
Can you connect the drive to another computer (Mac or PC) and use it?
Check for firmware updates to your Mac (they usually get installed by Software Update, but you might need to run them by hand from /Application/Utilities or download them from apple.com).
Check for firmware updates to your drive. This is somewhat iffier, and might require a Windows machine to upload them to the hardware.
If the drive works via the same connection on a different machine, you might have a defective motherboard. If the drive doesn't work in any machine, it's probably defective (this is much more likely, actually).


text:
Q: c# Delegate.BeginInvoke() and thread ID let's say we have some simple code like this :
private static void Main()
{
    Console.WriteLine("Main thread {0}\n", Thread.CurrentThread.ManagedThreadId);

    Action asyncCaller1 = () => LongPerfomingTask(5);
    Action asyncCaller2 = () => LongPerfomingTask(3);

    var asyncResult1 = asyncCaller1.BeginInvoke(null, null);
    var asyncResult2 = asyncCaller2.BeginInvoke(null, null);

    asyncResult1.AsyncWaitHandle.WaitOne();
    asyncResult2.AsyncWaitHandle.WaitOne();

    Console.WriteLine("Done");
}

private static void LongPerfomringTask(int seconds)
{
    Thread.Sleep(TimeSpan.FromSeconds(seconds));

    Console.WriteLine("Thread {0} finished execution", Thread.CurrentThread.ManagedThreadId);
}

Delegate.BeginInvoke() does not create a thread, It's executing code in a caller's thread when it is in idle state, right?So, why the output of this sample application is like this :
Main thread 1

Thread 4 finished execution
Thread 3 finished execution
Done

A: No, Delegate.BeginInvoke uses the thread pool. Always. There's no concept of "executing in the caller's thread when it's idle" unless you're thinking of adding tasks to a UI message queue... were you getting confused with Control.BeginInvoke / Dispatcher.BeginInvoke?
In this case you've got a console app - there's no message pumping going on to start with.

A: @taras.roshko: Here's a resource to boost your understanding of ThreadPool:
Chapter on Threading


text:
Q: Log of Heartbeat Calls I've read that Heartbeat can slow a WP site down and I'm assuming if our admins/store managers have a lot of admin windows/tabs open, this will exacerbate the issue.
If yes, is there a condition to test and log the calls that Heartbeat makes so I can see if the site slowdown could be related to an excess of Heartbeat calls?
I had a look in the documentation and elsewhere but only found ways to deregister the script ( wp_deregister_script('heartbeat'); ) - not what I need.
Or am I barking up the wrong tree and this is something that should be monitored via server logs, by watching: /wp-admin/admin-ajax.php ?

A: From quick look at the code, there is number of hooks firing in wp_ajax_heartbeat(). Out of which heartbeat_tick action seems quite appropriate to hook some logging logic too.
For the sake of completeness, while you are interested in logged in activity, the hook would be heartbeat_nopriv_tick for logged out users.


text:
Q: Load time payment method One page checkout very long I'm using the magento onepagecheckout extension from IWD but the load time of the payment method when customers click on order is very long! What can i do about that?

A: Use Magento One Page Checkout Extension for checkout process without facing any kind of difficulty, loading time and increase your website sales conversion exponentially.


text:
Q: How to find Gaussian primes $10^6 < |\mathfrak{p}| < 2 \times 10^6$ with Pari-GP? I am looking through the PARI/GP reference card.
Example, listing primes over $\mathbb{Z}$ is standard computer homework exercise [1]:

*

*100129

*126691

*193013

*284933

*492113

*769591

How to write a program to find Gaussian prime numbers $\mathfrak{p} = a + bi \in \mathbb{Z}[i]$ with $10^6 < |a|, |b| < 2 \times 10^6$ ?

Related:

*

*Prime elements in $\mathbb{Z}[\sqrt{2}]$

*Prime elements of $\mathbb{Z}[i\sqrt5]$.

*Finding Gaussian Primes along Lines in $\mathbb Z[i]$

A: I will compute below the numbers $\mathfrak p=a+ib$ constrained to the following "triangle" restrictions:
$$ 10^6< b<a<2\cdot 10^6\ .$$
(From here build conjugates and associates to get also $\pm a\pm ib$ and $\pm b\pm ia$.)
In particular, $\mathfrak p\not\in\Bbb Z$, so $p:=\mathfrak p\bar{\mathfrak p}=a^2+b^2$ is a prime in $\Bbb Z$ which splits in two parts in the Gaussian integers. Here, $p$ is congruent to $1$ modulo four lying in the interval $J$ between $2\cdot 10^{12}$ and $8\cdot 10^{12}$.
One (slow) algorithm would take all these primes $p$ one by one, write them in the form $p=a^2+b^2$ and check the "triangle" condition. There are roughly some
? floor(intnum(x=2*10^12, 8*10^12, 1/log(x)))
%3 = 205708205954

primes in $J$, and half of them split in $\Bbb Z[i]$. A lot of primes for my taste. Below, there is an old fashioned pari/gp code implementing this slow algorithm. (It avoids the prime $1+i$, just in case somebody wants to relax $b<a$ to $b\le a$...)
The "real job" is done by the pari/gp factorization of Gaussian integers, a prime p in $\Bbb Z$ was slightly changed to I*p to implicitly tell pari/gp to factor over $\Bbb Z[i]$.
{f(N) = local(p, z, a, b, c, count);
count = 0;
forprime(p=2*N^2, 8*N^2,
    if( (p-3) % 4,
        z = factor(I*p)[1, 1];
        a = real(z); b = imag(z);
        if(a < b, c = a; a = b; b = c;);
        if( (N < b) && (a < 2*N),
            z = a + I*b; count = count + 1;
            print(count, " --> ", z, " with norm ", p);)))}

Then f(100) delivers some $579$ such (normed) primes, and there is a quick end. The last ones are:
570 --> 190 + 189*I with norm 71821
571 --> 194 + 185*I with norm 71861
572 --> 195 + 184*I with norm 71881
573 --> 197 + 182*I with norm 71933
574 --> 195 + 188*I with norm 73369
575 --> 199 + 186*I with norm 74197
576 --> 196 + 191*I with norm 74897
577 --> 196 + 195*I with norm 76441
578 --> 199 + 194*I with norm 77237
579 --> 199 + 196*I with norm 78017
?

Seen from this perspective, this algorithm seems to be "better" than the brute force algorithm considering all $(a,b)$ with $100<b<a<200$, and testing for the primality of $a+ib$. At the cost of having a good primes generator for $\Bbb Z$.
I have also started...
? f(10^6)
1 --> 1000006 + 1000001*I with norm 2000014000037
2 --> 1000008 + 1000003*I with norm 2000022000073
3 --> 1000010 + 1000003*I with norm 2000026000109
4 --> 1000008 + 1000007*I with norm 2000030000113
5 --> 1000013 + 1000002*I with norm 2000030000173
6 --> 1000013 + 1000008*I with norm 2000042000233
7 --> 1000019 + 1000004*I with norm 2000046000377
8 --> 1000019 + 1000014*I with norm 2000066000557
9 --> 1000018 + 1000017*I with norm 2000070000613
10 --> 1000021 + 1000014*I with norm 2000070000637
11 --> 1000026 + 1000009*I with norm 2000070000757
12 --> 1000028 + 1000007*I with norm 2000070000833
13 --> 1000021 + 1000016*I with norm 2000074000697
14 --> 1000027 + 1000010*I with norm 2000074000829

and the primes are slowly printed one by one, as they are fished and tested for relevant...


text:
Q: Applying SSL Certificates using AWS / EC2 I'm attempting to add an SSL certificate to a couple of websites via AWS.
I'm more of a designer/programmer than a network/server guy, and this is becoming sort of a challenge. Please help a poor soul.
I have a single EC2 instance, running Windows w/ IIS.
Here's a couple things I've tried thus far:
1) I went to the Certificate Manager via the AWS Console. I was stopped in my tracks because this feature only seems to be available for the US East (N. Virginia) region currently; my server is in US West (Oregon) and I can't really justify changing that. I suppose that's a no go?
2) Uncle Google tells me that most other means of adding certs involve having a Load Balancer or a CDN. The EC2 server in question is only being run for a handful of businesses to use for internal processes, and a little file storage. There's no need for a CDN or Load Balancer, so this seems kind of counter-intuitive.
Does anyone have some knowledge to drop on me? I'd really like to enable SSL certificates on some of these sites without making such big changes. I'm shocked a service like AWS hasn't made this kind of information more available.

A: You wouldn't be able to use Certificate Manager without an ELB or CloudFront anyway. If you don't want to pay for the Load Balancer or use a CDN then you will have to obtain an SSL certificate from an SSL certificate authority and install it directly on IIS.


text:
Q: What does the :1 at the end of css mean or stand for? I'm trying to make a simple update to a css file which, when viewed in Chrome Developer Tools, looks like this colorbox5.min.css:1   (understand that this is the minified version)
Another file at this location called colorbox.css:1
The update I'm trying to make is from:
#colorbox {outline: 0;}

to this:
#colorbox {outline: 0; color:#333;}

Editing either of these files has no effect, yet if I edit these live in Developer Tools it shows the desired effect?
Two questions then, which version is used - the minified version or the full? How do I get my update to show?

A: :1 is the line number in the css file. Because you have a minified version of your css file, its line 1.
When you edit something in the dev tools, it will not save your file on the filesystem, unless you use a plugin that can handle it for you.
Maybe your css file is cached, so try to clear your cache and reload again. In dev tools, you can specify not to cache css/scripts file while its open.


text:
Q: jQuery - Chaining custom functions I am wondering how to chain my custom functions and maintain context of 'this'.
Example:
$.fn.foo = function() {
  var html = '

';
  if ($(this).hasClass(somthing) {
    $(this).prepend(html);
  }
}

$.fn.bar = function() {
  var html = '
bar
';
  $(this).find('.foo').prepend(html);
}

$('body').foo().bar();

When i try to use this code i get a TypeError: Cannot read property 'bar' of undefined

A: Return this:
$.fn.foo = function() {
    var html = '

';
    if ($(this).hasClass(somthing) {
        $(this).prepend(html);
    }
    return this;
};

$.fn.bar = function() {
    var html = '
bar
';
    $(this).find('.foo').prepend(html);
    return this;
};

$('body').foo().bar();

A: The jQuery extend function may be what you are looking for. It allows you to create a comma-separated list of functions that you can use in chained expressions
jQuery.fn.extend({
  check: function() {return this.each(function() { this.checked = true; });} ,
  uncheck: function() {return this.each(function() { this.checked = false;  });
  }})

Usage: this checks all checkboxes:
$( "input[type='checkbox']" ).check();

(example extracted from https://api.jquery.com/jquery.fn.extend/ )

A: You need to return current element context, i.e. this from you custom method.

$.fn.foo = function() {
  var html = '

';
  if ($(this).hasClass('somthing')) {
    $(this).prepend(html);
  }
  return this; //The magic statement
}

$.fn.bar = function() {
  var html = '
bar
';
  $(this).find('.foo').prepend(html);
  return this; //The magic statement
}

$('body').addClass('somthing').foo().bar();


text:
Q: jqueryUI autocomplete does not function I have an array with some data that I want to autocomplete in an input section on the HTML, kinda like predictive text. I'm using jqueryUI and following instructions as per https://jqueryui.com/autocomplete/ (to do some tests) but the code doesnt work - the data doesnt autocomplete when I fill out the input, even though its set up like the example? Its basically being loaded in order of (I am calling Jquery locally and JqueryUI externally):
<script src="jquery.2.1.4.min.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(function() {

  var locations = [
      "London",
      "Paris",
      "Moscow",
      "Melbourne"
      ];
  $("#start").autocomplete({
   source: locations
  });

  });
 </script>

 <input type="text" id="start"  placeholder="From" >

A: <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
 <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
 <script>
$(function() {

var locations = [
  "London",
  "Paris",
  "Moscow",
  "Melbourne"
  ];
 $("#start").autocomplete({
 source: locations
 });

  });
 </script>

 <input type="text" id="start"  placeholder="From" >


text:
Q: WinForms Data Binding Entity Framework 6 I have a ComponentOne Grid control on a WinForm Application and I'd like to bind a "LINQ Query" instead of the whole DbSet.
If I need the full DbSet the answer is here: Data binding directly to a store query (DbSet, DbQuery, DbSqlQuery) is not supported Entity Framework 5
gridControl1.DataSource = context.capitulo.Local.ToBindingList();
context.capitulo.Load();

But this do not work if I want to put an order and /or a where condition like:
gridControl1.DataSource = context.capitulo.OrderBy(x => x.Id).Local.ToBindingList();
context.capitulo.Load();

Because Local is a property of DbSet and not of IQuerable.
I found lots of solution for WPF but non solution for WinForms.

A: var capituloList = new ObservableCollection<capitulo>(context.capitulo.Local.OrderBy(x => x.Id));

gridControl1.DataSource = capituloList.ToBindingList();

context.capitulo.Load();

A: You need to apply a LINQ query to a bindable collection and get another bindable collection. That is done with LiveLinq, a part of the ComponentOne suits (together with C1DataSource, there is one in ComponentOne WinForms), so you probably have it. Just use the AsLive() extension method:
gridControl1.DataSource = context.capitulo.Local.AsLive().OrderBy(x => x.Id);
To have AsLive() available, you need
using C1.WPF.LiveLinq;
(but WPF here does not mean you are using WPF, it's just a name, you are still in WinForms)


text:
Q: How to connect to CloudSQL from a Dataflow job in Python SDK? --------------->  READ THE EDIT FIRST  <---------------
I'm trying to develop a Dataflow pipeline which reads and writes to CloudSQL, but I'm facing a lot of connectivity issues.
First of all, there is not a native template / solution to do that, so I'm using a library developed by the community -> beam-nuggets which provides a collection of transforms for the apache beam python SDK.
This is what I have done so far:
Template
import argparse

import apache_beam as beam
from apache_beam.options.pipeline_options import PipelineOptions, SetupOptions

from beam_nuggets.io import relational_db

def main():
    # get the cmd args
    db_args, pipeline_args = get_args()

    # Create the pipeline
    options = PipelineOptions(pipeline_args)
    options.view_as(SetupOptions).save_main_session = True
    with beam.Pipeline(options=options) as p:
        source_config = relational_db.SourceConfiguration(
            drivername=db_args.drivername,
            host=db_args.host,
            port=db_args.port,
            database=db_args.database,
            username=db_args.username,
            password=db_args.password,
        )

        data = p | "Reading records from db" >> relational_db.ReadFromDB(
            source_config=source_config,
            table_name=db_args.table
            query='select name, num from months'  # optional. When omitted, all table records are returned.
        )
        records | 'Writing to stdout' >> beam.Map(print)

def get_args():
    parser = argparse.ArgumentParser()
    # adding expected database args
    parser.add_argument('--drivername', dest='drivername', default='mysql+pymysql')
    parser.add_argument('--host', dest='host', default='cloudsql_instance_connection_name')
    parser.add_argument('--port', type=int, dest='port', default=3307)
    parser.add_argument('--database', dest='database', default='irmdb')
    parser.add_argument('--username', dest='username', default='root')
    parser.add_argument('--password', dest='password', default='****')
    parser.add_argument('--table', dest='table', default="table_name")

    parsed_db_args, pipeline_args = parser.parse_known_args()

    return parsed_db_args, pipeline_args

if __name__ == '__main__':
    main()

The job is created properly in Dataflow, but it remains loading without showing any logs:

It appears in red since I stopped the job.
Pipeline options:

Why can't I connect? What am I missing?
Thank you in advance for you help.

-------------------> EDIT <------------------------
Since I wasn't getting any results with the beam-nugget library, I've switched to the cloud-sql-python-connector library, which has been created by Google.
Let's start from scratch.
template.py
import argparse

from google.cloud.sql.connector import connector

import apache_beam as beam
from apache_beam.options.pipeline_options import PipelineOptions
from apache_beam.options.pipeline_options import SetupOptions

class ReadSQLTable(beam.DoFn):
    """
    parDo class to get all table names of a given cloudSQL database.
    It will return each table name.
    """

    def __init__(self, hostaddr, host, username, password, dbname):
        super(ReadSQLTable, self).__init__()

        self.hostaddr = hostaddr
        self.host = host
        self.username = username
        self.password = password
        self.dbname = dbname

    def process(self, element):
        # Connect to database

        conn = connector.connect(
            self.hostaddr,
            self.host,
            user=self.username,
            password=self.password,
            db=self.dbname
        )

        # Execute a query
        cursor = conn.cursor()
        cursor.execute("SELECT * from table_name")

        # Fetch the results
        result = cursor.fetchall()

        # Do something with the results
        for row in result:
            print(row)

def main(argv=None, save_main_session=True):
    """Main entry point; defines and runs the wordcount pipeline."""

    parser = argparse.ArgumentParser()
    parser.add_argument(
        '--hostaddr',
        dest='hostaddr',
        default='project_name:region:instance_name',
        help='Host Address')
    parser.add_argument(
        '--host',
        dest='host',
        default='pymysql',
        help='Host')
    parser.add_argument(
        '--username',
        dest='username',
        default='root',
        help='CloudSQL User')
    parser.add_argument(
        '--password',
        dest='password',
        default='password',
        help='Host')
    parser.add_argument(
        '--dbname',
        dest='dbname',
        default='dbname',
        help='Database name')
    known_args, pipeline_args = parser.parse_known_args(argv)

    # We use the save_main_session option because one or more DoFn's in this
    # workflow rely on global context (e.g., a module imported at module level).
    pipeline_options = PipelineOptions(pipeline_args)
    pipeline_options.view_as(SetupOptions).save_main_session = save_main_session
    with beam.Pipeline(options=pipeline_options) as p:
        # Read the text file[pattern] into a PCollection.

        # Create a dummy initiator PCollection with one element
        init = p | 'Begin pipeline with initiator' >> beam.Create(['All tables initializer'])
        tables = init | 'Get table names' >> beam.ParDo(ReadSQLTable(
            host=known_args.host,
            hostaddr=known_args.hostaddr,
            dbname=known_args.dbname,
            username=known_args.username,
            password=known_args.password))

if __name__ == '__main__':
    # logging.getLogger().setLevel(logging.INFO)
    main()

Following the Apache Beam documentation, we're supposed to upload a requirements.txt file to get the necessary packages.
requirements.txt
cloud-sql-python-connector==0.4.0

After that, we should be able to create the dataflow template.
python3 -m template --runner DataflowRunner /
                    --project project_name /
                    --staging_location gs://bucket_name/folder/staging /
                    --temp_location gs://bucket_name/folder/temp /
                    --template_location gs://bucket_name/folder//templates/template-df /
                    --region europe-west1 /
                    --requirements_file requirements.txt

But when I try to execute it, the following error appears:

The libraries are not being installed... neither apache-beam nor cloud-sql-python-connector

Since I was getting this errors on the Cloud shell, I tried to download the packages directly on the shell (Sounds desperate, I am.)
pip3 install -r requirements.txt
pip3 install wheel
pip3 install 'apache-beam[gcp]'

And I execute the function again. Now the template has been created properly:

Additionally, we should create a template_metatada which contains some information regarding the parameters. I don't know if I have to add anything else here, so:
{
  "description": "An example pipeline.",
  "name": "Motor prueba",
  "parameters": [
  ]

FINALLY, I'm able to create and execute the pipeline, but as the last time, it remains loading without showing any logs:

Any clue? :/

A: I haven't used the nugget.io library, so I'm unfamiliar with how it handles connectivity. I'd suggest trying out the Python connector maintained by Google:
https://github.com/GoogleCloudPlatform/cloud-sql-python-connector
See if that's able to connect for you.


text:
Q: How can I do a nested sort on NSManagedObjects iOS Does anyone know how to do a nested sort (not sure if that's the best term for it) using NSSortDescriptors?
I'm using NSSortDescriptors to fetch NSManagedObjects.
I have a NSManagedObject called Conversation that has a one-to-many relationship to Messages. Each Conversation has a NSSet of Messages.
Each Message has a timeReceived Date property. I'm trying to sort my Conversations by their respective latest Message's timeReceiveds
To restate: I'm trying to find the Message with the last timeReceived in each Conversation, then sort the Conversations by their respective latest Messages. Messages and Conversations are NSManagedObjects.
The Key string nature of these descriptors has made it really hard for me to figure out.
I saw something on SO that suggested something like:
NSSortDescriptor * sortByDate = [NSSortDescriptor sortDescriptorWithKey:@"messages.@min.timeReceived" ascending:NO];
But I just get a crash:
 *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Keypath containing KVC aggregate where there shouldn't be one; failed to handle messages.@max.timeReceived'

Have any of you done something like this before?
- (NSFetchedResultsController *) fetchSortedConversations
{
    NSSortDescriptor *sortByDate = [NSSortDescriptor sortDescriptorWithKey:@"latestMessage.timeReceived" ascending:NO];

    // I implemented a workaround where I set a latestMessage for each Conversation somewhere else, but I'd like to be able to sort the Conversations without having to manually manage the latest message.

    NSArray * sortDescriptors = @[sortByDate];

    NSFetchedResultsController * conversations = [self.coreDataManager fetchEntitiesWithName: NSStringFromClass([Conversation class]) sortDescriptors:sortDescriptors sectionNameKeyPath:nil predicate:nil];

    return conversations;
}

A: I would assume the problem you're facing can't be solved with NSFetchedResultsController as currently formulated, because it can't really be solved neatly in SQL. So NSFetchRequest probably just declines to do it, and that bubbles upward.
The easiest solution would be to implement - willSave on the managed object subclass you've got for Conversation and in that find @max.timeReceived and store it to a property directly in Conversation. Then tell your fetched results controller to sort on that.


text:
Q: Sequelize hasMany Join association I'm expanding my application and I need to join two models I had previously created with Sequelize, they are as follows:
Meal
sequelize.define('meal', {
    mealId: {
        type: DataTypes.INTEGER,
        primaryKey: true,
        autoIncrement: true
    },
    quantity: {
        type: DataTypes.DECIMAL,
        allowNull: false
    },
    period: {
        type: DataTypes.INTEGER,
        allowNull: false
    }
})

Food
sequelize.define('food', {
    idFood: {
        type: DataTypes.INTEGER,
        primaryKey: true,
        autoIncrement: true
    },
    nameFood: {
        type: DataTypes.STRING,
        allowNull: false
    }
})

I added the following relationship:
db.food.hasMany(db.meal, {as : 'Food', foreignKey : 'idFood'});

This line adds an idFood column on Meal
Quickly explaining what is going on, Food is a table with many foods (duh) like Bread, Rice, Beans, etc. Meal is a table that identifies which food the user has chosen with their details.
Therefore, my understanding was that Meal had many Food (as I added before) but Food didn't require any relationship with Meal, since it just holds data and isn't changed after I first populate it. But when I tried to join them with:
db.meal.findAll({ include : [db.food] }).then(function (meals) {
    console.log(JSON.stringify(meals));
});

I got the following error:
Unhandled rejection Error: food is not associated to meal!

Can anyone explain what I should do? I think it has to do with the relationships, but I couldn't find on the documentation any good explanation as to what I should do.
Thank you!
Edit: Reading the documentation (again), the example makes sense, but I don't think the example is applicable on my situation, because on their example, User has a Task, and Task belongs to User. But on my case, Food doesn't belong to a Meal, because many Meals can have the same Food in different amounts (or for different users).

A: The issue is that the relation has to be defined both ways. Currently, Sequelize knows how to get from Food -> Meal because of
db.food.hasMany(db.meal, {as : 'Food', foreignKey : 'idFood'});

but it does not know how to get from Meal -> Food. That's why you have to define the same relation the other way round, like so:
db.meal.belongsTo(db.food, {foreignKey : 'idFood'});

This does not add any new keys since it would define meal.idFood which you defined with your first statement already.
Now you should be able to execute
db.meal.findAll({ include : [db.food] }).then(function (meals) {
    console.log(JSON.stringify(meals)); <-- each array element of meals should have an attribute `food`
});

A: If you are using an alias on the association ({ as: 'Food' }) you need to use it on the include statement as well.
So it'd be like that:
db.meal.findAll({
  include : [{
    model: db.food,
    as: 'Food'
  }]
}).then(function (meals) {
  console.log(JSON.stringify(meals));
});

If an association is aliased (using the as option), you must specify
  this alias when including the model. Notice how the user's Tools are aliased as Instruments above. In order to get that right you have to specify the model you want to load, as well as the alias

More information here.

A: BelongsTo should also contain the foreign Key option with same key as in hasMany
Donor.hasMany(Donation, {
  foreignKey: "donorId",
  onDelete: "cascade",
});
Donation.belongsTo(Donor, { foreignKey: "donorId" });

This worked for me


text:
Q: microsoft-graph java sdk: java.lang.NoSuchMethodError: 'java.util.List com.azure.core.http.HttpHeader.getValuesList()' I'm trying out the microsoft-graph-sdk for Java
<dependency>
   <groupId>com.microsoft.graph</groupId>
      <artifactId>microsoft-graph</artifactId>
      <version>3.0.0</version>
</dependency>

And I'm just following the examples like:
         ClientSecretCredential clientSecretCredential = new ClientSecretCredentialBuilder()
         .clientId(clientId)
         .clientSecret(jwt.getRawToken())
         .tenantId(tenant)
         .build();

         TokenCredentialAuthProvider tokenCredentialAuthProvider = new TokenCredentialAuthProvider(scopes,
            clientSecretCredential);

         GraphServiceClient graphClient = GraphServiceClient
          .builder()
          .authenticationProvider(tokenCredentialAuthProvider)
          .buildClient();

          User me = graphClient.me().buildRequest().get();

When I run this code I get:
was thrown by a user handler's exceptionCaught() method while handling the following exception:: java.lang.NoSuchMethodError: 'java.util.List com.azure.core.http.HttpHeader.getValuesList()'
    at com.azure.core.http.netty.NettyAsyncHttpClient.lambda$bodySendDelegate$2(NettyAsyncHttpClient.java:115) ...

I'm running this on a Quarkus application.
What I'm missing here?
Thanks


text:
Q: Pigpio permission bloqued for my actual user on Raspberry-pi I am trying to read GPIO port 5 on a Raspberry pi, after trying some packages like onoff I decided to use Pigpio. It does connect to GPIO but the problem is that I dont have permissions for that user. It says:

Sorry, you don't have permission to run this program Try running as
root, e.g precede the command with sudo.
/home/pi/IsriBruster-service/node_modules/pigpio/pigpio.js:54
pigpio.gpioInitialise();

The code I run for calling gpio is the next one:
const Gpio = require('pigpio').Gpio
const gpio5 = new Gpio(5, {mode: Gpio.OUTPUT});
console.log(gpio5.pwmRead());

Thank you for your help!

A: I tried this with the onoff library and it worked finally:
const Gpio = require('onoff').Gpio;
const gpio5 = new Gpio(24,'out');
io.sockets.emit('gpio',res)


text:
Q: communicating the idea of stationary distribution and ergodic theorem I will teach the Markov chain for the first time to someone who has not much background in it, and I have little, but I am trying to read and understand intuitively to convey the idea in layman's terms.
Consider an irreducible, positive recurrent Markov chain with $3$ states with unique stationary probability distribution $\pi$ such that $\pi(1)=\frac{1}{2}=\pi_1, \pi(2)=\frac{1}{3}=\pi_2, \pi(3)=\frac{1}{6}=\pi_3$. Let $v_i(n)$ denote the number of visits of state $i$ before time $n$, and a well-known theorem says the following:
$$\mathbb P\left[\lim_{n\to \infty}\frac{v_i(n)}{n}\to\pi_i\right]=1.$$

*

*Can I say to the target audience that, by a stationary probability distribution, they can think that if they watch the evolution of the Markov chain for a long-time let's say for $10$ ( or should I say $100$) hours, considering discrete time step as minutes. They will see $\frac{1}{2}\times 10$ hours they will see the chain is visiting state $1$, $\frac{1}{3}\times 10$ hours in-state $2$ and $\frac{1}{6}\times 10$ hours in-state $3$. Is that the correct way to convey the intuition behind stationary probability distribution? They may ask in which order of hours they will see this event.

*And, the above limit precisely conveys the fact I just said in point $1$, with probability $1$.
Please let me know and suggest if this can be made far easier to convey.

*Another thing: if $f:\{1,2,3\}\to \mathbb R$ is any bounded function let say $f(x)=e^x$, ergodic theorem says $$\mathbb P\left[\lim_{n\to \infty}\frac{1}{n}\sum\limits_{k=0}^{n-1}f(X_k)\to\sum\limits_{i\in\{1,2,3\}}f(i)\pi_i\right]=1.$$
I am not sure, what is the intuition to bring $f$ here and how can I convey the usefulness of this result to a general audience without much background to the Markov chain.
Thank you.


text:
Q: Node.js + Socket.io + Apache I'm looking for a way to integrate Node.js + Socket.io + Apache in the following way:
I want apache to continue serving HTML / JS files.
I want node.js to listen for connection on port 8080. Something like this:
var util = require("util"),
    app = require('http').createServer(handler),
    io = require('/socket.io').listen(app),
    fs = require('fs'),
    os = require('os'),
    url = require('url');

app.listen(8080);

function handler (req, res) {

    fs.readFile(__dirname + '/index.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }

    res.writeHead(200);
    res.end(data);
  });
}

io.sockets.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });

  socket.on('my other event', function (data) {
    socket.emit('ok 1', { hello: 'world' });
  });

  socket.on('clientMSG', function (data) {
    socket.emit('ok 2', { hello: 'world' });
  });

});

if I access a HTML that connect to this server, it works, but I need to go to mydomian.com:8080/index.html.
What I want is to be able to go to mydomian.com/index.html. and be able to open a socket connection:
<script>
        var socket = io.connect('http://mydomain.com', {port: 8080});
        socket.on('news', function (data) {
            console.log(data);
            socket.emit('my other event', { my: 'data from the client' });
        });

        socket.on('connect', function (data) {
            console.log("connect");
        });

        socket.on('disconnect', function (data) {
            console.log("disconnect");
        });

            //call this function when a button is clicked
        function sendMSG()
        {
            console.log("sendMSG");
            socket.emit('clientMSG', { msg: 'non-scheduled message from client' });
        }

    </script>

In this example I had to use fs.readFile of wont work when I go to the port 8080 in the URL.
Any suggestions? Tks.

A: Serve your static content from Apache port 80 and serve your dynamic/data content over a Socket.IO server on port 8080. You don't need the app = require('http').createServer(handler) in your Socket.IO app
Apache port 80 |-------------| clients |------------| Socket.IO port 8080
var io = require('socket.io').listen(8080);

io.sockets.on('connection', function (socket) {
  io.sockets.emit('this', { will: 'be received by everyone'});

  socket.on('clientMSG', function (from, msg) {
    console.log('I received a private message by ', from, ' saying ', msg);
  });

  socket.on('disconnect', function () {
    sockets.emit('user disconnected');
  });
});

A: AWS + APACHE + NODEJS + SOCKET.IO + ANGULARJS

SERVER SIDE
This worked for me on a production server running apache on port 80 and NodeJS
on port 8000. Change the NodeJS port by your desired option…

*

*Create a folder named "nodejs" for the files of the NodeJS server at /var/www/html

*Run Nodejs on a different port than 80, for example port 8000

*Execute command: a2enmod proxy_http

*Execute command: a2enmod proxy_wstunnel

*Put the next 2 lines at the end of the following file: /etc/apache2/apache2.conf
LoadModule proxy_module /usr/lib/apache2/modules/mod_proxy.so
LoadModule proxy_http_module /usr/lib/apache2/modules/mod_proxy_http.so

*Put the next 12 lines at the end of the following file: /sites-available/000-default.conf
(If you have a different site created by you, put the lines there)
RewriteEngine On
RewriteCond %{REQUEST_URI}  ^socket.io          [NC]
RewriteCond %{QUERY_STRING} transport=websocket [NC]
RewriteRule /{.*}       ws://localhost:8000/$1  [P,L]

RewriteCond %{HTTP:Connection} Upgrade [NC]
RewriteRule /(.*) ws://localhost:8000/$1 [P,L]

ProxyPass /nodejs http://localhost:8000/
ProxyPassReverse /nodejs http://localhost:8000/

ProxyPass /socket.io http://localhost:8000/socket.io
ProxyPassReverse /socket.io http://loacalhost:8000/socket.io

ProxyPass /socket.io ws://localhost:8000/socket.io
ProxyPassReverse /socket.io ws://localhost:8000/socket.io

*sudo service apache2 restart

CLIENT SIDE
I use the following library to implement Socket.io in AngularJS, but
I think this guide is useful too for a basic Javascript implementation of socket.io technology.
To call my PHP server: example.com
To call NodeJS server: example.com/nodejs
To call NodeJS Socket: example.com  <---this call will be done by default by the library
I hope help you!

A: You can continue to serve pages from Apache, but you need to enable CORS in node.js/socket.io:
index.html (served from Apache)
<script src = "https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.0/socket.io.js"></script>
<script>
   const socket = io("ws://your.domain.com:8080");
<script>

app.js (In nodejs): (Enable CORS)
const express = require('express');
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http, {
    cors: {
      origin: "*",
      methods: ["GET", "POST"]
    }
});

http.listen(8080);


text:
Q: php pear: The default config file is not a valid config file or is corrupted I'm really in deep sh*t here. While running "pear install HTTP", my server get rebooted, when everything back, I continue my work, and...
$sudo pear install HTTP
ERROR: The default config file is not a valid config file or is corrupted.

$sudo pear list
ERROR: The default config file is not a valid config file or is corrupted.

$sudo pear
ERROR: The default config file is not a valid config file or is corrupted.

I try aptitude purge php-pear, and even delete everything on  /usr/share/php/ and install php-pear again, but the error still persist.
Oops... what did happen?

A: Had this error on Mac with MAMP. For me deleting .../MAMP/bin/php/php5.3.6/conf/pear.conf helped.

A: Deleting .pearrc on the home directories shall fix this problems. --Thanks God.


text:
Q: How can I move pagination of a DataTable to the top? I have tried these
"sDom": '<"top"<"actions">fpi<"clear">><"clear">rt<"bottom">',
"sDom": '<"top"p><"bottom"top><"clear">',
"sDom": '<"top"<"actions">fpil<"clear">><"clear">rt<"bottom">',

But it does not work, the pagination bar still on the bottom (like default)
My dataTable does not have fiter, info, length ..., just data and pagination.

A: "sDom": '<"top"flp>rt<"bottom"i><"clear">'


text:
Q: Does the Amazon RDS backup/snapshot service lock tables? We have a database that is 100+GB.  Most tables use the InnoDB engine.
A regular dump takes 1-2 hours.
If we moved to Amazon RDS, would this backup cause table locks?
Does Amazon use a simple mysqldump?

A: If there are any MyISAM tables present, as your wording implies, the RDS Documentation instructs you on how to handle it and what to expect
According to the RDS Documentation :

Automated Backups with Unsupported Storage Engines
Amazon RDS automated backups and DB Snapshots are currently supported
  for only the InnoDB storage engine. Use of these features with other
  MySQL storage engines, including MyISAM, may lead to unreliable
  behavior while restoring from backups. Specifically, since storage
  engines like MyISAM do not support reliable crash recovery, your
  tables can be corrupted in the event of a crash. For this reason, we
  encourage you to use the InnoDB storage engine.
If you choose to use MyISAM, you can attempt to manually repair tables
  that become damaged after a crash by using the REPAIR command ((see:
  http://dev.mysql.com/doc/refman/5.5/en/repair-table.html). However, as
  noted in the MySQL documentation, there is a good chance that you will
  not be able to recover all your data.
If you want to take DB snapshots with MyISAM tables, follow these
  steps:
Launch Process
1 Stop all activity to your MyISAM tables (that is, close all
  sessions)
2 Lock and flush each of your MyISAM tables
3 Issue a
  CreateDBSnapshot API call, or use the RDSCLI rds-create-db-snapshot
  command. When the snapshot has completed, release the locks and resume
  activity on the MyISAM tables. These steps force MyISAM to flush data
  stored in memory to disk thereby ensuring a clean start when you
  restore from a DB snapshot.
Finally, if you would like to convert existing MyISAM tables to InnoDB
  tables, you can use alter table command (for example, alter table
  TABLE_NAME engine=innodb;).

Believe me, large MyISAM tables have no place in Amazon RDS. InnoDB is far more accepted. Please, either convert them to InnoDB or live with doing your own locking and possible table crashes/repairs.


text:
Q: Using df.divide on preceding column total I have a df:
count      0       1    2     3      4
cohort
2020-10   46.0   18.0   10.0 3.0    NaN
2020-11   290.0  113.0  40.0 13.0   NaN
2020-12   370.0  176.0  61.0 6.0    1.0
2021-01   561.0  240.0  66.0 4.0    1.0
2021-02   575.0  280.0  80.0 5.0    NaN
2021-03   671.0  274.0  73.0 3.0    1.0
2021-04   1028.0 438.0  56.0 1.0    NaN
2021-05   1191.0 488.0  10.0 2.0    NaN
2021-06   1320.0 607.0  12.0 1.0    NaN
2021-07   1309.0 495.0  9.0  1.0    NaN
2021-08   921.0  209.0  NaN  NaN    NaN
2021-09   653.0   7.0   NaN  NaN    NaN
2021-10   633.0   3.0   NaN  NaN    NaN
2021-11   708.0   5.0   1.0  NaN    NaN
2021-12   390.0   4.0   NaN  NaN    NaN

I am doing a cohort analysis and I want  create two charts. One where each step is divided by the total cohort size, and one where it's divided by the previous column's size.
The first chart I was able to achieve by using
df1 = df.divide(df.iloc[:,0], axis = 0)
Which results:
count   0     1             2           3        4
cohort
2020-10 1.0  0.391304   0.217391    0.065217    NaN
2020-11 1.0  0.389655   0.137931    0.044828    NaN
2020-12 1.0  0.475676   0.164865    0.016216    NaN
2021-01 1.0  0.427807   0.117647    NaN         NaN
2021-02 1.0  0.486957   0.139130    NaN         NaN
2021-03 1.0  0.408346   0.108793    NaN         NaN
2021-04 1.0  0.426070   0.054475    NaN         NaN
2021-05 1.0  0.409740   NaN         NaN         NaN
2021-06 1.0  0.459848   NaN         NaN         NaN
2021-07 1.0  0.378151   NaN         NaN         NaN
2021-08 1.0  0.226927   NaN         NaN         NaN
2021-09 1.0  NaN        NaN         NaN         NaN
2021-10 1.0  NaN        NaN         NaN         NaN
2021-11 1.0  NaN        NaN         NaN         NaN
2021-12 1.0  NaN        NaN         NaN         NaN

However, now I want a similar table which instead of dividing by the 0 index throughout the entire df, I want every column to divide by the size of the previous column
Resulting Df portion (roughly):
count   0     1             2           3        4
cohort
2020-10 1.0  0.391304   0.555555    0.30        NaN
2020-11 1.0  0.389655   0.354       0.32        NaN

Constructor:
dictionary = {0: {Period('2020-10', 'M'): 46.0,
  Period('2020-11', 'M'): 290.0,
  Period('2020-12', 'M'): 370.0,
  Period('2021-01', 'M'): 561.0,
  Period('2021-02', 'M'): 575.0,
  Period('2021-03', 'M'): 671.0,
  Period('2021-04', 'M'): 1028.0,
  Period('2021-05', 'M'): 1191.0,
  Period('2021-06', 'M'): 1320.0,
  Period('2021-07', 'M'): 1309.0,
  Period('2021-08', 'M'): 921.0,
  Period('2021-09', 'M'): 653.0,
  Period('2021-10', 'M'): 633.0,
  Period('2021-11', 'M'): 708.0,
  Period('2021-12', 'M'): 390.0},
 1: {Period('2020-10', 'M'): 18.0,
  Period('2020-11', 'M'): 113.0,
  Period('2020-12', 'M'): 176.0,
  Period('2021-01', 'M'): 240.0,
  Period('2021-02', 'M'): 280.0,
  Period('2021-03', 'M'): 274.0,
  Period('2021-04', 'M'): 438.0,
  Period('2021-05', 'M'): 488.0,
  Period('2021-06', 'M'): 607.0,
  Period('2021-07', 'M'): 495.0,
  Period('2021-08', 'M'): 209.0,
  Period('2021-09', 'M'): 7.0,
  Period('2021-10', 'M'): 3.0,
  Period('2021-11', 'M'): 5.0,
  Period('2021-12', 'M'): 4.0},
 2: {Period('2020-10', 'M'): 10.0,
  Period('2020-11', 'M'): 40.0,
  Period('2020-12', 'M'): 61.0,
  Period('2021-01', 'M'): 66.0,
  Period('2021-02', 'M'): 80.0,
  Period('2021-03', 'M'): 73.0,
  Period('2021-04', 'M'): 56.0,
  Period('2021-05', 'M'): 10.0,
  Period('2021-06', 'M'): 12.0,
  Period('2021-07', 'M'): 9.0,
  Period('2021-08', 'M'): nan,
  Period('2021-09', 'M'): nan,
  Period('2021-10', 'M'): nan,
  Period('2021-11', 'M'): 1.0,
  Period('2021-12', 'M'): nan},
 3: {Period('2020-10', 'M'): 3.0,
  Period('2020-11', 'M'): 13.0,
  Period('2020-12', 'M'): 6.0,
  Period('2021-01', 'M'): 4.0,
  Period('2021-02', 'M'): 5.0,
  Period('2021-03', 'M'): 3.0,
  Period('2021-04', 'M'): 1.0,
  Period('2021-05', 'M'): 2.0,
  Period('2021-06', 'M'): 1.0,
  Period('2021-07', 'M'): 1.0,
  Period('2021-08', 'M'): nan,
  Period('2021-09', 'M'): nan,
  Period('2021-10', 'M'): nan,
  Period('2021-11', 'M'): nan,
  Period('2021-12', 'M'): nan},
 4: {Period('2020-10', 'M'): nan,
  Period('2020-11', 'M'): nan,
  Period('2020-12', 'M'): 1.0,
  Period('2021-01', 'M'): 1.0,
  Period('2021-02', 'M'): nan,
  Period('2021-03', 'M'): 1.0,
  Period('2021-04', 'M'): nan,
  Period('2021-05', 'M'): nan,
  Period('2021-06', 'M'): nan,
  Period('2021-07', 'M'): nan,
  Period('2021-08', 'M'): nan,
  Period('2021-09', 'M'): nan,
  Period('2021-10', 'M'): nan,
  Period('2021-11', 'M'): nan,
  Period('2021-12', 'M'): nan}}


text:
Q: Saving Data + String I'm trying to save & load data but I'm getting frustrated & need some damn sleep. I can't seem to figure this out without getting bugs or nulls.
My code:
public class Offers {

public static List<Offer> offers = new ArrayList<Offer>(2000);

public Offers() {
}

public static void saveOffers() {
        for (Offer offer : offers) {
            if (offer == null) {
                continue;
            }
            int id = offer.id;
            int item = offer.item;
            int amount = offer.amount;
            int price = offer.price;
            int currentAmount = offer.currentAmount;
            int removedAmount = offer.removedAmount;
            int type = offer.type;
            int completed = offer.completed ? 1 : 0;
            int aborted = offer.aborted ? 1 : 0;
            int currentPrice = offer.currentPrice;
            int slot = offer.slot;
            String owner = offer.owner;
            String VALUES(""+ id + "" + item + "" + amount + "" + price + "" + currentAmount + "" + removedAmount + "" + type + "" + completed + "" + aborted + "" + currentPrice + "" + slot + "" + owner + "");
        }
    }
}

public static void load() {
    BufferedReader stream = new BufferedReader(new InputStreamReader(
            new FileInputStream("GEoffers.txt")));
            int id = stream.readShort();
            int item = stream.read();
            int amount = stream.read();
            int price = stream.read();
            int currentAmount = stream.read();
            int removedAmount = stream.read();
            int type = stream.readShort();
            boolean completed = stream.readShort() == 1;
            boolean aborted = stream.readShort() == 1;
            int currentPrice = stream.read();
            int slot = stream.readShort();
            String owner = stream.readString();
            if (id != -1)
                offers.add(new Offer(id, item, amount, currentAmount, removedAmount, price, type, owner, completed, slot));
            for (Offer l : offers) {
                if (l == null) {
                    continue;
                }
                if (l.id == id && l.item == item && l.amount == amount && l.currentAmount == currentAmount && l.price == price && l.type == type && l.owner.equals(owner) && l.slot == slot) {
                    l.currentPrice = currentPrice;
                    l.aborted = aborted;
                    break;
                }
            }
        }
    }

What I'm trying to do in the same method is save all that into a string so when the load method is called it will load & set the variables to what was saved in that string.
for example saves as ""+ id + "" + item + "" + amount + "" + price + "" + currentAmount + "" + removedAmount + "" + type + "" + completed + "" + aborted + "" + currentPrice + "" + slot + "" + owner + ""
and loads as the same while setting the variables as they were when saved.
I'm so done with this I'm on the edge of paying someone like 5$ to just do it for me. Just asking for some help or if someone could be kind enough to fix my crap work. ++*10 for help.
Offer Class as requested:
public class Offer {

public int id = -1;
public int item = 0;
public int amount = 0;
public int currentAmount = 0;
public int removedAmount = 0;
public int price = 0;
public int type = 0;
public String owner = "";
public boolean completed = false;
public int currentPrice = 0;
public boolean aborted = false;
public int slot = 0;
public boolean itemsLeft = false;

/**
 * Creates a new global offer.
 *
 * @param id
 * @param item
 * @param amount
 * @param currentAmount
 * @param removedAmount
 * @param price
 * @param type
 * @param owner
 * @param completed
 * @param slot
 */
public Offer(int id, int item, int amount, int currentAmount, int removedAmount, int price, int type, String owner, boolean completed, int slot) {
    this.id = id;
    this.item = item;
    this.amount = amount;
    this.currentAmount = currentAmount;
    this.removedAmount = removedAmount;
    this.price = price;
    this.type = type;
    this.owner = owner;
    this.completed = completed;
    this.slot = slot;
    this.itemsLeft = false;
}

public void updatePrice(int amount, boolean bool) {
    if (bool) {
        currentPrice += amount;
    } else {
        currentPrice -= amount;
    }
}

public void clear() {
    id = -1;
    item = 0;
    amount = 0;
    currentAmount = 0;
    price = 0;
    type = -1;
    owner = "";
    completed = false;
    currentPrice = 0;
    aborted = false;
    itemsLeft = false;
}

public void delete() {
    Offers.offers.remove(this);
}

}

A: Maybe you want something like this
public class Offers {

    public static List<Offer> offers = new ArrayList<Offer>(2000);

    public Offers() {
    }

    public void saveOffers(int id, int item, int amount, int currentAmount,
                           int removedAmount, int price, int type, String owner,
                           boolean completed, int slot) {

        Offer offer = new Offer(id, item, amount, currentAmount, removedAmount,
                                price, type, owner, completed, slot)

       offers.add(offer);
   }
}

You haven't added any Offers to the offers list. So you cant change the values. That's why you're getting null. ArrayList<>(2000) doesnt add 2000 Offers, just creates a capacity of 2000. Depending on how you define Offer class and it's constructors and getter method (if any), you may want something like my code above.
To run it
public class TestOffers {
    public static void main(String[] args){
        Offers offers = new Offers();

        int id  = 1;
        int item = 1;
        int amount = 1;
        int currentAmount = 1;
        int removedAmount = 1;
        int price = 10;
        int type =- 1;
        String owner = "Me";
        boolean completed = true;
        int slot =1;

        offers.saveOffers(id, item, amount, currentAmount, removedAmount,
                                          price, type, owner, completed, slot);

        for (Offer offer : offers){
            System.out.println(offer);
        }
    }
}

You'll also want to override the toString() method in your Offer class, in order to get your desired output when you want to print an offer
public class Offer {
   ...

   @Override
   public String toString(){
       return id + " " + item + " " + amount + " " + price + " "
              + currentAmount + " " + removedAmount + " " + type + " "
              + completed + " " + aborted + " " + currentPrice + " "
              + slot + " " + owner;
   }
}


text:
Q: Is it worth coding for users who may not have JavaScript enabled?
Possible Duplicates:
How safe is it to assume that most users will have JS enabled?
Is it reasonable to assume my visitors have javascript enabled?

I'm worrying about this and don't know if I should be.

A: To cope with that, it is worth reading:

*

*Progressive enhancement

*Graceful degradation

A: To target the maximum amount of users you really want your site to have some functionality available when JavaScript is disabled. Now if this is some corporate intranet application then it is a different story because your IT department will be able to make sure their PCs are configured correctly.

A: Is SEO important to your site because Crawlers can't access any content that requires Javascript.  So if you want your site to perform well in google, etc. searches then make sure it works without javascript.  Otherwise, just consider your target audience and make a decision that way.
Also search for "unobtrusive javascript" on google, lots of hints / tips on how to do this.

A: I think it needs to be considered. At a minimum there should be a message on the page stating that Javascript is required for a particular element to function.

A: Definitely. According to W3Schools 5% of users don't have JavaScript enabled. So, the solution would be using JavaScript and also keeping that 5% in mind and providing additional information to them such as asking them to enable the feature or providing service using another approach.


text:
Q: R - Count observations per ID and dates I have a claim file with  2 columns: "Customer Id", "Date of the declaration".
I would like to see (and count) if a Customer was involved in more than one accident within X period of time (let's say one year).
My data looks like this:
Customer_Id     Declaration_date
001             12/10/2017
001             12/10/2017
002             24/10/2017
003             25/10/2017
004             25/10/2017
001             05/12/2017
006             07/12/2017

Here it is:
D <- data.frame(Customer_Id = c(001, 001, 002, 003, 004, 001, 006),
            Declaration_date = as.Date(c("12/10/2017", "12/10/2017", "24/10/2017", "25/10/2017", "25/10/2017", "05/12/2017", "07/12/2017"), format = "%d/%m/%Y"))

Here, we can see that the Customer "001" had two claims on the 12/10, but also had one claim on the 05/12. Thus, what  I would like to have is a third column counting the number of different claims, based on the dates, the customer had since 01/01/2016 for instance.
The output should look like this:
Customer_Id     Declaration_date     Number of claims
001             12/10/2017           2
001             12/10/2017           2
002             24/10/2017           1
003             25/10/2017           1
004             25/10/2017           1
001             05/12/2017           2
006             07/12/2017           1

Please note that having a customer id more than once for the same date should not sum the "number of claims".
In my example, the Customer 001 have "2" claims because he had one (or more) claim on the 12/10, but also on the 05/12.
Any help would be very much appreciated.
Thanks a lot,

A: We can use ave from base R to create a column by getting lengthofunique` elements of 'Declaration_date'
with(D, ave(as.numeric(Declaration_date), Customer_Id, FUN = function(x) length(unique(x))))

Or with dplyr
library(dplyr)
D %>%
  group_by(Customer_Id) %>%
  mutate(Number_of_claims = n_distinct(Declaration_date))

Or using data.table
library(data.table)
setDT(D)[,  Number_of_claims := uniqueN(Declaration_date), Customer_Id]


text:
Q: WooCommerce category specific add to cart button text If I have a Woo-Commerce product category titled ATV how would I go about changing the add to cart button text on just that category?
I found the documentation here of how to change the text on the add to cart button but this appears to be for specific product types not categories.
Anybody have a solution?

A: Use conditional logic. In this specifically, the function has_term()
add_filter( 'woocommerce_product_single_add_to_cart_text', 'woo_custom_cart_button_text' );    // 2.1 +

function woo_custom_cart_button_text( $text ) {
    if( has_term( 'your-special-category', 'product_cat' ) ){
        $text = __( 'My Button Text', 'your-plugin' );
    }
    return $text;
}

A: add_filter( 'woocommerce_product_add_to_cart_text', 'saan_archive_custom_cart_button_text' );
function saan_archive_custom_cart_button_text() {
global $product;
$terms = get_the_terms( $product->ID, 'product_cat' );
foreach ($terms as $term) {
$product_cat = $term->name;
break;
}

switch($product_cat){
case 'category1'; return 'Category 1 button text'; break;
case 'category2'; return 'Category 2 button text'; break;
//case .....
default; return 'Add to cart'; break;
}
}

Try this code once. Don't need to thank me..


text:
Q: How to fast custom AI model prediction through API? I develop API using Django for AI model but it's prediction is slow and i have lots of request which take time to execute through AI API, I need help to handle multiple Request at same time

A: If your AI model is stateless meaning new request can be processed independent of the previous requests, then you can run multiple instances of your AI model. You can use a Deployment with multiple replicas. Then, use a Service to load-balance between the instances.


text:
Q: Missing information after reading text file with textscan (Matlab) I am trying to read a comma delimited text file but there is information missing on my results.
The following is an extract of my text file:
number,datetime start,datetime arrive
4027,25/03/2016 11:20,25/03/2016 11:20
4000,25/03/2016 11:20,25/03/2016 11:20
4027,25/03/2016 11:21,25/03/2016 11:21
4000,25/03/2016 11:21,25/03/2016 11:21

My code:
file = fopen('myfile.txt');
TextCell=textscan(file,'%s');
Text=TextCell{1};
fclose(file);

containsStr = ~cellfun('isempty',strfind(Text,'4027'));
FilteredText=Text(containsStr); % filters the strings that contain 4027

Results obtained:
4027,25/03/2016
4027,25/03/2016

Results expected:
4027,25/03/2016 11:20,25/03/2016 11:20
4027,25/03/2016 11:21,25/03/2016 11:21

Where is my mistake?

A: Given the following CSV file:
number,datetime start,datetime arrive
4027,25/03/2016 11:20,25/03/2016 11:20
4000,25/03/2016 11:20,25/03/2016 11:20
4027,25/03/2016 11:21,25/03/2016 11:21
4000,25/03/2016 11:21,25/03/2016 11:21

We load the data into a MATLAB table. We specify the formatting to parse the last two columns as datetime objects.
t = readtable('file.csv', 'FileType','text', 'Delimiter',',', ...
    'Format','%f %{dd/MM/yyyy HH:mm}D %{dd/MM/yyyy HH:mm}D');

The result:
>> t
t =
    number     datetimeStart       datetimeArrive
    ______    ________________    ________________
    4027      25/03/2016 11:20    25/03/2016 11:20
    4000      25/03/2016 11:20    25/03/2016 11:20
    4027      25/03/2016 11:21    25/03/2016 11:21
    4000      25/03/2016 11:21    25/03/2016 11:21

(you might see a warning about identifiers being fixed, this is harmless. The reason is that the names in the header line contained spaces, and those are not valid in variable names).
Finally we select the rows where the first column is equal to 4027:
>> tt = t(t.number == 4027,:)
tt =
    number     datetimeStart       datetimeArrive
    ______    ________________    ________________
    4027      25/03/2016 11:20    25/03/2016 11:20
    4027      25/03/2016 11:21    25/03/2016 11:21

A: First you have comma as delimiter, better to use in textscan. Then you should specify the data columns in your text file. Moreover I would use CollectOutput option to get the data in the same cell array. Check the following code:
file = fopen('myfile.txt');
TextCell=textscan(file,'%s %s %s %s %*[^\n]', 'Delimiter',',', 'CollectOutput',1);
Text=TextCell{1};
fclose(file);

containsStr = ~cellfun('isempty',strfind(Text,'4027'));
FilteredText=Text(containsStr,:);

As a result, you will get a cell array as well.


text:
Q: Convert bitmap to byte array android makes app crash I'm trying to send image between android devices using socket. At first, selected image will be converted to bitmap, and then transformed to byte[] to send, but the process handle of bitmap always makes application force close
Here is the code
File imgFile = new File("/storage/emulated/0/DCIM/Camera/beach.jpg");
FileInputStream fis = null;
try{
 fis = new FileInputStream(imgFile);
} catch (FileNotFoundException e){
 e.printStackTrace();
}
Bitmap bm = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG,100,stream);
imageByte = stream.toByteArray();
OutputStream os = socket.getOutputStream();
os.write(imageByte);
os.flush();

When debugging on real device, the app always forced close at line bm.compress(Bitmap.CompressFormat.JPEG,100,stream);
I did try other way: create buffer for bitmap and allocate ByteBuffer, but processing bitmap always causes crash like: bm.getByteCount() or even bm.getHeight()
Anyone please help me with this problem?
Otherwise, can anybody just list some other methods to send data(image, media...) on android, I'm making an interaction app which provides sharing data between users. Thanks a lot.

A: Thanks everyone, this is just a mistake on displaying Toast causing app crashed, silly me!!!


text:
Q: Einstein's number of particles that experienced a certain shift explanation I am reading a Gardiner's Stochastic Methods handbook and I am wondering about the meaning of the following (this is the very beginning of the chapter):
$dn = n \phi(\Delta) d \Delta$
This is arrived at like so (looking at the particles suspended in a liquid):
There are $n$ particles suspended in a liquid. We choose time, $\tau$ at which the moves of the single particle are independent of its own moves at the previous time step $\tau$. Moves of all particles are also independent of each other. Introduce quantity $\Delta$, which is the move in the $x$ direction at time $\tau$ (this quantity can be either positive or negative). There is a certain frequency to these moves, so that the number $dn$ of particles that experience a move in the range $[\Delta, \Delta + d\Delta]$ is the equation that I have written initially.
I look at the $\phi(\Delta)$ as the probability that a particle experienced a move of size $\Delta$ then the number of particles that experienced such a move is expected to be $n\phi(\Delta)$ and I am not sure where the $d\Delta$ comes in there. Also, $\Delta$ is already a change in the $x$ direction of the position of the particle, then $d\Delta$ is like a change of the change? So the whole confusion I am experiencing comes from that last $d\Delta$ in that first equation.

A: If you chose an integer between 1 and 10, the probability for each is 1/10.
Now chose a real value between 1 and 10, what is the probability for 3? It is zero! You can compute the probability for your number to be between 2.9 and 3.1 though, this has a clear meaning.
So to describe this, you use a probability density. Then the probability for the above interval is $0.2\cdot\phi(3)$. This is an approximation in so far, as the probability density is changing over the interval, to be precise you would have to integrate.
That's what is happening in your formula. $\Delta$ describes a change, but is otherwise a normal variable. To get the probability of a particle to be in an interval $\mathrm d\Delta$ around $\Delta$ you take $\phi(\Delta)\mathrm d\Delta$. Multiplying by $n$ gives the number of particles in that interval.


text:
Q: Spring 5 reactive websocket and multiple endpoints? We are doing a little hackathon at work and I wanted to try some new technology to get away from the usual controller.
I started using Spring Webflux with reactive WebSockets and everything is working fine so far. I configured my WebSocket handler as follows:
import my.handler.DomWebSocketHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.HandlerMapping;
import org.springframework.web.reactive.config.WebFluxConfigurer;
import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping;
import org.springframework.web.reactive.socket.WebSocketHandler;
import org.springframework.web.reactive.socket.server.support.WebSocketHandlerAdapter;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class AppConfig implements WebFluxConfigurer {

    @Autowired
    private WebSocketHandler domWebSocketHandler;

    @Bean
    public HandlerMapping webSocketMapping() {
        Map<String, WebSocketHandler> map = new HashMap<>();
        map.put("/event-emitter", domWebSocketHandler);

        SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
        mapping.setOrder(1);
        mapping.setUrlMap(map);
        return mapping;
    }

    @Bean
    public WebSocketHandlerAdapter handlerAdapter() {
        return new WebSocketHandlerAdapter();
    }
}

After some more research, I learned that it is best practice to work with one connection per client.

Furthermore using more than a web-socket per browsing session for the same application seems overkill since you can use pub/sub channels. See answer here

Is there a way to restrict the connections per client and use only one endpoint for all required client "requests" or would it be better to create additional endpoints (like you would with a normal controller)?
Thank you in advance for the help.


text:
Q: How can I trace the SidHistory to the original and destination domain? I am seeing groups that either contain the current or prior SidHistory for a user in a large complex AD Forest with many domains.

*

*Is it possible to look at the first half of the SidHistory and identify which Tree or Domain that a particular Sid entry came from?

*Is this behavior expected? Under what conditions?

*Should these groups, with legacy Sids, be cleaned up somehow? (or not)

A:
Is it possible to look at the first half of the SidHistory and identify which Tree or Domain that a particular Sid entry came from?

Not usually. SIDHistory SIDs are typically from domains that were migrated from and hopefully no longer exist. If they do exist you could try running Sysinternals psgetsid.exe [SID] to see if it resolves to something.

Is this behavior expected? Under what conditions?

Yes, when your organization performed a migration that created the SIDHistory SIDs.

Should these groups, with legacy Sids, be cleaned up somehow?

Yes, that's the concept.

A:
Is it possible to look at the first half of the SidHistory and identify which Tree or Domain that a particular Sid entry came from?

Assume that Domain A is your source domain and Domain B is your destination domain. If the account is migrated with SID History, the migrated account in Domain B will have an attribute that holds the SID of the original account from Domain A.

Is this behavior expected? Under what conditions?

As said above If the account is migrated with SID History

Should these groups, with legacy Sids, be cleaned up somehow? (or not)

You can use script method to remove Sid history attribute.


text:
Q: $x^m \equiv 1$ (mod p) has $(m,p-1)$ roots Why is the following true?
"$x^m \equiv 1$ (mod p) has $(m,p-1)$ roots."
I know these things which could be relevant:
-$x^{p-1} \equiv 1$ (mod p) for any $(x,p)=1$ by Fermat's Little Theorem
-for any root, the order of the root must divide $m$ by Lagrange's Theorem
-$(\mathbb{Z}/p\mathbb{Z})^{*} $ is cyclic
But still can't put the pieces together.

A: All equalities I write will be mod $p$ when it's clear that they are.
Assume $x^m = 1$. Then the order of $x$ divides $m$, but also $p-1$ by Fermat's Little theorem, so it divides $gcd(m,p-1)$.
Conversely, if the order of $x$ divides $gcd(m,p-1)$, then $x^m = 1$.
Therefore we're just looking for $x$'s whose order divides $gcd(m,p-1)$.
Let $G$ be a cyclic group of order $n$ and let $d|n$. Then the set $H=\{x\in G\mid $ the order of $x$ divides $d\}$ is obviously a subgroup of $G$ (note that $G$ is abelian), so it is a cyclic subgroup. Its exponent is $d$, since its exponent divides $d$, and $G$ being cyclic, there exists $x\in G$ of order precisely $d$.
In cyclic subgroups, exponent and order coincide, thus $H$ is a cyclic subgroup of order $d$ : it has $d$ elements.
Do you see how this solves the question ?

A: Hint:
In a cyclic group of order $n$, generated by $\zeta$, the order of the element $\zeta^k$ is equal to $\;\dfrac{n}{\gcd(n,k)}$.

A: Using discrete logarithm wrt a primitive root $g$ on $$x^m\equiv1\pmod{p^n}$$ for any positive integer $n$
$m$ind$_gx\equiv0\pmod{\phi(p^n)}$
Now use Linear Congruence Theorem .


text:
Q: Form input elements are messing with URL of react page ContactData.js
import React, { Component } from 'react';
import Button from '../../../components/UI/Button/Button';
import classes from './ContactData.module.css'
class ContactData extends Component {
    state = {
        name: '',
        age: '',
        address: {
            street: '',
            postalCode: ''
        }
    }

    orderHandler = () => {
        console.log(this.props.ingredients)
    }

    render() {
        console.log(this.props.ingredients);
        return (

Enter Your Contact Data

                <form>
                    <input type="text" name="name" placeholder="Your Name" />
                    <input type="email" name="email" placeholder="Your Mail" />
                    <input type="text" name="street" placeholder="Street" />
                    <input type="text" name="postal" placeholder="Postal Code" />
                    <Button btnType="Success" clicked={this.orderHandler}>ORDER</Button>
                </form>

        );
    }
}

export default ContactData;

CheckOut.js
    import React from 'react';
import CheckoutSum from '../../components/Checkout/Checkout'
import { Route } from 'react-router-dom';
import ContactData from '../../container/Checkout/ContactData/ContactData'
class Checkout extends React.Component {
    state = {
        ingredients: {
            salad: 1,
            meat: 1,
            cheese: 1,
            bacon: 1
        }
    }

    componentDidMount() {
        const query = new URLSearchParams(this.props.location.search);
        const ingredients = {};
        for (let param of query.entries()) {
            ingredients[param[0]] = parseInt(param[1]);
        }
        // console.log(ingredients);
        this.setState({ ingredients: ingredients });

    }

    cancelHandle = () => {
        this.props.history.goBack();
    }

    continueHandle = () => {
        this.props.history.replace('/checkout/contact-data');
    }
    render() {
        console.log(this.props)
        console.log(this.state.ingredients)
        return (

                <CheckoutSum
                    cancel={this.cancelHandle}
                    continue={this.continueHandle}
                    ingredients={this.state.ingredients}
                />
                <Route
                    path={this.props.match.path + '/contact-data'}
                    exact
                    render={() => (<ContactData ingredients={this.state.ingredients} />)} />

        );
    }
}

export default Checkout;

Problem is when I hit Order button in CotanctData component the page reloads and for some reason my URL changes to  this  http://localhost:3000/checkout/contact-data?name=&email=&street=&postal= and then  Checkout component renders again and for some reason componentDidMount fires twice. At last I was expecting the printing of ingredients object.
Also, I'm using search query in URL to change the state of checkout component
Full Project At-https://github.com/aniket-hue/Burger-App-React/tree/Routes
Please bear with me if you don't like the question I didn't know how to frame the question.

A: You need to either:

*

*Call e.preventDefult() on the <form>'s submit event.

*OR, add <button type="button"> to your button to make it not submit your form.

A: You have to add preventDefault to your orderHandler method, beacause if button in form has no type, the type is automaticlly submit, so on every click your submitting a form. Also can you add type="button" to your button inside form.
orderHandler = e => {
    e.preventDefault();
    console.log(this.props.ingredients);
}


text:
Q: How to fix the error  After insert data to google sheet via python, I want to try and clear those data in google sheet and came into an error
<HttpError 404 when requesting https://sheets.googleapis.com/v4/spreadsheets/Master/values/Master%21A3%3AZ:clear?alt=json returned "Requested entity was not found.">

I don't know what happen since I followed instruction from quickstart python page https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/clear
here is the code I got so far
def remove():
    service=get_service()

    sheet_name = 'Master'
    range_values = sheet_name + '!A3:Z'

    clear_values_request_body = {
    # TODO: Add desired entries to the request body.
    }

    request = service.spreadsheets().values().clear(spreadsheetId=sheet_name, range=range_values, body=clear_values_request_body)
    response = request.execute()

    print(response)

I can't detect the error , have i done something wrong?

A: You should use a library instead which would help you tremendously. I'm the author of Python Sheetfu (https://github.com/socialpoint-labs/sheetfu).
There are other libraries that you should also look at too, gspread and pygsheet to name them, that would help.


text:
Q: sift implementation matlab I would like to know the answer to the following question regarding SIFT if anyone knows.
Before I start, I refer you to the implementation of David Lowe's paper through this link:
http://www.cs.ubc.ca/~lowe/keypoints/
The function declaration looks like this:
[image, descriptors, locs] = sift(image1);

I am not sure about the output parameter locs.  Does it return the location of descriptor as the vector [x y scale orientation]?
If it gives the location, then x and y must be a whole numbers, but it gives fractional values.

A: SIFT uses subpixel accuracy when locating the keypoint. This can be seen in Section 4 Lowe's 2004 SIFT paper.


text:
Q: They have liked the idea of me starting my own business
*

*They have liked the idea of me starting my own business.

*I've liked the song since my childhood.

*I've been liking the song since my childhood.
Q1) I think sentence (3) is not absolutely correct because it uses the stative verb "like" in  progressive form. So, the present perfect tense (sentence (2)) would be used to convey the meaning of sentence (3). Am I right?
Q2) Does sentence (1) suggest they have recently liked the idea (as in "I have done the homework"), or does it suggest they have continuously liked the idea and will continue to like it, the same way as sentence (2)?

A: These perfect forms are possible but not common with the verb "like".  As you note, "like" is a stative verb, so one use of the present perfect: experience of an action resulting in a present state, is not idiomatic.
So you can say "I've seen Mt Everest" (meaning "I saw it sometime in the past but not now"), but not usually "I've liked the song".  Instead you should say "I used to like the song."  So (1) is not idiomatic.  You can use a phrase like "start to like" as

They've started to like the idea of me starting my own business.

It suggests "recently" but you can make that explicit by adding the adverb "They've recently started..."
You can use the present perfect with a "since" phrase.  It is correct to say "I've liked the song since Monday.", meaning I started to like it on Monday and I still like it. So (2) is correct and idiomatic
Also (3) is not idiomatic, for the reasons you give.


text:
Q: Set a post to 'pending' if it get more then 3 reports in wordpress I am using wp user frontend, and I have also downloaded a plugin called 'WP-Reportpost'.
What I am trying to do is that I want users to add post with WP User Frontend (which is working), but when a post get more then 3 reports from other users it should change it status from 'Published' too 'Pending'.
I am trying to make a function in functions.php, but I can't get the code to work.
So far I got this:
 /* Set posts to pending */
function change_post_status($post_id,$status){
    $current_post = get_post( $post_id, 'ARRAY_A' );
    $current_post['post_status'] = $status;
    wp_update_post($current_post);
}

and in reports.php I have put this code:
if(count($report) >= 3){
    change_post_status($report->postID,'pending');
}

The the post still has status as 'Published' and not 'Pending'.
Any tips?

A: Thanks for the help with the code. I at least find the way to figur this out.
I placed this code inside the functions.php file
/* Code to change post status */
function change_post_status($post_id,$status){
    $current_post = get_post( $post_id, 'ARRAY_A' );
    $current_post['post_status'] = $status;
    wp_update_post($current_post);
}

to use the function I did this:
change_post_status($report->postID,'pending');

What I did was to use print_r to get what the $report object was saving and get the postID from there.
Thanks for the help guys!


text:
Q: Error al querer convertir un int a una tuple en python def negativo_grises(im):
    tiempoIn = time.time()
    ruta = ("C:/Users/HardSoft/Desktop/Imagenes/" +im)
    im = Image.open(ruta)
    im.show()
    im6 = im
    i = 0
    while i < im6.size[0]:
        j = 0
        while j < im6.size[1]:
            gris = im6.getpixel((i,j))
            valor = 255 - gris
            im6.putpixel((i,j), valor)
            j+=1
        i+=1
    im6.show()
    tiempoFin = time.time()
    print('El proceso tardo: ', tiempoFin - tiempoIn, 'segundos')

A: Si tu imagen no tiene cada pixel definido por un solo valor (modos l o L) Image.getpixel va a retornar una tupla con el valor de cada canal, por ejemplo (100, 100 ,125, 255) en RGBA (valores de cada canal). Lo mismo pasa con RGB, CMYK, YCbCr, LAB o HSV.
Teniendo en cuanta lo anterior, no puedes restar una tupla a un entero como dice el error. Tienes varias opciones dependiendo de lo que busques, una opción que te va a funcionar pero que es un poco fuerza bruta es convertir la imagen al modo L o l directamente:
imgray = img.convert('L')

Tres observaciones importantes:

*

*Usar un while es poco "pitónico" y además es considerablemente más ineficiente que un for para iterar sobre la imágen.

*Cuando haces im6 = im no estas creando una copia de la imagen, simplemente asignas el identificador im6 la referencia del objeto al que apunta im. Ambos identificadores apuntan al mismo objeto en memoria (a la misma imágen). Esto implica que cuando modificas im6 mediante putpixel también modifica im (en realidad ambas son la misma). Para realizar una copia haz im6 = im.copy()

*Para invertir la imágen la forma que usas no es la más eficiente (putpixel por lo general no lo es). Por ejemplo ImageChops.invert hace esto mismo:
from PIL import Image, ImageChops

im = Image.open(ruta)
ImageChops.invert(img.convert('L')).show()

Tu código podría quedar así:
import time
import os
from PIL import Image, ImageChops

def negativo_grises(im):
    tiempoIn = time.time()
    ruta = os.path.join("D:\Reproductor", im)
    img = Image.open(ruta)
    print(img.mode)
    imgray = img.convert('L')

    for i in range(imgray.size[0]):
        for j in range(imgray.size[1]):
            imgray.putpixel((i,j), 255 - imgray.getpixel((i,j)))

    print('El proceso tardo: {} segundos.'.format(time.time() - tiempoIn))

    img.show()
    imgray.show()

negativo_grises("ejemplo.png")

Si quieras aplicar la misma transformación a cada canal de un imagen RGB por ejemplo podrías hacer:
pixel = tuple(255 - ch for ch in imgray.getpixel((i,j)))
imgray.putpixel((i,j), pixel)

Si se va a trabajar intensivamente con los pixeles de la imagen puede ser mejor pasarla a un array NumPy y vectorizar las operaciones en lo posible.


text:
Q: Can I quickly disable access point radios in one building through Cisco Prime Infrastructure or wism-2 interface We are hosting a robotics competition and they require that all of our wireless AP's be disabled for the weekend. I am wondering if there is a way to do this from our management software. Added difficulty: on a per-building basis. So far, I have found that I can do it for an entire controller using the WiSM-2 web interface and disabling the network status of the radios. I can also do it via Prime Infrastructure using configuration templates. Unfortunately, both of these solutions affect ALL access points, nut just one building.

A: Here's how to do it in Prime Infrastructure 2.0:
1.) Switch to classic theme
2.) Choose Configure -> Lightweight AP configuration templates
3.) Create a new template & edit it
4.) Under the AP Parameters tab check the box for Admin status and leave enabled un-checked
5.) Go the the Select APs tab and choose your APs
6.) Go to the apply/schedule tab and save it, then apply it.
Viola!


text:
Q: Error en la llamada de una variable Tengo los dos siguientes programas

*

*Tracker.py: realiza los cálculos necesarios para apuntar una antena en azimut y elevación hacia un satélite

*Menú.py: es la parte principal del programa y llama a muchos otros núcleos

Querría darle la capacidad al programa de discernir si el satélite está visible o no, declarando la condición (elevacion<0)
Sin embargo, a pesar de hacer muchos intentos no estoy consiguiendo llamar al valor que quiero (visible=False)
Dejo los códigos aquí abajo:

    def Visible(self):

        self.set_epoch(time.time())

        if self.elevation()<0:
            self.visible = False
            return self.visible
        else:
            print("Satélite visible")

Menú.py

        elif opcion == 2:

            visible=Tracker.Tracker.Visible()
            if visible==False:
                print("Satélite no visible")
                satelite = Choose_Satellite.Choose_Satellite()
                print("Estos son los datos TLE del satélite seleccionado: %s \n" % satelite)
                tracker = Tracker.Tracker(satelite)

            try:
                tracker

                print ("\nComienzo seguimiento\n")
                while 1:
                    mensaje = tracker.Calculator()
                    cliente.Send_Data(mensaje)
                    time.sleep(1)
                    if keyboard.is_pressed('esc') or keyboard.is_pressed('q'):
                        print("Ha pulsado la tecla para parar")
                        break

            except NameError:
                print("Debe definir antes un satelite")
                satelite = Choose_Satellite.Choose_Satellite()
                print("Estos son los datos TLE del satélite seleccionado: %s \n" % satelite)
                tracker = Tracker.Tracker(satelite)

Por lo tanto lo que estoy intentando hacer es declarar falso si la elevación es negativa y que el programa principal para que lo reconozca antes de fallar.

A: Creo que el problema está aquí:
    def Visible(self):
        self.set_epoch(time.time())
        if self.elevation()<0:
            self.visible = False
            return self.visible
        else:
            print("Satélite visible")

Si self.elevation()<0: entonces retornas el valor de self.visible, que es False, pero ¿qué ocurre en caso contrario?
En caso contrario no estás retornando nada, sino haciendo un print(). Cuando una función no retorna nada, retorna en realidad None. Si quien recibe el resultado lo usa en un contexto booleano (por ejemplo en un if) se interpretará como False.
Por tanto tu función nuca retorna True. La solución es sencilla:
    def Visible(self):
        self.set_epoch(time.time())
        if self.elevation()<0:
            self.visible = False
        else:
            self.visible = True
        return self.visible


text:
Q: ImportError: cannot import name 'LayoutlmConfig' from 'layoutlm I am trying to save the predictions for the LayoutLM model.
paper - https://arxiv.org/abs/1912.13318
Notebook - https://www.kaggle.com/code/iamarjunchandra/layoutlm-document-sequence-labeling-model/notebook
The problem arises when I run the below code for making prediction
! python unilm/layoutlm/examples/seq_labeling/run_seq_labeling.py
                               --do_predict
                               --data_dir data
                               --model_type layoutlm
                               --model_name_or_path output
                               --output_dir output
                               --labels data/labels.txt \
                               --fp16

I am getting the below error.
Traceback (most recent call last):
  File "unilm\\layoutlm\\examples\\seq_labeling\\run_seq_labeling.py", line 53, in <module>
    from layoutlm import FunsdDataset, LayoutlmConfig, LayoutlmForTokenClassification
ImportError: cannot import name 'LayoutlmConfig' from 'layoutlm' (c:\Users\jyoti\anaconda3\lib\site-packages\layoutlm\__init__.py)


text:
Q: Trace identity for symmetric matrix.
If $A^*\in S^n$, is a symmetric matrix, then is true that
$$\mbox{ Tr }(A^*A)=\sum_{i=1}^n (\lambda_i)^2$$

I know, bt the spectral theorem, that For any symmetric matrix, there are eigenvalues $\lambda_1,\ldots,\lambda_n$, with corresponding eigenvectors $v_1,\ldots,v_n$ which are orthonormal. We can then write $$\sum_{i=1}^n v_i^T\lambda_i v_i=V\Lambda V,$$
where $V$ is the matrix with $v_i$'s arranged as column vectors and $\Lambda$ is the diagonal matrix of eigenvalues. But, is always true that $\mbox{ Tr }(A^*A)=\sum_{i=1}^n v_i^T(\lambda_i A)v_i$, is very weird, 'cause is this should be the square of the term of matrix $A*$. Thanks

A: If $A$ is a complex symmetric matrix, then $A=V\Lambda V^*$ for some unitary $V$ and diagonal $\Lambda$. (Note that the asterisk $*$ denotes conjugate transpose.)
Then $A^* A = V \Lambda^* \Lambda V^*$ and using the cyclic property of the trace, we have
$$\operatorname{Tr}(A^* A) = \operatorname{Tr}(V \Lambda^* \Lambda V^*)
= \operatorname{Tr}(\Lambda^* \Lambda V^* V) = \operatorname{Tr}(\Lambda^* \Lambda) = \sum_{i=1}^n \overline{\lambda_i} \lambda_i = \sum_{i=1}^n |\lambda_i|^2.$$
When $A$ is real symmetric, this reduces to $\operatorname{Tr}(A^\top A) = \sum_{i=1}^n \lambda_i^2$, and in the comments I mentioned that $v_i^\top (\lambda_i A) v_i = \lambda_i^2$.
(Note that the assumption that $\operatorname{Tr}(A)=1$ is not needed.)

Regarding the "very weird" comment in your last sentence:
You are correct that $\operatorname{Tr}(A^\top A)$ is the sum of squares of the entries of $A$. The above work shows that for symmetric matrices, it is also the sum of squares of the eigenvalues.


text:
Q: Converge relationship between two series Suppose $\{a_n\}_{n=1}^{\infty}$ is a non-negative sequence. I'm considering the relationship between the following two series.
$$
\sum_{n=1}^{\infty} \left[ a_n - log(1+a_n) \right] \quad \textit{and} \quad \sum_{n=1}^{\infty} a_n^{2}
$$
My question is does the first one converge imply the second one converges? How about reverse direction?
I try to expand $f(x) = x - log(1+x)$ by Taylor expansion, which is
$$
f(x) = x - log(1+x) = \frac{x^2}{2} - \frac{x^3}{3} + \frac{x^4}{4} - \cdots
$$
and try to use Limit comparison test, where we let $g(x) = x^2$.
However, I stuck at how check if $\lim_{n\rightarrow\infty} \frac{f(a_n)}{g(a_n)}$ exist and not equal to zero.

A: Note that $f(0)=0$ and that $f(x)>0$ if $x\ne0$. Besides, it's not hard to prove that $\lim_{n\to\infty}a_n=0$ if and only if $\lim_{n\to\infty}f(a_n)=0$. So:

*

*If $\displaystyle\sum_{n=1}^\infty\bigl(a_n-\log(1+a_n)\bigr)$ converges, then $\lim_{n\to\infty}f(a_n)=0$, and so $\lim_{n\to\infty}a_n=0$. But then$$\lim_{n\to\infty}\frac{a_n-\log(1+a_n)}{a_n^{\,2}}=\frac12$$and therefore the series $\displaystyle\sum_{n=1}^\infty a_n^{\,2}$ converges too (not that $a_n-\log(1+a_n)=f(a_n)\geqslant0$ for every $n\in\Bbb N$).

*If $\displaystyle\sum_{n=1}^\infty a_n^{\,2}$ converges, then the same argument as above shows that the series $\displaystyle\sum_{n=1}^\infty\bigl(a_n-\log(1+a_n)\bigr)$ converges too.


text:
Q: Apache2 + mod_ruby - how to handle all requests with one script? I was about writing my own HTTP Server. Well I did, but conerning security issues it was too time expensive doing it on and I drove back having a unique solution with Apache2 and Mod_Ruby in-between.
Now I have a single Ruby Script, launching other scripts. I want that single Ruby Script to be the only script accessed by Apache each request:
domain.com/path/to?arguments=value
will be sent to my script test.rbx, whatever will be entered.
How can I do this?
Actually I can only access the test.rbx itself. From there I can call Apache::Request.unparsed_uri, which would receive the complete path with parameters. But only by accessing domain.com/test.rbx - how to call domain.com/test.rbx for every request implicitly?
Joern.


text:
Q: Overriding scientific notation in ggplot's legend This should be very simple, but I can't seem to find a solution. I am looking for the equivalent of scale_y_continuous, or scale_x_continuous in ggplot, but for the legend rather than the chart axes.
Very simply, I am getting 5e+05 where I want 500000.
I assume this can be controlled through something like legend.text inside theme:
legend.text=element_text(scale_continuous)

Can someone please provide the correct code? Many thanks in advance.