Q: Does Akka Decider have access to the full failure scenario? New to Akka. Creating a new Scala class that extends SupervisorStrategy gives me the following template to work with:
class MySupervisorStrategy extends SupervisorStrategy {
  override def decider: Decider = ???

  override def handleChildTerminated(context: ActorContext, child: ActorRef,
    children: Iterable[ActorRef]): Unit = ???

  override def processFailure(context: ActorContext, restart: Boolean,
    child: ActorRef, cause: Throwable, stats: ChildRestartStats, children: Iterable[ChildRestartStats]): Unit = ???
}

I'm looking for a way to access:

*

*The Throwable/Exception that was thrown from the child actor

*The child actor ActorRef that threw the exception

*The message that was passed to the child actor that prompted the exception to be thrown

I think the Decider (which is actually a PartialFunction[Throwable,Directive]) gets passed the Throwable whenever the child throws the exception, but I'm not seeing where I could get access to #2 and #3 from my list above. Any ideas?

Update
From the posted fiddle, it looks like a valid Decider is:
{
    case ActorException(ref,t,"stop")      =>
      println(s"Received 'stop' from ${ref}")
      Stop
    case ActorException(ref,t,"restart")      =>
      println(s"Received 'restart' from ${ref}")
      Restart
    case ActorException(ref,t,"resume")      =>
      println(s"Received 'resume' from ${ref}")
      Resume
}

Above, I see all three:

*

*The exception that was thrown by the child

*The child (ref) that threw the exception

*The message that was sent to the child originally (that caused the exception to be thrown)

It looks like there's nothing in that Decider that needs to be defined inside that Supervisor class. I'd like to pull the Decider logic out into, say, MyDecider.scala and find a way to refactor the Supervisor so that its supervisorStrategy uses an instance of MyDecider, so maybe something similar to:
class Supervisor extends Actor {
  import akka.actor.OneForOneStrategy
  import akka.actor.SupervisorStrategy._
  import scala.concurrent.duration._

  var child: ActorRef = _

  override val supervisorStrategy =
    OneForOneStrategy(maxNrOfRetries = 10, withinTimeRange = 1 minute, decider = myDecider)

  ...
}

A: For #2 you could access the sender "if the strategy is declared inside the supervising actor"

If the strategy is declared inside the supervising actor (as opposed to within a companion object) its decider has access to all internal state of the actor in a thread-safe fashion, including obtaining a reference to the currently failed child (available as the sender of the failure message).

The message is not made available so the only option is to catch your exception and throw a custom one with the message that was received.
Here is a quick fiddle
class ActorSO extends Actor {

  def _receive: Receive = {
    case e =>
      println(e)
      throw new RuntimeException(e.toString)
  }

  final def receive = {
    case any => try {
      _receive(any)
    }
    catch {
      case t:Throwable => throw new ActorException(self,t,any)
    }

  }

}

Update
A Decider is just a PartialFunction so you can pass it in the constructor.
object SupervisorActor {
  def props(decider: Decider) = Props(new SupervisorActor(decider))
}

class SupervisorActor(decider: Decider) extends Actor {

  override val supervisorStrategy = OneForOneStrategy()(decider)

  override def receive: Receive = ???
}

class MyDecider extends Decider {
  override def isDefinedAt(x: Throwable): Boolean = true

  override def apply(v1: Throwable): SupervisorStrategy.Directive = {
    case t:ActorException => Restart
    case notmatched => SupervisorStrategy.defaultDecider.apply(notmatched)
  }
}

object Test {
  val myDecider: Decider = {
    case t:ActorException => Restart
    case notmatched => SupervisorStrategy.defaultDecider.apply(notmatched)
  }
  val myDecider2 = new MyDecider()
  val system = ActorSystem("stackoverflow")
  val supervisor = system.actorOf(SupervisorActor.props(myDecider))
  val supervisor2 = system.actorOf(SupervisorActor.props(myDecider2))
}

By doing so, you won't be able to access supervisor state like the ActorRef of the child that throw the exception via sender() (although we are including this in the ActorException)
Regarding your original question of accessing from the supervisor the child message that cause the exception, you can see here (from akka 2.5.3) that the akka developers choose to not make it available for decision.
  final protected def handleFailure(f: Failed): Unit = {
    // ¡¡¡ currentMessage.message is the one that cause the exception !!!
    currentMessage = Envelope(f, f.child, system)
    getChildByRef(f.child) match {
      /*
       * only act upon the failure, if it comes from a currently known child;
       * the UID protects against reception of a Failed from a child which was
       * killed in preRestart and re-created in postRestart
       */
      case Some(stats) if stats.uid == f.uid ⇒
        // ¡¡¡ currentMessage.message is not passed to the handleFailure !!!
        if (!actor.supervisorStrategy.handleFailure(this, f.child, f.cause, stats, getAllChildStats)) throw f.cause
      case Some(stats) ⇒
        publish(Debug(self.path.toString, clazz(actor),
          "dropping Failed(" + f.cause + ") from old child " + f.child + " (uid=" + stats.uid + " != " + f.uid + ")"))
      case None ⇒
        publish(Debug(self.path.toString, clazz(actor), "dropping Failed(" + f.cause + ") from unknown child " + f.child))
    }
  }


Q: How to install packages with conda into /usr/bin/python3 I have a package, that is only downloadable with conda. When I startup a shell and type which python3, I get /home/usr/miniconda3/bin/python. Then I do conda deactivate and my python3 is /usr/bin/python3. Is there any chance to install packages from conda, so that the python-interpreter in that location finds them?


Q: Examples of continuous functions that are not homotopic to each other. Let $f,g:X \to Y$ be continuous functions. Then, consider $F:X \times I \to Y$ defined as follows:$$F(x,t) = f(1-t)+gt$$
How does one check whether $F$ is continuous(w.r.t the product topology)?
Is there any other way to define a homotopy between two functions?
As an example, take $f,g :  \mathbb{R} \to \mathbb{R}$ to be $f(x) = x, g(x) = sin(x)$. Then how does one PROVE that the homotopy map as defined above is continuous?
Moreover, what are some examples of maps that are not homotopic?

A: The identity map of the circle $\rm{id}:S^1\to S^1$ and a constant map on $S^1$ are continuous but not homotopic.  This is due to a result by Heinz Hopf, from one point of view.
Intuitively the unit circle is not contractible.
By the alluded to result, we can wrap the circle around itself as many times as we like, continuously, and get non-homotopic maps.

The homotopy you refer to is the straight line homotopy.  There are plenty of others.

A: Generally, this all comes down to a space being path connected. If the path the homotopy described is contained in the space then it will be continous. For example, if we want to see the circular sector of radii 1 and 2 is homotopic to the unit circumference, we might consider the following map:
$$
f(x)=\frac{x}{||x||}
$$
It normalizes every point of the sector. It is continous because $0$ is not contained in the sector, thus, it is a retraction into the unit sphere. We want to prove it is a deformation retract, so we can end our proof, concluding that the two sets have the same type of homotopy. We consider the following homotopy:
$$
H(x,t)=f(x)·t+x·(1-t)
$$
Because of what I said earlier, one can check it is radial, making it thus continious (the sector is path connected).

A: The homotopy you describe for maps to $\mathbb{R}$ (or maybe $\mathbb{R}^n$) is continuous because addition and multiplication on $\mathbb{R}$ are continuous operations, along with the functions $f$ and $g$ being continuous.
In general, maps $f$ and $g$ are not homotopic if some $f(x)$ and $g(x)$ are in different path components (essentially using that if $f$ and $g$ were homotopic then so would be the compositions $\{x\} \hookrightarrow X \to Y$). This tells you for example that the identity of $\mathbb{R} - 0$ is not homotopic to the map $x \mapsto -x$.
Looking at such compositions with maps $Z \to X$ from other 'test' spaces $Z$ can often detect if $f$ and $g$ are not homotopic. For example looking at all maps $S^n \to X$ composed with $f$ and $g$ is the same as looking at the maps $\pi_n(X) \to \pi_n(Y)$ induced by $f$ and $g$.


Q: how to show product SKU below product name only on product page I am using porto theme in magento 1.9. i want to display product SKU only on product page below product name. how can we add product SKU on product page.

A: Edit file
app/design/frontend/yourtheme/package/template/catalog/product/view.phtml
if you want to add SKU then please add following code underneath of H1 tag (product name).

<?php echo $_helper->productAttribute($_product, $_product->getSku(), 'sku') ?>

To remove the attribute from details section, comment out the line
<?php echo $_product->getSku(); ?>


Q: Map newlines in GHCi Simple question, but I can't seem to figure it out. I have a list, and I want to print out each element of it on its own line. I can do
map show [1..10]

for example, which will print out them all together, but with no newlines. My thought was to do map (putStrLn $ show) [1..10] but this won't work because I just get back an [IO()]. Any thoughts?

A: Aren't these answers putting too much emphasis on IO?  If you want to intersperse newlines the standard Prelude formula is :
> unlines (map show [1..10])
"1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n"

This is the thing you want written - newlines are characters not actions, after all. Once you have an expression for it, you can apply putStrLn or writeFile "Numbers.txt" directly to that.  So the complete operation you want is something like this composition:
putStrLn . unlines . map show

In ghci you'd have
> (putStrLn . unlines . map show) [1,2,3]
1
2
3

A: Try this: mapM_ (putStrLn . show) [1..10]

A: Here is my personal favourite monad command called sequence:
sequence :: Monad m => [m a] -> m [a]

Therefore you could totally try:
sequence_ . map (putStrLn . show) $ [1..10]

Which is more wordy but it leads upto a function I find very nice (though not related to your question):
sequence_ . intersperse (putStrLn "")

Maybe an ugly way to do that but I thought it was cool.


Q: Google Maps API Drawing Rectangle This is the meat of the code I am using and I am not getting errors, but I am not seeing the points that are in the area of the rectangle. Any help would be appreciated:
`enter code here`/** @this {google.maps.Rectangle} */
function showNewRect(event) {
 var ne = rectangle.getBounds().getNorthEast();
var sw = rectangle.getBounds().getSouthWest();
google.maps.event.addlistener(rectangle, "bounds_changed", function(){
  document.getElementById("map-selected").innerHTML=rectangle.getBounds();
  var rectA = (ne*sw);
 })

}

function listSelected () {
var inside = $.map( sites, function ( s ) {
  var d;

  if ( ( (d = google.maps.geometry.poly.containsLocation( s.position )) <= rectA  ) )
     return s.location + ' ('+(Math.round(d/100)/10)+' km)';
      $('#map-selected').html( inside.sort().join('') );

});
}

    google.maps.event.addListener(drawingManager, 'rectanglecomplete', function( rectangle )    {

   selectedArea = rectangle;
  listSelected();

  google.maps.event.addListener(rectangle, 'center_changed', listSelected);
  google.maps.event.addListener(rectangle, 'bounds_changed', listSelected);I am working with the Google maps API and I have a map I am drawing on with a rectangle. I need to have a user draw the rectangle, and on the map there will be predefined locations, that when the rectangle crosses the locations there will be details of each location put into a list.

This is an example:
http://hmoodesigns.com/ksi/
I have an example using the circle draw tool, which I can get to work fine, but the rectangle tool I have not been able to have this identify the points on the map.
How can I check for these points without having a predefined rectangle on the page?
Thanks,

A: When the Rectangle has been drawn iterate over the locations and use the method contains() of the Rectangle's bounds to test if the LatLng's are within the bounds of the Rectangle


Q: PHP DomDocument appendChildNode where I have  tags in the text I would like to append some text to a dom element as a child node.
The problem is that in the text I can have tags as <i>, <bold> etc.
Actually, with this method:
private function appendChildNode($dom_output, $cit_node, $nodeName, $nodeText)
{
    if ($nodeText != null && $nodeText != "" ) {
        $node = $dom_output->createElement($nodeName);
        $node->appendChild($dom_output->createTextNode($nodeText));
        $cit_node->appendChild($node);
        return $node;
    }
}

When I have tags in the $nodeText, then the <i> will be converted to <i> and so on.
How can I append this text by keeping the tags as they are?
Thank you.

A: I managed to find the solution.
Thanks to this post: DOMDocument append already fixed html from string
I did:
private function appendChildNode($dom_output, $cit_node, $nodeName, $nodeText)
{
    if ($nodeText != null && $nodeText != "" ) {
        $node = $dom_output->createElement($nodeName);
        $fragment = $dom_output->createDocumentFragment();
        $fragment->appendXML( $nodeText);
        $node->appendChild($fragment);
        $cit_node->appendChild($node);
        return $node;
    }
}


Q: Can I have different ESX hosts accessing the same LUN over different protocols? I currently have a cluster of two ESX 3.5U2 servers connected directly via FiberChannel to a NetApp 3020 cluster.  These hosts mount four VMFS LUNs for virtual machine storage.  Currently these LUNs are only made available via our FiberChannel initator in the Netapp configuration
If I were to add an ESXi host to the cluster for internal IT use can I:

*

*Make the same VMFS LUNs available via the iSCSI target on the Netapp

*Connect this ESXi host to those LUNs via iSCSI

*Do all of this while the existing two ESX hosts are connected to those LUNs via FiberChannel

Does anyone have experience with this type of mixed protocol environment, specifically with Netapp?

A: As long as the Netapp can present a LUN to both the fibre channel and iSCSI interfaces at the same time it shouldn't be a problem.  However to do this the ESXi host would need to be a member of the cluster that the other two machines are members of, otherwise the volume will become corrupt.

A: First you should note that ESXi cannot be part of a Cluster, in fact it can't be managed from VirtucalCenter/vSphere without paying for the licensing.
That being said. Once you have it part of the cluster, You will need to make sure that your SAN is presenting the LUN with the same ID (most do but some don't). If it isn't you need to resignature your LUN. See VMWare Documentation for help
If you cannot get the licensing, you will need to give it it's own storage.
Edit: Clarified what i was saying as to ESXi not being able to be managed by VC/vSphere


Q: How to type "line1", "line2", "line3".... using for loop in python For example, I want to generate below output using a "for" loop, having the for loop automatically populate the number at the end of the word line:
line1
line2
line3
line4
line5
line6
line7

A: Here is how to do it with "f-strings" and the range() class object in a for loop:
for_loop_basic_demo.py:
#!/usr/bin/python3

END_NUM = 7
for i in range(1, END_NUM + 1):
    print(f"line{i}")

Run command:
./for_loop_basic_demo.py

Output:
line1
line2
line3
line4
line5
line6
line7

Going further: 3 ways to print
The 3 ways I'm aware of to print formatted strings in Python are:

*

*formatted string literals; AKA: "f-strings"

*the str.format() method, or

*the C printf()-like % operator

Here are demo prints with all 3 of those techniques to show each one for you:
#!/usr/bin/python3

END_NUM = 7
for i in range(1, END_NUM + 1):
    # 3 techniques to print:

    # 1. newest technique: formatted string literals; AKA: "f-strings"
    print(f"line{i}")

    # 2. newer technique: `str.format()` method
    print("line{}".format(i))

    # 3. oldest, C-like "printf"-style `%` operator print method
    # (sometimes is still the best method, however!)
    print("line%i" % i)

    print() # print just a newline char

Run cmd and output:
eRCaGuy_hello_world/python$ ./for_loop_basic_demo.py
line1
line1
line1

line2
line2
line2

line3
line3
line3

line4
line4
line4

line5
line5
line5

line6
line6
line6

line7
line7
line7

References:

*

****** This is an excellent read, and I highly recommend you read and study it!: Python String Formatting Best Practices

*Official Python documentation for all "Built-in Functions". Get used to referencing this: https://docs.python.org/3/library/functions.html

*

*The range() class in particular, which creates a range object which allows the above for loop iteration: https://docs.python.org/3/library/functions.html#func-range

A: You can use f strings.\
n = 7
for i in range(1, n + 1):
    print(f"line{i}")


Q: Getting Facebook Access Token from User Id and Facebook App Secret? I'm trying to understand how the facebook api works. The end goal is to be able to read the posts from a facebook page.
If someone has connected with my app on facebook can my c# application then get the posts from a public facebook page if it knows their facebook account id (and has the facebook app secret hard coded).
If so what are the http requests it needs to make in order to get the access token which can then be used to get the posts, and what are the requests to get a new access token before one expires?
If you could provide an example in c# (maybe using the acebooksdk.net library) that would be great!
Thanks.

A: The way to do it was using "The Login Flow for Web (without JavaScript SDK)" api to get a user access token. A user access token is required to be sent with graph api queries in order to get page posts.
The first step is to create an app on facebook where you specify what information you want the program to be able to access via the graph api. The end user will then choose to accept these permissions later.
The program creates a web browser frame and navigates to https://www.facebook.com/dialog/oauth?client_id={app-id}&redirect_uri=https://www.facebook.com/connect/login_success.html&response_type=token
The response type "token" means that when the (embedded) web browser is redirected to the redirect_uri the user access token will be added to the end of the url as a fragment. E.g the browser would end up on the page with url https://www.facebook.com/connect/login_success.html#access_token=ACCESS_TOKEN...
The redirect uri can be anything but facebook has that specific one set aside for this scenario where you are not hosting another server which you want to receive and process the response.
Basically facebook gathers all the information required from the user and then sends them to the redirect_uri. Some information they may require is for them to login and accept permissions your app on facebook requires.
So the program simply keeps an eye on what url the embedded browser is on and when it matches the redirect_uri it parses the url which will contain the data as fragments and can then close the browser.


Q: "Call to undefined method PHPUnit\Framework\TestSuite::sortId()" Error while executing Test Case with Coverage
Call to undefined method PHPUnit\Framework\TestSuite::sortId()

Getting this error while trying to execute test case with coverage.
Command:
phpunit -v --debug ./Test.php --coverage-clover ../clover.xml

Putput: (first two lines)
PHPUnit 9.5.4 by Sebastian Bergmann and contributors.
Runtime:       PHP 7.3.33-1+ubuntu21.10.1+deb.sury.org+1
...

A: It appears that you have different installations of PHPUnit mixed up.
For instance, you may have used Composer to install PHPUnit and have configured the autoloader generated by Composer as PHPUnit's bootstrap script but then you invoke PHPUnit using an executable other than vendor/bin/phpunit.


Q: Retrieving data from PostgresQL database with millions of rows takes very long I've been working on a system where users can register as an user, create a book club and invite other people (members) to join. The user and member can all add books to the club, and also vote for books that other members have added. I recently tried to add a lot of data to check if the database is performing well, after which I found out that it takes a lot of time to actually get the data I like. I would like to get all books in a club, including their votes and the name of the members that have voted for it.
My database diagram (created via dbdiagram.io, check it out)

In order to freely query the database without too much hassle, I decided to use Hasura, an open source service that can create a GraphQL backend by just looking at the data structure (I am using PostgresQL). I Use the following query to get the data I want:
query GetBooksOfClubIncludingVotesAndMemberName {
  books(
    where: {
      club_id: {_eq: "3"},
      state:{_eq: 0 }
    },
    order_by: [
      { fallback : asc },
      { id: asc }
    ]
  ) {
    id
    isbn
    state
    votes {
      member {
        id
        name
      }
    }
  }
}

This query of course gets converted to a SQL statement
SELECT
  coalesce(
    json_agg(
      "root"
      ORDER BY
        "root.pg.fallback" ASC NULLS LAST,
        "root.pg.id" ASC NULLS LAST
    ),
    '[]'
  ) AS "root"
FROM
  (
    SELECT
      row_to_json(
        (
          SELECT
            "_8_e"
          FROM
            (
              SELECT
                "_0_root.base"."id" AS "id",
                "_0_root.base"."isbn" AS "isbn",
                "_7_root.ar.root.votes"."votes" AS "votes"
            ) AS "_8_e"
        )
      ) AS "root",
      "_0_root.base"."id" AS "root.pg.id",
      "_0_root.base"."fallback" AS "root.pg.fallback"
    FROM
      (
        SELECT
          *
        FROM
          "public"."books"
        WHERE
          (
            (("public"."books"."club_id") = (('3') :: bigint))
            AND (("public"."books"."state") = (('0') :: smallint))
          )
      ) AS "_0_root.base"
      LEFT OUTER JOIN LATERAL (
        SELECT
          coalesce(json_agg("votes"), '[]') AS "votes"
        FROM
          (
            SELECT
              row_to_json(
                (
                  SELECT
                    "_5_e"
                  FROM
                    (
                      SELECT
                        "_4_root.ar.root.votes.or.member"."member" AS "member"
                    ) AS "_5_e"
                )
              ) AS "votes"
            FROM
              (
                SELECT
                  *
                FROM
                  "public"."votes"
                WHERE
                  (("_0_root.base"."id") = ("book_id"))
              ) AS "_1_root.ar.root.votes.base"
              LEFT OUTER JOIN LATERAL (
                SELECT
                  row_to_json(
                    (
                      SELECT
                        "_3_e"
                      FROM
                        (
                          SELECT
                            "_2_root.ar.root.votes.or.member.base"."id" AS "id",
                            "_2_root.ar.root.votes.or.member.base"."name" AS "name"
                        ) AS "_3_e"
                    )
                  ) AS "member"
                FROM
                  (
                    SELECT
                      *
                    FROM
                      "public"."members"
                    WHERE
                      (
                        ("_1_root.ar.root.votes.base"."member_id") = ("id")
                      )
                  ) AS "_2_root.ar.root.votes.or.member.base"
              ) AS "_4_root.ar.root.votes.or.member" ON ('true')
          ) AS "_6_root.ar.root.votes"
      ) AS "_7_root.ar.root.votes" ON ('true')
    ORDER BY
      "root.pg.fallback" ASC NULLS LAST,
      "root.pg.id" ASC NULLS LAST
  ) AS "_9_root";

When executing this statement using EXPLAIN ANALYZE in front of it, it tells me that it took approximately 9217 milliseconds to finish, check the analyze response below
                                                                         QUERY PLAN
-------------------------------------------------------------------------------------------------------------------------------------------------------------
 Aggregate  (cost=12057321.11..12057321.15 rows=1 width=32) (actual time=9151.967..9151.967 rows=1 loops=1)
   ->  Sort  (cost=12057312.92..12057313.38 rows=182 width=37) (actual time=9151.856..9151.865 rows=180 loops=1)
         Sort Key: books.fallback, books.id
         Sort Method: quicksort  Memory: 72kB
         ->  Nested Loop Left Join  (cost=66041.02..12057306.09 rows=182 width=37) (actual time=301.721..9151.490 rows=180 loops=1)
               ->  Index Scan using book_club on books  (cost=0.43..37888.11 rows=182 width=42) (actual time=249.506..304.469 rows=180 loops=1)
                     Index Cond: (club_id = '3'::bigint)
                     Filter: (state = '0'::smallint)
               ->  Aggregate  (cost=66040.60..66040.64 rows=1 width=32) (actual time=49.134..49.134 rows=1 loops=180)
                     ->  Nested Loop Left Join  (cost=0.72..66040.46 rows=3 width=32) (actual time=0.037..49.124 rows=3 loops=180)
                           ->  Index Only Scan using member_book on votes  (cost=0.43..66021.32 rows=3 width=8) (actual time=0.024..49.104 rows=3 loops=180)
                                 Index Cond: (book_id = books.id)
                                 Heap Fetches: 540
                           ->  Index Scan using members_pkey on members  (cost=0.29..6.38 rows=1 width=36) (actual time=0.005..0.005 rows=1 loops=540)
                                 Index Cond: (id = votes.member_id)
                                 SubPlan 2
                                   ->  Result  (cost=0.00..0.04 rows=1 width=32) (actual time=0.000..0.000 rows=1 loops=540)
                     SubPlan 3
                       ->  Result  (cost=0.00..0.04 rows=1 width=32) (actual time=0.000..0.000 rows=1 loops=540)
               SubPlan 1
                 ->  Result  (cost=0.00..0.04 rows=1 width=32) (actual time=0.001..0.002 rows=1 loops=180)
 Planning Time: 0.788 ms
 JIT:
   Functions: 32
   Options: Inlining true, Optimization true, Expressions true, Deforming true
   Timing: Generation 4.614 ms, Inlining 52.818 ms, Optimization 113.442 ms, Emission 81.939 ms, Total 252.813 ms
 Execution Time: 9217.899 ms
(27 rows)

With table sizes of:
   relname    | rowcount
--------------+----------
 books        |  1153800
 members      |    19230
 votes        |  3461400
 clubs        |     6410
 users        |        3

This takes way too long. In my previous design, I did not have any indexes, which caused it to be even slower. I have added indexes, but I'm still not quite happy about the fact that I'll have to wait that long. Is there anything that I can improve concerning the data structure or anything?
EDIT
Same select statement, but now using EXPLAIN (ANALYZE, BUFFERS) as suggested:
                                                                         QUERY PLAN
-------------------------------------------------------------------------------------------------------------------------------------------------------------
 Aggregate  (cost=12057321.11..12057321.15 rows=1 width=32) (actual time=8896.202..8896.202 rows=1 loops=1)
   Buffers: shared hit=2392279 read=9470
   ->  Sort  (cost=12057312.92..12057313.38 rows=182 width=37) (actual time=8896.097..8896.106 rows=180 loops=1)
         Sort Key: books.fallback, books.id
         Sort Method: quicksort  Memory: 72kB
         Buffers: shared hit=2392279 read=9470
         ->  Nested Loop Left Join  (cost=66041.02..12057306.09 rows=182 width=37) (actual time=222.978..8895.801 rows=180 loops=1)
               Buffers: shared hit=2392279 read=9470
               ->  Index Scan using book_club on books  (cost=0.43..37888.11 rows=182 width=42) (actual time=174.471..214.000 rows=180 loops=1)
                     Index Cond: (club_id = '3'::bigint)
                     Filter: (state = '0'::smallint)
                     Buffers: shared hit=113 read=9470
               ->  Aggregate  (cost=66040.60..66040.64 rows=1 width=32) (actual time=48.211..48.211 rows=1 loops=180)
                     Buffers: shared hit=2392166
                     ->  Nested Loop Left Join  (cost=0.72..66040.46 rows=3 width=32) (actual time=0.028..48.202 rows=3 loops=180)
                           Buffers: shared hit=2392166
                           ->  Index Only Scan using member_book on votes  (cost=0.43..66021.32 rows=3 width=8) (actual time=0.018..48.187 rows=3 loops=180)
                                 Index Cond: (book_id = books.id)
                                 Heap Fetches: 540
                                 Buffers: shared hit=2390546
                           ->  Index Scan using members_pkey on members  (cost=0.29..6.38 rows=1 width=36) (actual time=0.004..0.004 rows=1 loops=540)
                                 Index Cond: (id = votes.member_id)
                                 Buffers: shared hit=1620
                                 SubPlan 2
                                   ->  Result  (cost=0.00..0.04 rows=1 width=32) (actual time=0.000..0.000 rows=1 loops=540)
                     SubPlan 3
                       ->  Result  (cost=0.00..0.04 rows=1 width=32) (actual time=0.000..0.000 rows=1 loops=540)
               SubPlan 1
                 ->  Result  (cost=0.00..0.04 rows=1 width=32) (actual time=0.008..0.008 rows=1 loops=180)
 Planning Time: 0.400 ms
 JIT:
   Functions: 32
   Options: Inlining true, Optimization true, Expressions true, Deforming true
   Timing: Generation 2.060 ms, Inlining 9.923 ms, Optimization 94.927 ms, Emission 68.793 ms, Total 175.702 ms
 Execution Time: 8898.360 ms
(35 rows)

EDIT 2:
Using select * from pg_prepared_xacts; and select * from pg_stat_activity; as suggested in an answer. The first statement does not show any rows, and for the second one I did not notice any old xact_start times, and this was done after previously (yesterday) running VACUUM FULL votes. Running VACUUM FULL votes unfortunately does not fix the problem.
Output of statements:
booky=# select * from pg_prepared_xacts;
 transaction | gid | prepared | owner | database
-------------+-----+----------+-------+----------
(0 rows)

booky=# select * from pg_stat_activity;
 datid  | datname | pid | usesysid | usename  | application_name | client_addr | client_hostname | client_port |         backend_start         |          xact_start           |          query_start          |         state_change          | wait_event_type |     wait_event      | state  | backend_xid | backend_xmin |              query              |         backend_type
--------+---------+-----+----------+----------+------------------+-------------+-----------------+-------------+-------------------------------+-------------------------------+-------------------------------+-------------------------------+-----------------+---------------------+--------+-------------+--------------+---------------------------------+------------------------------
        |         |  31 |          |          |                  |             |                 |             | 2020-04-05 08:41:47.959657+00 |                               |                               |                               | Activity        | AutoVacuumMain      |        |             |              |                                 | autovacuum launcher
        |         |  33 |       10 | postgres |                  |             |                 |             | 2020-04-05 08:41:47.959964+00 |                               |                               |                               | Activity        | LogicalLauncherMain |        |             |              |                                 | logical replication launcher
 169575 | booky   |  48 |       10 | postgres | psql             |             |                 |          -1 | 2020-04-05 10:05:20.847798+00 | 2020-04-05 10:07:47.534381+00 | 2020-04-05 10:07:47.534381+00 | 2020-04-05 10:07:47.534382+00 |                 |                     | active |             |     15265333 | select * from pg_stat_activity; | client backend
        |         |  29 |          |          |                  |             |                 |             | 2020-04-05 08:41:47.959346+00 |                               |                               |                               | Activity        | BgWriterHibernate   |        |             |              |                                 | background writer
        |         |  28 |          |          |                  |             |                 |             | 2020-04-05 08:41:47.959688+00 |                               |                               |                               | Activity        | CheckpointerMain    |        |             |              |                                 | checkpointer
        |         |  30 |          |          |                  |             |                 |             | 2020-04-05 08:41:47.959501+00 |                               |                               |                               | Activity        | WalWriterMain       |        |             |              |                                 | walwriter
(6 rows)

A:   ->  Index Only Scan using member_book on votes  (cost=0.43..66021.32 rows=3 width=8) (actual time=0.024..49.104 rows=3 loops=180)
         Index Cond: (book_id = books.id)
         Heap Fetches: 540

49.104 * 180 = 8839, which is substantially all of your time.  Most likely most of this time is going to IO to read random pages from the table (if you turn on track_io_timings and then do EXPLAIN (ANALYZE, BUFFERS) we would have a definitive answer to that).
If you vacuum "votes", and so get rid of the heap fetches, it would almost surely solve the problem.
   ->  Index Only Scan using member_book on votes  (cost=0.43..66021.32 rows=3 width=8) (actual time=0.018..48.187 rows=3 loops=180)
           Index Cond: (book_id = books.id)
           Heap Fetches: 540
           Buffers: shared hit=2390546

If this was done after the VACUUM was done, then you probably have some kind of long-running transaction being held open, which is preventing VACUUM from doing its job effectively.  Also, hitting 2,390,546 buffers to get 540 row seems incredibly outlandish.  Again, that could be due to some long-open transaction causing massive bloat in your index and/or table.
Does select * from pg_prepared_xacts; show any rows?  Does select * from pg_stat_activity show any old times for xact_start?  If neither of those, then can you do a VACUUM FULL votes and see if that fixes the problem?

A: Thanks to @Lennart, I've added an INDEX which seems to have fixed the issue. It went from around 8900 milliseconds all the way to 35 milliseconds, which is awesome
Index to be created:
CREATE INDEX IX1_VOTES ON VOTES (book_id, member_id)


Q: python csv delimiter doesn't work properly I try to write a python code to extract DVDL values from the input.  Here is the truncated input.
      A V E R A G E S   O V E R   50000 S T E P S

 NSTEP =    50000   TIME(PS) =     300.000  TEMP(K) =   300.05  PRESS =   -70.0
 Etot   =    -89575.9555  EKtot   =     23331.1725  EPtot      =   -112907.1281
 BOND   =       759.8213  ANGLE   =      2120.6039  DIHED      =      4231.4019
 1-4 NB =       940.8403  1-4 EEL =     12588.1950  VDWAALS    =     13690.9435
 EELEC  =   -147238.9339  EHBOND  =         0.0000  RESTRAINT  =         0.0000
 DV/DL  =        13.0462
 EKCMT  =     10212.3016  VIRIAL  =     10891.5181  VOLUME     =    416404.8626
                                                Density    =         0.9411
 Ewald error estimate:   0.6036E-04

      R M S  F L U C T U A T I O N S

 NSTEP =    50000   TIME(PS) =     300.000  TEMP(K) =     1.49  PRESS =   129.9
Etot   =       727.7890  EKtot   =       115.7534  EPtot      =       718.8344
BOND   =        23.1328  ANGLE   =        36.1180  DIHED      =        19.9971
1-4 NB =        12.7636  1-4 EEL =        37.3848  VDWAALS    =       145.7213
EELEC  =       739.4128  EHBOND  =         0.0000  RESTRAINT  =         0.0000
DV/DL  =         3.7510
EKCMT  =        76.6138  VIRIAL  =      1195.5824  VOLUME     =     43181.7604
                                                Density    =         0.0891
 Ewald error estimate:   0.4462E-04

Here is the script.  Basically we have a lot of DVDL in the input (not in the above truncated input) and we only want the last two.  So we read all of them into a list and only get the last two.  Finally, we write the last two DVDL in the list into a csv file. The desire output is
13.0462, 3.7510
However, the following script (python 2.7) will bring the output like this.  Could any guru enlighten?  Thanks.
13.0462""3.7510""
Here is the script:
import os
import csv

DVDL=[]
filename="input.out"
file=open(filename,'r')

with open("out.csv",'wb') as outfile: # define output name
    line=file.readlines()
    for a in line:
        if ' DV/DL  =' in a:
            DVDL.append(line[line.index(a)].split('        ')[1])  # Extract DVDL number

    print DVDL[-2:]        # We only need the last two DVDL
    yeeha="".join(str(a) for a in DVDL[-2:])
    print yeeha
    writer = csv.writer(outfile, delimiter=',',lineterminator='\n')#Output the list into a csv file called "outfile"
    writer.writerows(yeeha)

A: As the commenter who proposed an approach has not had the chance to outline some code for this, here's how I'd suggest doing it (edited to allow optionally signed floating point numbers with optional exponents, as suggested by an answer to Python regular expression that matches floating point numbers):
import re,sys

pat = re.compile("DV/DL += +([+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?)")
values = []
for line in open("input.out","r"):
    m = pat.search(line)
    if m:
        values.append(m.group(1))
outfile = open("out.csv","w")
outfile.write(",".join(values[-2:]))

Having run this script:
$ cat out.csv
13.0462,3.7510

I haven't used the csv module in this case because it isn't really necessary for a simple output file like this. However, adding the following lines to the script will use csv to write the same data into out1.csv:
import csv

writer = csv.writer(open("out1.csv","w"))
writer.writerow(values[-2:])


Q: Perl (opendir): Receiving "Can't use an undefined value as a symbol reference at line 46." I am trying to use opendir to open a directory. When ever this happens I get the error: "Can't use an undefined value as a symbol reference at line." From searching other questions this usually originates from trying to use a variable that is out of scope. From all that I can tell my variable that I am using for my directory location is in scope and my handler for opendir is defined in the function like all examples. Please help me figure out what is going wrong. Line 46 where it is claiming the error is at is double starred.
use File::Find;
use File::Copy;
use File::Path;

my @imagelocations = ('/some/location1','/some/location2');
my $destination = '/some/location';

foreach $a (@imagelocations)
{
    find (\&Move_Images, $a);
}

sub Move_Images
{
     my $file = $_;
     if (-e $file && $File::Find::dir eq $a && $file ne ".")
     {
        if (-M $file < 1)
        {
            my @folder = split(/_/, $file);
            my ($var1,$var2,$var3) = @folder[0,1,4];
            if (lc $var1 ne "manual" && lc $var1 ne "test")
            {
                if (-d ($File::Find::dir.'/'.$file))
                {
                    $var3 = substr ($var3,1,-2);
                    my $open = $File::Find::dir."/$file";
                    **opendir (my $dh, $open) or die "Can't open directory $!";**
                    my @files = readdir($dh);
                    ...


Q: How to fix unexpected token in ESLint? I install ESLint globally using the command npm install -g eslint on my Mac. It was successful installing, but when I run eslint -v this is the issue I encounter:
$ npm install -g eslint
path/to/bin/eslint -> path/to/lib/node_modules/eslint/bin/eslint.js
+ eslint@7.3.1
added 107 packages from 63 contributors in 4.823s

$ eslint -v
path/to/lib/node_modules/eslint/bin/eslint.js:93
        } catch {
                ^

SyntaxError: Unexpected token {
    at createScript (vm.js:80:10)
    at Object.runInThisContext (vm.js:139:10)
    at Module._compile (module.js:617:28)
    at Object.Module._extensions..js (module.js:664:10)
    at Module.load (module.js:566:32)
    at tryModuleLoad (module.js:506:12)
    at Function.Module._load (module.js:498:3)
    at Function.Module.runMain (module.js:694:10)
    at startup (bootstrap_node.js:204:16)
    at bootstrap_node.js:625:3

I would like to know what are the missing steps that cause this issue? I'm using Node.js v8.16.2 and NPM v6.4.1.

A: The error happens because } catch { is a relatively recent (ES2019) language feature called "optional catch binding"; prior to its introduction, binding the caught error (e.g. } catch (err) {) was required syntactically. Per node.green, you need at least Node 10 to have that language feature.
So why does this happen in ESLint? Per e.g. the release blog, version 7 has dropped support for Node 8; they're no longer testing against that version and more modern language features will be assumed to be supported.
To fix it, either:

*

*Upgrade Node (Node 8 is out of LTS, which is why ESLint dropped support); or

*npm install eslint@6 (with -g if you want to install globally) to use the older version of ESLint with Node 8 support.

A: In case it's helpful for anyone, I had a slightly different twist on the other answer. In my case, the error was happening during the Travis CI build process and causing it to fail. The solution in my case was to update my .travis.yml file to node_js: "16"


Q: IE11 emulates IE7 even though it's set to EDGE My website has the following settings:

But IE11 renders the page in IE7 mode:

This is on a machine with a fresh IE11 install, and it's the first time I'm visiting the website with the browser.
Any idea what could be wrong?

A: Does moving the X-UA-Compatible  tag to be immediately underneath the  tag make a difference?
See answer by neoswf:
X-UA-Compatible is set to IE=edge, but it still doesn't stop Compatibility Mode
Cheers,


Q: How to create read-only user in pgAdmin 4? Creating a read-only user in pgAdmin 4 is a little tricky.
Here is a guide on how I did it.
First of all a few words about the process.
The whole process is based on editing a schema (very simple and safe) for your DB, so this creates limitations for using the method for all the DBs you have unless you edit schemas for each DB (again, it is easy).
First, we have to open a main dialogue, select the target DB you need the read-only user for -> Schemas -> right mouse click on "public" schema -> Properties.

In the opened window go to "Default privileges" and click the "+" in the right corner.

*

*In the "Grantee" column enter: "pg_read_all_data",

*in "Privileges" column click on the field and you will see options. Enable only "Select".

On the rest tabs (Sequences, Functions, Types) you can do the same (Select or Usage).
Hit "Save".
In the left sidebar scroll down and find "Login/Group Roles". Click right button -> Create -> Login/Group Role.
OR if you have an existed user role you want to make read-only, click the right button on it and select "Properties".
In the opened window enter the name of the user, on the "Definition" tab enter a password, on the "Previliges" tab select "Can login" and "Inherit rights from the parent roles?"
In the "Membership" tab hit "+" in the "Member of" table and type "pg_read_all_data" into the "User/Role" column.

In the "Parameters" tab hit "+".
Select "role" in the "Name" column's dropdown,
type "pg_read_all_data" in the "Value" column.
In the "Database" column select the desired DB (where you have edited the schema in the previous steps).
Note, you can add more rows with the same settings for different databases (of course, if those DBs have edited schemas as shown above).

Click "Save".
Now you can log into your PhpPgAdmin (or psql or wherever you need) under this user and do only selects. A real read-only user role.

I hope it will help someone.

A: I don't have enough reputation to comment on your very helpful post, but wanted to add that the public schema by default gives full access to the PUBLIC role (implicit role that all users belong to).
So you would first need to revoke this access.
This can be done in pgAdmin in the Security tab of the schema properties dialog, or with the SQL command
REVOKE CREATE ON SCHEMA public FROM PUBLIC;

See also:

*

*Issue creating read-only user in PostgreSQL that results in user with greater permission with public schema

*PostgreSQL - Who or what is the "PUBLIC" role?


Q: Grouping rows with Groupby and converting date & time of rows of start date-time and end date- time columns I have a dataset looking like this:

Blast Hole East Coordinate North Coordinate Collar Theoritical Depth Tag Detector ID Date and Time Detection_Location Detection Date & Time
64 16745.42 107390.32 2634.45 15.95 385656531 23-08-2018 2:39:34 PM CV23 2018-09-08 14:18:17
61 16773.48 107382.6 2634.68 16.18 385760755 23-08-2018 2:38:32 PM CV23 2018-09-08 14:24:19
63 16755.07 107387.68 2634.58 16.08 385262370 23-08-2018 2:39:30 PM CV23 2018-09-08 14:12:42
105 16764.83 107347.67 2634.74 16.24 385742468 23-08-2018 2:41:29 PM CV22 2018-09-06 20:02:46
100 16752.74 107360.32 2634.33 15.83 385112050 23-08-2018 2:41:08 PM CV22 2018-09-06 20:15:42
99 16743.1 107362.96 2634.36 15.86 385087366 23-08-2018 2:41:05 PM CV22 2018-09-06 20:49:21
35 16747.75 107417.68 2635.9 17.4 385453358 23-08-2018 2:36:09 PM CV22 2018-09-23 05:47:44
5 16757.27 107452.4 2636 17.5 385662254 23-08-2018 2:35:03 PM CV22 2018-09-23 05:01:12
19 16770.89 107420.83 2634.81 16.31 385826979 23-08-2018 2:35:50 PM CV22 2018-09-23 05:52:54

I intended to group all the rows having 3 detections at one place ( in column Detection_location) in one hour.
I used the following code for grouping the rows falling in one hour per 3 detection:
df2 = df1.groupby([pd.Grouper(key = 'Detection Date & Time', freq = 'H'),
      df1.Detection_Location]).size().reset_index(name = 'Tags')

This code gave me a result like this:

I would rather like to have result in which each rows have start time when the first detection was there in that hour and when the last detection was seen and thus i would like to have a result like this:

This is the required output:

Detection Date & Time - Start  Detection Date & Time - End Detection_Location Tags
2018-09-06 20:02:46 2018-09-06 20:49:21 CV22 3
2018-09-08 14:12:42 2018-09-08 14:24:19 CV23 3
2018-09-23 05:01:12 2018-09-23 05:47:44 CV22 3

Can anyone suggest what else should i add in my group-by function to get this result.
Thanks

A: Check if this works for you. Inside the aggregate function, you can pass all the values that you want to capture.
df2 = (df.groupby([pd.Grouper(key = 'Detection Date & Time', freq = 'H'),df.Detection_Location],sort=False)['Detection Date & Time']
   .agg(['first','last','size'])).reset_index().rename(columns={"first": "Detection Date & Time - Start", "last": "Detection Date & Time - End", "size": "Tags"})


Q: Linking to iOS simulator binaries on OSX I was curious what would happen if I linked to an iOS simulator framework in a Mac app. So I copied UIKit to it's own folder (so the Framework search path wouldn't include all the iOS simulator framework, as like CoreFoundation is both on Mac and iOS but has different headers), and dragged it into the link section in Xcode. The error Xcode gave me was:

building for MacOSX, but linking against dylib built for iOS Simulator
  file '/Users/jonathan/Desktop/macuikit/UIKit.framework/UIKit' for
  architecture x86_64

Both architectures are x86_64, so how can it tell the framework is specifically for the iOS simulator, I removed all references to iOS in things like Info.plist, even tried deleted everything but the UIKit binary, but the same error came up. Is there something in the binary it self that tells the linker which platform it can run on, rather than just the architecture? I looked at the Mach-O header but there is only fields for CPU type and subtype, and neither has a value for the simulator as expected.

A: After a little bit of digging, it turns out that the platform on which the library can run on is indeed specified in the binary. In fact, you can edit the binary in your favorite Hex editor and make the linker skip this check entirely.
This information is not specified in the Mach-O header (as you have already realized). Instead, it is specified as a load command type. You can see the available types by digging through the LLVM sources. Specifically, the enum values LC_VERSION_MIN_MACOSX and LC_VERSION_MIN_IPHONEOS look interesting.
Now, find the offset for this in our binary. Open the same in MachOView (or any other editor/viewer or your choice) and note the offset:

Once the offset is noted, jump to the same in a Hex editor and update it. I modified LC_VERSION_MIN_IPHONEOS (25) to LC_VERSION_MIN_MACOSX (24)
Save the updates and try linking again. The error should go away. Of course, you will hit other issues when you try to actually run your example. Have fun with LLDB then :)


Q: Find all the combinations that return a particular value from a function This is a variation on finding all the combinations that add to a target, with two constraints:

*

*We have a limited set of numbers to work with.

*The numbers must result in the target number when fed into a separate function.

In this case, the limited set of numbers include 25, 50, 100, 200, 450, 700, 1100, 1800, 2300, 2900, 3900, 5000, 5900, 7200, 8400, etc.
And the function is to add the values together and then multiply by a number based on how many numbers we had:

*

*If 1 number, multiply by 1.

*If 2 numbers, multiply by 1.5

*If 3-6 numbers, multiply by 2

*If 7-10 numbers, multiply by 2.5

*If >10 numbers, multiply by 3

Examples:
[50, 50, 50] => 300
[100, 100] => 300
Target numbers include 300, 600, 900, 1500, 3000, 3600, 4400, 5600, 6400, 7600, 9600, etc.
My intuition is that this can't be done recursively, because each step doesn't know the multiplier that will eventually be applied.

A: Here's a recursive example in JavaScript that seems to answer the requirements:

function getNextM(m, n){
  if (n == 1)
    return 1.5;
  if (n == 2)
    return 2;
  if (n == 6)
    return 2.5;
  if (n == 10)
    return 3;

  return m;
}

function g(A, t, i, sum, m, comb){
  if (sum * m == t)
    return [comb];

  if (sum * m > t || i == A.length)
    return [];

  let n = comb.length;

  let result = g(A, t, i + 1, sum, m, comb);

  const max = Math.ceil((t - sum) / A[i]);

  let _comb = comb;

  for (let j=1; j<=max; j++){
    _comb = _comb.slice().concat(A[i]);
    sum = sum + A[i];
    m = getNextM(m, n);
    n = n + 1;
    result = result.concat(g(
      A, t, i + 1, sum, m, _comb));
  }

  return result;
}

function f(A, t){
  return g(A, t, 0, 0, 1, []);
}

var A = [25, 50, 100, 200, 450, 700, 1100, 1800, 2300, 2900, 3900, 5000, 5900, 7200, 8400];

var t = 300;

console.log(JSON.stringify(f(A, t)));

A: I wrote a small script in Python3 that may solve this problem.
multiply_factor = [0,1,1.5,2,2,2,2,2.5,2.5,2.5,2.5,3]
def get_multiply_factor(x):
    if x< len(multiply_factor):
        return multiply_factor[x]
    else:
        return multiply_factor[-1]

numbers = [25, 50, 100, 200, 450, 700, 1100, 1800, 2300, 2900, 3900, 5000, 5900, 7200, 8400]
count_of_numbers = len(numbers)

# dp[Count_of_Numbers]
dp = [[] for j in range(count_of_numbers+1)]

#Stores multiplying_factor * sum of numbers for each unique Count, See further
sum_found =[set() for j in range(count_of_numbers+1)]

# Stores Results in Unordered_Map for answering Queries
master_record={}

#Initializing Memoization Array
for num in numbers:
    dp[1].append(([num],num*get_multiply_factor(1)))

for count in range(2,count_of_numbers+1):   # Count of Numbers
    for num in numbers:
        for previous_val in dp[count-1]:
            old_factor = get_multiply_factor(count-1)   #Old Factor for Count Of Numbers = count-1
            new_factor = get_multiply_factor(count)     #New Factor for Count Of Numbers = count

            # Multiplying Factor does not change
            if old_factor==new_factor:
                # Scale Current Number and add
                new_sum = num*new_factor+previous_val[1]
            else:
                #Otherwise, We rescale the entire sum
                new_sum = (num+previous_val[1]//old_factor)*new_factor

            # Check if NEW SUM has already been found for this Count of Numbers
            if new_sum not in sum_found[count]:
                # Add to current Count Array
                dp[count].append(([num]+previous_val[0],new_sum))
                # Mark New Sum as Found for Count Of Numbers = count
                sum_found[count].add(new_sum)
                if new_sum not in master_record:
                    # Store Seected Numbers in Master Record for Answering Queries
                    master_record[new_sum] = dp[count][-1][0]

# for i in dp:
#   print(i)
print(master_record[1300])
print(master_record[300])
print(master_record[2300])
print(master_record[7950])
print(master_record[350700.0])

Output :-
[100, 100, 450]
[100, 100]
[25, 25, 1100]
[25, 50, 3900]
[1800, 5900, 8400, 8400, 8400, 8400, 8400, 8400, 8400, 8400, 8400, 8400, 8400, 8400, 8400]
[Finished in 0.3s]

My Algo in a nutshell.
Iterate over Count[2, Limit], I've considered limit = Number of Elements
    Iterate over List of Numbers
        Iterate over Sums found for previous count.
            Calculate New Sum,
            If it does not exist for current count, update.

I am assuming that the number of queries will be large so that memorization pays off. The upper limit for count may break my code as the possibilities may grow exponentially.


Q: Multiple widget changes based on one button event in Kivy I'm trying to build this application which contains multiple buttons. I can bind each button event to a callback but I am not able to change the state (namely the label) of any other button except for the one that fired the event. Does anyone know how to do this?

A: All you need is a reference to the other button, then you can do other_button.text = 'whatever'.
The way to do this depends on how you've constructed the program. For instance, if you constructed in the program in kv language, you can give your buttons ids with id: some_id and refer to them in the callback with stuff like on_press: some_id.do_something().
In pure python, you could keep references to the button in the parent class when you create them (e.g. self.button = Button()) so that the callback can reference self.button to change it. Obviously that's a trivial example, but the general idea lets you accomplish anything you want.

A: Probably not the official way, but try out the following code. It will change the text property of the buttons...
Ezs.kv file:
 #:kivy 1.8.0

<Ezs>:
    BoxLayout:
        orientation: 'vertical'
        padding: 0
        spacing: 6

        #choose
        Button:
            id: btn_1
            text: 'text before'
            on_press: btn_2.text = 'Whatever'
            on_release: self.text = 'Who-Hoo'
        #choose
        Button:
            id: btn_2
            text: 'Press this'
            on_release: self.text = 'HEEYY'
            on_press: btn_1.text = 'text after'

.py file:
class Ezs(BoxLayout):

class EzsApp(App):

    def build(self):
        return Ezs

if __name__ == '__main__':
    EzsApp().run()


Q: C++ CLI error C3767: candidate function(s) not accessible I'm new to C++ CLI coming from unmanaged C++ world.
I'm getting this error:
candidate function(s) not accessible

when I pass a std::string as part of the method argument.
Here's the exact code:
Lib Project (compiled as .dll project)
//Lib.h
#pragma once

public ref class Lib
{
public:
  Lib(void);

public:
  void Extract( std::string& data_ );
};

//Lib.cpp
#include "Lib.h"

Lib::Lib(void)
{
}

void Lib::Extract( std::string& data_ )
{
  data_.empty();
}

LibTest Project (compiled as application.exe)
// LibTest.h
#pragma once

ref class LibTest
{
public:
  LibTest(void);
};

// LibTest.cpp
#include "LibTest.h"

LibTest::LibTest(void)
{
  Lib^ lib = gcnew Lib;
  lib->Extract( std::string("test") );
}

int main()
{
  return 0;
}

Compiler Error:
1>------ Build started: Project: LibTest, Configuration: Debug Win32 ------
1>Compiling...
1>LibTest.cpp
1>.\LibTest.cpp(7) : error C3767: 'Lib::Extract': candidate function(s) not accessible

A: if you simply must access the internal methods another work around would be making the projects as Friend Assemblies like that:
//Lib Project
#pragma once

//define LibTest as friend assembly which will allow access to internal members
using namespace System;
using namespace System::Runtime::CompilerServices;
[assembly:InternalsVisibleTo("LibTest")];

public ref class Lib
{
 public:
  Lib(void);

 public:
  void Extract( std::string& data_ );
};

//LibTest Project
#pragma once

#using <Lib.dll> as_friend

ref class LibTest
{
  public:
    LibTest(void);
};

A: The problem is that std::string will compile as a internal (non public) type. This is actually a change in VS 2005+:
http://msdn.microsoft.com/en-us/library/ms177253(VS.80).aspx:
Native types are private by default outside the assembly
Native types now will not be visible outside the assembly by default. For more information on type visibility outside the assembly, see Type Visibility. This change was primarily driven by the needs of developers using other, case-insensitive languages, when referencing metadata authored in Visual C++.
You can confirm this using Ildasm or reflector, you will see that your extract method is compiled as:
public unsafe void Extract(basic_string<char,std::char_traits<char>,std::allocator<char> >* modopt(IsImplicitlyDereferenced) data_)

with basic_string being compiled as:
[StructLayout(LayoutKind.Sequential, Size=0x20), NativeCppClass, MiscellaneousBits(0x40), DebugInfoInPDB, UnsafeValueType]
internal struct basic_string<char,std::char_traits<char>,std::allocator<char> >

Note the internal.
Unfortunately you are then unable to call a such a method from a different assembly.
There is a workaround available in some cases: You can force the native type to be compiled as public using the make_public pragma.
e.g. if you have a method Extract2 such as:
void Extract2( std::exception& data_ );

you can force std::exception to be compiled as public by including this pragma statement beforehand:
#pragma make_public(std::exception)

this method is now callable across assemblies.
Unfortunately make_public does not work for templated types (std::string just being a typedef for basic_string<>)
I don't think there is anything you can do to make it work. I recommend using the managed type System::String^ instead in all your public API. This also ensures that your library is easily callable from other CLR languages such as c#

A: In addition to the solutions described above, one can subclass the templated type to obtain a non-templated type, and include its definition in both projects, thus overcoming some of the problems mentioned above.


Q: using sass with compass - 404 css not found I'm using the followig config for compass with grunt:
   compass: {
    options: {
    sassDir: '<%= yeoman.app %>/styles',
    cssDir: '.tmp/styles',
    imagesDir: '<%= yeoman.app %>/images',
    javascriptsDir: '<%= yeoman.app %>/scripts',
    fontsDir: '<%= yeoman.app %>/styles/fonts',
    importPath: 'app/components',
    relativeAssets: false
  },
  dist: {},
  server: {
    options: {
      debugInfo: true
    }
  }
},

and I see that the sass is getting compiled since it shows in the .tmp/styles folder
but for some reason when I call the css files from the <%= yeoman.app %>/styles filder it's not found


Q: Javascript - change r attribute of circle wrapped in #shadow-root My html tree looks as follows:
<svg id="floating-button-svg" style={{fill: `${floatingButton.backgroundColor}`}}>
  <use id="use-tag" href="
     <svg>
       <circle id="semi-circle" class="cls-1" cx="500" cy="500" r="50"/>
     </svg>"
  />
</svg>

Afer compilation the href dissolves to data:image/svg+xml;base64,PCEtLSA8P3htbCB2ZXJzaW9uPSIxLjAiIGVuY29kaW5nPSJ1dGYtOCI/Pgo8c3ZnIHZlcnNpb249IjEuMCIgeD0iMHB4IiB5PSIwcHgiIHdpZHRoPSIxMDAlIiBoZWlnaHQ9IjEwMCUiIHZpZXdCb3g9IjAgMCAxMDAwIDUwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayI+CjxjaXJjbGUgaWQ9InNlbWktY2lyY2xlIiBjeD0iNTAwIiBjeT0iNTAwIiByPSI1MDAiLz4KPC9zdmc+IC0tPgoKCjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB3aWR0aD0iMTAwMCIgaGVpZ2h0PSI1MDAiIHZpZXdCb3g9IjAgMCAxMDAwIDUwMCI+CiAgPGRlZnM+CiAgICA8c3R5bGU+CiAgICAgIC5jbHMtMSB7CiAgICAgICAgZmlsbDogIzAwMDsKICAgICAgfQogICAgPC9zdHlsZT4KICA8L2RlZnM+CiAgPGNpcmNsZSBpZD0ic2VtaS1jaXJjbGUiIGNsYXNzPSJjbHMtMSIgY3g9IjUwMCIgY3k9IjUwMCIgcj0iNTAiLz4KPC9zdmc+Cgo=#semi-circle
If anyone wants to test it, please replace the value in the href above with this link.
I am trying to change the radius of the circle through
document.getElementById('use-tag').setAttribute('r', '25')

but instead it only gives use an attribute of r=25. Is there any way I can change the radius of the circle? I have tried to fetch it using
 getElementById

but it just gives me null (I'm assuming because it's wrapped in a shadow root).
edit: The gist of the problem here I believe is that I am trying to change the attributes of a closed shadow root which is impossible to achieve. So can someone please tell me why am I get a closed root instead of an open one? And how can I get an open one?
edit: Here is a demo of this situation: https://codesandbox.io/embed/smoosh-sun-nnevd?fontsize=14&hidenavigation=1&theme=dark

A: Since you have direct access to circle with id semi-circle, you can update it as the below snippet.
The snippet is running under a setTimeout to show the difference.

setTimeout(function() {
  var circle = document.getElementById('semi-circle');
  circle.setAttribute('r', 60)
}, 3000)
<svg id="floating-button-svg" height="100" width="100">
  <circle id="semi-circle" class="cls-1"  cx="50" cy="50" r="40" fill="red" />
</svg>

You can also do it in another way, check the snippet

setTimeout(function() {
  var circle = document.getElementById('floating-button-svg');
  circle.firstElementChild.setAttribute('r', 60)
}, 1500)
<svg id="floating-button-svg" height="400" width="400">
      <circle id="semi-circle" class="cls-1"  cx="80" cy="80" r="40" fill="red" />
</svg>


Q: How to replace this componentWillReceiveProps? I have a login and register component with forms that were created a while ago before these methods were deprecated, I've been looking around but cannot seem to find a solution, how would I go about refactoring this to using getDerivedStateFromProps?
  componentWillReceiveProps(nextProps) {
    if (nextProps.auth.isAuthenticated) {
      this.props.history.push("/dashboard")
    }

    if (nextProps.errors) {
      this.setState({
        errors: nextProps.errors
      });
    }

A: Since you're using componentWillReceiveProps to keep a local state in sync with props you have two alternatives:
Declare your initial state based on props and use componentDidUpdate to ensure props synchronicity
class Component extends React.Component{
    state = { foo : this.props.foo }

    componentDidUpdate(prevProps){
        if(this.props.foo !== prevProps.foo)
            this.setState({ foo : prevProps.foo })
    }
}

This is actually triggering an extra render everytime, if you have some local state that is always equal to some prop you can use the prop directly instead.
Use getDerivedStateFromProps to update the state based on a prop change, but keep in mind that you probably don't need to use it
class Component extends React.Component{
    static getDerivedStateFromProps(props){
        return { foo : props.foo }
    }
}

A: The answer to the question you asked is probably not going to be satisfactory. :-) The answer is that if you really need to derive state from props (you probably don't, just use props.errors directly in render), you do it with the newer getDerivedStateFromProps static method that accepts props and state and (potentially) returns a state update to apply:
static getDerivedStateFromProps(props, state) {
    return props.errors ? {errors: props.errors} : null;
}

or with destructuring and without the unused state parameter:
static getDerivedStateFromProps(({errors})) {
    return errors ? {errors} : null;
}

But, you're saying "But that doesn't do the authentication thing...?" That's right, it doesn't, because that componentWillReceiveProps shouldn't have, either, it violates the rule props are read-only. So that part shouldn't be there. Instead, if that entry in props.history is supposed to be there, it should be put there by the parent component.


Q: Finding value of the limit: $ \lim_{t \to 0} \frac{\varphi(1+t) - \varphi(t)}{t}$ Let $$\varphi(x) = e^{-x} + \frac{x}{1!} \cdot e^{-2x} + \frac{3x^{2}}{2!}\cdot e^{-3x} + \frac{4^{2} \cdot x^{3}}{3!} \cdot e^{-4x} + \cdots$$
Then what is the value of: $$ \displaystyle\lim_{t \to 0} \frac{\varphi(1+t) - \varphi(t)}{t}$$
I am not getting any idea as to how to proceed for this problem. I tried summing up the expression but no avail. I also tried differentiating $\varphi(x)$ since the limit quantity which we require seems to involve derivative but again i couldn't find any pattern. Any ideas on how to solve this problem.

A: The function $\varphi(x)$ can be written as
$$
\begin{eqnarray}
\varphi(x)
  &=& \frac{1}{x} \sum_{n=1}^{\infty} \frac{n^{n-1}}{n!}\left(xe^{-x}\right)^{n} \\
  &=& -\frac{1}{x} \sum_{n=1}^{\infty} \frac{(-n)^{n-1}}{n!}\left(-xe^{-x}\right)^{n} \\
  &=& -\frac{1}{x} W_0\left(-xe^{-x}\right),
\end{eqnarray}
$$
where $W_0$ is the Lambert W-function's main branch.  For sufficiently small $y$, the definition of the W-function ensures that $W_0(ye^y)=y$, so for small $t$,
$$
\begin{eqnarray}
\varphi(t)
  &=& -\frac{1}{t}W_0\left(-te^{-t}\right) \\
  &=& -\frac{1}{t}(-t) \\
  &=& 1.
\end{eqnarray}
$$
In fact this equality holds for all $0 \le t < 1$.  For values slightly larger than $1$, we use
$$
-(1+t)e^{-(1+t)} = \frac{-(1+t)}{1+t+\frac{1}{2}t^2+O(t^3)} = -1 + \frac{1}{2}t^2+O(t^3) = -(1-t)e^{-(1-t)},
$$
so
$$
\begin{eqnarray}
\varphi(1+t) &=& -\frac{1}{1+t}W_0(-(1+t)e^{-(1+t)}) \\ &\approx& -\frac{1}{1+t}W_0(-(1-t)e^{-(1-t)}) \\ &=& \frac{1-t}{1+t} \\ &=& 1 - 2t + O(t^2).
\end{eqnarray}
$$
The desired limit, then, is
$$
\lim_{t\rightarrow 0}\frac{\varphi(1+t) - \varphi(t)}{t} = \lim_{t\rightarrow 0}\frac{(1-2t) - 1}{t} = -2.
$$

A: Hmm, using Pari/GP, I just tried to find the coefficients of $ \varphi (t) $
polcoeffs(exp(-x)*sumalt(k=0,exp(-k*x)*x^k/k!*(k+1)^(k-1)*1.0))

(where the polcoeffs-function just retrieves the whole vector of coefficients up to the defined series-precision and I used x instead of t )
The result of this is an (arbitrary near) approximation to the formal powerseries $ \varphi(t) = 1.0 $ So it may be useful to analyze the approximation of that powerseries to the constant in order to evaluate  your limit-formula.

[update] If one expands the powerseries for $e^{- k x}$ and collect coefficients at like powers of x then indeed all coefficients at a certain power of x sum to zero, thus vanish (at least heuristically up to $x^{64}$, I did not do final analysis) . Then all derivatives are also zero and even the L'Hospital-rule is of no use here. However, I don't know whether there could be some special reason that this expansion into powerseries might not be feasible/allowed because the result is an infinite sum of formal powerseries. [end update]

[update 2]
$ \varphi(x)=e^{-x}+xe^{-2x}\frac1{1!}
+x^2e^{-3x}\frac3{2!}
+x^3e^{-4x}\frac{4^2}{3!} + \ldots
  $
$\begin{array} {rrrr}
\varphi(x)= ( &  1 & -x & + \frac{x^2}{2!}&+ \frac{x^3}{3!} & + \ldots )\\
+ \frac{x}{1!}(& 1 & -2x & + \frac{2^2x^2}{2!}&+ \frac{2^3x^3}{3!} & + \ldots ) \\
+ \frac{3x^2}{2!}(& 1 & -3x & + \frac{3^2x^2}{2!}&+ \frac{3^3x^3}{3!} & + \ldots ) \\
+ \ldots \\
\end{array} $
Collecting equal powers of x means to add coefficients along the antidiagonal so
$\begin{array} {rrrr}
\varphi(x)= 1 \\
- x (&\frac{1}{1!}& - \frac{1}{1!} ) \\
+ x^2 (&\frac{1}{2!}& - \frac{2}{1!}& + \frac{3^1}{2!}) \\
- x^3 (&\frac{1}{3!}& - \frac{2^2}{2!}& + \frac{3^2}{2!}& - \frac{4^2}{3!}) \\
+ \ldots \\
\end{array} $
All the parentheses seem to form binomially weighted sums of like powers with alternating signs which are known to evaluate to zero, so the coefficients at each power of x should be zero and if this is so, the taylorseries is then $\varphi(x)=1 $
[end update 2]


Q: For the torus to rotate 180 degrees around the East-West symmetry axis, what happens? (Suppose to ignore the deformed friction and torus when rotating)


Q: Axios import breaks rest of javascript file I'm using encore and yarn to set up my javascript and css in a symfony project. I want to use axios so I use:
yarn add axios

then I add this code to app.js
import '../css/app.scss';
import axios from "axios";

console.log('test');

axios({
    url: 'https://dog.ceo/api/breeds/list/all',
    method: 'get',
    data: {
        foo: 'bar'
    }
});

Then yarn watch picks up the modifications and compiles it to this:
(window["webpackJsonp"] = window["webpackJsonp"] || []).push([["app"],{

/***/ "./assets/css/app.scss":
/*!*****************************!*\
  !*** ./assets/css/app.scss ***!
  \*****************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

// extracted by mini-css-extract-plugin

/***/ }),

/***/ "./assets/js/app.js":
/*!**************************!*\
  !*** ./assets/js/app.js ***!
  \**************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _css_app_scss__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../css/app.scss */ "./assets/css/app.scss");
/* harmony import */ var _css_app_scss__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_app_scss__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! axios */ "./node_modules/axios/index.js");
/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(axios__WEBPACK_IMPORTED_MODULE_1__);

console.log('test');
axios__WEBPACK_IMPORTED_MODULE_1___default()({
  url: 'https://dog.ceo/api/breeds/list/all',
  method: 'get',
  data: {
    foo: 'bar'
  }
});

/***/ })

},[["./assets/js/app.js","runtime","vendors~app~normalization"]]]);

When I remove the import of Axios the console.log('test') runs but when I add the import it won't. So the import breaks the other code.
Could someone explain how I import axios without trouble?


Q: Css counter for list I am trying to use the counter increment in css on my ordered list but its not working
This is what I want to display:
1. Acknowledgements
   1.1 blah, blah ....
   1.2 blah, blah ....
   1.3 blah, blah ....

2. Risk Statement
   2.1 blah, blah ....
   2.2 blah, blah ....
   2.3 blah, blah ....

3. License
   3.1 blah, blah ....
   3.2 blah, blah ....
   3.3 blah, blah ....

But this s what is happening... http://jsfiddle.net/XQKcy/

A: Demo Fiddle
You were very close:
body {
    counter-reset: listCounter;
}
ol {
    counter-increment: listCounter;
    counter-reset: itemCounter;
    list-style:none;
}
li{
    counter-increment: itemCounter;
}
li:before {
    content: counter(listCounter) "." counter(itemCounter);
    left:10px;
    position:absolute;
}


Q: Global var vs Shared Instance swift What is the difference between global variable and shared instance in Swift? what are their respective field of use? Could anyone clarify their concept based upon Swift.

A: A global variable is a variable that is declared at the top level in a file. So if we had a class called Bar, you could store a reference to an instance of Bar in a global variable like this:
var bar = Bar()

You would then be able to access the instance from anywhere, like this:
bar
bar.foo()

A shared instance, or singleton, looks like this:
class Bar {
    static var shared = Bar()
    private init() {}
    func foo() {}
}

Then you can access the shared instance, still from anywhere in the module, like this:
Bar.shared
Bar.shared.foo()

However, one of the most important differences between the two (apart from the fact that global variables are just generally discouraged) is that the singleton pattern restricts you from creating other instances of Bar. In the first example, you could just create more global variables:
var bar2 = Bar()
var bar3 = Bar()

However, using a singleton (shared instance), the initialiser is private, so trying to do this...
var baaar = Bar()

...results in this:

'Bar' initializer is inaccessible due to 'private' protection level

That's a good thing, because the point of a singleton is that there is a single shared instance. Now the only way you can access an instance of Bar is through Bar.shared. It's important to remember to add the private init() in the class, and not add any other initialisers, though, or that won't any longer be enforced.
If you want more information about this, there's a great article by KrakenDev here.

A: Singleton (sharing instance)
Ensure that only one instance of a singleton object is created & It's provide a globally accessible through shared instance of an object that could be shared even across an app.
The dispatch_once function, which executes a block once and only once for the lifetime of an app.
Global variable
Apple documentation says Global variables are variables that are defined outside of any function, method, closure, or type context.


Q: How to set layout with XML in View for BaseAdapter getView() method The following Java code (from https://www.intertech.com/Blog/android-adapters-adapterviews/) is from getView(), a method implementation from a Android Adapter class, and it builds a View in Java to populate items on a List. I get how it works, but the same page says it can be built using an XML file, which makes sense to me, but I'm unable to find any examples. I understand how to use XML resource files to set Activity layout using setContentView(). But how would I invoke an XML resource file to build the View in the getView() method?
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if (convertView == null) {
        Context context = parent.getContext();
        LinearLayout view = new LinearLayout(context);
        view.setOrientation(LinearLayout.HORIZONTAL);
        view.addView(new CheckBox(context));
        TextView nameTextView = new TextView(context);
        nameTextView.setText(courses.get(position).getName());
        nameTextView.setPadding(0, 0, 10, 0);
        view.addView(nameTextView);
        TextView parTextView = new TextView(context);
        parTextView.setText(Integer.toString(courses.get(position).getPar()));
        view.addView(parTextView);
        return view;
    }
    return convertView;
}

A: like this
item_test.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        tools:text="name" />
</LinearLayout>

adapter
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    Holder holder; // use holder
    if (convertView == null) {
        convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_test, parent, false);
        holder = new Holder(convertView);
        convertView.setTag(holder);
    } else {
        holder = (Holder) convertView.getTag();
    }
    holder.name.setText("name");
    return convertView;
}

public class Holder {
    private TextView name;

    public Holder(View view) {
        name = view.findViewById(R.id.name);
    }
}


Q: project using moleculer-sentry example I have been trying to use the moleculer-sentry mixing in a moleculer project. But it is not working.
Does someone have an example project using this mixing?
Also i have been searching answers in internet, but nothing.


Q: How Javascript asyc and await working in this particular code? I have implemented an async function which creates an XHR object inside a Promise, requests a data from the server and fulfills the Promise with the response received from the server
async function playWordsAudio(id, type, check=false){

    let file_namePromise = new Promise(function (onSuccess, onFailure){
        var xhttp = new XMLHttpRequest();
        xhttp.onload = function(){
            if(this.readyState == 4 && this.status == 200){
                if(this.responseText !== "No Data"){
                    file_name = this.responseText;
                    if(check == false){
                        audio = new Audio('assets/uploads/wav/' + file_name);
                        audio.play();
                    }else{
                        onSuccess(file_name);
                    }
                }else{
                    if(check){
                        onSuccess('Not Found');
                    }
                }
            }
        };

        xhttp.open("GET", "scripts/get_word_audio.php?id=" + id + "&type=" + type, true);
        xhttp.send();
    });

    let resultant = await file_namePromise;

    if(check){
        return resultant;
    }
}

Later I have defined another function which calls the async function shown above
function modify_object(id, type, obj){
    result = playWordsAudio(id, type, true);
    result.then(function(value){
        if(value == "Not Found"){
            obj.classList.remove('fa-play');
        }
    });
}

Later in the implementation I also call the modify_object function and pass it an object for modification as described in the function.
modify_object(id, type, plays[i]);

In the async function I have created a Promise, on success I pass it the file_name received from the XHR response or else I pass it 'Not Found'.
Here I am confused on how the await part works inside the asyc function.
It returns the resultant to the caller of the async function which is
result = playWordsAudio(id, type, true);

If so, what does the onSuccess method in the Promise do
let file_namePromise = new Promise(function (onSuccess, onFailure){
/*
    Some Codes
*/

onSuccess(file_name);

/*
    Some more code
*/

onSuccess('Not Found);

/*
    Rest of the Code
*/
}

As I have checked by commenting out the return statement after the await statement
if(check){
//    return resultant;
}

The Promise is not fulfilled.
How does each part of the implementation work as described above?


Q: Convert ts object to data.frame and keep row- and colnames I want to convert a ts (i.e. timeseries) R object to a data.frame. The names of rows and columns of the ts object should be retained.
Consider the AirPassengers data set:
data(AirPassengers)

I could convert this ts object to a data.frame as follows:
AirPassengers <- data.frame(matrix(as.numeric(AirPassengers), ncol = 12, byrow = TRUE))
colnames(AirPassengers) <- c("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
rownames(AirPassengers) <- 1949:1960

However, this seems to be way too complicated. Surprisingly, a google search didn't show a simpler solution.
Question: Is there a simple solution how to convert ts objects to a data.frame without losing colnames and rownames?

A: The underlying issue is that the output of print for a time series object is quite heavily processed by .preformat.ts. If you want to convert it to a data frame that is visually similar to the print results this should do:
df <- data.frame(.preformat.ts(datasets::AirPassengers), stringsAsFactors = FALSE)

Note that this will produce characters (as that is how .preformat.ts works), so be careful with the use (not sure what is the purpose of the conversion?).


Q: Where does setup.py install console scripts to? When I set up my package using setup.py to have a console script entry point, pip install -e . creates a cli exe in the C:\Users\...\anaconda3\envs\envname\Scripts\foo.exe.
However on a separate computer the python executable is the one from the Windows Store:
C:\Users\...\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.10_qbz5n6khra8p0\python.exe
This doesn't set the PATH environment variable correctly to make .exes in the Scripts folder callable from the command line, so I need the full path to the .exe to call it.
Anyway I want to find the location of foo.exe on this second computer (which I don't have access to), is there a command I can instruct the second computer to run which will tell me where a console script will be located for that given sys.executable? I.e. for my computer, I expect it to print C:\Users\...\anaconda3\envs\envname\Scripts.

FWIW, this is my setup.cfg:
[options]
py_modules = xml2csv
python_requires = >=3.10

[options.entry_points]
console_scripts =
    xml2csv=xml2csv:main


Q: Using the button tag, can I customize the button? I want to use a custom button image that I drew up for my application, but doing so I need to use different images for the button being focused and another for it being pressed.
I came across the selector tags but for some reason it doesn't like it. Eclipse complains about a 'broken rendering library'. The error I get is this:
Broken rendering library; unsupported DPI. Try using the SDK manager to get updated.

And I have, I've updated every API past 10. If it matters, my target API is 15 and my compile API is 17.
If I can't get this working, can I simply use the Button tag and maybe change it in the Java src code or something?

A: use a custom layout like this
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@drawable/pressed"></item>

    <item android:state_focused="true" android:drawable="@drawable/focus"></item>

    <item android:drawable="@drawable/normal"></item>
</selector>

Also note that the the selector should be defined in this particular way else they will give problem .i.e.
1)state_pressed
2)state_focused ( work only if you scroll to that button using the hardware key)
3)drawable i.e. normal

If you changed the ordering of the selector then it won't work. One easy way to remember it is visualizing a qwerty phone - first i saw the button (normal), then moved to that particular button using arrow keys (state_focused), then i pressed that button (state_pressed). Now write them backwards.

A: Instead of button,create ImageView and do necessary things on click of the image.
    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="Method_Name"
        android:src="@drawable/selector" >
    </ImageView>

Also inorder to give different images on click and focus,create selector.xml in drawable folder and set background of imageview as selector file.
selector.xml
    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android" >

     <item android:drawable="@drawable/image1"  android:state_focussed="true" />
     <!-- Inactive tab -->
    <item android:drawable="@drawable/image2"  android:state_pressed="true" />
     <!-- Pressed tab -->

     </selector>

Hope this will help you!


Q: How to show button when adding fragment? Bottom button(234) is not showing after adding fragment. I don't want to resize my fragment size.

Home_Fragment.xml This is the main Fragment page. It also have profile Fragment. From Profile Fragment we are calling next fragment that is hiding bottom button (TV_Chat button name)
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white">

    <!-- View pager to swipe views -->
    <Button
        android:id="@+id/button3"
        android:layout_width="125dp"
        android:layout_height="59dp"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="0dp"
        android:background="@color/white"
        android:text="" />

    <com.medyc.us.customViews.CustomViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/tabLayout"
        android:background="@color/light_background"
        />

    <Button
        android:id="@+id/tv_chat"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:background="@drawable/circle_blue_gradient"
        android:text="234"
        android:gravity="center"
        android:textSize="@dimen/twenty_sp"
        android:textColor="@color/white"
        android:textStyle="bold"
        android:visibility="visible"
        android:fontFamily="@font/helvetica"
        android:layout_centerHorizontal="true"
        android:layout_alignBottom="@+id/tabLayout"
        android:layout_marginBottom="@dimen/thirty_dp"
        />
    <!-- our tablayout to display tabs  -->
    <android.support.design.widget.TabLayout
        android:id="@+id/tabLayout"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_alignParentBottom="true"
        app:tabIndicatorHeight="0dp"
        />

    <View
        android:id="@+id/bottomview"
        android:layout_width="match_parent"
        android:layout_height="43dp"
        android:layout_alignParentBottom="true"

        android:layout_alignParentStart="true"
        android:layout_marginBottom="50dp" />

</RelativeLayout>


Q: ASP.NET/GridView: Using only a subset of the data fields in the table I have a list of objects called Activity and I want to display the date, type and notes for each and every one of these activities. This is the code I'm using.
<asp:GridView ID="gvTable" runat="server" AllowSorting="true" ShowHeader="true">
  <Columns>
    <asp:BoundField DataField="ActivityDate" HeaderText="Date"
      HeaderStyle-CssClass="date" />
    <asp:BoundField DataField="ActivityType" HeaderText="Type" />
    <asp:BoundField DataField="ActivityNotes" HeaderText="Notes" />
  </Columns>
  <PagerSettings Position="Bottom" Mode="NextPrevious" PageButtonCount="5"
    PreviousPageText="Older activities" NextPageText="Newer activities" />
</asp:GridView>

However, all of the attributes of each object is displayed in the header. How can I force it to display only the columns that I want to use?

A: gvTable.AutoGenerateColumns = false
or
<asp:GridView ID="gvTable" runat="server" AutoGenerateColumns="False" AllowSorting="true" ShowHeader="true">

should do the trick.

A: Set the attribute on your gridview:
AutoGenerateColumns="false"

A: You need to set the AutoGenerateColumns property on the grid to false.

A: Have you tried AutoGenerateColumns="false" in the gridview?


Q: iOS Build Error: missing file Icon102.png I have a Xamarin Forms App running on Android and iOS. Everything works fine on a Simulator and on lokal devices.
When I push the Buid to AppCenter, the Android Version gets build without a problem, but the iOS Build alsways fails with the following error:
(_CoreCompileImageAssets target) ->   /Users/runner/runners/2.165.1/work/1/s/O365Info/O365Info.iOS/Assets.xcassets/AppIcon.appiconset/Icon1024.png : error : File not found: /Users/runner/runners/2.165.1/work/1/s/O365Info/O365Info.iOS/Assets.xcassets/AppIcon.appiconset/Icon1024.png [/Users/runner/runners/2.165.1/work/1/s/O365Info/O365Info.iOS/O365Info.iOS.csproj]
24 Warning(s)
1 Error(s)

Time Elapsed 00:01:01.73
[error]Xamarin.iOS task failed with error Error: /Library/Frameworks/Mono.framework/Versions/6_6_1/bin/msbuild failed with return code: 1. For guidance on setting up the build definition, see https://go.microsoft.com/fwlink/?LinkId=760847.
[section]Finishing: Build Xamarin.iOS solution.
In the first builds I didn't even had a Iconset called AppIcon.appiconset (my Iconset was named appiconset1) and the whole project didn't include a file named "Icon1024.png".
I then renamed my Iconset to appioconset and included a file named "Icon1024.png", but I'm still getting the same error.
No ideas, where this error might come from. Any suggestions?

A: Copied From ColeX at:
https://forums.xamarin.com/discussion/179775/build-error-with-missing-file-icon1024-png

*

*Edit csproj file to remove the bogus entries (just delete them)

*Ensure that a 1024*21024 png icon (file does not have Alpha or transparent) add into Assets.xcassets

*Ensure the 1024 file information included in csproj file

Refer
Where to find 'Missing Marketing Icon'
https://forums.xamarin.com/discussion/129252/problems-with-missing-appicons-files


Q: What really happens internally when an update happens on a record with indexed column in sql server I know that when a table has indexed column(s), sql server duplicates the data of these columns so that it can be accessed fast without looking through every record. And if the index is covered with other columns then all these included columns are also stored along with the indexed columns.
So, I am assuming when an update happens on any of the indexed columns or included columns then it is obvious that the update should happen in both the actual record location and the index location. This point looks interesting to me because if a table is expected to have more updates than searches, then wouldn't it be overhead to have the index? I wanted to confirm on this and also would like to know the internals on what actually happens behind the screen when a update happens.

A: Yes, you have it correct.  There is a trade-off when adding indexes.  They have the potential to make selects faster, but they will make updates/inserts/deletes slower.

A: When you design an index, consider the following database guidelines:

*

*Large numbers of indexes on a table affect the performance of INSERT, UPDATE, DELETE, and MERGE statements because all indexes must be adjusted appropriately as data in the table changes. For example, if a column is used in several indexes and you execute an UPDATE statement that modifies that column's data, each index that contains that column must be updated as well as the column in the underlying base table (heap or clustered index).

*Avoid over-indexing heavily updated tables and keep indexes narrow, that is, with as few columns as possible.

*Use many indexes to improve query performance on tables with low update requirements, but large volumes of data. Large numbers of indexes can help the performance of queries that do not modify data, such as SELECT statements, because the query optimizer has more indexes to choose from to determine the fastest access method.

*Indexing small tables may not be optimal because it can take the query optimizer longer to traverse the index searching for data than to perform a simple table scan. Therefore, indexes on small tables might never be used, but must still be maintained as data in the table changes.

For more information have a look at the below link:-
http://technet.microsoft.com/en-us/library/jj835095(v=sql.110).aspx


Q: How do I clear an array in the state of my Redux store? I am building a small e-commerce shop and I am trying to clear my cart after a successful checkout. The cart contains cartItems which are stored in the Redux store. I am getting the console log in my function in the StripeCheckoutForm component and the action creator.
I am not seeing the console log for the reducer so I suspect something is wrong with my action creator. I am not sure about best practices concerning action creators. I was wondering when, why, and how to use dispatch in the action creator. The docs for Redux aren't exactly clear for me.
Here is my StripeCheckout:
import React, {Component} from 'react';
import { CardElement, injectStripe } from 'react-stripe-elements';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import { clearCart } from '../actions/clearCartAction';
import getTotal from '../helpers/getTotalHelper';
import { Container, Col, Form, FormGroup, Input } from 'reactstrap';
import './StripeCheckoutForm.css';

const cardElement = {
  base: {
    color: '#32325d',
    width: '50%',
    lineHeight: '30px',
    fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
    fontSmoothing: 'antialiased',
    fontSize: '18px',
    '::placeholder': {
      color: '#aab7c4'
    }
  },
  invalid: {
    color: '#fa755a',
    iconColor: '#fa755a'
  }
};

const FIREBASE_FUNCTION = 'https://us-central1-velo-velo.cloudfunctions.net/charge/';

// Function used by all three methods to send the charge data to your Firebase function
async function charge(token, amount, currency) {
  const res = await fetch(FIREBASE_FUNCTION, {
      method: 'POST',
      body: JSON.stringify({
          token,
          charge: {
              amount,
              currency,
          },
      }),
  });
  const data = await res.json();
  data.body = JSON.parse(data.body);
  return data;
}

class CheckoutForm extends Component {
  constructor(props) {
    super(props);
    this.submit = this.submit.bind(this);
  }

  state = {
    complete: false
  }

  clearCartHandler = () => {
    console.log('clearCartHandler');
    this.props.onClearCart()
  }

  // User clicked submit
  async submit(ev) {
    console.log("clicked!")
    const {token} = await this.props.stripe.createToken({name: "Name"});
    const total = getTotal(this.props.cartItems);
    const amount = total; // TODO: replace with form data
    const currency = 'USD';
    const response = await charge(token, amount, currency);

    if (response.statusCode === 200) {
      this.setState({complete: true});
      console.log('200!!',response);
      this.clearCartHandler();

    } else {
      alert("wrong credit information")
      console.error("error: ", response);
    }
  }

  render() {

    if (this.state.complete) {
      return (

Purchase Complete

          <Link to='/'>
            <button>Continue Shopping</button>
          </Link>

      );
    }

    return (

      <Container className="App">

Let's Checkout

          <Form className="form">
            <Col>
              <FormGroup>
                <Input
                  type="first name"
                  name="first name"
                  id="exampleEmail"
                  placeholder="first name"
                />
              </FormGroup>
            </Col>
            <Col>
              <FormGroup>
                <Input
                  type="last name"
                  name="last name"
                  id="exampleEmail"
                  placeholder="last name"
                />
              </FormGroup>
            </Col>
            <Col>
              <FormGroup>
                <Input
                  type="address"
                  name="address"
                  id="exampleEmail"
                  placeholder="address"
                />
              </FormGroup>
            </Col>
            <Col>
              <FormGroup>
                <Input
                  type="city"
                  name="city"
                  id="exampleEmail"
                  placeholder="city"
                />
              </FormGroup>
            </Col>
            <Col>
              <FormGroup>
                <Input
                  type="prefecture"
                  name="prefecture"
                  id="exampleEmail"
                  placeholder="prefecture"
                />
              </FormGroup>
            </Col>
            <Col>
              <FormGroup>
                <Input
                  type="zipcode"
                  name="zipcode"
                  id="exampleEmail"
                  placeholder="zipcode"
                />
              </FormGroup>
            </Col>
            <Col>
              <FormGroup>
                <Input
                  type="email"
                  name="email"
                  id="exampleEmail"
                  placeholder="myemail@email.com"
                />
              </FormGroup>
            </Col>

            <CardElement style={cardElement}/>

          </Form>
        <button className="checkout-button" disabled={false} onClick={this.submit}>Submit</button>
      </Container>

    );
  }
}

const mapStateToProps = state => {
  return {
    cartItems: state.shoppingCart.cartItems
  }
}

const mapDispatchToProps = state => {
  return {
    onClearCart: () => (clearCart())
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(injectStripe(CheckoutForm));

Here is my action creator:
import { CLEAR_CART } from './types';

// export const clearCart = (dispatch)  => {
//   console.log('clear_action')
//   dispatch({
//     type: CLEAR_CART,
//   })
// }

export function clearCart() {
  console.log('clear_action')
  return {
    type: CLEAR_CART
  }
}

and finally my reducer:
import {ADD_TO_CART} from '../actions/types';
import {REMOVE_FROM_CART} from '../actions/types';
import {CLEAR_CART} from '../actions/types';

const initialState = {
  cartItems: [],
}

export default function(state = initialState, action) {
  switch(action.type) {
    case ADD_TO_CART:
    console.log('ADD_reducer');
      return {
        ...state,
        cartItems: [...state.cartItems, action.payload],
      }
    case REMOVE_FROM_CART:
    console.log('REMOVE_REDUCER', action.payload, state.cartItems);
      return {
        ...state,
        cartItems: state.cartItems.filter(item => item.id !== action.payload.id)
      }
    case CLEAR_CART:
    console.log('CLEAR_REDUCER');
      return {
        ...state,
        cartItems: []
      }
    default:
      return state;
  }
}

A: Action has to be dispatched like below. Let me know if it works
const mapDispatchToProps = (dispatch) => {
  return {
    onClearCart: () => (dispatch(clearCart()))
  }
};