text:
Q: Elegant way to select nested objects with the associated key based on a specific criteria Given an example document in JSON similar to this:
{
  "id": "post-1",
  "type": "blog-post",
  "tags": [
    {
      "id": "tag-1",
      "name": "Tag 1"
    },
    {
      "id": "tag-2",
      "name": "Tag 2"
    }
  ],
  "heading": "Post 1",
  "body": "this is my first blog post",
  "links": [
    {
      "id": "post-2",
      "heading": "Post 2",
      "tags": [
        {
          "id": "tag-1",
          "name": "Tag 1"
        },
        {
          "id": "tag-3",
          "name": "Tag 3"
        }
      ]
    }
  ],
  "metadata": {
    "user": {
      "social": [
        {
          "id": "twitter",
          "handle": "@user"
        },
        {
          "id": "facebook",
          "handle": "123456"
        },
        {
          "id": "youtube",
          "handle": "ABC123xyz"
        }
      ]
    },
    "categories": [
      {
        "name": "Category 1"
      },
      {
        "name": "Category 2"
      }
    ]
  }
}

I would like to select any object (regardless of depth) that has an attribute "id", as well as the attribute name of the parent object. The above example should be taken as just that, an example. The actual data, that I'm not at liberty to share, can have any depth and just about any structure. Attributes can be introduced and removed at any time. Using the Blog Post style is just because it is quite popular for examples and I have very limited imagination.
The attribute signifies a particular type within the domain, that might also be (but is not necessarily) coded into the value of the attribute.
If an object does not have the "id" attribute it is not interesting and should not be selected.
A very important special case is when the value of an attribute is an array of objects, in that case I need to keep the attribute name and associate it with each element in the array.
An example of the desired output would be:
[
  {
    "type": "tags",
    "node": {
      "id": "tag-1",
      "name": "Tag 1"
    }
  },
  {
    "type": "tags",
    "node": {
      "id": "tag-2",
      "name": "Tag 2"
    }
  },
  {
    "type": "links",
    "node": {
      "id": "post-2",
      "heading": "Post 2",
      "tags": [
        {
          "id": "tag-1",
          "name": "Tag 1"
        },
        {
          "id": "tag-3",
          "name": "Tag 3"
        }
      ]
    }
  },
  {
    "type": "tags",
    "node": {
      "id": "tag-1",
      "name": "Tag 1"
    }
  },
  {
    "type": "tags",
    "node": {
      "id": "tag-3",
      "name": "Tag 3"
    }
  },
  {
    "type": "social",
    "node": {
      "id": "twitter",
      "handle": "@user"
    }
  },
  {
    "type": "social",
    "node": {
      "id": "facebook",
      "handle": "123456"
    }
  },
  {
    "type": "social",
    "node": {
      "id": "youtube",
      "handle": "ABC123xyz"
    }
  }
]

It isn't strictly necessary that the output is identical, order for instance is irrelevant for my use-case it could be grouped as well. Since the top level object has an attribute "id" it could be included with a special name, but I'd prefer if it was not included at all.
I've tried to use walk, reduce and recurse to no avail, I'm afraid my jq skills are too limited. But I imagine that a good solution would make use of at least one of them.
I would like an expression something like
to_entries[] | .value | .. | select(has("id")?)

which would select the correct objects, but with .. I'm no longer able to keep the associated attribute name.
The best I've come up with is
. as $document
| [paths | if length > 1 and .[-1] == "id" then .[0:-1] else empty end]
| map(. as $path
      | $document
      | { "type": [$path[] | if type == "string" then . else empty end][-1],
           "node": getpath($path) })

Which works, but feels quite complicated and involves first extracting all paths, ignoring any path that does not have "id" as the last element, then remove the "id" segment to get the path to the actual object and storing the (by now last) segment that is a string, which corresponds to the parent objects attribute containing the interesting object. Finally the actual object is selected through getpath.
Is there a more elegant, or at the least shorter way to express this?
I should note that I'd like to use jq for the convenience of having bindings to other languages as well as being able to run the program on the command line.
For the scope of this question, I'm not really interested in alternatives to jq as I can imagine how to solve this differently using other tooling, but I would really like to "just" use jq.

A: This works:
[
    foreach (paths | select(.[-1] == "id" and length > 1)[:-1]) as $path ({i:.};
        .o = {
            type: last($path[] | strings),
            node: (.i | getpath($path))
        };
        .o
    )
]

The trick is to know that any numbers in the path indicates the value is part of an array. You'll have to adjust the path to get the parent name. But using last/1 with a string filter makes it simpler.

A: Since the actual requirements aren't clear to me, I'll assume that the given implementation defines the functional requirements, and propose a shorter and hopefully sleeker version:
. as $document
| paths
| select(length > 1 and .[-1] == "id")
| .[0:-1] as $path
| { "type": last($path[] | strings),
    "node": $document | getpath($path) }

This produces a stream, so if you want an array, you could simply enclose the above in square brackets.
last(stream) emits null if the stream is empty, which accords with the behavior of .[-1].


text:
Q: System.IO.Path.GetTempPath() access denied im creating temporary files to be stored in the Temp folder found by:
string path = System.IO.Path.GetTempPath()
method returns C:\windows\Temp\
i append my filename:
string filename = myfile.txt
System.IO.Path.Combine(path,filename)

However, this gives me a
"Message":"The given path\u0027s format is not supported.","StackTrace":" at System.Security.Util.StringExpressionSet.CanonicalizePath(String path, Boolean needFullPath)\r\n   at System.Security.Util.StringExpressionSet.CreateListFromExpressions(String[] str, Boolean needFullPath)\r\n   at System.Security.Permissions.FileIOPermission.AddPathList(FileIOPermissionAccess access, AccessControlActions control, String[] pathListOrig, Boolean checkForDuplicates, Boolean needFullPath, Boolean copyPathList)\r\n   at System.Security.Permissions.FileIOPermission..ctor(FileIOPermissionAccess access, AccessControlActions...... and so on
I have tried modifying the rights to the TEMP folder, so that NETWORK SERVICES has rights..
Any ideas?

A: Your path contains an invalid character. Unicode code is 0027 which is a single quote "'" so you need to check where you are adding a single quote to the path.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Calling exec() or spawn(P_OVERLAY) unblocks the console; any way to keep the console blocked? Ina  console application, passing _P_OVERLAY to a spawn function (which has the same effect as calling exec), destroys the current process.
This would be the desired behavior if it were not for the fact that doing so causes the calling process (which is often cmd.exe) to assume its callee has returned, whereas in reality the spawned sub-process of that callee is still running and therefore the caller should wait for that callee to terminate before continuing to use the console.
So, if the caller is cmd.exe (the command prompt), what happens is that as soon as the callee spawns the sub-process, the user is immediately prompted with the C:\Users\User> prompt, and becomes free to type in more commands, even though the sub-process is still running.
The best solution I have is to avoid terminating the current process until the child has terminated, but I'm wondering: is there any way to have the calling process wait on the spawned sub-processes before continuing when the callee has terminated?

A: No, there is no way to do this - if you want cmd.exe to wait for your child to exit, then you need to wait for your child to exit.
The reason is that when cmd.exe launches your process it receives a process handle; it then waits for that process handle to become signaled.  Most other parents (for example, the C runtime library) will behave the same way.  Process handles are signaled when the process they refer to exits, and there is no way to change that behaviour.
Workaround: presumably you are using _P_OVERLAY because you're porting from UNIX code.  If there is too much code to conveniently change all of the instances to wait for the child before exiting, you could start a child process as soon as your process starts, and run all of the UNIX-based code in the child.  In this model, the only thing the top-level process does is to wait for the rest of the process tree to exit.  (You can use a job object to keep track of the process tree.)


text:
Q: Как перехватить нажатия клавиш? Пишу калькулятор под WPF. На данный момент нажатие на кнопки производит запись данных в textbox, но хотелось бы чтобы при нажатии цифр на клавиатуре они были забиндены к методам, т.е. чтобы тупо было перехват кнопок. Делать через WinApi думаю будет слишком избыточно, нет ли в самом WPF такого?
  private void One_Click(object sender, RoutedEventArgs e)
        {
            if (totalled == true)
            {
                Display.Content = "";
                totalled = false;
            }
            Display.Content += "1";
            storageVariable += "1";
        }
        private void Two_Click(object sender, RoutedEventArgs e)
        {
            if (totalled == true)
            {
                Display.Content = "";
                totalled = false;
            }
            Display.Content += "2";
            storageVariable += "2";
        }
        private void Three_Click(object sender, RoutedEventArgs e)
        {
            if (totalled == true)
            {
                Display.Content = "";
                totalled = false;
            }
            Display.Content += "3";
            storageVariable += "3";
        }
        private void Four_Click(object sender, RoutedEventArgs e)
        {
            if (totalled == true)
            {
                Display.Content = "";
                totalled = false;
            }
            Display.Content += "4";
            storageVariable += "4";
        }

A: Проще всего подписаться на события KeyDown или PreviewKeyDown в окне.
Порядок доставки такой: сначала приходит PreviewKeyDown окну, затем по цепочке внутрь контролу, у которого фокус, потом приходит KeyDown контролу, и по цепочке вверх к окну.
Если вам не нужны на уровне окна нажатия на служебные клавиши, которые обработает TextBox (left/right/del), подписывайтесь на KeyDown. PreviewKeyDown позволяет также заблокировать ввод текста (например, вы хотите запретить ввод буквы A), и получает всё подряд.
Пример:
<Window ...
    PreviewKeyDown="OnPreviewKeyDown">
    ...
</Window>

void OnPreviewKeyDown(object sender, KeyEventArgs e)
{
    var key = e.Key;
    if (key == Key.A)
        e.Handled = true;
}


text:
Q: create_resources - can't convert String into Hash I am using the elasticsearch-logstash module from
https://forge.puppetlabs.com/elasticsearch/logstash
this is how my hiera looks like...
---
classes:
  - 'profile::logstash'

profile::logstash::conf:
  package_url: "https://download.elasticsearch.org/logstash/logstash/packages/centos/logstash-contrib-1.4.2-1_efd53ef.noarch.rpm"

and this is the logstash.pp from profile
class profile::logstash {

  $conf   = hiera('profile::logstash::conf',{})

  validate_hash($conf)

  create_resources('logstash',$conf)

}

I get this error...
Error: can't convert String into Hash at /tmp/vagrant-puppet-2/modules-0/profile/manifests/logstash.pp:10 on node pw-idx-11.local
Wrapped exception:
can't convert String into Hash
Error: can't convert String into Hash at /tmp/vagrant-puppet-2/modules-0/profile/manifests/logstash.pp:10 on node pw-idx-11.local

UPDATE:
fixed using this....
class profile::elasticsearch {

  class { '::elasticsearch':
    version => '1.1.1-1'
  }

  $elasticsearch_configs   = hiera_hash('profile::elasticsearch::instance',{})

  validate_hash($elasticsearch_configs)

  create_resources(elasticsearch::instance,$elasticsearch_configs)

  package { 'java-1.7.0-openjdk.x86_64':
    ensure => 'installed'
  }

}

A: Your data is not fit for use with create_resources, which expects a nested hash.
data_identifier:
  resource_title1:
    res1_param1: value
    res1_param2: value
  resource_title2:
    res2_param1: value
    ...

Since your data is a flat hash, resources cannot be created from it. You likely need to add a resource title layer.

A: That's a complicated way of doing it, what about
class profile::logstash($conf = {}) {
  validate_hash($conf)
  create_resources('logstash',$conf)
}

assuming in your site.pp you already have
hiera_include('classes')

See an example at https://ask.puppetlabs.com/question/3608/parametrized-classes-with-hiera_includeclasses/


text:
Q: .net 6 web api request change float model I send request from web:

in model:
public float Team { get; set; }

But i got incorrect value:

What is problem with rounded ?
How fix it in webapi?
I have many method , fields , levels i dont want resolve by hand every fields by Math.Round or other functions ....
update 1. for @MdFaridUddinKiron
public IActionResult Save([FromBody] Model req){
     return Ok();
}

public class Model {
   public float Team { get; set; }
}

A: try using a double instead.
floats, by how they are rapresented, are not good for precision unless we are talking about extremely small numbers.
Here is a nice little article explaining why floats may lose precision (its for cpp, but the general concept should be the same for c#):
https://learn.microsoft.com/en-us/cpp/build/why-floating-point-numbers-may-lose-precision?view=msvc-170
Edit:
I found this 13 years old question in the suggested section that might definitivelty help you understand more about floats and doubles:
Difference between decimal, float and double in .NET?


text:
Q: how do you reverse an element in a list in python Like if you have a list as names = ["Alice", "Opoku", "Kti", "Aben"] and you want to reverse a particular entry in the list like Alice as ecilA. How do you do that?

A: With a list containing strings, get the element of the list and slice it:
>>> list = ["Alice", "Opoku", "Kti", "Aben"]
>>> list[0] = list[0][::-1]
>>> list
>>> ['ecilA', 'Opoku', 'Kti', 'Aben']


text:
Q: $(K(x) : F(U))$ is a Galois extension then $U$ is finite. Let $K(x)$ be the rational function field over a field $K$.
Show that for a subgroup $U \leq Aut(K(X)/K)$ the following conditions are equivalent:
$(1)$ $(K(x) : F(U))$ is a Galois extension;
$(2)$ $U$ is finite;
$(3)$ there is a non constant rational function with $U= \{\sigma \in G \mid \sigma * \phi = \phi\}$.

A field extension $(L : K)$ is called a Galois extension, if $F(Aut(L/K)) = K$, i.e., if for any $a \in L- K$ there is an automorphism of $L$ which leaves $K$ pointwise fixed, but actually moves $a$.
$Aut(K(X)/K) = \{\phi \mid \phi : K(X) \to K(X) , \phi(k) = k \ \ \forall k \in K\}$ where $\phi$ is an automorphism.

A: If $\mathbb{F}$ is any field and $G$ is a finite group of automorphisms of $\mathbb{F}$ then $\mathbb{F}/\mathbb{F}^G$ is Galois with group $G$ - this is just Artin's theorem which more or less implies that $(2)\Rightarrow (1)$.
Assuming (3), you get that $U$ contains all the automorphisms that keep $K(\phi(x))$ invariant where $\phi(x)$ is not constant. Since $[K(x):K(\phi(x))]$ is finite (of degree $\deg(\phi)$), then $U$ must be finite which is exactly (2).
Finally, assume (1), so that $[K(x):K(x)^U]$ is Galois. Since $K\leq K(x)^U \leq K(x)$, you can use Luroth theorem which states that $K(x)^U=K(f(x))$ for some rational function $f$. This function is not going to be constant, since $K(x)/K$ is not Galois (it is not an algebraic extension). You then get that $f(x)$ is a nonconstant rational function that is invariant under $U$. Moreover, since $U$ is the Galois group of $K(x)/K(x)^U=K(x)/K(f(x))$ (again by using Artin's theorem), any other automorphism that keeps $f(x)$ invariant will keep $K(f(x))$ invariant, and therefore will be in $U$, so we get that $(1)\Rightarrow (3)$.
By the way, your definition of Galois is not true for infinite extensions. For example, $K(x)/K$ is not Galois because it is not an algebraic extension, but for every $f(x)\in K(x)-K$ there is a $K$-automorphism which moves $f(x)$. More precisely, you have the automorphisms defined by $x\mapsto ax+b$ for any $a,b \in K$ where $a\neq 0$. Writing $f(x)=f_1(x)/f_2(x)$ with $(f_1,f_2)=1$, if it is invariant under such automorphism, then you get that $f_1(ax+b)f_2(x)=f_1(x)f_2(ax+b)$ as polynomials. If $f(x)$ is invariant under all the automorphisms above, then comparing the leading coefficients show that we must have $\deg(f_1)=\deg(f_2)$. Suppose that $f$ is not constant, so that both $f_1,f_2$ are not constant and since they are coprime we can find a root $\alpha$ for $f_1$ which is not a root for $f_2$, but then we get that $f_1(a\alpha+b)f_2(\alpha)=0$ for all $a,b$ which implies that $f_1=0$ - contradiction. It follows that $K=(K(x))^{Aut(K(x)/K)}$ .


text:
Q: Google map round pin before putting on map Hi there I tried googling extensively but nothing seems to help.
This is my scenario:

*

*Company logos are stored on an external domain/url (rectangular in shape).

*Ionic application with a google map that places these logos as markers onto the map.

The markers look ugly and I want to make them round on the map.
I have found that if I add css to the entire page to say:
img { border-radius: 50%; }

Then it rounds the images but also rounds the map background.  I cannot specify the image url to style in css as each logo url will be different.  How can I achieve this via javascript alone or how can I assign a css class to each map pin?
EDIT:  Just to specify, I added such a generalized css styling because when I inspect the element then the map pin is part of the canvas and does not show up for me to inspect.  As mentioned above I would love to assign a css class to the pin so that I can target it directly.

A: You can create custom markers, using your own images..
https://developers.google.com/maps/documentation/javascript/examples/marker-symbol-custom
And try here:
https://m.youtube.com/watch?v=ZtNrt9vRt10
That should get you started..

A: @MikeCave's suggestion is great. I especially like this because high resolution screens will display markers better since Google Maps is constricting about multiple resolutions.
As the comment above, you need to be more specific if you're going to apply a general rule to all images like that. You can specify iframe img to get more specific since Google Maps puts the map inside an iframe. Better yet, check out this answer to see about adding a class name to markers for better targeting.

A: I was able to achieve this with the plugin MarkerWithLabel.  Then by placing the image in as a label under the marker I could hide the marker by defining the icon url as an empty string and then placing the image url into the label, the label then has a css class that I could manipulate via css.


text:
Q: ETW: Emitting an event through an existing provider I have an application that uses native plugins. I have my own binary format for these plugins. Each plugin is loaded at runtime using a method similar to mapping a DLL into the process' space. This means, each plugin have its own ImageBase, sections like .text or .data are handled in the same way as conventional DLLs. The only thing that is different is the binary format of the plugin (it's not a PE file) and the loader code that maps the plugin into the process space.
Now I know that ETW when doing the trace by this command-line:
xperf -on latency -stackwalk profile -buffersize 1024 -minbuffers 300 -start tracea1 -on Microsoft-Windows-Win32k:::'stack'

will emit events that can be used to reconstruct the process environment during the trace capture. That is, it will emit events like "add process", "add thread to a process", "add DLL module to a process", so that tools like xperfview can build a virtual environment of the state of processes in the system and build information like current process tree. These events are, for example, ImageLoad events that provide information about each DLL that is being loaded before, or during the trace.
Of course, for my plugins these ImageLoad events are not generated, because they're not technically DLLs (that is, not loaded by the same functions as DLLs, although their function is the same). That is why tools like xperfview don't know about their existence in the process space.
What I'd like to do, is to write my own EventWrites in my plugin loader code, and emit these ImageLoad events with necessary information, so that xperfview, and similar tools, can interpret my plugins as normal DLLs. I would fill up necessary info like ImageBase, ProcessId, ImageSize, etc.
To do this, I understand that I need to register the event MSNT_SystemTrace provider, which is the owner of ImageLoad events, build the event with this kind of structure:
    <Data Name="ImageBase">0x7FEFDBD0000</Data>
    <Data Name="ImageSize">0x12D000</Data>
    <Data Name="ProcessId">     548</Data>
    ...
    <Data Name="Reserved0">       0</Data>
    <Data Name="DefaultBase">0x7FEFDBD0000</Data>

and emit the event.
The problem is that I'm getting ERROR_ACCESS_DENIED when trying to register another MSNT_SystemTrace, which is logical, since this provider already exists.
But that forces me to ask the question, is the thing that I'm trying to do even supported by ETW?

A: I think I've found a solution.
While I don't know how to emit an event through an existing provider in realtime, Windows 8 exposes an interface which allows to modify ETL trace logs, so it's possible to alter the ProviderId of an event to a different value. The interface in question is ITraceRelogger. You need these guids:
EXTERN_GUID(CLSID_TraceRelogger, 0x7b40792d, 0x05ff, 0x44c4, 0x90, 0x58, 0xf4, 0x40, 0xc7, 0x1f, 0x17, 0xd4);
DEFINE_GUID(IID_ITraceRelogger, 0xF754AD43, 0x3BCC, 0x4286, 0x80, 0x09,0x9C, 0x5D, 0xA2, 0x14, 0xE8, 0x4E); // {F754AD43-3BCC-4286-8009-9C5DA214E84E}
DEFINE_GUID(IID_ITraceEventCallback, 0x3ED25501, 0x593F, 0x43E9, 0x8F, 0x38,0x3A, 0xB4, 0x6F, 0x5A, 0x4A, 0x52); // {3ED25501-593F-43E9-8F38-3AB46F5A4A52}

and relogger.h file from Windows 8 SDK (c:\Program Files (x86)\Windows Kits\8.0\Include\um\relogger.h). Original relogger.h seems to be broken somehow, because it references some external symbols, but it seems there's no LIB file to supplement it. I'm sure you will manage to resolve this though!
To use it, simply create an instance by:
ITraceRelogger *relog = NULL;
hres = CoCreateInstance(CLSID_TraceRelogger, 0, CLSCTX_INPROC_SERVER, IID_ITraceRelogger2, (LPVOID *)& relog);

add you input.etl and output.etl files:
#include <windows.h>
#include <cguid.h>
#include <atlbase.h>
#include <comdef.h>
...
CComBSTR input = "input.etl";
CComBSTR output = "output.etl";
...
hres = relog->AddLogfileTraceStream(input, NULL, & trace);
...
hres = relog->SetOutputFilename(output);

Then, you need to register a callback, which will handle event modification. Event callback's implementation example is placed at the end of this answer. Here's the code on how to use it with current ITraceRelogger:
EventCallback *ec = new EventCallback();
hres = relog->RegisterCallback(ec);
...
hres = relog->ProcessTrace();

Warning:ProcessTrace() will return an error if you haven't register any callbacks.
Here's an example of a working callback:
class EventCallback: public ITraceEventCallback {
private:
    DWORD ref_count;
    DWORD64 evno;

public:
    EventCallback() {
        ref_count = 0;
        evno = 0;
    }

    STDMETHODIMP QueryInterface(const IID& iid, void **obj) {
        if(iid == IID_IUnknown) {
            *obj = dynamic_cast<IUnknown *>(this);
        } else if(iid == IID_ITraceEventCallback) {
            *obj = dynamic_cast<ITraceEventCallback *>(this);
        } else {
            *obj = NULL;
            return E_NOINTERFACE;
        }

        return S_OK;
    }

    STDMETHODIMP_ (ULONG) AddRef(void) {
        return InterlockedIncrement(& ref_count);
    }

    STDMETHODIMP_ (ULONG) Release() {
        ULONG ucount = InterlockedDecrement(& ref_count);
        if(ucount == 0) {
            delete this;
        }

        return ucount;
    }

    HRESULT STDMETHODCALLTYPE OnBeginProcessTrace(ITraceEvent *HeaderEvent, ITraceRelogger *Relogger)   {
        return S_OK;
    }

    HRESULT STDMETHODCALLTYPE OnEvent(ITraceEvent *Event, ITraceRelogger *Relogger) {
        // Your main method.
        evno++;
        Relogger->Inject(Event);
    }

    HRESULT STDMETHODCALLTYPE OnFinalizeProcessTrace(ITraceRelogger *Relogger) {
        return S_OK;
    }
};

Relogger->Inject will copy current Event to the output file. You can use MSDN for ITraceRelogger to check for the available methods which will allow you to change desired event properties. The method that I was interested in was SetProviderId().
Also, have in mind that MSDN states, that ITraceRelogger is available in Windows 7. That's not what I experienced -- I can't instantiate this class in Windows 7, so MSDN can have wrong information about this subject.


text:
Q: Image load  by jQuery We have image and links in separate blocks.
When link is clicked, its href attribute puts to src of the image.
What I'm trying to do:
If image is not already loaded (not cached) {
    fadeOut previous image {
        fadeIn loader {
            load image (when animation of loader ends) {
                fadeOut loader {
                    fadeIn image
                }
            }
        }
    }
} else (if image is cached, do not show loader) {
    fadeOut previous image {
        fadeIn new image
    }
}

Here is what I have: http://jsfiddle.net/EvXJr/13/
First part works, don't know how to code the second (else) part.
Please help.

A: The dirty way would be to assign ids to loaded images, if there is no element with such id on a page - show loader, else just animate image.
Example:
html:

js:
$('#container').delegate('a', 'click', function () {
   var sel_id = this.id;
   if (!document.getElementById('img_' + this.id)) {
      //create image with  id  like: sel_id = 'img_' + this.id
   } else {
      //just show image
   }
});

A: Couldn't get the jsfiddle to load but if I understand correctly I would just set the background image of the element that holds the images to a loading gif then you don't have to worry about fading in and out a loader. If an image is already cached it will load so quickly you will never see the loading gif. And if it isn't and takes a while to load the user will see the loading gif and using the function below the image will fade in nicely once loaded.
And if you want to perform a function once an image has loaded use
$("img").load(function(){
    //do stuff once image has loaded.
    //for example
    $(this).fadeIn("slow");
});

A: Why don't you just keep track of what HREFs you have loaded with a javascript array that you have loaded and if your HREF can be found in the loaded array just take out the loader related functions.


text:
Q: Scroll down a container with hidden overflow using jquery and css3 animation(flip vertically) I have a div which contains 20 lines of text.
I want to disable normal scroll and use flip effect (vertical) when I scroll down to see the text.
How can I do that using jQuery and CSS3 animation?
Like Flipboard app for example.


text:
Q: Distinct items in List using LINQ I have following class:
public class CustomerDTO
    {
            public string CardNumber { get; set; }
            public string CustomerNumber { get; set; }
            public DateTime FetchedDate { get; private set; } = DateTime.Now;
    }

This class gets added to a List as so
    var duplicateCustomers = new List<CustomerDTO>
                {
                    new CustomerDTO { CardNumber = "123456", CustomerNumber = "1234" },
                    new CustomerDTO { CardNumber = "123456", CustomerNumber = "1234" },
                    new CustomerDTO { CardNumber = "654321", CustomerNumber = "4321" },
                    new CustomerDTO { CardNumber = "654321", CustomerNumber = "4321" }
                };

What i want to achieve is have this list filtered to distinct items so just have 2 of the four items & ensuring the FetchedDate field of the duplicate entries is the MAX one.
So all 4 items in above list would appear like following:

*

*123456, 1234, 2018-03-16 20:17:001

*123456, 1234, 2018-03-16 20:17:002

*654321, 4321, 2018-03-16 20:17:003

*654321, 4321, 2018-03-16 20:17:004

Then when this list is filtered (using an extension method perhaps) it would appear as so:

*

*123456, 1234, 2018-03-16 20:17:002

*654321, 4321, 2018-03-16 20:17:004

Could someone show me how to achieve this?

A: Try using GroupBy:
duplicateCustomers = duplicateCustomers.GroupBy(item => new
{
    CardNumber = item.CardNumber,
    CustomerNumber = item.CustomerNumber
})
.Select(item => new CustomerDTO()
{
    CardNumber = item.Key.CardNumber,
    CustomerNumber = item.Key.CustomerNumber,
    FetchedDate = item.Max(m => m.FetchedDate)
})

A: Try this:
var results = duplicateCustomers
     .GroupBy(c => new { c.CardNumber, c.CustomerNumber })
     .Select(d => d.OrderByDescending(e => e.FetchedDate)
     .First())
     .ToList();

Basically what I am doing here is using GroupBy to select distinct items on your list based on two properties, CardNumber and CustomerNumber. Then select the first results in the item results.

A: You can try below code it will work for your requirement
 static void Main(string[] args)
        {
            var duplicateCustomers = new List<CustomerDTO>
                {
                    new CustomerDTO { CardNumber = "123456", CustomerNumber = "1234" },
                    new CustomerDTO { CardNumber = "123456", CustomerNumber = "1234" },
                    new CustomerDTO { CardNumber = "654321", CustomerNumber = "4321" },
                    new CustomerDTO { CardNumber = "654321", CustomerNumber = "4321" }
                };
           // var nonduplicates= duplicateCustomers.Distinct(x => x.).ToList();//duplicateCustomers.Select(x => x.CustomerNumber).Distinct().ToList();
            List<CustomerDTO> distinctCustomers = duplicateCustomers
   .GroupBy(p => p.CardNumber)
   .Select(g => g.FirstOrDefault())
   .ToList();
            foreach (var item in distinctCustomers)
            {
                Console.WriteLine("Details  "+item.CardNumber +" "+ item.CustomerNumber + "   "+item.FetchedDate);
                //Console.WriteLine("cust Number" + item.CustomerNumber);
            }

            Console.ReadLine();
        }


text:
Q: TMDB API elements are not displaying on screen - React I'm using TMDB and I'm trying to display pictures (posters) of top rated movies, but it isn't displaying anything. In console I check if there are elements and there were but nothing is displaying. I followed this video for instruction but I have no clue why is it not working for me: https://www.youtube.com/watch?v=sZ0bZGfg_m4
Here is my current code:
App.js:
import {useEffect, useState} from 'react';
import './App.css';
import Movie from './components/Movie';

//due to it being a demo project I will not safe keep the API
const API ="https://api.themoviedb.org/3/discover/movie?sort_by=popularity.desc&api_key=89eef3426d167c3c8145a257ebe68357&page=1";
const SEARCH_API="https://api.themoviedb.org/3/search/movie?api_key=89eef3426d167c3c8145a257ebe68357&query=";
const TOP_RATED_API="https://api.themoviedb.org/3/movie/top_rated?api_key=89eef3426d167c3c8145a257ebe68357&page=1"

function App() {
  const [movies, setMovies] = useState([]);

useEffect(()=>{
  fetch(TOP_RATED_API)
  .then((res)=>res.json())
  .then((data)=>{
    console.log(data);
    setMovies(data.result);
  });

},[]);

  return
{movies?.length > 0 && movies.map((movie)=>
  <Movie key={movie.id} {...movie}/>
  )}

}

export default App;

and Movie.js:
import React from "react";
const IMG_API="https://image.tmdb.org/t/p/w500/";

const Movie =({title, backdrop_path, vote_average})=>
(

);

export default Movie;

After changing the last part in App.js ->
return
{movies?.length > 0 && movies.map((movie)=>
      <Movie key={movie.id} {...movie}/>
      )}

to this (removed ? after movies)
return
{movies.length > 0 && movies.map((movie)=>
          <Movie key={movie.id} {...movie}/>
          )}

it displays an error:
TypeError: Cannot read property 'length' of undefined

Any help would be great, thanks in advance :D

A: It was a typo, it is data.results not data.result
useEffect(()=>{

fetch(TOP_RATED_API)
  .then((res)=>res.json())
  .then((data)=>{
    console.log(data);
    setMovies(data.results);
  });

},[]);

A: Ultimately it was a typo. result should have been results.
Without that you were setting movies to undefined.
Here's a runnable version that works.

//due to it being a demo project I will not safe keep the API
const API = "https://api.themoviedb.org/3/discover/movie?sort_by=popularity.desc&api_key=89eef3426d167c3c8145a257ebe68357&page=1";
const SEARCH_API = "https://api.themoviedb.org/3/search/movie?api_key=89eef3426d167c3c8145a257ebe68357&query=";
const TOP_RATED_API = "https://api.themoviedb.org/3/movie/top_rated?api_key=89eef3426d167c3c8145a257ebe68357&page=1"

function App() {
  const [movies, setMovies] = React.useState([]);

  React.useEffect(() => {
    fetch(TOP_RATED_API)
      .then((res) => res.json())
      .then((res) => {
        console.log("inside use effect", res);
        setMovies(res.results);
      });

  }, []);

console.log(movies);
  return movies &&
 {
    movies.map((movie) => <Movie key = {movie.id} { ...movie}  />)
  }

}

const IMG_API = "https://image.tmdb.org/t/p/w500/";

const Movie = ({
    title,
    backdrop_path,
    vote_average
  }) =>
  (

  );

ReactDOM.render( <App / > , document.querySelector('#root'));


text:
Q: Given ∼R and ∼ B, derive ∼ (R ∨ B) *This question deals with the derivation system SD (Sentential Derivation), the rules of which can be seen on pages 3-4 here: http://www.shamik.net/teaching/materials/dasgupta%20SL%20definitions.pdf
I've begun with the assumption (R v B) with the intentions of using Negation Introduction, then within that subderivation another 2 separate assumptions R and B with the intentions of using Disjunction Elimination. I'm trying to find a contradiction within the first subderivation in order to introduce the negation. Any help would be greatly appreciated.
Edit: In my class we use ~ instead of ¬, in case anyone was confused (trivial, I know)

A: So you're assuming $\neg R$ and $\neg B$, and have further assumed $R\lor B$ with the intention of using your $\neg\mathbf{Intro}$ rule in order to conclude $\neg(R\lor B)$. So far so good. You now need to produce a contradiction.
It also looks right to use the $\lor\mathbf{Exit}$ on the $R\lor B$ assumption. The problem now is that in each of those branches it's easy to produce a contradiction -- in one of them you're assuming $R$ which contradicts your overall $\neg R$ assumption, and in the other you're assuming $B$ which contradicts the overall $\neg B$ assumption. But the $\lor\mathbf{Exit}$ rule wants the two branches to have the same conclusion, and what you have easily is two different contradictions.
The trick for getting around this is to use $\neg\mathbf{Exit}$ in one of the branches to convert one contradiction to another. For example, let's say we're in the $R$ branch and we want to conclude $B\&\neg B$. Preparing to use $\neg\mathbf{Exit}$ we assume $\neg(B\&\neg B)$, and then immediately derive our already-present contradiction $R$ with $\neg R$. (We never use the assumption $\neg(B\&\neg B)$ while doing that, but nobody says we have to, as long as we end up with the premises the rule wants!). Thus we can conclude $B\&\neg B$. We can also immediately get that in the $B$ branch, so the proof now fits together!
As a bit of optimization we can save a bit of "plumbing" by letting the conclusion of the $\lor\mathbf{Exit}$ be just $B$ instead of $B\&\neg B$. Then we can draw on overall $\neg B$ assumption outside $\lor\mathbf{Exit}$. The $B$ branch of $\lor\mathbf{Exit}$ is now extremely simple; in the $R$ branch we conclude $B$ using $\neg\mathbf{Exit}$. (Namely, assume $\neg B$ (in addition to the assumption we already have), ignore that assumption, and pull the contradiction $R$ with $\neg R$ out of the other assumptions).
(Sorry if the prose description is hard to follow. It's not clear to me how your system wants formal proof sequences written down graphically such that assumptions are being properly kept track of).


text:
Q: How to represents stacked bar plot integer values in percentage Help please,
A, B and C are columns
X , Y , Z, Q , R are my index values
I want to make a stacked bar plot in python (matplot lib) which calculates the normalized - percentage values for each OUT_CAUSE per market and represents it in the chart.
 OUT_CAUSE  A   B   C
 MARKET
 X  12.0    11.0    4.0
 Y  9.0     12.0    3.0
 Z  16.0    40.0    1.0
 Q  23.0    19.0    3.0
 R  17.0    15.0    2.0

X axis of the plot should be MARKET
Y axis of the plot should be % contribution of OUT_CAUSE for each market.
Sum of the % should be equal to 100

I was using this for representation of direct numbers
df(kind='bar', stacked=True ,figsize=(8, 8));

A: You can have a loop to create %age for all columns:
for colname in df.columns:
    colsum = sum(df[colname])
    df[colname+'%'] = round(100*df[colname]/colsum,1)  # create new column for %ages

Output:
      A     B    C    A%    B%    C%
X  12.0  11.0  4.0  15.6  11.3  30.8
Y   9.0  12.0  3.0  11.7  12.4  23.1
Z  16.0  40.0  1.0  20.8  41.2   7.7
Q  23.0  19.0  3.0  29.9  19.6  23.1
R  17.0  15.0  2.0  22.1  15.5  15.4

You can then use following command to create your stacked bar chart:
df.iloc[:,3:].T.plot.bar(stacked=True, rot=0)
plt.show()

If you cannot count the number of columns, you can filter out columns names by presence of % character:
colnames = list(filter(lambda x: '%' in x, df.columns.tolist()))
df[colnames].T.plot.bar(stacked=True, rot=0)
plt.show()

A: A simple (but probably not the most effective) way to do it is to simply create a new column:
df['percentage'] = df['A']/df['A'].sum()

And then you simply plot the 'percentage' column.


text:
Q: Netbeans not running PHPUnit tests I am running PHP7.1 in the latest Netbeans version and am trying to run PHPUnit 6.5 along with it.  When I run the tests in Netbeans, they are not executed and the output window gives the following stacktrace:
"C:\bin\phpunit.bat" "--colors" "--log-junit" "C:\Users\rwinkler\AppData\Local\Temp\nb-phpunit-log.xml" "C:\bin\phpunit.phar"

Fatal error: Uncaught PHPUnit\Runner\Exception: Class 'C:\bin\phpunit' could not be found in 'C:\bin\phpunit.phar'. in phar://C:/bin/phpunit.phar/phpunit/Runner/StandardTestSuiteLoader.php:102
Stack trace:
#0 phar://C:/bin/phpunit.phar/phpunit/Runner/BaseTestRunner.php(130): PHPUnit\Runner\StandardTestSuiteLoader->load('C:\\bin\\phpunit', 'C:\\bin\\phpunit....')
#1 phar://C:/bin/phpunit.phar/phpunit/Runner/BaseTestRunner.php(73): PHPUnit\Runner\BaseTestRunner->loadSuiteClass('C:\\bin\\phpunit', 'C:\\bin\\phpunit....')
#2 phar://C:/bin/phpunit.phar/phpunit/TextUI/Command.php(169): PHPUnit\Runner\BaseTestRunner->getTest('C:\\bin\\phpunit', 'C:\\bin\\phpunit....', Array)
#3 phar://C:/bin/phpunit.phar/phpunit/TextUI/Command.php(148): PHPUnit\TextUI\Command->run(Array, true)
#4 C:\bin\phpunit.phar(570): PHPUnit\TextUI\Command::main()
#5 {main}
  thrown in phar://C:/bin/phpunit.phar/phpunit/Runner/StandardTestSuiteLoader.php on line 102
PHP Fatal error:  Uncaught PHPUnit\Runner\Exception: Class 'C:\bin\phpunit' could not be found in 'C:\bin\phpunit.phar'. in phar://C:/bin/phpunit.phar/phpunit/Runner/StandardTestSuiteLoader.php:102
Stack trace:
#0 phar://C:/bin/phpunit.phar/phpunit/Runner/BaseTestRunner.php(130): PHPUnit\Runner\StandardTestSuiteLoader->load('C:\\bin\\phpunit', 'C:\\bin\\phpunit....')
#1 phar://C:/bin/phpunit.phar/phpunit/Runner/BaseTestRunner.php(73): PHPUnit\Runner\BaseTestRunner->loadSuiteClass('C:\\bin\\phpunit', 'C:\\bin\\phpunit....')
#2 phar://C:/bin/phpunit.phar/phpunit/TextUI/Command.php(169): PHPUnit\Runner\BaseTestRunner->getTest('C:\\bin\\phpunit', 'C:\\bin\\phpunit....', Array)
#3 phar://C:/bin/phpunit.phar/phpunit/TextUI/Command.php(148): PHPUnit\TextUI\Command->run(Array, true)
#4 C:\bin\phpunit.phar(570): PHPUnit\TextUI\Command::main()
#5 {main}
  thrown in phar://C:/bin/phpunit.phar/phpunit/Runner/StandardTestSuiteLoader.php on line 102
Done.

My test is a sample test I pulled from a tutorial:
<?php
require_once 'PHPUnit/Autoload.php';
declare(strict_types=1);

use PHPUnit\Framework\TestCase;

final class EmailTest extends TestCase
{
    public function testCanBeCreatedFromValidEmailAddress(): void
    {
        $this->assertInstanceOf(
            Email::class,
            Email::fromString('user@example.com')
        );
    }

    public function testCannotBeCreatedFromInvalidEmailAddress(): void
    {
        $this->expectException(InvalidArgumentException::class);

        Email::fromString('invalid');
    }

    public function testCanBeUsedAsString(): void
    {
        $this->assertEquals(
            'user@example.com',
            Email::fromString('user@example.com')
        );
    }
}

A: Per xmike in the comments:
"i guess you have misconfigured Project properties -> Testing -> PHPUnit -> Use custom test suite (leave it empty) "


text:
Q: Как сделать проверки на requests.get("https://pastebin.com/raw/WdXuJnN2").json() Например, если паста https://pastebin.com/raw/WdXuJnN2 не доступна, или удалена, то он обращяется к другой пасте (тобиш резервную), а если уже она не доступна, то он выведит ошибку в плане print('Paste deleted')
попробовал так, но не работает
    mainJson = requests.get("https://pastebin.com/raw/0tEKwzzn").json()
    if mainJson["IsEnabled"] == False:
        print("Falsed!")
    elif mainJson["IsEnabled"] == True:
        print("Trued!")

A: Почекайте HTTP-код ответа от Pastebin, наверняка там будет 404:
response = requests.get(url)
if response.status_code != 200:
    // Что-то пошло не так, обрабатываем
   ...
else:
    // Всё идёт по плану
    mainJson = response.json()
    ...


text:
Q: NSKeyedArchiver returning nil for UIView's subviews I have one ViewController, in this i have added one Custom UIView named as DrawingView. I want to add dynamic number of UITextView in this DrawingView so i subclassed UITextView with class name as CustomTextView. In ViewController i have following code to add textview to DrawingView.
- (void)viewDidLoad
{
    [super viewDidLoad];
    DrawingView * newDrawingView = [[DrawingView alloc]init];
    self.drawingView = newDrawingView ;
}

-(void)setDrawingView:(DrawingView *)_drawingView
{
    if (drawingView != _drawingView)
    {
        [drawingView removeFromSuperview];
        drawingView = _drawingView;
        drawingView.customDelegate = self;
        drawingView.frame = scrollView.bounds;
        drawingView.layer.cornerRadius = 8;
        drawingView.backgroundColor = [UIColor whiteColor];
        drawingView.clipsToBounds = YES;

        [self.view addSubview:drawingView];
    }
}

On button action i add the CustomTextView in the drawing view.
currentText = [[TextViewContainer alloc]init];
[drawingView currentText];

Now I want to archive this DrawingView along with its subviews i.e the CustomTextView.
So in CustomTextView i added NSCoding Protocol and added properties in it
- (id)initWithCoder:(NSCoder *)aDecoder
{
     if ((self  =  [super initWithCoder:aDecoder]))
     {
         self.layer.borderWidth  =  [aDecoder decodeFloatForKey: @"borderWidth"] ;
     }
}

- (void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeFloat:self.layer.borderWidth forKey:@"borderWidth"];
}

there are other custom properties in the above methods.
For archiving i am using following methods.
- (NSData *)dataForView:(UIView *)view:(NSString *)fileName
{

    NSMutableData *data = [NSMutableData data];
    NSKeyedArchiver  *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    [archiver encodeObject:view forKey:fileName];
    [archiver finishEncoding];

    return (id)data;
}

-(void)saveChangesInFile :(NSString *)fileName
{
    NSData *data = [self dataForView:drawingView:fileName];

    NSString *docsDirectory  =  [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

    NSString *dataPath  =  [docsDirectory stringByAppendingPathComponent:@"/.hidden"];

    if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
    {
        [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:nil];
    }

    NSString *pathes  =  [dataPath stringByAppendingPathComponent:fileName];

    [data writeToFile:pathes atomically:YES];
}

- (UIView *)viewForData:(NSData *)data:(NSString*)key
{
    NSKeyedUnarchiver  *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];

    UIView *view = [unarchiver decodeObjectForKey:key];

    [unarchiver finishDecoding];

    return view;
}

-(void)openSavedFileWithName:(NSString*)fileName{

    NSString *docsDirectory  =  [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

    NSString *dataPath  =  [docsDirectory stringByAppendingPathComponent:@"/.hidden"];
    NSString *filepath = [dataPath stringByAppendingFormat:@"/%@",fileName];
    NSData *data = [NSData dataWithContentsOfFile:filepath];

    if (data)
    {
        UIView *newDrawView = [self viewForData:data:fileName];
    }
    NSLog(@"neew :%@",newDrawView.subviews);
    self.drawingView = (DrawingView *)newDrawView ;
    NSLog(@"self.drawingView :%@",self.drawingView.subviews);
}

But I am getting subview array as nil. Can anybody help me please.

A: Think you are trying to archive a view itself.
[archiver encodeObject:view forKey:fileName];

I think its wrong. You cannot Archive any UI components but you can only archive the model.
For example you can save the model (including the size, color and background images of the particular view) to the database and cannot save the view itself to the database. Likewise for archiving, u need to archive its data(viz, array, image, etc.) and not the UI components themselves.
Have a look at the NSKeyedArchiver ClassReference for the further details.
Also, please look at the link for detailed explaination.
Thanks.


text:
Q: Is it still a good practice to log parameters and returns? Just a context, I am currently making a base code for a Java Spring Boot Application.
I am currently setting up the logging of the application and I stumbled upong this url and found it helpful. Although it is a little bit outdated.
Questions

*

*In the url, 7) Log method arguments and return values, is this still relevant today? Should I manually do it in my methods?

*In an MVC application, should I do it in all layers? (Controllers, Services, and DAOs)?

A: I don't think that article is implying that every method should should be logged that way, it's just saying when you're logging make sure you capture the context in which the log occurred.
For example, if you have a log which says only "User cannot be found", if you're actually trying to understand the scenario which lead to that log then you probably need to know the user ID at least. Typically function arguments have the most significant affect on the output of a function so that's the most important context to capture, but class or global variables might also be just as important depending on the situation.
In the case of a Spring web application, I definitely wouldn't be putting logging in every single function, but I would be logging where failures are likely. For example, if you make a call to an external service.
The article itself states:

Of course, you must be reasonable but every method that: accesses
  external system (including database), blocks, waits, etc. should be
  considered.

Although, some of this logging might already be provided by your ORM or RDBMS so I wouldn't go adding logging to every single database call either.
The article also states:

You should consider DEBUG or TRACE levels as best suited for these
  types of logs.

Which typically aren't logged in production, so you might consider it an alternative to temporary print/echo statements during development. Again, only where appropriate.

A: Are you ever going to use the information logged?
It could be possibly be useful for debugging but then you will probably use a debugger anyway.
I have worked on projects where practicality everything was logged, but there was a real business requirement -- they needed forensic proof if bad/fraudulent behavior by "trusted" associates was detected.

A: From my option - logging parameters and return values must be present but turned off by default. E.g. by default nothing is logged or just needed things. But when somethings goes wrong you can easy enable logging via file config changing (log4j and logback support config updating with time interval).
What it give for you and what my goes wrong?

*

*First of all this approach is very usefully for situations when you can not run you code locally. For example aws lambda which may needs some security setting and may communicate with some other aws resources. In that case you can easy enable logging and rerun lambda to see what happens.

*Consider you production environment when bug can not be reproduced locally. In case when issue is hard to reproduce you can just enable extra logging for limited time (1 minutes or less for example) and see what happens in production. Small time period limit performace degradation for extra logging.

*Often during developent you code and then think - "It does not work, I have to add logging more here". Possibility of logging methods and parameters leads to less coding.

Do not mix bussines logging logic and logging for debug
For example if you work with external system it is better to add logging directly like: logger.info("Order created id={}", id) then enable all logging for all layer to see order id in logs.


text:
Q: \Underfull badness(10000) error message Can someone rectify this. Thanks in advance.
\textbf{Sub interval 1:}($t_{o}-t_{1}$)\\\
This sub-interval starts when D1 and D4 are Forward biased, so in this sub-interval D1-D4 and D6-D7 are conducting Bridge voltages $V_{h1}$, $V_{h2}$ and primary current $i_{r1}$ is as shown in waveform. This sub-interval ends when current is commuted from D6-D7 to S6-S7and from D1-D4 to S1-S4. Hence for ZVS operation of S1 and S4, primary current \fbox{ $i_{r}(t_{0})<0$}.\\


text:
Q: unable to post data for registering new user in mysql database using postman I am trying to post data to phpmyadmin mysql database for registering new users using postman.
I have the following files and i am using visual studio code editor:
1) Constants.php
2) DbConnect.php
3) DbOperations.php
4) register.php

Files 1,2 and 3 are contained in "includes" folder inside shoppingapptut folder in htdocs. File 4 is contained in "v1" folder inside shoppingapptut folder in htdocs
My Database Picture
postMan post parameters
PostMan Json Response
Constants.php Location:("C:\xampp\htdocs\shoppingapptut\includes\Constants.php")
<?php
    define('DB_NAME','shoppingapptut');
    define('DB_USER','root');
    define('DB_PASSWORD','');
    define('DB_HOST','localhost');
?>

DbConnect.php ("C:\xampp\htdocs\shoppingapptut\includes\Dbconnect.php")
<?php

    class DbConnect{
         private $con;

         function __construct(){

        }
    //Check con
    function connect(){
        include_once dirname(__FILE__).'/Constants.php';
        $this-> con = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);

        if(msqli_connect_errno()){
            echo "Failed to connect with database".mysqli_connect_err();
        }

        return $this->con;
    }

}

DbOperations.php ("C:\xampp\htdocs\shoppingapptut\includes\DbOperations.php")
<?php

    class DbOperations{
        private $con;

        //change equals with highphen
        function __construct(){
            require_once dirname(__FILE__).'/DbConnect.php';
            $db = new DbConnect();
            $this->con = $db->connect();
        }

        public function createUser($firstname, $lastname, $phonenumber, $username, $email, $pass){
            if($this->isUserExist($username, $email)){
                return 0;
            }else{
                $password = md5($pass);
                $query = $this -> con -> prepare("INSERT INTO `customer` (`id`,`firstname`,`lastname`,`phonenumber`,
                `username`,`email`,`password`) VALUES (NULL,?,?,?,?,?,?);");
                $query->bind_param("ssssss",$firstname,$lastname,$phonenumber,$username,$email,$password);

                if($query->execute()){
                    return 1;
                }else{
                    return 2;
                }
            }
        }

        private function isUserExist($username, $email){
            $query = $this ->con-> prepare("SELECT id FROM customer WHERE username = ? OR email = ?");
            $query->bind_param("ss", $username, $email);
            $query->execute();
            $query->store_result();

            return $query->num_rows > 0;
        }
    }
?>

register.php ("C:\xampp\htdocs\shoppingapptut\v1\register.php")
<?php

    require_once '../includes/DbOperations.php';

    $response = array();

    if($_SERVER['REQUEST_METHOD'] == 'POST'){
        if(isset($_POST['firstname']) and isset($_POST['lastname']) and
        isset($_POST['phonenumber']) and isset($_POST['username']) and
        isset($_POST['email']) and isset($_POST['password'])){
            $db = new DbOperations();

            $result = $db->createUser( $_POST['firstname'], $_POST['lastname'], $_POST['phonenumber'],
            $_POST['username'], $_POST['email'], $_POST['password'] );

            if($result == 1){
                $response['error'] = false;
                $response['message'] = "Registration Success";
            }elseif($result == 2){
                $response['error'] = true;
                $response['message'] = "Some error occured please try again";
            }elseif ($result == 0) {
                $response['error'] = true;
                $response['message'] = "It seems you are already registered,please login or choose a different email and username";
            }
        }else {
            $response['error'] = false;
            $response['message'] = "Required fields are missing";
        }

    }else {
        $response['error'] = true;
        $response['message'] = "Invalid Request";
    }

    echo json_encode($response);

?>

Am getting the following error on posting data:

Fatal error: Uncaught Error: Call to undefined function msqli_connect_errno() in
C:\xampp\htdocs\shoppingapptut\includes\Dbconnect.php:14
Stack trace:
0 C:\xampp\htdocs\shoppingapptut\includes\DbOperations.php(10): DbConnect->connect()
1 C:\xampp\htdocs\shoppingapptut\v1\register.php(11): DbOperations->__construct()
2 {main}
thrown in C:\xampp\htdocs\shoppingapptut\includes\Dbconnect.php on line 14
I want to be able to post new user data using postman and in doing soo register new user in the database


text:
Q: A simple question about rational numbers without a simple proof? As in this question, study the quasigroup $(Q_+,/)$ of positive rational numbers under division. There are two obvious identities:

*

*$a/(b/c)=c/(b/a)$, for all $a,b,c\in Q_+$

*$(a/b)/c=(a/c)/b$, for all $a,b,c\in Q_+$

How to decide if there are other independent identities, not possible to derive?
Could there be "mystical" identities of great complexity including several variables which are independent of 1 and 2?
The only way to go, as I can see, is to study equivalence classes of binary trees corresponding to expressions in $(Q_+,/)$.


text:
Q: Spring JPA skips inserting entity sometimes I have a springboot application, and have a custom implementation to record history of changes on JPA entities.
My main entity is Test, which extends from a Base class. The base class has the following annotations
@EntityListeners(HistoryEntityUpdater.class)
@Inheritance(strategy = InheritanceType.JOINED)
@DiscriminatorColumn(name = "object_type")

I have a custom entity listener with methods annotated with @PostPersist and @PostUpdate. In these methods I create an instance of TestHistory and call entityManager.persist. Although this works, but some of the history records are not getting inserted. Here's the log when the save is called, but database is not updated.
2016-04-22 19:57:58.428 TRACE 18060 --- [nio-9285-exec-2] o.h.e.jdbc.internal.JdbcCoordinatorImpl  : Releasing statement [sql : 'update managed_object set last_updated_time=?, name=?, workflow_status=? where id=?', parameters : ['2016-04-22 19:57:26.185','tests1','ERROR',1]]
2016-04-22 19:57:58.429 TRACE 18060 --- [nio-9285-exec-2] o.h.e.jdbc.internal.JdbcCoordinatorImpl  : Closing prepared statement [sql : 'update managed_object set last_updated_time=?, name=?, workflow_status=? where id=?', parameters : ['2016-04-22 19:57:26.185','tests1','ERROR',1]]
2016-04-22 19:57:58.429 TRACE 18060 --- [nio-9285-exec-2] o.h.e.jdbc.internal.JdbcCoordinatorImpl  : Starting after statement execution processing [ON_CLOSE]
2016-04-22 19:57:58.429 TRACE 18060 --- [nio-9285-exec-2] o.h.internal.util.SerializationHelper    : Starting clone through serialization
2016-04-22 19:57:58.429 TRACE 18060 --- [nio-9285-exec-2] o.h.internal.util.SerializationHelper    : Starting serialization of object [2016-04-22T14:27:26.185Z]
2016-04-22 19:57:58.429 TRACE 18060 --- [nio-9285-exec-2] o.h.internal.util.SerializationHelper    : Starting deserialization of object
2016-04-22 19:57:58.433 TRACE 18060 --- [nio-9285-exec-2] o.h.internal.util.SerializationHelper    : Attempting to locate class [java.time.Ser]
2016-04-22 19:57:58.434 DEBUG 18060 --- [nio-9285-exec-2] c.b.b.m.db.history.HistoryEntityUpdater  : postUpdate com.xyz.model.db.Test@4dcfc8b8
2016-04-22 19:57:58.435 TRACE 18060 --- [nio-9285-exec-2] o.hibernate.engine.spi.IdentifierValue   : ID unsaved-value strategy UNDEFINED
2016-04-22 19:57:58.436 TRACE 18060 --- [nio-9285-exec-2] o.h.e.i.AbstractSaveEventListener        : Transient instance of: com.xyz.model.db.history.TestHistory
2016-04-22 19:57:58.436 TRACE 18060 --- [nio-9285-exec-2] o.h.e.i.DefaultPersistEventListener      : Saving transient instance
2016-04-22 19:57:58.437 DEBUG 18060 --- [nio-9285-exec-2] o.h.e.i.AbstractSaveEventListener        : Generated identifier: component[id,revisionTime,revisionType]{revisionType=UPDATED, id=1, revisionTime=Fri Apr 22 19:57:58 IST 2016}, using strategy: org.hibernate.id.CompositeNestedGeneratedValueGenerator
2016-04-22 19:57:58.437 TRACE 18060 --- [nio-9285-exec-2] o.h.e.i.AbstractSaveEventListener        : Saving [com.xyz.model.db.history.TestHistory#component[id,revisionTime,revisionType]{revisionType=UPDATED, id=1, revisionTime=Fri Apr 22 19:57:58 IST 2016}]
2016-04-22 19:57:58.437 TRACE 18060 --- [nio-9285-exec-2] org.hibernate.engine.spi.ActionQueue     : Adding an EntityInsertAction for [com.xyz.model.db.history.TestHistory] object
2016-04-22 19:57:58.437 TRACE 18060 --- [nio-9285-exec-2] org.hibernate.engine.spi.ActionQueue     : Adding insert with no non-nullable, transient entities: [EntityInsertAction[com.xyz.model.db.history.TestHistory#com.xyz.model.db.history.HistoryObject$HistoryId@4b74eea0]]
2016-04-22 19:57:58.437 TRACE 18060 --- [nio-9285-exec-2] org.hibernate.engine.spi.ActionQueue     : Adding resolved non-early insert action.
2016-04-22 19:57:58.437 TRACE 18060 --- [nio-9285-exec-2] o.h.a.i.UnresolvedEntityInsertActions    : No unresolved entity inserts that depended on [[com.xyz.db.history.TestHistory#com.xyz.db.history.HistoryObject$HistoryId@4b74eea0]]
2016-04-22 19:57:58.437 TRACE 18060 --- [nio-9285-exec-2] o.h.a.i.UnresolvedEntityInsertActions    : No entity insert actions have non-nullable, transient entity dependencies.
2016-04-22 19:57:58.438 TRACE 18060 --- [nio-9285-exec-2] o.h.e.jdbc.internal.JdbcCoordinatorImpl  : Starting after statement execution processing [ON_CLOSE]
2016-04-22 19:57:58.438 TRACE 18060 --- [nio-9285-exec-2] o.h.e.i.AbstractFlushingEventListener    : Post flush
2016-04-22 19:57:58.438 TRACE 18060 --- [nio-9285-exec-2] org.hibernate.internal.SessionImpl       : before transaction completion
2016-04-22 19:57:58.440 DEBUG 18060 --- [nio-9285-exec-2] o.h.e.t.internal.jdbc.JdbcTransaction    : committed JDBC Connection
2016-04-22 19:57:58.440 DEBUG 18060 --- [nio-9285-exec-2] o.h.e.t.internal.jdbc.JdbcTransaction    : re-enabling autocommit
2016-04-22 19:57:58.441 TRACE 18060 --- [nio-9285-exec-2] o.h.e.t.i.TransactionCoordinatorImpl     : after transaction completion
2016-04-22 19:57:58.442 TRACE 18060 --- [nio-9285-exec-2] org.hibernate.internal.SessionImpl       : after transaction completion
2016-04-22 19:57:58.443 TRACE 18060 --- [nio-9285-exec-2] org.hibernate.internal.SessionImpl       : Closing session
2016-04-22 19:57:58.443 TRACE 18060 --- [nio-9285-exec-2] o.h.e.jdbc.internal.JdbcCoordinatorImpl  : Closing JDBC container [org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl@5be5a598]
2016-04-22 19:57:58.443 DEBUG 18060 --- [nio-9285-exec-2] o.h.e.jdbc.internal.JdbcCoordinatorImpl  : HHH000420: Closing un-released batch
2016-04-22 19:57:58.443 TRACE 18060 --- [nio-9285-exec-2] o.h.e.j.internal.LogicalConnectionImpl   : Closing logical connection
2016-04-22 19:57:58.443 DEBUG 18060 --- [nio-9285-exec-2] o.h.e.j.internal.LogicalConnectionImpl   : Releasing JDBC connection
2016-04-22 19:57:58.443 DEBUG 18060 --- [nio-9285-exec-2] o.h.e.j.internal.LogicalConnectionImpl   : Released JDBC connection
2016-04-22 19:57:58.443 TRACE 18060 --- [nio-9285-exec-2] o.h.e.j.internal.LogicalConnectionImpl   : Logical connection closed

The postUpdate and postPersist methods on HistoryEntityUpdater are annotated with @Transactional

A: The JPA specs state that EntityListeners should not use the EntityManager.
This makes them useless for most use cases, including yours.
I was not aware of that either.
From your stacktrace it looks like the JDBC transaction is already committed and the entitymanager is flushed.
So at least you don't have any transaction when your listener runs. And this might lead to situations where the written history entities are not written to the database.
The EntityListener is called by hibernate and not by spring, so any @Transactional annotations on your listener will not work.
Finally there is a solution for you, use 'Envers' to implement entity auditing :
database auditing jpa


text:
Q: Refresh layout when get push notification How can I refresh layout when get push notification?
I get class:
    @Override
    protected void onHandleIntent(Intent intent) {
        Bundle extras = intent.getExtras();
        GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
        // The getMessageType() intent parameter must be the intent you received
        // in your BroadcastReceiver.
        String messageType = gcm.getMessageType(intent);

        if (!extras.isEmpty()) {  // has effect of unparcelling Bundle
            /*
             * Filter messages based on message type. Since it is likely that GCM will be
             * extended in the future with new message types, just ignore any message types you're
             * not interested in, or that you don't recognize.
             */
            if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
                sendNotification("Send error: " + extras.toString());
            } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
                sendNotification("Deleted messages on server: " + extras.toString());
                // If it's a regular GCM message, do some work.
            } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
                // This loop represents the service doing some work.
                for (int i = 0; i < 5; i++) {

                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                    }
                }
                // Post notification of received message.
                message = extras.getString("message");
                badgeCount = extras.getString("badge");
                sendNotification("Received: " + extras.toString());
            }
        }
        // Release the wake lock provided by the WakefulBroadcastReceiver.
        GcmBroadcastReceiver.completeWakefulIntent(intent);
    }

    // Put the message into a notification and post it.
    // This is just one simple example of what you might choose to do with
    // a GCM message.
    private void sendNotification(String msg) {

        int requestID = (int) System.currentTimeMillis();

        mNotificationManager  = (NotificationManager)getApplication().getSystemService(Context.NOTIFICATION_SERVICE);

        Intent notificationIntent = new Intent(getApplicationContext(), MainPageActivity.class);

        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

        PendingIntent contentIntent = PendingIntent.getActivity(this, requestID,notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext())
                .setSmallIcon(R.drawable.icons)
                .setContentTitle(getString(R.string.app_name))
                .setStyle(new NotificationCompat.BigTextStyle()
                        .bigText(message))
                .setContentText(message).setAutoCancel(true);
        mBuilder.setContentIntent(contentIntent);
        mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());

        try {
            if(Integer.parseInt(badgeCount) != 0)
                ShortcutBadger.setBadge(getApplicationContext(), Integer.parseInt(badgeCount));
        } catch (ShortcutBadgeException e) {
            //handle the Exception
        }

    }

}

where I receive push  notification. So, when I am in first activity and get push notification I want to refresh all this activity. This should work with 3 activities, so when I am in second activity and get push so this second activity should recreate. Any ideas how can I do that?

A: You can make user of LocalBroadcastManager
ReceiverActivity.java
An activity that watches for notifications for the event named "custom-event-name".
@Override
public void onCreate(Bundle savedInstanceState) {

  ...

  // Register to receive messages.
  // We are registering an observer (mMessageReceiver) to receive Intents
  // with actions named "custom-event-name".
  LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
      new IntentFilter("custom-event-name"));
}

// Our handler for received Intents. This will be called whenever an Intent
// with an action named "custom-event-name" is broadcasted.
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
  @Override
  public void onReceive(Context context, Intent intent) {
    // Get extra data included in the Intent
    String message = intent.getStringExtra("message");
    Log.d("receiver", "Got message: " + message);
  }
};

@Override
protected void onDestroy() {
  // Unregister since the activity is about to be closed.
  LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
  super.onDestroy();
}

SenderActivity.java
The second activity that sends/broadcasts notifications.
@Override
public void onCreate(Bundle savedInstanceState) {

  ...

  // Every time a button is clicked, we want to broadcast a notification.
  findViewById(R.id.button_send).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
      sendMessage();
    }
  });
}

// Send an Intent with an action named "custom-event-name". The Intent sent should
// be received by the ReceiverActivity.
private void sendMessage() {
  Log.d("sender", "Broadcasting message");
  Intent intent = new Intent("custom-event-name");
  // You can also include some extra data.
  intent.putExtra("message", "This is my message!");
  LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}

You can send message(SecondActivity.java) from the onMessage method of your notification receiver.


text:
Q: Execute java spring project from command line I have a Java Spring project, using tomcat, and I want to know how to run it with command line, today I only know using eclipse, I would like to run something like in Rails
rails s

How can I do that?

A: Have a look at Spring Boot - if the app is already built using Spring it will probably port pretty easily. It allows you to build the app as a jar file and it'll start it's own embedded servlet container to provide the environment for your app to run in.

A: There are some ways to do it, if you have a Spring MVC project you could build a war file and deploy it as a web application on tomcat (put a war file to tomcat webapps dir and start a tomcat - you can do it with startup.sh file in tomcat bin directory).
If you have a Spring boot application you can package your application as jar/war and start it with java -jar application.war command.

A: in springboot application we can use embedded servers like tomcat or jetty , just include corresponding entries in pom.xml and build war file.
for ex:
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
     </dependency>
<dependency>
   <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
 </dependency>

OR
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jetty</artifactId>
</dependency>

and then open cmd and run any of the command:
java -jar application.war
javaw -jar application.war


text:
Q: React parent access state from child How can I display state from child inside parent in React?
var Form = React.createClass({
    render: function() {
        return (
        <form>

***CHILD STATE CHECKED***

            {this.props.children}
        </form>
        )
    }
})

var Checkbox = React.createClass({
    getInitialState: function() {
        return {
            checked: true
        }
    },

    toggle: function() {
        this.setState({
            checked: !this.state.checked
        });
    },

    render: function() {
        return (

        );
    }
})

ReactDOM.render(
    <Form>
        <Checkbox />
    </Form>,
    document.querySelector('#app')
);

What is the best way to display the state of the child inside its parent (especially inside this  tag in parent component)?
Is this possible without "ugly tricks"?
I want add some nodes or other components to the form when checkbox is checked.

A: Do not call toggle in Checkbox. Pass a callback from Form class to CheckBox class.
In Form Class:
return(
        <CheckBox onClick={this.onClick} />
)

    onClick(){
        console.log('Checkbox clicked');
    }

In CheckBox class:

Manage state in parent class, not in child class.

A: Although if the answer to manage the state for this CheckBox in parent's state is correct, in some a bit more complicated cases you might still need to pass the state from child to component: concept is similar, you'll need to pass a function from parent to child, which will be used like a callback, and in which you will handle that child's state:
var Form = React.createClass({
    handleChildStateChange: function(newChildState) {
        // handle the child state change here
    }

    render: function() {
        const updatedChildren = React.Children.map(this.props.children,
            (child) => {
                return React.cloneElement(child, { updateParent: this.handleChildStateChange });
        });
        return (
            <form>

***CHILD STATE CHECKED***

                {updatedChildren}
            </form>
        )
    }
})

Then, when updating the state in child component, call the passed function with new state as a parameter (I use functional setState here because of asynchronous nature of state):
var Checkbox = React.createClass({
    getInitialState: function() {
        return {
            checked: true
        }
    },

    toggle: function() {
        this.setState((state) => {
            state.checked = !state.checked;
            this.props.updateParent(state);
            return state;
        });
    },

    render: function() {
        return (

        );
    }
})

In the end, the render you used remains the same:
ReactDOM.render(
    <Form>
        <Checkbox />
    </Form>,
    document.querySelector('#app')
);

If you want to learn more about passing of props from children to parents, this article might be helpful.


text:
Q: Could not start a website in android emulator with capybara, appium, ruby I try to open a website in chrome and native android browser (emulated Android 5.0 and 6) to check several items.
every time i run the test, the choosen browser get started and in the url field stays 'data:,' btw the actual tab is also loaded two times.
I know there is a way to do this with selenium webdriver, but this is not the right way for me because i used the followed code for several emulated devices to test this website and on iOS/Mac osx its working.
So why not on android. My way to test this website is with capybara, appium and ruby.
on iOS there exists a
:safariInitialUrl =>'http://www.mypage.com'

cap.
but not for android.
So, my question is: how is it possible to start my website on an emulated android devices without using selenium webdriver.
code:
Capybara.register_driver :androidphone do |app|

capabilities = {
:deviceName => 'nex5_5',
:avd => 'nex5_5',
:browserName => 'Chrome',
:platformVersion => '5.0',
:platformName => 'Android',
:automationName => 'Appium',
}

url = "http://localhost:4723/wd/hub"

appium_lib_options = {
server_url: url
}

all_options = {
appium_lib: appium_lib_options,
caps: capabilities,
}

Appium::Capybara::Driver.new app, all_options

A: You have to add this line in your config file :
    exports.config = {
        directConnect:false,
    }
I think you have also to add the Timeout in your configuration file, if you are using jasmine framework for example add this code :
 jasmineNodeOpts: {
        defaultTimeoutInterval: 30000
    }


text:
Q: Mathematically rigorous Quantum Mechanics I am a student of mathematics attending a course in Quantum Mechanics. This course is held by a physicist, and it is really confusing for me to follow his reasonments. With this, I do not mean to be arrogant or disrespectful, it is only  a matter of backgrounds. I was wondering if anyone knows a textbook which is mathematically rigorous, in the sense that the functional analytical structure of the subject (distributions, measures, Hilbert spaces, duality)  is properly handled. Instead of doing inconceivable (for me) things such as considering Dirac's delta a function or distinguishing between a state in $L^2(V)$ and its Fourier coefficients in $l^2$, when we have a nice isomorphism between these two.
I have background in Functional Analysis, Measure Theory and Topology, but a reference which explains also some mathematics would be good, you never know. The course covers all the basis of quantum mechanics, hence: Schroedinger and Dirac's picture with examples (hclassical problems, harmonic oscillator, hydrogen atom), spins and reaches the helium atom. Mostly it follows Schwabl Quantum Mechanics https://www.springer.com/it/book/9783540719328, which I consulted but does not provide what I search for.
I really want to make it clear: I really appreciate physicists and their stunning mind elasticity: after all, most of distribution theory was developed to underpin what Dirac had grasped with intuition. But I am just a student trying to do my best at college, and I need to cope with my background!
Thanks in advance.

A: You might try Hall, "Quantum Theory for Mathematicians".

A: To just place most of the course on a firm math footing, you could read Von Neumann's " Mathematical Foundations of Quantum Mechanics ISBN-13: 978-0691028934, particularly chapter 2. You would still be missing the Clifford algebra that underlies the Dirac equation, but there are several good math books on that.
But you are clearly missing the point of the class.  Form a purely intellectual point of view, the professor is trying to convey applied math techniques that are relevant to the physics of elementary particles/fields.  (BTW, "field" in this sense is not the same word as "field" in the sense of a set with two operations obeying certain properties.)
So for example, the course should cover some aspects of perturbation theory, some aspects of Fourier theory, more orthogonal function theory (Laguerre polynomials and spherical harmonics, for example), Green's functions, and so forth.  If you get stuck on the foundational aspects of each of these, you will never make it to an understanding of the calculational techniques, which should be the fun part of the course for a strong mathematician.  And you also will never make it to an understanding of the underlying physics ideas (which you might not care about, and that's OK).

You need to treat this course as an excursion into mathematics which is different than the math you have already studied. The fact that the Delta functions and Fourier analysis used are closely related to concepts you are already comfortable with should not be dwelt on, or you will miss the real content of the course.

As a test of whether you grasp what the professor is trying to teach, try finding the energy levels and orbital structures oa 4-dimensional Hydrogen atom (still assuming a $\frac1{r^2}$ central attractive force).  That should lead you to Gegenbaur polynomials instead of Legendre polynomials.
Then redo that using a $\frac1{r^3}$ force, which would be necessary to have the same Gauss's Law relation between charge and flux in 4 space dimensions.  Based on the different nature of that problem, you could speculate why our usual physics only works in three dimensions.


text:
Q: Given two probability measures, which Markov kernels act on the first to give the second? Suppose I have a Markov kernel $\Sigma \colon \Omega\to\Delta(S)$.
For any measure $\tau \in \Delta(\Omega)$, I can obtain a measure $\tau\Sigma \in \Delta(S)$ considering
$$(\tau\Sigma)(A) = \int_{\Omega} \Sigma(\omega)(A) \,\mathrm{d}\tau(\omega) \,.$$
In other words, I can obtain a measure on $S$ by considering the average of the kernel with respect to the measure on $\Omega$.
Suppose now I have two probability measures $\mu \in \Delta(\Omega)$ and $\nu \in \Delta(S)$, it makes sense to consider the (maybe empty) set
$$\{\Sigma \colon \Omega \to \Delta(S) \mid \mu\Sigma = \nu\} \,.$$
How can I characterize such a set? When $\Omega$ and $S$ are finite sets, one can represent Markov kernels as matrices (summing to one on coloumns) and probability distribution as vectors, and the problem  reduces to a linear algebra one, but still, I can't see an easy general solution.
Do you have any reference on the  operation above producing a probability measure from a probability measure and a Markov kernel? I can only notice thatwhen the Markov kernel is something of the form $\Omega \to \Delta(\Omega)$ (a coalgebra for $\Delta$) it seems to define the action of the (monoid?) of such Markov kernels over $\Delta(\Omega)$.

A: Using the Disintegration theorem, it suffices that there exist a map $\pi : S \rightarrow \Omega $ such that $\mu$ is the pushforward of $\nu$ with respect to $\pi$. Then, for each such $\pi$, the disintegration theorem furnishes you with a unique Markov kernel (up to measure zero).
Now, given measures $\mu$ and $\nu$, does there always exist such a map $\pi$? For general spaces this is a complicated question. However, in the discrete case you are considering, one can always produce such a map provided that the cardinality of the support of $\mu$ divides that of $\nu$ (for instance, the solution to the so-called Monge problem from optimal transport provides such a map).
However, you ask for how to characterize the set of all Markov kernels K for which $ K \mu = \nu $. In principle this set is at least as complicated as the set of all functions $\pi$ that push forward $\nu$ to $\mu$. I expect this set is very complicated unless one puts very strict assumptions on $\mu$ and $\nu$, but am not aware of any general work in this direction.


text:
Q: How to include many pages dynamically using ui:include Primefaces? I am beginner.
I am doing a project using Primefaces.
I need to include many pages dynamically when triggering the p:menuitem.
I already tried but the dynamic pages are not included properly when clicked on p:menuitem and that page only show when refresh of the page(browser).
Sample Code

    <ui:include src="#{Pages.dynamicaPagesInclude}"/>

I do not know where I did mistake.
Any Idea?

A: Please, try this:
index.xhtml:This file is the "main" page, the page which contains the menu to select the dynamic pages to load.
When you press over the menuItem, the page attribute is set to the selected page value. Then, an ajax request invokes to changePage method which is in charge to set the page to load. We say to menuItem that we need to update the outputPanel which contains the new page load to show it on the browser.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<h:head>
    <title>Test Prime</title>
</h:head>

<h:body>
    <h:form id="formulario">

            <ui:include src="#{pages.dynamicaPagesInclude}" />

    </h:form>
</h:body>

page1.xhtml:Dummy page which represents a new page.
<ui:composition
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:ui="http://java.sun.com/jsf/facelets">

PAGE 1

</ui:composition>

page2.xhtml:Dummy page which represents a different page.
<ui:composition
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:ui="http://java.sun.com/jsf/facelets">

PAGE 2

</ui:composition>

Pages.java:This java class is the ManagedBean for controlling the view. It contains a string field called dynamicaPagesInclude with the path of the page to load.
The method changePage gets the attribute page which was set by the menuitem. Depending its value, chooses a page or other.
import javax.faces.bean.ManagedBean;
import javax.faces.event.ActionEvent;

@ManagedBean
public class Pages {

    private String dynamicaPagesInclude;

    public String getDynamicaPagesInclude() {
        return dynamicaPagesInclude;
    }

    public void setDynamicaPagesInclude(String dynamicaPagesInclude) {
        this.dynamicaPagesInclude = dynamicaPagesInclude;
    }

    public void changePage(int itemSelected ) {
        if (itemSelected == 1) {
            dynamicaPagesInclude = "page1.xhtml";
        } else {
            dynamicaPagesInclude = "page2.xhtml";
        }
    }
}

Sorry for my English level.


text:
Q: Evaluating the sum using Taylor series I want to find
$$\sum\limits_{x=0}^{\infty} \frac{xe^{2x-5}5^x}{x!} $$
The book has this problem in says to use for the Taylor series of $e^x = \sum\limits_{j=1}^{\infty} \frac{x^j}{j!} $ . I then got no idea how the book came to a final answer of $4e^2$. Any help from anyone would be greatly appreciated :)

A: Hint
1) First huge hint: change that awfully lookin  running index $\;x\;$ for $\;k,n,m\;$ or something similar.
2) Use the series for the exponential function with
$$\sum_{k=0}^\infty\frac{k\,3^{2k-5}5^k}{k!}=\frac1{e^5}\sum_{k=1}\frac{(5e^2)^k}{(k-1)!}$$


text:
Q: Inno Setup Delete method not working as expected I have an application version that includes a hash. For sake of the installer, I want a simple version without the hash. I have the following code which mostly works, the part in question is the Delete call which according to the documentation Deletes the specified number of characters beginning with Index from S. S is passed by reference (therefore is modified).
#define FullAppVersion "0.0.9 - abcdef012345"
#expr WriteIni("D:\\debug.txt", "Debug", "Full", FullAppVersion)

#define SimpleVersion FullAppVersion
#expr WriteIni("D:\\debug.txt", "Debug", "SimpleBefore", SimpleVersion)

#define HashPos Pos(' ', SimpleVersion)
#expr WriteIni("D:\\debug.txt", "Debug", "Pos", HashPos)

#expr Delete(SimpleVersion, HashPos)
#expr WriteIni("D:\\debug.txt", "Debug", "SimpleAfter", SimpleVersion)

However, when the above is executed, the debug looks as such:
[Debug]
Full=0.0.9 - abcdef012345
SimpleBefore=0.0.9 - abcdef012345
Pos=6
SimpleAfter=0.0.90.0.9 - abcdef012345

Delete seems to partially work by trimming from the specified position, but then additionally concatenates the entire string at the end.
Am I doing something incorrectly, or is there a glitch in the function? Using Inno Setup Compiler 5.5.5 and Inno Script Studio 2.2.1.31


text:
Q: Multi database query ACCESS and SQL SERVER I'm not able to figure out how to make a multi database query usign two diffent ditabase.
The first database is an ACCESS mdb database and the second one is a SQL Server 2012 database.
I'm using Visual Basic 6.
The code I'm using is that:
ConnectionString1 = "Provider=Microsoft.Jet.OLEDB.4.0;Persist Security Info=False;Data Source=C:\MyDatabase.mdb"
ConnectionString2 = "DSN=ODBC_NAME;UID=user;PWD=password"

SQL = "SELECT tabScheda.sWorkNum FROM tabScheda WHERE codScheda NOT IN" + _
      "  (SELECT ORDERID FROM [" + ConnectionString2 + "].V_PRESETTING_SP_HEADER WHERE MODE = 'TC')"

cn.Open ConnectionString1

Set rc = cn.Execute(SQL)

rc.Close
Set rc = Nothing
cn.Close
Set cn = Nothing

Please help me :D


text:
Q: Counting the same column with different where conditions I have a table called employees, whose schema looks like the following:
mysql> desc employees;
+------------+---------------+------+-----+---------+-------+
| Field      | Type          | Null | Key | Default | Extra |
+------------+---------------+------+-----+---------+-------+
| emp_no     | int(11)       | NO   | PRI | NULL    |       |
| birth_date | date          | NO   |     | NULL    |       |
| first_name | varchar(14)   | NO   |     | NULL    |       |
| last_name  | varchar(16)   | NO   |     | NULL    |       |
| gender     | enum('M','F') | NO   |     | NULL    |       |
| hire_date  | date          | NO   |     | NULL    |       |
+------------+---------------+------+-----+---------+-------+

I just want to query the count of emp_no for Males (where generder = 'M') and females (where generder = 'F').
I want the results like:
+--------+--------+
| Male   | FeMale |
+--------+--------+
| 300    | 120    |
+--------+--------+

Any suggestion on how to do that in a single query?

A: SELECT SUM(gender = 'M') AS Male, SUM(gender = 'F') AS Female
FROM employees

A: select sum(case when gender = 'm' then 1 else 0 end) male,
sum(case when gender = 'f' then 1 else 0 end) female,
from employees

you could try something like that


text:
Q: How to selectively start and end a persistent Apache::DBI for perl from the client/browser? This question is related to our web-based application, which uses perl, apache, Apache::DBI and a database (MySQL, SQLite, or anything).
We know that Apache::DBI is used to create persistent db connections.  These connections live in memory from the time the Apache web server starts to the time it shuts down.
My Question is: Is it possible to create persistent db connections at any arbitrary time between the start and end of Apache process? We don't want to have persistent connections throughout the life of the Apache web server process.
We need to create persistent connections any time after the Apache web server is started. And we need to end persistent connections any time before the Apache web server is shut down.

A: I'm not pretty sure about the way to do it.
But i would suggest to create a module, specifically to launch your connection, use
it, and end it.
Inside it you get your connection as a scalar, say $dbh, that will be common to everyone calling DBI functions (ùaking request to your mysql server).

package myBDDConnection;
use DBI;
our @EXPORT_OK = qw(&Query);

our $dbh = Connect();

sub Connect(){
my $dbh = DBI->connect(...);
...
return $dbh;
}
sub Query() {
 if(!$dbh) {$dbh=Connect()}
  //then perform query
}

sub Close(){
 $dbh->close() //or finish, i'm not sure
}

then, in your other modules, you import your myBDDConnection, and perform queries through the Query function from the previous module.


text:
Q: How do I access elements in multiple nested fragment from an activity in android I am working on a "guided tour" feature for my android application and need to dim and brighten certain elements on the current screen. I am using fragments for each screen and when I try to access elements in those fragments from the activity they are always null. I have been through countless questions and none seem to help me.
The structure of the fragments is as follows:

*

*I'm using a Fragment TabHost that has only two tabs.

*Each tab widget has a container fragment that I use to switch between a fragment A and a fragment B within one tab.

I'm going to start the tour from Tab one, fragment b but everytime I try to get the elements they are null even if I create a new fragment the line before let alone try to drill down into nested fragments.
I am trying to find the fragment using getSupportFragmentMangager() but since I have to get elements 3 fragments deep I end up trying to do an operation on an element that is null. I hope I am not missing something simple here. I am unsure where to start.

A: Why not store a static reference to the variables you need global access to in the Activity, then access them like MyActivity.class.myVariable and use getSupportFragmentManager#replace() to swap out the fragments dynamically?

A: You can use getChildFragmentManager() instead of getSupportFragmentMangager()

A: I discovered my problem was that the view being created by the fragment was simply not finished and therefore not displayed when I called my code to get elements from the fragment layout. I needed to wait until it was done being created and then I could find any element including elements in nested fragments. The nesting of views didn't matter.
This code fixed my problem:
import android.os.Handler;

//After doing replace transaction
final FragmentManager fragmentManager = getSupportFragmentManager();
final Handler handler = new Handler();
//Wait for fragment view to be created
handler.postDelayed(new Runnable() {
    @Override
    public void run(){
        //Do stuff after 100 miliseconds
        TabHostParent_Fragment myFrag = (TabHostParent_Fragment) fragmentManager.findFragmentByTag("tabhost_frag");
        Switch auto_switch = (Switch) findViewById(R.id.auto_switch);
        auto_switch.performClick();
    }
}, 100);


text:
Q: Using variables for CSS properties in Sass I am writing a @mixin with some math in it that calculates the percentage width of an element, but since it is very useful I would like to use the same function for other properties too, like margins and paddings.
Is there a way to pass the property name as an argument to a mixin?
@mixin w_fluid($property_name, $w_element,$w_parent:16) {
    $property_name: percentage(($w_element/$w_parent));
}

A: You need to use interpolation (eg. #{$var}) on your variable in order for Sass to treat it as a CSS property.  Without it, you're just performing variable assignment.
@mixin w_fluid($property_name, $w_element, $w_parent:16) {
    #{$property_name}: percentage(($w_element / $w_parent));
}

A: In addition to the @rcorbellini response
You can use string and variable together
@mixin margin($direction) { // element spacing

    margin-#{$direction}: 10px;

}


text:
Q: Build a plot with data from three different areas to observe trends I'm working on trace element concentrations in rivers inside a catchment area. I'm always looking at the same two elements, cadmium (Element 1) and aluminium (Element 2).
I have three different rivers, with fluctuating concentrations, found at the same date (3 different teams on each river).
My aim would be to have a chart where the three rivers appear, but where rivers are ranked according to the concentrations found (where we could see which river contributes the most i.e. which river is the most impacted).
Any thoughts on how I could proceed? I'm using excel, but can jump on R if needed.


text:
Q: Notation problem in Sets Consider two sets :
$\{1,2,3\}$ and $\{1,2,3,4\}$
What is $\{1,2,3\}\setminus\{1,2,3,4\}$?
I am giving an example of the two sets. I want to understand what that $\setminus$
of the two sets above imply?

A: $A\setminus B$ is the set containing all elements of $A$ not in $B$. It is a subset of $A$.
Here, as $A\subseteq B$, $A\setminus B=\varnothing$.


text:
Q: ReactiveUI Invoke Command on ViewModel when event fires in View I am using the Reactive UI events expansion to Reactive UI.
Just playing around getting events to connect to the ViewModel.
Originally I had in my constructor of my View
        this.Events().KeyDown.Select(x => x.Key).InvokeCommand(ViewModel.NewTextCommand);

However, this has the issue in the constructor the view model does not exist yet. I considered adding a WhenAnyValue and setting up the Invoke but not sure if this could lead to memory leaks.
At the moment I have
        this.Events().KeyDown.Select(x => x.Key).Subscribe(
            x =>
            {
                if (ViewModel != null)
                {
                    if (ViewModel.NewTextCommand.CanExecute(x))
                    {
                        ViewModel.NewTextCommand.Execute(x);
                    }
                }
            });

This seems a bit clumsy though.

A: You can definitely use WhenAnyValue, but there's also a built-in InvokeCommand overload in ReactiveUI to do this:
this.Events().KeyDown.Select(x => x.Key).InvokeCommand(this, v => v.ViewModel.NewTextCommand);


text:
Q: Cannot complete the kubernetes cluster authentication step with python client I want to authenticate to a kubernetes cluster through python client library from here. The cluster information:

Kubernetes control plane is running at https://127.0.0.1:34823
CoreDNS is running at https://127.0.0.1:34823/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy

I did all the steps with no problem. But in:
curl -s -k -XGET -H "Authorization: Bearer $KIND_TOKEN" -H "Accept: application/json, */*" -H "Content-Type: application/json" \
    -H "kubernetes/$Format" 'https://127.0.0.1:34823/api/v1/namespaces/default/pods/example' | jq .status.phase

got error:

jq: error (at :12): Cannot index string with string "phase"

Also once I tried to test:
from kubernetes import client
import os

configuration = client.Configuration()
configuration.api_key_prefix["authorization"] = "Bearer"
configuration.host = "https://127.0.0.1:34823"
configuration.api_key["authorization"] = os.getenv("KIND_TOKEN", None)
configuration.verify_ssl = False  # Only for testing with KinD!
api_client = client.ApiClient(configuration)
v1 = client.CoreV1Api(api_client)

ret = v1.list_namespaced_pod(namespace="default", watch=False)
for pod in ret.items:
    print(f"Name: {pod.metadata.name}, Namespace: {pod.metadata.namespace} IP: {pod.status.pod_ip}")

An other error:

MaxRetryError: HTTPConnectionPool(host=' https', port=80): Max retries exceeded with url: //127.0.0.1:34823/api/v1/namespaces/default/pods?watch=False (Caused by ProtocolError('Connection aborted.', InvalidURL("URL can't contain control characters. ' https' (found at least ' ')")))

The jq version is jq-1.6.