text:
Q: helmfile sync vs helmfile apply
sync      sync all resources from state file (repos, releases and chart deps)
apply     apply all resources from state file only when there are changes

sync

The helmfile sync sub-command sync your cluster state as described in your helmfile ... Under
the covers, Helmfile executes helm upgrade --install for each release declared in the
manifest, by optionally decrypting secrets to be consumed as helm chart values. It also
updates specified chart repositories and updates the dependencies of any referenced local
charts.

For Helm 2.9+ you can use a username and password to authenticate to a remote repository.

apply

The helmfile apply sub-command begins by executing diff. If diff finds that there is any changes
sync is executed. Adding --interactive instructs Helmfile to request your confirmation before sync.
An expected use-case of apply is to schedule it to run periodically, so that you can auto-fix skews
between the desired and the current state of your apps running on Kubernetes clusters.

I went through the Helmfile repo Readme to figure out the difference between helmfile sync and helmfile apply. It seems that unlike the apply command, the sync command doesn't do a diff and helm upgrades the hell out of all releases . But from the word sync, you'd expect the command to apply those releases that have been changed. There is also mention of the potential application of helmfile apply to periodically syncing of releases. Why not use helmfile sync for this purpose? Overall, the difference didn't become crystal clear, and I though there could probably be more to it. So, I'm asking.

A: Everything in the other answers is correct. However, there is one additional important thing to understand with sync vs apply:

*

*sync will call helm upgrade on all releases. Thus, a new helm secret will be created for each release, and releases' revisions will all be incremented by one. Helm 3 uses three-way strategic merge algorithm to compute patches, meaning it will revert manual changes made to resources in the live cluster handled by Helm;

*apply will first use the helm-diff plugin to determine which releases changed, and only run helm upgrade on the changed ones. However, helm-diff only compares the previous Helm state to the new one, it doesn't take the state of the live cluster into account. This means if you modified something manually, helmfile apply (or more precisely the helm-diff plugin) may not detect it, and leave it as-is.

Thus, if you always modify the live cluster through helm, helmfile apply is the way to go. However, if you can have manual changes and want to ensure the live state is coherent with what is defined in Helm/helmfile, then helmfile sync is necessary.

If you want more details, checkout my blog post helmfile: difference between sync and apply (Helm 3)

A: Consider the use case where you have a Jenkins job that gets triggered every 5 minutes and in that job you want to upgrade your helm chart, but only if there are changes.
If you use helmfile sync which calls helm upgrade --install every five minutes, you will end up incrementing Chart revision every five minutes.
$ helm upgrade --install httpd bitnami/apache > /dev/null
$ helm list
NAME    REVISION        UPDATED                         STATUS          CHART           APP VERSION     NAMESPACE
httpd   1               Thu Feb 13 11:27:14 2020        DEPLOYED        apache-7.3.5    2.4.41          default
$ helm upgrade --install httpd bitnami/apache > /dev/null
$ helm list
NAME    REVISION        UPDATED                         STATUS          CHART           APP VERSION     NAMESPACE
httpd   2               Thu Feb 13 11:28:39 2020        DEPLOYED        apache-7.3.5    2.4.41          default

So, each helmfile sync will result new revision. Now if you were to run helmfile apply, which will first check for diffs and only then (if found) will call helmfile sync which will in turn call helm upgrade --install this will not happen.

A: In simple words, this is how both of them works:

*

*helmfile sync calls helm upgrade --install

*helmfile apply calls helm upgrade --install if and only if helm diff returns some changes.
So, generally, helmfile apply would be faster and I suggest using it most of the time.
But, put in your consideration that if someone has deleted any deployments or configmaps manually from the chart, helm diff won't see any changes hence,helmfile apply won't work and these resources will still be deleted, while helmfile sync will recreate it restoring original chart configuration.

A: We have detected one significant issue that also has implications.
Sometimes a sync or apply operation can fail due to:

*

*Timeout with wait: true. E.g. k8s cluster needs to add more nodes and operation takes longer than expected (but eventually everything is deployed).

*Temporary error on a postsync hook.

In these cases a simple retry on the deployment job of the pipeline would solve the issue but succesive helmfile apply will skip both helm upgrade and hook execution, even if release is in status failed.
So my conclusions are:

*

*apply is usually faster but can lead to situations where manual (outside CI/CD logic) are required.

*sync is more robust (CI/CD friendly) but usually slower.


text:
Q: Access the PHP session name in Javascript I'm currently using this to check if a cookie name exist in the browser:
document.cookie.indexOf('myCookie=')
This works if the cookie was set via PHP's setcookie() but this doesn't appear to work on PHP sessions.
E.g. if the "cookie" was set through session_start();, you can see in the browser inspector the cookie name with an expiration of "Session". I can't seem to access that session cookie name via JS. Any ideas?
To be clear: I need to check if the PHP session cookie name is present in the browser, not the session data.

A: It is possible to set the PHP session cookie to be available only via HTTP (i.e. not in JS) if your session.cookie_httponly PHP configuration setting is enabled. In other words, you need to disable it / set it to false for your session cookie to be accessible in JS.
You can check its value like so:
<?php
var_dump(ini_get('session.cookie_httponly'));

Generally, this setting is enabled for security reasons, so I would highly suggest questioning the necessity of doing this.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can BizTalk validate signatures created with OpenSSL? We use BizTalk to transfer files from one place to another. At the source, the file will be placed in a folder and its corresponding signature file generated using OpenSSL will be placed next to it. We want BizTalk to verify the signature file to see whether the file is intact. We want to do this because the file being read by BizTalk has actually come from a remote source and we need to validate the authenticity.
Can BizTalk do such validation?

A: Yes.   If you can write a C# helper class for it, then yes, BizTalk can call the helper class, from either a map, a pipeline component or Orchestration, and do the validation.


text:
Q: Slow query when sorting and filtering I'm using mongodb version 3.6.5. I would like to do a query on a collection, and then sorting it based on date. I work on a (what I think) is a pretty large dataset, currently 195064301 data in this collection, and it's growing.
Doing the filter or the sort in separated query work perfectly
db.getCollection('logs').find({session: ObjectId("5af3baa173faa851f8b0090c")})
db.getCollection('logs').find({}).sort({date: 1})

The result is returned is less than 1 sec, but if I try to do it in a single query like so
db.getCollection('logs').find({session: ObjectId("5af3baa173faa851f8b0090c")}).sort({date: 1})

Now it take about 5minutes to return the data. I was thinking it was a index problem, but as far as I can tell, the index seems fine
> db.logs.getIndexes();
[
    {
        "v" : 2,
        "key" : {
            "_id" : 1
        },
        "name" : "_id_",
        "ns" : "client1.logs"
    },
    {
        "v" : 2,
        "key" : {
            "session" : 1
        },
        "name" : "session_1",
        "ns" : "client1.logs",
        "background" : true
    },
    {
        "v" : 2,
        "key" : {
            "date" : 1
        },
        "name" : "date_1",
        "ns" : "client1.logs",
        "background" : true
    },
    {
        "v" : 2,
        "key" : {
            "user" : 1
        },
        "name" : "user_1",
        "ns" : "client1.logs",
        "background" : true
    }
]

I'm still new to mongo, I try thoses request directly in the console, I also tried to use the reIndex() method, but nothing really help.
So I'm hoping there is a solution on this.
Thanks.


text:
Q: Index of $G^n$ in $G$, an $s$-step nilpotent group of rank $\leq r$ For a group $G$ and $n \in \mathbb N$, let $G^n = \langle g^n \mid g \in G \rangle $
I am asked to show that if $G$ is $s$-step nilpotent and of rank at most $r$, then $[G:G^n] \leq n^{O_{r,s}(1)}$
I believe that the right way to approach this is to find a subset $X \subset G$ that definitely contains a complete set of coset representatives of $G^n$ in $G$, such that $|X| \leq n^{ O_{r,s}(1)}$.
Additionally, given that what we want to show is a power of $n$, I assume that we need to consider $O_{r,s}(1)$ things, each of which have $n$ possibilities, in some sense.
However, I am not entirely sure what these $O_{r,s}(1)$ things should be.
I have also considered that perhaps this question should be approached from in a more inductive way, since $G^n \leq G^m, \; \forall m \mid n$,
Thus if we can show the result for prime powers, $p$, then we would be better off since if $K \leq H \leq G$, then:
$$[G:K] = [G:H][H:K]$$
Thus: $[G:G^{pq}] = [G:G^p][G^p : G^{pq}]$
If we can then show that $(G^p)^q = G^{pq}$, then I think we would be done.
However, I can't seem to show the result for primes, nor can I show that $G^{pq} = (G^p)^q$.
I wanted to ask if either of these approaches are actually correct, and if so how I might actually go about showing this. Any help you may be able to offer would be very much appreciated, thank you!

A: Let $G$ be any group, and let $G = \gamma_1(G) \ge \gamma_2(G) \ge \cdots$ be the lower central series of $G$,
where $\gamma_{i+1}(G) := [G,\gamma_i(G)]$ for $i \ge 1$.
Let $G = \langle x_1,x_2,\ldots,x_r \rangle$. It can be proved using the commutator laws that, for $w,x \in G$ and $y,z \in \gamma_{i}(G)$ for some $i \ge 1$, we have $[wx,y] = [w,y][x,y]  \bmod \gamma_{i+1}(G)$ and $[w,yz] = [w,y][w,z] \bmod \gamma_{i+1}(G)$.
It follows that, if $\gamma_i(G)/\gamma_{i+1}(G)$ is generated by the images in $\gamma_i(G)$ of the elements $y_{i1},y_{i2},\ldots,y_{ik_i}$ of $\gamma_i(G)$, then $\gamma_{i+1}(G)/\gamma_{i+2}(G)$ is generated by the  images of the elements $rk_i$ elements $[x_j,y_{il}]$ ($1 \le j \le r$, $1 \le l \le k_i$) of $\gamma_{i+1}(G)$.
So we can take $k_i=r^i$ for all $i$. (In fact we could take $k_2 = r(r-1)/2$.)
Furthermore, since the groups $\gamma_i(G)/\gamma_{i+1}(G)$ are all abelian, every element of $G/\gamma_{i+1}(G)$ can be written mod $\gamma_{i+1}(G)$ as a product of integral powers of the $r+r^2+r^3+ \cdots +r^i$ elements $x_1,x_2,\ldots,x_r,y_{21},\ldots,y_{2k_2},\ldots, y_{i1},\ldots,y_{ik_i}$ of $G$.
All of that is true for any group $G$, but if $G$ is nilpotent of class $s$, then $\gamma_{s+1}(G)=1$, so every element of $G$ can be written as a product of powers of a list of $f(r,s) := r+r^2+\cdots+r^s$ elements.
Then every element can be written mod $G^n$ as a product of such powers with exponents in the range $0 \ldots n-1$, and hence $[G:G^n] \le n^{f(r,s)}$.


text:
Q: Function/macro to execute function body only when arguments changed from last call This should work similar to memoize, but very differently. While memoize should be used with pure functions, it is often useful to speed up IO related functions.
The function/macro I'm looking for should behave like higher order function. The function it produces should:

*

*when called for 1st time, it should call the original function, passing arguments to it

*remember: arguments, return value

*when called 2nd time

*

*with the same arguments: it should return memoized return value

*with different arguments: forget last arguments and return value, call the original function, remember current arguments and return value

*when called nth time, always compare the arguments to the last call, and behave like described above.

A: It would be easy enough to modify the source of memoize to do this.
(defn memo-one [f]
  (let [mem (atom {})]
    (fn [& args]
      (if-let [e (find @mem args)]
        (val e)
        (let [ret (apply f args)]
          (reset! mem {args ret})
          ret)))))

(defn foo [x] (println "called foo") x)
(def memo-foo (memo-one foo))

However, there is already a flexible memoization library available that can do this.
(require '[clojure.core.memoize :as memo])

(defn foo [x] (println "called foo") x)
(def memo-foo (memo/lru foo :lru/threshold 1))

(memo-foo 1)
; called foo
; 1
(memo-foo 1)
; 1
(memo-foo 2)
; called foo
; 2
(memo-foo 1)
; called foo
; 1

A: Here is a version using clojure.core only. I borrowed the foo function from A. Webb's example for demonstration.
(defn memoize-1
  [f]
  (let [previous (atom nil)]
    (fn [& args]
      (second
       (swap! previous
              (fn [[prev-args prev-val :as prev]]
                (if (and prev (= prev-args args))
                  prev
                  [args (apply f args)])))))))

user> (defn foo [x] (println "called foo") x)
#'user/foo
user> (def memo-foo (memoize-1 foo))
#'user/memo-foo
user> (memo-foo 1)
called foo
1
user> (memo-foo 1)
1
user> (memo-foo 2)
called foo
2
user> (memo-foo 1)
called foo
1


text:
Q: Can't Import Python Module in QGIS I'm trying to import the dateutil.rrule module in the python console of QGIS. That package is installed in my system, i can import it in the python2 console, but inside QGIS i get this error:
from dateutil.rrule import rrule
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/usr/share/qgis/python/qgis/utils.py", line 607, in _import
    mod = _builtin_import(name, globals, locals, fromlist, level)
ImportError: No module named rrule

I also have this problem with dateutil.easter and dateutil.zoneinfo.
I don't have it with dateutil.parser, datetime.tz and dateutil.relativedelta module
I'm using QGIS 2.18, python 2.7.12, python2-dateutil 2.5.3-1 in archilinux up to date.

A: I've figured out the reason, qgis installed a stripped down version of the dateutil library in the folder /usr/share/qgis/python/dateutil who lacked the rrule, easter and zoneinfo modules. Once i removed that folder, qgis reads the one installed by the system in /usr/lib/python2.7/site-packages/dateutil which is complete.


text:
Q: Foreman not working with a rake tast on rails So I have my rails backend running at port 3001 and may React frontend running at port 3000.
I want to setup a simple rake start task to start both.
To do so, I use the foreman gem, which works perfectly when I run: foreman start -f Procfile.dev.
However: when I run my task: rake start, I get the following error:
Running via Spring preloader in process 36257
15:56:57 web.1  | started with pid 36258
15:56:57 api.1  | started with pid 36259
15:56:57 api.1  | /usr/local/opt/rbenv/versions/2.3.4/lib/ruby/gems/2.3.0/gems/foreman-0.64.0/bin/foreman-runner: line 41: exec: PORT=3001: not found
15:56:57 api.1  | exited with code 127
15:56:57 system | sending SIGTERM to all processes
15:56:57 web.1  | terminated by SIGTERM

Here is my my start.rake file:
namespace :start do
  desc 'Start dev server'
  task :development do
    exec 'foreman start -f Procfile.dev'
  end

  desc 'Start production server'
  task :production do
    exec 'NPM_CONFIG_PRODUCTION=true npm run postinstall && foreman start'
  end
end
task :start => 'start:development'

and my Procfile.dev file:
web: cd client && PORT=3000 npm start
api: PORT=3001 && bundle exec rails s

Any idea ?

A: I faced the same issue. I am not sure why, but when foreman is running from rake, it is unable to handle multiple commands on the same line, e.g.
web: cd client && PORT=3000 npm start

To solve the issue, I changed my Procfile.dev to
web: npm start --prefix client
api: bundle exec rails s -p 3001

and in my package.json, I changed
"scripts": {
    "start": "react-scripts start",
    ...
}

to
"scripts": {
    "start": "PORT=3000 react-scripts start",
    ...
}

This allows you to specify the ports for both react and rails servers, and works fine with both
foreman start -f Procfile.dev and rake start

A: I don't know Foreman, but every morning I start my dev environment with teamocil. Here is an example file.
Add an alias to your .bash_alias file:
 alias s2="cd /home/manuel/chipotle/schnell && tmux new-session -d 'teamocil schnell' \; attach"

so you just need to type "s2" in the console and all, including the database prompt, is up and ready.

A: I know I'm a little bit late, but essentially you shouldn't use multi-line command, always try avoiding then. you could change your syntax and make it online with some flags as fallow:
web: npm start --port 3000 --prefix client
api: bundle exec rails s -p 3001

I hope it could help anyone facing the same issue.
Happy Coding


text:
Q: Using .format to turn a float to an integer Very quick question.
x = 10
print("value is {:d}".format(x))

returns
value is 10

on the other hand:
x = 10.0
print("value is {:d}".format(x))

returns
ValueError: Unknown format code 'd' for object of type 'float'

Why doesnt this work?

A: You would use f not d for floats. And then specify the precision width as 0:
>>> print("value is {:.0f}".format(x))
value is 10

A: From Python docs: 'd' Decimal Integer. Outputs the number in base 10.
It will output the number in base 10, thats why you are getting the ValueError.


text: Q: Are all metric tensors of 3 dimensional surfaces 2x2? I was doing some work with the volume surface area ratio when I worked it out, I had assumed the metric tensor to be 3x3. I looked for some examples of surfaces test on trecs.se but I saw that all of the first fundemental forms of the surfaces in the surface index were 2x2. Am I dealing with a small minority where this is true or is there some way to introduce a third parameter keeping the surface the same?


text:
Q: Django search returns "Page not found (404) error Like many other questions on here (Writing a very basic search form in Django, django search page not found error), I am using Django and I have a search bar in a form that when submitted, returns a "Page not found" error. Getting the urls correct tends to be my achilles and I am hoping an extra set of eyes can spot my error.
Here are excerpts of my code:
models.py
class Tool(models.Model):
    tool_name = models.CharField(max_length=200)
    release_date = models.DateField('release_date', null=True, blank=False)

views.py
def search_results(request):
   if request.GET:
      search_term = request.GET['search_box']
      results = Tool.objects.filter(tool_name__icontains=search_term)

      return render(request, 'search_results.html', {'results': results})
   return render(request, 'search_results.html')

urls.py
urlpatterns = [
   ...
   path('search_results/', views.search_results, name='search_results'),
]

templates/base_generic.html
<form name="search_form" method="GET" action="{ % url 'search_results' %}">
   <input  id="search_box" type="text" name="search_box"  placeholder="Search tools..." >
   <button id="search_submit" type="submit" >Submit</button>
</form>

templates/search_results.html
{% extends "base_generic.html" %}
...
{% if results %}

         Tool
         Release Date

      {% for t in results %}

            {{ t.tool_name }}
            {{ t.release_date }}

      {% endfor %}

   {% else %}

Your search term returned no items, please try again.

   {% endif %}

{% endblock %}

file structure
├── models.py
├── templates
│   ├── base_generic.html
│   ├── index.html
│   ├── packages
│   │   ├── developer_detail.html
│   │   ├── developer_list.html
│   │   ├── publication_detail.html
│   │   ├── publication_list.html
│   │   ├── tool_detail.html
│   │   └── tool_list.html
│   ├── search_results.html
├── urls.py
└── views.py

Error

Page not found (404)
Request Method:     GET
Request URL:    http://localhost:8000/packages/%7B%20%25%20url%20'search_results'%20%25%7D?search_box=Scampy

Using the URLconf defined in Bio.urls, Django tried these URL patterns, in this order:

    admin/
    packages/ [name='index']
    packages/ tools/ [name='tools']
    packages/ tool/<int:pk> [name='tool-detail']
    packages/ developers/ [name='developers']
    packages/ developer/<int:pk> [name='developer-detail']
    packages/ publications/ [name='publications']
    packages/ publication/<int:pk> [name='publication-detail']
    packages/ new_developer/ [name='new_developer']
    packages/ new_tool/ [name='new_tool']
    packages/ thanks/ [name='thanks']
    packages/ signup/ [name='signup']
    packages/ accounts/
    packages/ search_list/ [name='search_list']
    packages/ search_results/ [name='search_results']
    accounts/
    ^static/(?P<path>.*)$

The current path, packages/{ % url 'search_results' %}, didn't match any of these.

If anyone with insight into my error could assist me I would greatly appreciate it.

A: When you are including search.urls in your project urls.py are u using namespace?
Something like this
path('packages/',include("search.urls",namespace='search')),

if yes u should use method="GET" action='{% url "search:search_results"%}'
in general namespace:name


text:
Q: Why does my fast exponentiation algorithm give me a 'cannot find symbol' error in the parameter of a lambda? Background/Goal I am trying to accomplish:
I am attempting to implement the fast exponentiation algorithm in Java from scratch (as practice).  The algorithm is as follows (explanation taken from johndcook.com):
Input: base b, exponent n.
Write the exponent n in binary. Read the binary representation from left to right, starting with the second bit from the left. Start with the number a, and every time you read a 0 bit, square what you've got. Every time you read a 1 bit, square what you've got and multiply by a. It follows that an can be computed using no more than 2 log2(n) multiplications.
I am not looking for a better way to implement this algorithm, but rather why I am getting this particular error.
What the problem is
I tried to implement this algorithm using a recursive lambda in Java, and when I went to run the program, I got the following errors:

Main.java:11: error: cannot find symbol
exponentiator = (int runningResult, int binLength, int binInt, int expBase) -> {
                                                               ^

Main.java:11: error: lambda expression not expected here
exponentiator = (int runningResult, int binLength, int binInt, int expBase) -> {
^

Main.java:23: error: cannot find symbol
exponentiator(b, length, nBinInt, b);
^

I have no explanation for these errors, can anyone help me out?
Code:
class Main {
  public static void main(String[] args) {
    fastExp(2, 13);
  }
  //This is the algorithm itself
  public static int fastExp(int b, int n) {
    //converts n (b^n) to binary for algorithm
    String nBinStr = Integer.toBinaryString(n);
    int nBinInt = Integer.parseInt(nBinStr);
    int length = String.valueOf(nBinInt).length();
    exponentiator = (int runningResult, int binLength, int binInt, int expBase) -> {
      int firstDigit = Integer.parseInt(Integer.toString(binInt).substring(1, 2));
      if(binLength = 0){
        return runningResult;
      }
      else if(firstDigit = 0){
        exponentiator((runningResult * runningResult), (binLength - 1), (binInt % (int) Math.pow(10, (int) Math.log10(binInt))), expBase);
      }
      else {
      exponentiator((runningResult * runningResult * base), (binLength - 1), (binInt % (int) Math.pow(10, (int) Math.log10(binInt))), expBase);
      }
    };
    exponentiator(b, length, nBinInt, b);
  }
}

https://repl.it/@Jodastt/Fast-Exponentiation

A: One major problem you have is that your lambda doesn't have a type. You need to give it one. I am not aware of any types in java.util.function that can represent a function taking 4 parameters, so you probably need to declare this type yourself.
The other major problem is that you are using the variable exponentiator inside its declaration, which is invalid. To work around this, you need to add a fifth parameter to your lambda, to which the lambda itself will be passed. You will then replace the recursive calls with calls to this parameter.
Let's declare the type to represent this lambda first.
interface IntQuadRecursiveFunction {
    int apply(int a, int b, int c, int d, IntQuadRecursiveFunction f);
}

And then exponentiator can be redeclared like so:
// note the type and extra parameter "f"
IntQuadRecursiveFunction exponentiator = (runningResult, binLength, binInt, expBase, f) -> {
   int firstDigit = Integer.parseInt(Integer.toString(binInt).substring(1, 2));
   if (binLength == 0) { // It's "==", not "="
       return runningResult;
   } else if (firstDigit == 0) {
        // note the word "return", which you were missing
        // also the extra argument "f"
       return f.apply((runningResult * runningResult), (binLength - 1), (binInt % (int) Math.pow(10, (int) Math.log10(binInt))), expBase, f);
   } else {
       // should be "expBase", not "base"
       return f.apply((runningResult * runningResult * expBase), (binLength - 1), (binInt % (int) Math.pow(10, (int) Math.log10(binInt))), expBase, f);
   }
};

usage:
// you are missing a return in "fastExp" as well
return exponentiator.apply(b, length, nBinInt, b, exponentiator); // note the last argument

To be honest, if I were you I would just save all this trouble and write a normal method instead:
public static int fastExp(int b, int n) {
    //converts n (b^n) to binary for algorithm
    String nBinStr = Integer.toBinaryString(n);
    int nBinInt = Integer.parseInt(nBinStr);
    int length = String.valueOf(nBinInt).length();
    return exponentiator(b, length, nBinInt, b);
}

private static int exponentiator(int runningResult, int binLength, int binInt, int expBase) {
    int firstDigit = Integer.parseInt(Integer.toString(binInt).substring(1, 2));
    if (binLength == 0) {
        return runningResult;
    } else if (firstDigit == 0) {
        return exponentiator((runningResult * runningResult), (binLength - 1), (binInt % (int) Math.pow(10, (int) Math.log10(binInt))), expBase);
    } else {
        return exponentiator((runningResult * runningResult * expBase), (binLength - 1), (binInt % (int) Math.pow(10, (int) Math.log10(binInt))), expBase);
    }
}


text:
Q: how to enable https in my facebook app i created an app and set my web URL which is https://www.mysite.com but i keep getting a message from Facebook's comments plugin in the little yellow box saying "warning: cant find http://www.mysite.com"
the plugin is working great and i can see comments and even share and like.
how can i fix that?
here is a print screen:

A: I am adding screen shot of one of my app, you can follow these screen shot:
Make sure to disable Sandbox mode and you should fill required URL as shown below.

A: problem found. we have a loadbalancer that causes that in the inner server he sees itself as http and in the outer is actually https. i had to manually add the "s" to the output.
thx for all the help!


text:
Q: Opencart: Add extra features under the same product I am new to programing and to Opencart. I am populating a site for a beauty shop http://sunrisebeautysupplies.com/Go_oshopping . I need when my customers go to a particular product, (lets say wigs), somewhere on the same page to display images of colors available at the store - these images are representaed with number variables  since some products have #s as their ids in the market.  Example - wigs # 121 refers to dark or wigs # 131 refering to dark brown. The customer  uses mouse over for quicker perusal and color selection without page reloading and open on a space within the page. in admin section, I need to be able to add these extra features under the same product. After the customer selection, their choice of coler is included in the order or checkout proceess.
I have added a table with images as test as seen here: http://sunrisebeautysupplies.com/Go_oshopping but I need each product page to feature its own category.
Any help is much appreciated.
Mkarimu

A: Why dont you try with the Catalog->Options->Insert and select Image type, or actually The select type (with image you will be able to do what you requiered).
If you have problems tell me and I can indicate you a little bit more :)


text:
Q: Scaling down a gif using pyglet I am currently trying to make a simple image viewers that lets me view images or gifs. I've done most of the work and it's coming out how I'd like it, but I'd also like to be able to view gifs that are too big for my screen. I have a normal 1080p monitor, but the images are 1900x1300, which I understand is an odd image size for gifs. Problem is, pyglet has no obvious way to scale down gifs when drawing them. I'm using sprites, but scaling down the sprite merely returns an error, as the image itself hasn't actually changed, and is still 1900x1300.
What I need is a method to take a gif file, scale it down by 1/2, and render that gif using pyglet. I could probably use other libraries, but I'm trying to keep the project small.
Thanks!


text:
Q: vertical-align css3. tried everything else I am trying to vertically align the 's inside my navigation divs, and it is for some reason not working. I've already checked that there are no other styles overriding my code, and several combinations of positioning.

Gallery

Events

Home

Info

Contact

CSS
#logodiv {
    width:100%;
    height:100px;
    position:relative;
    display:block;

}

#flexbox{
    background-color:#f5b00e;
    float:right;
    width:65%;
    min-width:400px;
    height:30px;
    padding:0;
    margin:0;
    white-space:nowrap;
    margin-bottom:0px;
    position:absolute;
    right:0px;
    bottom:0px;
    display:inline;
}

.menudiv{
    width:20%;
    height:100%;
    line-height:100%;
    display:inline;
    float:left;
    margin:0 auto;
    padding:0;
    vertical-align:middle;
    position:relative;
}

.menua{
    line-height:100%;
    height:100%;
    font-family: font, Arial, sans-serif;
    font-size:15pt;
    text-decoration:none;
    text-shadow:none;
    margin-top:10px;
    vertical-align:bottom;
}

any help would be appreciated.

A: Check it http://jsfiddle.net/mKbLW/1/
Changed around some of your values. Had some unneeded css rules.
#logodiv {
    width:100%;
    height:100px;
    position:relative;
    display:block;

}

#flexbox{
    background-color:#f5b00e;
    float:right;
    width:65%;
    min-width:400px;
    height:30px;
    padding:0;
    margin:0;
    white-space:nowrap;
    margin-bottom:0px;
    position:absolute;
    right:0px;
    bottom:0px;
    display:inline;
}

.menudiv{
    width:20%;
    height:100%;
    float:left;
    padding:0;
    position:relative;
}

.menua {
    height:100%;
    line-height:30px;
    display:inline;
    font-family: font, Arial, sans-serif;
    font-size:15pt;
    text-decoration:none;
    text-shadow:none;
    margin-top:10px;
}


text:
Q: onclick radio button active color change using css when we click on the radio button background color and label color will change I have written CSS but it is not working. I don't want to change my HTML structure with my code only how can I add color to the label on active. Can anyone suggest me.

const handleVisibility = (e) => {
  e.target.closest('.case-inner-info').querySelectorAll('.inner_div [data-ref]').forEach(i => i.style.display = i.dataset.ref === e.target.dataset.ref ? 'block' : 'none');
}
const allOnOffButtons = document.querySelectorAll("div.case-inner-info input");
allOnOffButtons.forEach(button => {
  button.addEventListener('click', handleVisibility);
})
.switch-label {
  position: relative;
  width: 58px;
  float: left;
  line-height: 26px;
  font-size: 16px;
  font-weight: 900;
  text-align: center;
  cursor: pointer;
  color: #051326;
  z-index: 2;
}

.switch-input {
  display: none;
}

.switch-input:checked .switch-label {
  color: #fff;
  -webkit-transition: 0.15s ease-out;
  -o-transition: 0.15s ease-out;
  transition: 0.15s ease-out;
  -webkit-transition-property: color;
  -o-transition-property: color;
  transition-property: color;
}

.switch-input:checked+.switch-label-off~.switch-selection {
  left: 60px;
}

.switch-selection {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  position: absolute;
  left: 0;
  width: 70px;
  height: 40px;
  border-radius: 4px;
  color: #fff;
  z-index: 1;
  -webkit-transition: left 0.15s ease-out;
  -o-transition: left 0.15s ease-out;
  transition: left 0.15s ease-out;
}

.case-switch .switch-selection {
  background-color: red;
}

 Paragrapgh1

 Paragrapgh2

      <input type="radio" class="switch-input" name="switch-toggle" data-ref="on" checked>
      On

      <input type="radio" class="switch-input" name="switch-toggle" data-ref="off">
      Off

A: Please check this, if this is something resolves your issue, I have removed the span

 Paragrapgh1

 Paragrapgh2

      <input type="radio" class="switch-input" name="switch-toggle" data-ref="on" checked>
      On

      <input type="radio" class="switch-input" name="switch-toggle" data-ref="off">
      Off

const allOnOffButtons = document.querySelectorAll("div.case-inner-info input");
const handleVisibility = (e) => {

  e.target.closest('.case-inner-info').querySelectorAll('.inner_div [data-ref]')
  .forEach(i =>
     i.style.display = i.dataset.ref === e.target.dataset.ref ? 'block' : 'none');
     allOnOffButtons.forEach(i => i.parentNode.style.backgroundColor = i.dataset.ref === e.target.dataset.ref ? 'red' : 'transparent');
}

allOnOffButtons.forEach(button => {
  button.addEventListener('click', handleVisibility);
})

Here is the codepen

A: Change the position of switch-selection using the position of the label.
But this is not the best solution. You can just use background on switch-label-on and switch-label-off classes and style it like your example using css.
My two cents.

A:

// Cache the inputs
const inputs = document.querySelectorAll('.switch-input');

// Add event listeners to them
inputs.forEach(() => addEventListener('change', handleRadio, false));

function handleRadio(e) {

  // Remove the switch-selection class from
  // all the inputs/label background
  inputs.forEach(label => {
    label.parentNode.classList.toggle('switch-selection');
  });

  // And then just toggle it on the radio that's
 // been clicked
  e.target.classList.toggle('switch-selection');
}
.switch-selection { background-color: red; }

      <input type="radio" class="switch-input" name="switch-toggle" data-ref="on" checked>
      On

      <input type="radio" class="switch-input" name="switch-toggle" data-ref="off">
      Off


text:
Q: Show mouseover text at certain width I got an  tag, that has text inside of it.
On a phone screen the text is too long, so I hide it at a certain width.
When it's hidden I want to activate a mouseover text instead.
I tried it with  but that mouseover-text stays visible when the screen is wide enough for the regular text.
How can I disable that mouseover text at a certain screen-width?
Or: Any better alternatives to have a mouseover-text that hides at a certain width?

@media (max-width: 700px) {
  #changePw {
    font-size: 0;
  }
  .fa {
    font-size: initial;
  }
}

  Icon Change Password

A: OK so I think what I would do is use a pseudo-class:

@media (max-width: 700px) {
  #changePw {
    font-size: 0;
  }
  #changePw:hover:after  {
    content: "Change Password";
    padding: 4px 8px;
    background-color: #333;
    color: #fff;
    font-size: 10pt;
    text-decoration: none;
    display: block;
    width: 5em;
  }
  .fa {
    font-size: initial;
  }
}

  Icon Change Password

(don't forget to test this in a window of less than 700px width)

A: It is not possible to remove it with CSS, you will need to use javascript / jQuery like so:
$('a').mouseover(function(e){
    if($(window).width() > 700){
        $('a').removeAttr("title");
    }
    else{
        $('a').attr("title", "Title");
    }
});

Working fiddle.
This is a quick/dirty solution and i don't think this is great for SEO.
The (IMO) correct way would be to always have the title tag, on desktop and mobile.
EDIT: Spelling


text:
Q: Rails4: Form-Update via Ajax not working -> Template error I am trying to update a section in a form when the user enters a valid date. CoffeeScript is
initiating a call to the controller and the controller starts a '.js.erb' action for rendering
a form partial. What I want is to supply the user-entered date to a 'autocomplete' field, so
only values with a certain validity date will be returned and offered...
See code below:
flights.s.coffee:
$ ->
    $("#flight_f_date").focusout ->
        $.ajax
            url: "/flight/populateAircraftsSelection"
            data:
                f_date: $('#flight_f_date').val()
            dataType: "script"

My controller function looks like:
def populateAircraftsSelection

  puts "AircraftsSelection" + params[:f_date.to_s]

  @flight_date = params[:f_date].to_s

  respond_to do |format|
    format.js
  end
end

populateAircraftsSelection.js.erb:
$("#flight_test").html("<%= escape_javascript render partial: 'test', :locals => { flight: @flight, flight_date: @flight_date  }  %>");

and the _test.htnl.erb partial

    <%= f.label :aircraft_id, "Kennzeichen" %>

    <%= f.hidden_field :aircraft_id %>
    <%= f.autocomplete_field :helper_registration_field ,
                             autocomplete_aircraft_registration_flights_path(:flight_date =>
                             @flight_date.to_s),
                             :update_elements => { :id => '#flight_aircraft_id', :acfttype =>
                             '#flight_helper_aircraft_field' } %>

I am getting the following error:
ActionView::Template::Error (undefined local variable or method `f' for #<#
<Class:0x007fee2cb62c28>:0x007fee298a0ec0>):
    1:

    2:
    3:
    4:  <%= f.label :aircraft_id, "Kennzeichen" %>

    5:                      <%= f.hidden_field :aircraft_id %>
    6:
    7:                  <%= f.autocomplete_field :helper_registration_field ,
 autocomplete_aircraft_registration_flights_path(:flight_date => @flight_date.to_s),

app/views/flights/_test.html.erb:4:in
`_app_views_flights__test_html_erb__1386346884294841760_70330389540980'
  app/views/flights/populateAircraftsSelection.js.erb:1:in
 `_app_views_flights_populate_ircrafts_election_js_erb__2604210186479166916_70330440189180'
   app/controllers/flights_controller.rb:179:in `populateAircraftsSelection'

I thought 'f' must be know, because I am adding this partial into a bigger form where 'f' is
already known.....
What I am doing wrong? Or: is there a much better way to update a a clue inside a form after
user interaction.....?
Thanks in advance for any help you can provide...
Dirk

A: OK, found a trick on my own - using a session variable. I know, it's dirty, and has nothing to do with AJAX as it was designed, - but it works...
Only problem to distinguish in two or three location when to use params and when to use session. But
still using AJAX and Coffeescript to initiate this kind of a call....


text:
Q: How to get values from a multiple checkbox and insert into database? I am working on a certain form that accepts multiple values using checkbox and I find it hard to get all the values of the checked boxes and store them into the database.
Everytime my insertion query is being executed.. the only value that is stored in the database is the last checkbox the user selects thus ignoring the others..
here's my code:
----form-----------------------------------------------------------------'
<form name="addRes" method="post" action="addReservation_code.php">

Activity Date:
    <select name="month">
  <option value="January">January</option>
  <option value="February">February</option>
  <option value="March">March</option>
<option value="April">April</option>
<option value="May">May</option>
<option value="June">June</option>
<option value="July">July</option>
<option value="August">August</option>
<option value="September">September</option>
<option value="October">October</option>
<option value="November">November</option>
<option value"December">December</option>

</select>
<select name="day">
<?php for($ctr=1;$ctr<=31;$ctr++){ ?>
<option value="<?php print($ctr); ?>"><?php print($ctr); ?></option>
<?php } ?>
</select> -
<select name="day2">
<?php for($ctr=1;$ctr<=31;$ctr++){ ?>
<option value="<?php print($ctr); ?>"><?php print($ctr); ?></option>
<?php } ?>
</select>
<input type="text" name="year"/>

Activity Name:	<input type="text" name="act_name" />

Activity Time:	<input type="text" name="act_time" />

Room:

     <select name="room">
      <?php
       include 'RRSdbconnect.php';
        $query = "SELECT room_name from room";
        $result=mysql_query($query) or die('Invalid query'.mysql_error());
         while ($row = mysql_fetch_array($result, MYSQL_BOTH))
         {
          echo "<option>$row[room_name]";
         }
      ?>
      </option>
     </select>

     Resources Needed:
        <input type="checkbox" name="resources" value="cpu" />CPU

        <input type="checkbox" name="resources" value="lcd" />LCD

        <input type="checkbox" name="resources" value="sounds" />Sounds

        <input type="checkbox" name="resources" value="sounds" />Others, Pls. specify<input type="text" name="others" />

No. of Person	<input type="text" name="noOfPerson"/>

Reserved by:	<input type="text" name="reservedby" />

<input type="submit" name="submit" value="Submit"/><input type="reset" name="clear" value="Clear"/>

</form>

------------action code----------------------------------------------------
<?php
include 'RRSdbconnect.php';
session_start();

$date =  $_POST['month'] . ' ' .$_POST['day']. '-' .$_POST['day2']. ', ' . $_POST['year'] ;
$name=$_POST['act_name'];
$time=$_POST['act_time'];
$room=$_POST['room'];
$resources=$_POST['resources'];
$noOfPerson=$_POST['noOfPerson'];
$reservedby=$_POST['reservedby'];

//insertions for add reservations
 $query="insert into reservation (activity_date, activity_name, activity_time, room, resources_needed, no_person, reserved_by) values('$date','$name','$time','$room','$resources','$noOfPerson','$reservedby')";
 $result=mysql_query($query,$link) or die("Error!".mysql_error());
?>

PS.
 I am using checkbox on the column resources needed..
any help will be appreciate..tnx

A: If you change the name attribute of the checkbox to name="resources[]" you should get an array in the $_POST['resources']
Once you have the array in $_POST['resources']you can store/retrieve it in the database how you like. For example either as a string using implode() / explode() or serialize() / unserialize().


text:
Q: Pull JSON values and add to new column in existing CSV I am trying to take values from JSON (below) and insert them into a new column of an existing CSV. With my current code (also below), all that's being added to the new row is the word "Array" on each line. How can I adjust my code so that it works properly? Also, is there a way for me to set a header name for the new column I'm creating?
Thank you, please look at my code below and let me know if you have any questions.
JSON blob:
{
 "test":{"12345":"98765","56789":"54321"},
 "control":{"99999":"987651","88888":"987652","22222":"987653","27644":"987655"}
}

Current CSV:
userid,foo_date,bar,baz,qux,country
"12345","2013-03-14","1.72500","1","1055.74","UK"
"38726","2013-03-14",\N,"1","3430.07","UK"
"85127","2013-03-14",\N,"0","635.25","US"
"16984","2013-03-14",\N,"1","5233.09","US"

Current PHP (as per How to add columns to CSV using PHP):
$json = json_decode($s, true);
$json_values = array_values($json['control']);

$newCsvData = array();

if (($handle = fopen("testgroup.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $data[] = $json_values;
        $newCsvData[] = $data;
    }
    fclose($handle);
}

$handle = fopen('testgroup.csv', 'w');

foreach ($newCsvData as $line) {
   fputcsv($handle, $line);
}

fclose($handle);

$s equals the JSON blob.
Resulting CSV should look like:
userid,foo_date,bar,baz,qux,country,extra
"12345","2013-03-14","1.72500","1","1055.74","UK","987651"
"38726","2013-03-14",\N,"1","3430.07","UK","987652"
"85127","2013-03-14",\N,"0","635.25","US","987653"
"16984","2013-03-14",\N,"1","5233.09","US","987655"

A: Try this (tested):
$data = <<<EOF
{
 "test":{"12345":"98765","56789":"54321"},
 "control":{"99999":"987651","88888":"987652","22222":"987653","27644":"987655"}
}
EOF;

$json = json_decode($data, true);
$json_values = array_values($json['control']);
// add column header to the start of the array
array_unshift($json_values, 'extra');

// open the file in read write mode.
$fd = fopen('testgroup.csv', 'r+');
// add the last field for each record
$records = array();
while($record = fgetcsv($fd)) {
    $record []= array_shift($json_values);
    $records []= $record;
}

// clear file and set seek to start
ftruncate($fd, 0);
fseek($fd, 0);

// rewrite file
foreach($records as $record) {
   fputcsv($fd, $record);
}

fclose($fd);

A: another quick and naive way to do this is:
$json = json_decode($s, true);
$json_values = array_values($json['control']);

$i = 0;
if (($handle = fopen("csvFile.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
       //seperate your header data
        $i++;
        if($i==1)
            $header = $data;
        else
            $datas[] = $data; //all the data
        $i++;
    }
    fclose($handle);
}

//adding the json now to the data based on the test value
// assuming that your json data length will be same as number of rows in csv
//you can modify the code easily to make it dynamic
$j=0;
foreach($datas as &$d){
    array_push($d, $json_values[$j]);
    $j++;
}

//than append data in the file
$handle = fopen('testgroup.csv', 'r+');
//put the header inside the csv
fputcsv($handle, $header);

foreach ($datas as $line) {
   fputcsv($handle, $line);
}

fclose($handle);

this is first way you should implement once you are able to figure out a better way to do this like the one @hek2mgl suggested.. Just wanted to throw it out there....
Dins


text:
Q: Haskell: Making packages available for a new GHC installation If I have GHC installed in /opt/ghc and all the Haskell libraries in /opt/haskell (--global), how would I go about GHC upgrades?
All I need to do to upgrade GHC is remove its directory and untar a new one.
How do I make this new GHC installation aware about all the packages in /opt/haskell?
Do I have to recompile all the packages with the new GHC?  Is there a bulk register command or something?
Thanks.

A: This is a bad idea. Packages compiled with one GHC aren't compatible with packages compiled with another; the ABI isn't stable, and upgrading to a new major version of GHC practically guarantees that previously-compiled libraries won't work. You'll have to recompile your packages when you upgrade GHC, I'm afraid.
See this GHC FAQ entry: Do I have to recompile all my code if I upgrade GHC?


text:
Q: Routing FQDN to Web Server on Specific Port I am running multiple web servers on a single machine.
localhost:9000

localhost:8080

I want external requests (from the open net) to mysite.com to route to port 9000 and myevenbettersite.com to port 8080.
I know the system hosts file does not accept ports so it cannot be used as a solution.
Would IpTables be the proper fit for this?
I would ultimately rather use something like the Mac Server or a Linux GUI to do this for more complex configurations.

This question is clearly about networking so is on-topic.  What do you guys not like about the question?

A: No, you can't do this with DNS, IPtables or the hosts file.
You'd need to point those domains to a proxy, or something that has knowledge of what you want done, which will in turn re-direct the clients to the "right" place.


text:
Q: Splitchunk plugin with dynamic import I am using dynamic import at route level with react router and also for some common modal components.
There is a utils folder with all atoms, like button, calendar, form etc.
When using default config of splitchunk plugin, these utils and other common components are part of entry chunk (have Single entry points).
When using a cache group in splitchunk config, it extracts the common components to a separate chunk.
common: {
   name: 'common',
   minChunks: 3,
   reuseExistingChunk: true,
   enforce: true,
   priority: -20,
}

Is it a good idea to extract common code like this?
Now when using mini-css-extract-plugin plugin, it gives conflicts warning.
WARNING in chunk common [mini-css-extract-plugin]
    Conflicting order. Following module has been added:
     * css ./node_modules/css-loader/dist/cjs.js??ref--8-1!./node_modules/postcss-loader/src??ref--8-2!./src/js/views/xtra/Tab/Tab.sss
    despite it was not able to fulfill desired ordering with these modules:
     * css ./node_modules/css-loader/dist/cjs.js??ref--8-1!./node_modules/postcss-loader/src??ref--8-2!./src/js/views/Box/Box.sss
       - couldn't fulfill desired order of chunk group(s) Box
       - while fulfilling desired order of chunk group(s) Bucket

Though I didn't notice any issue in UI. Any idea about it?
Also if I use style loader in dev, it breaks the UI in many places as it is adding style tag on demand which breaks the order of css. we are not using modular css. any idea how to fix this?


text:
Q: Windows Components section is missing from my Add/Remove Programs I'm guessing it's a group policy thing, because I have to run appwiz.cpl from cmd to launch the add / remove programs window.
Is there a command line utility to control windows components? If not, how do I edit my policy to let me see the windows components?

A: This may also help:
start > run > %windir%\system32\sysocmgr.exe /i:%windir%\inf\sysoc.inf

A: Check: How to add or remove Windows Components by using Sysocmgr.exe.
also look at this thread.

A: If it is disabled by group policy you can go to the following registry key:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\Uninstall

Change the NoWindowsSetupPage value to 0.


text:
Q: appcmd.exe causes IIS service to drop I am using appcmd.exe to add IP addresses to the ipSecurity module of IIS. I am using a very basic Powershell script which reads a list from a web service of no more than 10-20 IPs, and I am adding those into the ipSecurity. I then run my Powershell through Task Scheduler, every 5 minutes to keep this list updated.
The command I am using via Powershell to add the IPs is
 & $appcmd set config  -section:system.webServer/security/ipSecurity /+"[ipAddress='$ip_address',subnetMask='$subnet_address',allowed='False']" /commit:apphost | Out-null
Perhaps it's important to say that on every execution of my Powershell, I am clearing first this list entirely using this command.
 & $appcmd clear config /delete:true /section:system.webServer/security/ipSecurity /commit:apphost | Out-null
and then I add the new, updated IP list.
When I do this, I have noticed that the IIS service may drop. It does not happen always. But sometimes it does. When I stop the scheduler my IIS service works like a charm.
Any help? I couldn't find anything related at the Microsoft pages to be honest.
thank you


text:
Q: getApplication () in FirebaseMessagingService Apparently FirebaseInstanceIdService is depricated. So, I'm trying to changed this code:
import androidx.annotation.Nullable;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;

public class InstanceIDService extends FirebaseInstanceIdService {

    @Override
    public void onTokenRefresh() {
        // Get updated InstanceID token.
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        sendRegistrationToServer(refreshedToken);
    }

    private void sendRegistrationToServer(@Nullable String token) {
        if (token != null) {
            ((SubApp) getApplication()).getRepository().registerInstanceId(token);
        }
    }
}

to the code below and adapt to the new Firebase requirements:
import androidx.annotation.Nullable;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.messaging.FirebaseMessagingService;

public class InstanceIDService extends FirebaseMessagingService {

    @Override
    public void onNewToken (@Nullable String token) {
        // Get updated InstanceID token.
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        sendRegistrationToServer(refreshedToken);
    }

    private void sendRegistrationToServer(@Nullable String token) {
        if (token != null) {
            ((SubApp) InstanceIDService.this.getApplication()).getRepository().registerInstanceId(token);
        }
    }
}

It seems getApplication() does not work here. Even with getActivity().getApplication(). The error is:

cannot resolve method getApplication().

Also I have the error below for @override in FirebaseMessagingService:

Method does not override method from superclass


text:
Q: Expected value of measurements associated to die rolls Suppose that we throw a die four times. Let $M$ be the smallest of the four rolls and let $S$ be the sum of the largest three rolls.

What is $E\;[M]$ and $E\;[S]$?

For $E\;[M]$ I suppose I could try and compute the distribution of $M$ and find the expected value directly, but there has to be an easier way. As for $E\;[S]$ I'm lost.

A: For $E(M)$, the procedure you mentioned is reasonable. Let us start the calculate. The probability that $M=6$ is $\left(\frac{1}{6}\right)^3$.
For the probability that $M=5$, note this occurs if all the tosses are $\ge 5$, but they are not all $6$. Thus $\Pr(M=5)=\left(\frac{2}{6}\right)^3-\left(\frac{1}{6}\right)^3$.
Similarly, $M=4$ occurs if the numbers are all $\ge 4$, but they are not all $\ge 5$. Thus $\Pr(M=4)=\left(\frac{3}{6}\right)^3-\left(\frac{2}{6}\right)^3$.
And so on.
When you find the expectation, something nice will happen.
Let $X$ be the sum of all four rolls. Note that $E(X)=4(3.5)$.
Note also that $X=M+S$, and therefore $14=E(M)+E(S)$.


text:
Q: How do threads take up stack space? So to start and avoid confusion, the code below is what sparked my thought, it doesn't necessarily have much to do much with my question except for an example to explain where my question is coming from.
I was just looking at some code in javascript here:
https://jsfiddle.net/Daniel_Hug/pvk6p/
var h1 = document.getElementsByTagName('h1')[0],
    start = document.getElementById('start'),
    stop = document.getElementById('stop'),
    clear = document.getElementById('clear'),
    seconds = 0, minutes = 0, hours = 0,
    t;

function add() {
    seconds++;
    if (seconds >= 60) {
        seconds = 0;
        minutes++;
        if (minutes >= 60) {
            minutes = 0;
            hours++;
        }
    }

    h1.textContent = (hours ? (hours > 9 ? hours : "0" + hours) : "00") + ":" + (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" + (seconds > 9 ? seconds : "0" + seconds);

    timer();
}
function timer() {
    t = setTimeout(add, .1);
}
timer();

/* Start button */
start.onclick = timer;

/* Stop button */
stop.onclick = function() {
    clearTimeout(t);
}

/* Clear button */
clear.onclick = function() {
    h1.textContent = "00:00:00";
    seconds = 0; minutes = 0; hours = 0;
}

The person seemed to use recursion to make a stop watch, in timer and add.
If I do it recursively, by changing this function to this:
function timer() {
    add();
}

it takes up stack space, and eventually breaks, stops some where under 3:00:00.
But then I realized in the original code they used setInterval(), which just creates a separate thread then ends the thread, releasing the stack space. The code just does this repeatedly which is why the stack doesn't seem to overflow.
What I am having a hard time understanding is how does this work on a lower level? In one of my courses I took, I was required to make my own memory allocator(which i understand takes up heap space), but we never had to worry about threads and am wondering how I will do it with this.
So lets say I have a thread, and then the kernel switches to another thread, and then another, then one thread ends and another one begins, I am assuming there  is going to be gaps in the stack in between threads ending and being created, correct?. I read in another post (more related to java, not sure if programming language matters) that each thread takes its own space on the stack. So I was wondering, each time I make a thread, does it just fill in gaps like a memory allocator does? What if a thread ends up taking up too much space? Does the program know to realloc memory somewhere else? Am I thinking of this wrong?

A: Javascript is single threaded. See, for example, https://stackoverflow.com/questions/13504811. The main and the single javascript thread has one queue of ready tasks, and one queue of timed tasks. It cycles over the first queue until it is empty, then over the second queue until all timed tasks with exceeded time limit are executed, and the sleeps until new ready task appear, or time comes of some timed tasks.
Expression setTimeout(add, .1) just adds a task to the queue of timed tasks. It will be executed when the .1 timeout exceeded, and the main thread is able to execute next tasks.


text:
Q: How can I parse nested JSON in PowerShell? I'm trying to parse the results of a cURL command and the information I need is in a structure.
I tried getting to the data unsuccessfully and tried converting to PS Object but not sure how to access the structure as I'm new to PS.
Below is a sample of our cURL response.
I have a git commit hash ('c64a568399a572e82c223d55cb650b87ea1c22b8' matches latestCommit in fromRef for entry id 1101) and I need to find the corresponding displayId ('develop' in toRef)
I've done this in Linux using jq but need to replicate this in PS.
jq '.values | map(select(.fromRef.latestCommit=="'"$HASH"'")) | .[0].toRef.displayId'
I'm having 2 issues.

*

*I can get to fromRef but it looks like @{id=refs/heads/feature/add-support; displayId=feature/add-support; latestCommit=c64a568399a572e82c223d55cb650b87ea1c22b8; repository=} and I cannot figure out how to parse

*I'm not sure how to get the id so I can find the correct corresponding toRef

Any help would be greatly appreciated.
{
    "size":  15,
    "limit":  20,
    "isLastPage":  true,
    "values":  [
                   {
                       "id":  1101,
                       "version":  0,
                       "title":  "Added header",
                       "description":  "Added notes in header",
                       "state":  "OPEN",
                       "open":  true,
                       "closed":  false,
                       "createdDate":  1595161367863,
                       "updatedDate":  1595161367863,
                       "fromRef":  "@{id=refs/heads/feature/add-support; displayId=feature/add-support; latestCommit=c64a568399a572e82c223d55cb650b87ea1c22b8; repository=}",
                       "toRef":  "@{id=refs/heads/develop; displayId=develop; latestCommit=58b3e3482bb35f3a735048849c2474cc676fbd9b; repository=}",
                       "locked":  false,
                       "author":  "@{user=; role=AUTHOR; approved=False; status=UNAPPROVED}",
                       "reviewers":  "    ",
                       "participants":  "",
                       "properties":  "@{mergeResult=; resolvedTaskCount=0; openTaskCount=0}",
                       "links":  "@{self=System.Object[]}"
                   },
                   {
                       "id":  1053,
                       "version":  4,
                       "title":  "Help with checking,",
                       "description":  "fixed up code.",
                       "state":  "OPEN",
                       "open":  true,
                       "closed":  false,
                       "createdDate":  1591826401310,
                       "updatedDate":  1595018917357,
                       "fromRef":  "@{id=refs/heads/bugfix/checking-2.7; displayId=bugfix/checking-2.7; latestCommit=cf7d8860262c6a46b0b65ef5b6d66ae8cd698b75; repository=}",
                       "toRef":  "@{id=refs/heads/hotfix/2.7_Improvements; displayId=hotfix/2.7_Improvements; latestCommit=01f1100c559ba41ec317421399c3bfb9a0aea91f; repository=}",
                       "locked":  false,
                       "author":  "@{user=; role=AUTHOR; approved=False; status=UNAPPROVED}",
                       "reviewers":  "    ",
                       "participants":  "",
                       "properties":  "@{mergeResult=; resolvedTaskCount=0; commentCount=4; openTaskCount=0}",
                       "links":  "@{self=System.Object[]}"
                   }
               ],
    "start":  0
}

A: Once you have converted the result with ConvertTo-Json and the correct -Depth parameter, you can get the values of the returned object quite easily in PowerShell.
Let's say you have used something like $json = $curlResult | ConvertTo-Json -Depth 100, then finding the displayId from the corresponding toRef can be done like this:
# this is the known hashvalue of the `fromRef` value to look for
$latestCommitHash = "c64a568399a572e82c223d55cb650b87ea1c22b8"

# get the value item. from here you can get all other properties belonging to that item
$valueItem = $json.values | Where-Object { $_.fromRef.latestCommit -eq $latestCommitHash }

# get the displayId value of the corresponding 'toRef' element:
$displayId = $valueItem.toRef.displayId

Returns

develop


text:
Q: How to get one value from Hashmap to intent without using textview?
I retrieve few data from database then store it into hashmap  and display it on listview.
HashMap<String, String> map = new HashMap<String, String>();

            map.put(TAG_NAME, name);
            map.put(TAG_ADDRESS, address);
            map.put(TAG_VID, vid);
            venueList.add(map);

This is the value i wanna past to another page.

@Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            // getting values from selected ListItem
            String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
            String address = ((TextView) view.findViewById(R.id.address)).getText().toString();
            String vid = "NEED HELP HERE"

            // Starting new intent
            Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
            in.putExtra(TAG_NAME, name);
            in.putExtra(TAG_ADDRESS, address);
            in.putExtra(TAG_VID, vid);
            startActivity(in);
        }

I manage to pass the value which are display on TextView, but how do i pass the VID which are not TextView??
String vid = getListAdapter().getItem(position).toString();

I tried this but it show all the data. How do i select one particular VID??
Thanks.

A: You can put vid into bundle directly from map
in.putExtra(TAG_VID, map.get(TAG_VID));


text: Q: What are the task of Job Scheduling and VM Scheduling in cloud computing? I am new to cloud computing and may be my question not appropriate here, but I want to know that, are Job Scheduling and VM Scheduling are same process? And one another thing is what are the disadvantages of WRR (Weighted Round Robin) algorithm in VM Scheduling?


text:
Q: Efficiency given two temperatures Not sure what formula to use for this question? I am new to physics and the regular efficiency formula doesn't seem like the one I should be using. I was thinking the carnot efficiency, since it claims it is a "perfect" power plant:
I build the perfect power plant that operates between 350 deg.C and 20 deg.C.  What is its efficiency?

A: You have to use the formula
$$\eta=1-\frac{T_1}{T_2}$$

A: Well, if you want to maximize the efficiency (work/heat transfer), you can use the Carnot efficiency, which yngabl already pointed out is $\eta=1-T_1/T_2$.  But one cycle takes an infinite amount of time, and therefore your power output will be zero.  If you want to maximize power instead of work you'll have to do an irreversible process, and then the efficiency might be given by the Chambadal-Novikov efficiency $\eta=1-\sqrt{T_1/T_2}$.  See
https://en.wikipedia.org/wiki/Endoreversible_thermodynamics


text:
Q: Python How to close a socket instantiated in a thread? I have a multithreaded program which instantiates 5 Socket Objects as Follows:
class myThread (threading.Thread):
    def __init__(self, pid, port_num, restart):
        threading.Thread.__init__(self)
        self.hostname = '127.0.0.1'
        self.pid = pid
        self.port_num = port_num
        self.ID = pid
        self.restart = restart
        self.delay = pid*4*1000

    def run(self):
        try:
            s = timer(self.hostname, self.port_num, self.pid)
            #print "Socket S run"+str(s)
            sendToSocket(self.pid, s, self.t, self.ID)
        except Exception as e:
            raise

Here the function timer is used to Instantiate a thread in the Following manner:
def timer(host, port, pid):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    timed = pid * 4 * 100
    s.settimeout(timed)
    s.bind((host, port))
    s.listen(5)
    return s

I Want to terminate one of the sockets at a particular port say 5005.
The pid in the above example goes from 5001 to 5005.
I Want to shut down a socket in between - say 5005.
So I used this method:
s = socket.socket()
s.connect(('127.0.0.1', 5005))
s.close()

But the Socket doesn't close.
I need to call the above procedure from an external function.
In short, if there is a socket bound to port 5005, I want to close the socket and make it unavailable so that we'd get a Port not found exception.

A: You could make a dictionary with port as key and socket as value .
my_sockets = {}

Then add all your new sockets in that dictionary in the run or timer function .
def timer(host, port, pid):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    timed = pid * 4 * 100
    s.settimeout(timed)
    s.bind((host, port))
    s.listen(5)
    my_sockets[port] = s
    return s

Finally make a function to close and remove sockets from that dictionary .
def close_socket(port):
    if port in my_sockets :
        my_sockets[port].close()
        my_sockets.pop(port)


text:
Q: All values null when submit button clicked from a created form I'm trying to get the value from form and when I debug it, it shows me only null. Is there any thing wrong with my binding request? Or something else?
create.scala.index:
@(bookform : Form[Book])
@import helper._

    <title>Create Book</title>

All Books

    @helper.form(CSRF(routes.BooksController.save())){
        @helper.inputText(bookform("id"))
        @helper.inputText(bookform("title"))
        @helper.inputText(bookform("price"))
        @helper.inputText(bookform("author"))

        <input type="submit" value="create book">
    }

BookController.java:
import views.html.books.*;
import javax.inject.Inject;
public class BooksController extends Controller {

    //help to create forms
    @Inject
    FormFactory formFactory;

    //for all book
    public Result index(){
        Set<Book> books= Book.allBook();
        return  ok(index.render(books));
    }

    //create book
    public Result create(){
        Form<Book> bookForm = formFactory.form(Book.class);
        return  ok(create.render(bookForm));
    }

    //to save book
    public Result save(){
        Form<Book> bookForm=formFactory.form(Book.class).bindFromRequest();
        Book book1= bookForm.get();
        Book.add(book1);

        return  redirect(routes.BooksController.index());
    }
}

Book.java:
public static Set<Book> allBook(){
    return books;
}

public static void add(Book book){
    books.add(book);
}

A: This is my whole book.java class
package models;
import java.util.HashSet;
import java.util.Set;

public class Book {
public Integer id;
public String title;
public Integer price;
public String author;

public Book() {

}

public Book(Integer id, String title, Integer price, String author) {
    this.id = id;
    this.title = title;
    this.price = price;
    this.author = author;
}

private static Set<Book> books;

static {
    books= new HashSet<>();
    books.add(new Book(1,"C++",1100,"Abc"));
    books.add(new Book(2,"JAVA",1100,"Scd"));

}

public static Set<Book> allBook(){
    return books;
}

public static Book findById(Integer id){
    for(Book books:books) {
        if (id.equals(books.id)){
            return books;
        }
    }
    return null;
}

public static void add(Book book){
    books.add(book);
}

public static boolean remove(Book book){
    return books.remove(book);
}

}


text:
Q: How to get component value from ActionEvent object? i am using ajax4jsf with jsf 1.1 and i have code like:
<h:selectOneMenu id="INPUT_PO_DocCategory" binding="#{PrinceOfficeBean.PO_DocCategory}" style="width:200px;">
          <f:selectItem itemLabel="test" itemValue="123"/>
          <f:selectItem itemLabel="test2" itemValue="456"/>
         <a4j:support event="onchange" actionListener="#{PrinceOfficeBean.processDocumentCategoryValueChange}" reRender="INPUT_PO_DocType" />
</h:selectOneMenu>

this code is static and i can get selectOne value through PO_DocCategory binded object
the question is: is it possible to get the component value in actionlistener through the action event object ?
public void processDocumentCategoryValueChange(ActionEvent e) throws Exception {
   // get component value from ActionEvent
 }

A: Classic way in JSF is to use value attribute of input component, e.g.:
<h:selectOneMenu value="#{bean.value}">
    ...
</h:selectOneMenu>

The input value will be stored in value attribute of the bean, and can be used by action listener to operate on.
It is still possible to get the value in action listener in 'alternative' way:
((EditableValueHolder) event.getComponent().getParent()).getValue()


text:
Q: Cannot use git actions in VisualStudio (git-askpass.exe: No such file or directory) I have been using BitBucket as my code repository with Visual Studio, but today I'm not able to push code.
I tried to fetch, it opens a window to input the BitBucket credentials (username/email and password), the window closes and VisualStudio gives an error:

Fetching from origin Error encountered while fetching: Git failed with
  a fatal error. HttpRequestException encountered.    An error occurred
  while sending the request. cannot spawn /c/program files
  (x86)/microsoft visual
  studio/2017/community/common7/ide/commonextensions/microsoft/teamfoundation/team
  explorer/Git/mingw32/libexec/git-core/git-askpass.exe: No such file or
  directory could not read Password for
  'https://username@bitbucket.org': terminal prompts disabled

I tried the following but the error continues:

*

*Update the Visual Studio

*Installing the BitBucket extension for Visual Studio

*Clearing and inserting the git credentials manually

A: If you are still getting this error for Visual Studio 2019 and updating GCM is not working then please use app password instead of your regular BitBucket login password.
As of Mar 1 2022, BitBucket stopped using regular password for API based authentication. See reference
https://community.atlassian.com/t5/Bitbucket-articles/Announcement-Bitbucket-Cloud-account-password-usage-for-Git-over/ba-p/1948231

To get the app password

*

*Go to the bitbucket.org website and log in

*From your avatar in the bottom left, and click Personal settings

*Click App passwords under Access management

*Click Create app password

*Give the app password sufficient rights, and a label related to the application that will use the password

*Don't forget to save that password

A: After trying different solutions for a while I found the solution in the VisualStudio forums:
https://developercommunity.visualstudio.com/solutions/310409/view.html
Thanks to James Mu.
Here are the detailed steps that worked for me:

*

*Install the latest pre-release of Git Credential Manager for Windows.
You can download the .exe here: https://github.com/Microsoft/Git-Credential-Manager-for-Windows/releases/tag/v1.16.3

*Open the folder C:\Program Files\Git\mingw64\libexec\git-core with the windows file explorer, order files by "Date modified" descending (most recent first), and copy the top 6 files to %DevEnvDir%\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\Git\mingw32\libexec\git-core.

*

*For me the folder is C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\Git\mingw32\libexec\git-core.

*If it is not for you, view the value of %DevEnvDir% with "Developer Command Prompt for VS 2017" and the "set" command.

*Replace the files in the destination folder.

A: *

*Close Visual Studio and open CMD as administrator

*Run this command: mklink /D "C:\Git" "C:\Program Files\Git"

*Open Environment Variables and add GIT_ASKPASS variable with value "C:\Git\mingw64\libexec\git-core\git-askpass.exe"

*Open Visual Studio and push/pull or sync!

A: I was using the buttons included in menus in IntelliJ which kept giving me "\intellij-git-askpass.sh" errors and also "could not read Username for 'https://github.com': No such file or directory" and then started using the commands in the terminal instead and started working, such as:
git push --all

and/or specifically,
git push <remote> <branch>

There's also a really good cheat sheet for anyone starting out using commands

A: I have my repository in azure devops.
The night before azure devops was down completely and the next morning I could not push or pull from my repository.
The accepted answer did not work for me. I downloaded the latest version of GIT, installed it.
It did change  files in both the C:\Program Files\Git\mingw64\libexec\git-core folder and
C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\Git\mingw32\libexec\git-core  folder.
Tried to push again and it worked.
It might be visual studio somehow losing credentials (could be related to the outage) or I just had an older version of GIT installed.

A: As suggested by @CuriousDeveloper,  you need to use app-passwords starting from Mar 2022. But I was not being prompted to enter the password anywhere, when I used the Git "Sync" button in Visual Studio's "Git Changes" tab.
When I ran git pull in the "Developer PowerShell", it then prompted me to enter a password and also displayed a warning regarding the use of app-passwords (below warning).

I followed the below steps to create a app-password and used it to login:

*

*Go to the bitbucket.org website and log in

*From your avatar in the bottom left, and click Personal settings

*Click App passwords under Access management

*Click Create app password

*Give the app password sufficient rights, and a label related to the application that will use the password

*Don't forget to save that password

Note that you will not be able to view you app-password again once you close the settings window, so be sure to record it.

ERROR in terminal:
fatal: Invalid credentials
remote: Bitbucket Cloud recently stopped supporting account passwords for Git authentication.
remote: See our community post for more details: https://atlassian.community/t5/x/x/ba-p/1948231
remote: App passwords are recommended for most use cases and can be created in your Personal settings:
remote: https://bitbucket.org/account/settings/app-passwords/
fatal: Authentication failed for 'https://bitbucket.org/<org>/<repo>.git/'


text:
Q: Will these LinkedList nodes be eligible for garbage collection? I am implementing my own LinkedList. Right now, I'm on the clear() function which removes all of the elements from the list.
Here is my code so far:
public class LinkedList<E> {
    // the first element of this LinkedList
    private Node start;

    // the last element of this LinkedList
    private Node end;

    // the number of elements that constitute this LinkedList
    private int length;

    private class Node {
        private Node last;
        private Node next;

        private E data;

        // each Node has a reference to the previous Node and
        // the next Node. The first element of the LinkedList
        // will have a null reference to the previous element
        // and the last element will have a null reference to
        // the next element. Each Node stores a piece of data
        // in the data variable.
    }

    public void clear() {
        start = null;
        end = null;

        length = 0;
    }

    // other methods omitted
}

In the clear() function, I set the start and end references to null. I am unsure how this will affect the nodes in the middle of the linked list (or even the start and end nodes).
If I have four nodes (or more) in my LinkedList, the middle two (or more) will point to each other. Once I set start and end to null, my code doesn't have any references to those objects anymore, but they have references to each other.
Will these middle nodes, or even the start and end nodes, be eligible for garbage collection or not, and why?
Bonus question: how could I figure this out experimentally?

A: Seems to me like you are worrying about the wrong thing here. GC will track all roots and clear children for them also. For you example this would mean that as soon as LinkedList is not used by active Threads, it will be eligible for Garbage Collection, even if children will point to some real data (Nodes in your case). What is the use of having an Object that is not needed anymore even if it relates itself to some data?
 LinkedList
    |   |

Node1  Node2

if LinkedList is Garbage Collected, so will the Nodes, you do not have to worry about this. Thus your clear method has to reset the LinkedList to a default, empty one and not worry about GC.
P.S. You might want to read how GC works, at least to understand roots.

A: Do not set null to the objects explicitly ... you create linked list object in some scope and when the scope is over it(along with nodes) is eligible to be garbage collected.
If its a web application write finalize() to log a message.


text:
Q: TCP client does not send ACK while handshaking My testing environment
client

*

*IP 192.168.0.2/24

*gateway 192.168.0.1

server

*

*IP 192.168.0.1/24

*http service run on port 80

When I try getting web page hosted on server, everything goes fine.
Then I write a kernel module using netfilter on server, which will change dest IP to 192.168.0.1 if the origin dest IP is 192.168.1.1, and will change source IP to 192.168.1.1 if origin source IP is 192.168.0.1. I think you can understand that I'm just pretending the server to be 192.168.1.1 for the client.(IP header Checksum and TCP Checksum are changed properly)
I use the web browser(chrome, firefox...) on client to visit 192.168.1.1 and capture the packets on the client, results are like:
192.168.0.2:someport_1 -> 192.168.1.1:80 [SYN]
192.168.1.1:80 -> 192.168.0.2:someport_1 [SYN, ACK]
192.168.0.2:someport_2 -> 192.168.1.1:80 [SYN]
192.168.1.1:80 -> 192.168.0.2:someport_2 [SYN, ACK]
192.168.0.2:someport_3 -> 192.168.1.1:80 [SYN]
192.168.1.1:80 -> 192.168.0.2:someport_3 [SYN, ACK]

I don't know why the client will never send the last ACK of TCP handshaking, any ideas?
Edit1:
Now I think that the browser didn't get the [SYN, ACK] packet from the server although wireshark  can see it, so maybe it's because that the OS(Windows7) dropped the [SYN, ACK] packet from the server. Now the question becomes that why would windows drop a correct [SYN, ACK] packet?

A: You said the IP checksum is OK, but what about the TCP checksum, which is computed from a pseudo-header which includes source and destination IP ?

A: I've made three mistakes.
The first one is that skb can be nonlinear, which will cause the checksum got from csum_partial() be incorrect.
The second one is that I use csum_tcpudp_magic() to get the checksum, but forgot to change skb->ip_summed, so the NIC will use my correct checksum as the partial checksum of tcp pseudo-header to recalculate the checksum, leading checksum incorrect in the packet.
The third mistake is that my wireshark seems to be set to ignore the tcp checksum, and it always shows the packets with wrong checksum as good ones, while tcpdump will tell me incorrect checksums.


text:
Q: How it's called the java overriding functions after a new I'm finding this kind of overriding after a new in java code very often
classB body
....
    ClassA a = new ClassA(){
@Override
public void funcion(){
 atributeClassB = whatever
   }
 } ;
....

How is it called this kind of constructing ? when is executed the code between brackets ? how this code can have access to a classB attribute ?
in fact if i only know how this way of working is called i can document myselve in google but without a key name i couldn't find it.
the code where i've found it is this here on line 151

A: That's an anonymous inner class.

A: It's called an anonymous local derived class (or "anonymous inner class", though there's a difference between just being "inner" and being local [all local classes are inner; not all inner classes are local; more below]). The code within the curly braces forms part of the class definition of the anonymous class.
This
ClassA a = new ClassA(){@Override public void funcion(){ atributeClassB = whatever } } ;

...is effectively equivalent to this:
ClassA a = new SubClassA();

...where SubClassA is defined within the containing class:
class SubClassA extends ClassA {
    @Override public void funcion(){ atributeClassB = whatever }
}

...although there's a bit more to it than that because the anonymous class in your example is defined within a method (that's the "local" vs. "inner" thing), more in the various sections starting here.

A: The other two answers are correct.  I just want to add that the @Override annotation means exactly the same thing here as it would in an ordinary method declaration.  It is saying that the method is overriding a method declared in a superclass or (Java 6 and later) implementing a method declared in an interface or abstract superclass.


text:
Q: Constructor that will take any type of function as a parameter Purpose of Code: I need to be able to feed in any function type as a parameter to a constructor so that I may call it from inside that class.
Why does it have to be this way? Because I'm using Unreal Engine 4 FRunnable threading which is done is such a way that the thread will call specific interfaces (virtual member functions) to run the thread so unless I want to make a new class for every thread task I would like to assign, I have to try and feed it generic functions so that I can have maximum functionality from my Threading class.
What am I using the threading class for? SQLite3 queries, each query that requires data saving always requires different parameters where as my SELECT queries.
This is my code below, the first part works fine but the second constructor, does not;
Threading class constructor
FThreading::FThreading(std::function<void()> funcTask) {

    //Check if the Thread has not been defined and that the system supports multi threading
    if (!Thread && FPlatformProcess::SupportsMultithreading()) {

        //Create our thread
        voidNoParaFunc = funcTask;
        curFlag = 1;
        Thread = FRunnableThread::Create(this, TEXT("FThreading"), 0, TPri_BelowNormal);

    } else {

        //Can't multithread, call the function straight
        funcTask();

    }
}

The call:
std::function<void()> passFunc = std::bind(&UCP_GameInstance::InitDB, GameInst);
FThreading* threadPointer = new FThreading(passFunc);

Now this is the code that won't work that I need help with:
FThreading::FThreading(std::function<bool(FString, FString)> funcTask) {

    //Check if the Thread has not been defined and that the system supports multi threading
    if (!Thread && FPlatformProcess::SupportsMultithreading()) {

        //Create our thread
        boolTwoString = funcTask();
        curFlag = 2;
        Thread = FRunnableThread::Create(this, TEXT("FThreading"), 0, TPri_BelowNormal);

    }
    else {

        //Can't multithread, call the function straight
        funcTask();

    }
}

The call:
void UCP_GameInstance::AddNewSurvivor(FString First, FString Second, FString Nation, FString Age, FString Blood, FString Level, FString Spec) {

FString Query = "INSERT INTO SurvivorData (First, Second, Nation, Age, Blood, Level, Spec) " +
    "VALUES (" + First + ", " + Second + ", " + Nation + ", " + Age + ", " + Blood + ", " + Level + ", " + Spec + ");";

std::function<bool(FString, FString)> passFunc = std::bind(&USQLiteDatabase::ExecSql, GetDBName(), Query);
FThreading* threadPointer = new FThreading(passFunc);
}

Any help would be greatly appreciated as I've been stuck on this issue for a while and now, even design suggestions/changes would be more than invited.
Thank you for your time.

A: As you figured out with the std::bind, you can't really pass any random function - how would FThreading know how to call it? There is an actual call instruction funcTask(); which tells us immediately that funcTask takes no arguments.
Now, in your second overload, funcTask takes two FString arguments. Obviously, that means the funcTask(); call there is nonsense. It's simply missing both arguments. We cannot invent those arguments for you.
This is a general problem with the idea in your title, "take any type of function as a parameter". It generally fails, not because it's impossible to pass any function, but because it's then impossible to call that function.
PS. boolTwoString = funcTask(); should be just boolTwoString = funcTask - it's after all not a direct call there.


text:
Q: struggling to understand how "collapsed margin" works for "parent and first/last child" I'm currently learning about collapsed margin on MDN. Collapsed margin for adjacent siblings are pretty easy to understand. However, I'm struggling to understand how collapsed margin works for "parent and first/last child", especially the last sentence highlighted in blue.
How could a collapsed margins ends up outside the parent? I can't seem to picture it in my head.

A: Does this help? The 50px margin on .outer and 100px margin on .inner have collapsed to a single 100px margin from .inner, and .inner's margin is outside of the parent, rather than inside like you would expect.

.outer {
  background: #eee;
  height: 100px;
}
.inner {
  background: red;
  height: 10px;
  margin-top: 100px;
}

A: Here is an interesting example for you. The first parent does not have a border set. It automatically assumes that you do not want to use the child margin, yet it does stand of from the top.
The second example does have a border set. Now the browser assumes you explicitly want to make use of the native margin of the h1 tag and the parent adapts to show this.

.parent1 {
  background-color: #669;
}
.parent2 {
  background-color: #969;
  border: 1px solid #000;
}

hello World

hello World


text:
Q: How to include SQLAlchemy Data types in Python dictionary I've written an application using Python 3.6, pandas and sqlalchemy to automate the bulk loading of data into various back-end databases and the script works well.
As a brief summary, the script reads data from various excel and csv source files, one at a time, into a pandas dataframe and then uses the df.to_sql() method to write the data to a database.  For maximum flexibility, I use a JSON file to provide all the configuration information including the names and types of source files, the database engine connection strings, the column titles for the source file and the column titles in the destination table.
When my script runs, it reads the JSON configuration, imports the specified source data into a dataframe, renames source columns to match the destination columns, drops any columns from the dataframe that are not required and then writes the dataframe contents to the database table using a call similar to:
df.to_sql(strTablename, con=engine, if_exists="append", index=False, chunksize=5000, schema="dbo")

The problem I have is that I would like to also specify the data types in the df.to_sql method for columns and provide them as inputs from the JSON configuration file however, this doesn't appear to be possible as all the strings in the JSON file need to be be enclosed in quotes and they don't then translate when read by my code.  This is how the df.to_sql call should look:
df.to_sql(strTablename, con=engine, if_exists="append", dtype=dictDatatypes, index=False, chunksize=5000, schema="dbo")

The entries that form the dtype dictionary from my JSON file look like this:
"Data Types": {
                "EmployeeNumber": "sqlalchemy.types.NVARCHAR(length=255)",
                "Services": "sqlalchemy.types.INT()",
                "UploadActivities": "sqlalchemy.types.INT()",
                 ......

and there a many more, one for each column.
However, when the above is read in as a dictionary, which I pass to the df.to_sql method, it doesn't work as the alchemy datatypes shouldn't be enclosed in quotes but, I can't get around this in my JSON file.  The dictionary values therefore aren't recognised by pandas.  They look like this:
{'EmployeeNumber': 'sqlalchemy.types.INT()', ....}

And they really need to look like this:
{'EmployeeNumber': sqlalchemy.types.INT(), ....}

Does anyone have experience of this to suggest how I might be able to have the sqlalchemy datatypes in my configuration file?

A: You could use eval() to convert the string names to objects of that type:
import sqlalchemy as sa

dict_datatypes = {"EmployeeNumber": "sa.INT", "EmployeeName": "sa.String(50)"}
pprint(dict_datatypes)
"""console output:
{'EmployeeName': 'sa.String(50)', 'EmployeeNumber': 'sa.INT'}
"""
for key in dict_datatypes:
    dict_datatypes[key] = eval(dict_datatypes[key])
pprint(dict_datatypes)
"""console output:
{'EmployeeName': String(length=50),
 'EmployeeNumber': <class 'sqlalchemy.sql.sqltypes.INTEGER'>}
"""

Just be sure that you do not pass untrusted input values to functions like eval() and exec().


text:
Q: Crash using Swipe Gesture Recognizer with Custom Container View Controller XCode 9.1
iPhoneX simulator
iPhone6 11.1.2
I have wasted days trying to track down a crash that appears to manifest in memory corruption (because it seems to be different each time).
I have narrowed it down to using a (simple) Container View Controller with Swipe Gesture Recognizer(s).

You can see the two (left and right) Swipe Gesture Recognizers and also two (Prev and Next) buttons in the Navigation Bar. The UIViewController has a simple UILabel.
The Gesture Recognizers are configured as:

The transition is performed by:
  private func addViewToLayout(view: UIView) {
    let views = ["view": view]

    view.translatesAutoresizingMaskIntoConstraints = false
    container.addSubview(view)

    container.addConstraints(
        NSLayoutConstraint.constraints(withVisualFormat: "V:|[view]|",
        options:NSLayoutFormatOptions.alignAllLeft, metrics:nil, views:views))
    container.addConstraints(
        NSLayoutConstraint.constraints(withVisualFormat: "H:|[view]|",
        options:NSLayoutFormatOptions.alignAllLeft, metrics:nil, views:views))
  }

  private func transition(direction: Direction = .left) {
    let controllerPrevious = childViewControllers.first

    if let controllerNext = storyboard?.instantiateViewController(
        withIdentifier: "Test") {
      addChildViewController(controllerNext)
      addViewToLayout(view: controllerNext.view)

      if let controllerPrevious = controllerPrevious {
        controllerNext.view.transform = startTransform(direction: direction)

        UIView.animate(withDuration: transitionDuration,
            animations: {
              controllerNext.view.transform = CGAffineTransform.identity
              controllerPrevious.view.transform =
                  self.endTransform(direction: direction)
            },
            completion: { (finished: Bool) in
              controllerPrevious.view.removeFromSuperview()
              controllerPrevious.removeFromParentViewController()
              controllerNext.didMove(toParentViewController: self)
            })
      }
    }
  }

The crashes can occur during/after a transition or after navigating away from the Container View Controller. The debugger usually ends up in the main thread with no meaningful stack trace.

The crashes are relative easy to cause, but do not always occur from the same actions, e.g. (logs obtained by running on a device):
EXC_BAD_ACCESS (SIGSEGV)
KERN_INVALID_ADDRESS at 0x4054600000000000
Thread 0 name:  Dispatch queue: com.apple.main-thread
Thread 0 Crashed:
0   libobjc.A.dylib                 0x0000000180f68428 objc_msgSend + 8
1   UIKit                           0x000000018b40dda4 -[UIView _layoutConstraintCleanup] + 204

or
EXC_CRASH (SIGABRT)
0x0000000000000000, 0x0000000000000000
EXC_CORPSE_NOTIFY
Thread 0 Crashed:
0   libsystem_kernel.dylib          0x000000018181d348 __pthread_kill + 8
1   libsystem_pthread.dylib         0x0000000181931344 pthread_kill$VARIANT$mp + 396
2   libsystem_c.dylib               0x000000018178cfb8 abort + 140
3   libsystem_malloc.dylib          0x0000000181863a08 nanozone_default_reader + 0

Note, the crashes do not happen if only the Buttons in the Navigation Bar are used.
Is there anything that can help isolate the cause of the crashes?
Do the Gesture Recognizers need to be fiddled with when releasing the current child view controller after the transition?
This question appears to have similar symptoms, but doesn't really have any useful suggestions.
Edit:
I have uploaded a project that exhibits the crash to Dropbox. Compile project, run, tap Next, use two-touch swipes left and right multiple times, tap Back, tap Next, repeat until crash. Sometimes crash is immediate, sometimes it might take 20 or more actions.

A: From the limited data you've provided, it looks like you have a memory smasher.
You should use the tools that Xcode provides to debug such problems and provide the results of that investigation.  Use static analysis of your project.  Run with ASan, NSZombies, GuardMalloc, etc.
If you provide more results from such investigation, it will be easier to help you figure out next steps.

A: This may be simplistic, but I've run into problems with Interface Builder and 2 finger swipes. When I assign it 1 finger, it works fine, but it crashes on 2 finger.
If I leave it as 1 finger in IB and change it to 2 finger in viewDidLoad, my problem goes away.


text:
Q: Is it ok to poll Azure SQL Database "very" often? Since we cannot use Service Broker on Azure SQL Database, is it ok to poll every 250ms?
The query should be fairly light as it is executed against a table that has very few records. Whenever a new record is found, it is processed and deleted.
Will I get charged extra?

A: On Azure SQL Database you get charged by hours consumed of reserved resources, it does not matter if you use the resources or not, you have them reserved and you pay hourly for those resources assigned to your subscription. The only exception is Azure Serverless where you are charged by the minute, and the database is auto-paused after 1 hour or more of inactivity (depending of how you configured it).
You won't be charged by bandwidth in egress also as you are deleting rows.
In summary, that kind of activity on the database won't make you pay more.

A: I think it should be fine and you won't be charged per transaction if you are on DTU's or vCores plan.