text:
Q: How do I install netfilterqueue for python3? I am doing a project with python3.8 as my interpreter in pycharm.
How do I install netfilterqueue so that it works in python3? I have tried to run the following command in my kali terminal but I get the following error:
root@kali:~/PycharmProjects/dns_spoof# pip3 install netfilterqueue
Collecting netfilterqueue
  Cache entry deserialization failed, entry ignored
  Using cached https://files.pythonhosted.org/packages/39/c4/8f73f70442aa4094b3c37876c96cddad2c3e74c058f6cd9cb017d37ffac0/NetfilterQueue-0.8.1.tar.gz
Building wheels for collected packages: netfilterqueue
  Running setup.py bdist_wheel for netfilterqueue ... error
  Complete output from command /usr/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-install-evvln_9d/netfilterqueue/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d /tmp/pip-wheel-z72tnt4e --python-tag cp37:
  running bdist_wheel
  running build
  running build_ext
  building 'netfilterqueue' extension
  creating build
  creating build/temp.linux-x86_64-3.7
  x86_64-linux-gnu-gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -g -fwrapv -O2 -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I/usr/include/python3.7m -c netfilterqueue.c -o build/temp.linux-x86_64-3.7/netfilterqueue.o
  netfilterqueue.c: In function '__pyx_f_14netfilterqueue_6Packet_set_nfq_data':
  netfilterqueue.c:2150:68: warning: passing argument 2 of 'nfq_get_payload' from incompatible pointer type [-Wincompatible-pointer-types]
   2150 |   __pyx_v_self->payload_len = nfq_get_payload(__pyx_v_self->_nfa, (&__pyx_v_self->payload));
        |                                                                   ~^~~~~~~~~~~~~~~~~~~~~~~
        |                                                                    |
        |                                                                    char **
  In file included from netfilterqueue.c:440:
  /usr/include/libnetfilter_queue/libnetfilter_queue.h:122:67: note: expected 'unsigned char **' but argument is of type 'char **'
    122 | extern int nfq_get_payload(struct nfq_data *nfad, unsigned char **data);
        |                                                   ~~~~~~~~~~~~~~~~^~~~
  netfilterqueue.c: In function '__pyx_pf_14netfilterqueue_6Packet_4get_hw':
  netfilterqueue.c:2533:17: warning: implicit declaration of function 'PyString_FromStringAndSize'; did you mean 'PyBytes_FromStringAndSize'? [-Wimplicit-function-declaration]
   2533 |     __pyx_t_3 = PyString_FromStringAndSize(((char *)__pyx_v_self->hw_addr), 8); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 111, __pyx_L1_error)
        |                 ^~~~~~~~~~~~~~~~~~~~~~~~~~
        |                 PyBytes_FromStringAndSize
  netfilterqueue.c:2533:15: warning: assignment to 'PyObject *' {aka 'struct _object *'} from 'int' makes pointer from integer without a cast [-Wint-conversion]
   2533 |     __pyx_t_3 = PyString_FromStringAndSize(((char *)__pyx_v_self->hw_addr), 8); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 111, __pyx_L1_error)
        |               ^
  netfilterqueue.c: In function '__Pyx_PyCFunction_FastCall':
  netfilterqueue.c:6436:13: error: too many arguments to function '(PyObject * (*)(PyObject *, PyObject * const*, Py_ssize_t))meth'
   6436 |     return (*((__Pyx_PyCFunctionFast)meth)) (self, args, nargs, NULL);
        |            ~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  netfilterqueue.c: In function '__Pyx__ExceptionSave':
  netfilterqueue.c:7132:21: error: 'PyThreadState' {aka 'struct _ts'} has no member named 'exc_type'; did you mean 'curexc_type'?
   7132 |     *type = tstate->exc_type;
        |                     ^~~~~~~~
        |                     curexc_type
  netfilterqueue.c:7133:22: error: 'PyThreadState' {aka 'struct _ts'} has no member named 'exc_value'; did you mean 'curexc_value'?
   7133 |     *value = tstate->exc_value;
        |                      ^~~~~~~~~
        |                      curexc_value
  netfilterqueue.c:7134:19: error: 'PyThreadState' {aka 'struct _ts'} has no member named 'exc_traceback'; did you mean 'curexc_traceback'?
   7134 |     *tb = tstate->exc_traceback;
        |                   ^~~~~~~~~~~~~
        |                   curexc_traceback
  netfilterqueue.c: In function '__Pyx__ExceptionReset':
  netfilterqueue.c:7141:24: error: 'PyThreadState' {aka 'struct _ts'} has no member named 'exc_type'; did you mean 'curexc_type'?
   7141 |     tmp_type = tstate->exc_type;
        |                        ^~~~~~~~
        |                        curexc_type
  netfilterqueue.c:7142:25: error: 'PyThreadState' {aka 'struct _ts'} has no member named 'exc_value'; did you mean 'curexc_value'?
   7142 |     tmp_value = tstate->exc_value;
        |                         ^~~~~~~~~
        |                         curexc_value
  netfilterqueue.c:7143:22: error: 'PyThreadState' {aka 'struct _ts'} has no member named 'exc_traceback'; did you mean 'curexc_traceback'?
   7143 |     tmp_tb = tstate->exc_traceback;
        |                      ^~~~~~~~~~~~~
        |                      curexc_traceback
  netfilterqueue.c:7144:13: error: 'PyThreadState' {aka 'struct _ts'} has no member named 'exc_type'; did you mean 'curexc_type'?
   7144 |     tstate->exc_type = type;
        |             ^~~~~~~~
        |             curexc_type
  netfilterqueue.c:7145:13: error: 'PyThreadState' {aka 'struct _ts'} has no member named 'exc_value'; did you mean 'curexc_value'?
   7145 |     tstate->exc_value = value;
        |             ^~~~~~~~~
        |             curexc_value
  netfilterqueue.c:7146:13: error: 'PyThreadState' {aka 'struct _ts'} has no member named 'exc_traceback'; did you mean 'curexc_traceback'?
   7146 |     tstate->exc_traceback = tb;
        |             ^~~~~~~~~~~~~
        |             curexc_traceback
  netfilterqueue.c: In function '__Pyx__GetException':
  netfilterqueue.c:7201:24: error: 'PyThreadState' {aka 'struct _ts'} has no member named 'exc_type'; did you mean 'curexc_type'?
   7201 |     tmp_type = tstate->exc_type;
        |                        ^~~~~~~~
        |                        curexc_type
  netfilterqueue.c:7202:25: error: 'PyThreadState' {aka 'struct _ts'} has no member named 'exc_value'; did you mean 'curexc_value'?
   7202 |     tmp_value = tstate->exc_value;
        |                         ^~~~~~~~~
        |                         curexc_value
  netfilterqueue.c:7203:22: error: 'PyThreadState' {aka 'struct _ts'} has no member named 'exc_traceback'; did you mean 'curexc_traceback'?
   7203 |     tmp_tb = tstate->exc_traceback;
        |                      ^~~~~~~~~~~~~
        |                      curexc_traceback
  netfilterqueue.c:7204:13: error: 'PyThreadState' {aka 'struct _ts'} has no member named 'exc_type'; did you mean 'curexc_type'?
   7204 |     tstate->exc_type = local_type;
        |             ^~~~~~~~
        |             curexc_type
  netfilterqueue.c:7205:13: error: 'PyThreadState' {aka 'struct _ts'} has no member named 'exc_value'; did you mean 'curexc_value'?
   7205 |     tstate->exc_value = local_value;
        |             ^~~~~~~~~
        |             curexc_value
  netfilterqueue.c:7206:13: error: 'PyThreadState' {aka 'struct _ts'} has no member named 'exc_traceback'; did you mean 'curexc_traceback'?
   7206 |     tstate->exc_traceback = local_tb;
        |             ^~~~~~~~~~~~~
        |             curexc_traceback
  error: command 'x86_64-linux-gnu-gcc' failed with exit status 1

  ----------------------------------------
  Failed building wheel for netfilterqueue
  Running setup.py clean for netfilterqueue
Failed to build netfilterqueue
Installing collected packages: netfilterqueue
  Running setup.py install for netfilterqueue ... error
    Complete output from command /usr/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-install-evvln_9d/netfilterqueue/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-record-7hb6tfdl/install-record.txt --single-version-externally-managed --compile:
    running install
    running build
    running build_ext
    building 'netfilterqueue' extension
    creating build
    creating build/temp.linux-x86_64-3.7
    x86_64-linux-gnu-gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -g -fwrapv -O2 -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I/usr/include/python3.7m -c netfilterqueue.c -o build/temp.linux-x86_64-3.7/netfilterqueue.o
    netfilterqueue.c: In function '__pyx_f_14netfilterqueue_6Packet_set_nfq_data':
    netfilterqueue.c:2150:68: warning: passing argument 2 of 'nfq_get_payload' from incompatible pointer type [-Wincompatible-pointer-types]
     2150 |   __pyx_v_self->payload_len = nfq_get_payload(__pyx_v_self->_nfa, (&__pyx_v_self->payload));
          |                                                                   ~^~~~~~~~~~~~~~~~~~~~~~~
          |                                                                    |
          |                                                                    char **
    In file included from netfilterqueue.c:440:
    /usr/include/libnetfilter_queue/libnetfilter_queue.h:122:67: note: expected 'unsigned char **' but argument is of type 'char **'
      122 | extern int nfq_get_payload(struct nfq_data *nfad, unsigned char **data);
          |                                                   ~~~~~~~~~~~~~~~~^~~~
    netfilterqueue.c: In function '__pyx_pf_14netfilterqueue_6Packet_4get_hw':
    netfilterqueue.c:2533:17: warning: implicit declaration of function 'PyString_FromStringAndSize'; did you mean 'PyBytes_FromStringAndSize'? [-Wimplicit-function-declaration]
     2533 |     __pyx_t_3 = PyString_FromStringAndSize(((char *)__pyx_v_self->hw_addr), 8); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 111, __pyx_L1_error)
          |                 ^~~~~~~~~~~~~~~~~~~~~~~~~~
          |                 PyBytes_FromStringAndSize
    netfilterqueue.c:2533:15: warning: assignment to 'PyObject *' {aka 'struct _object *'} from 'int' makes pointer from integer without a cast [-Wint-conversion]
     2533 |     __pyx_t_3 = PyString_FromStringAndSize(((char *)__pyx_v_self->hw_addr), 8); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 111, __pyx_L1_error)
          |               ^
    netfilterqueue.c: In function '__Pyx_PyCFunction_FastCall':
    netfilterqueue.c:6436:13: error: too many arguments to function '(PyObject * (*)(PyObject *, PyObject * const*, Py_ssize_t))meth'
     6436 |     return (*((__Pyx_PyCFunctionFast)meth)) (self, args, nargs, NULL);
          |            ~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    netfilterqueue.c: In function '__Pyx__ExceptionSave':
    netfilterqueue.c:7132:21: error: 'PyThreadState' {aka 'struct _ts'} has no member named 'exc_type'; did you mean 'curexc_type'?
     7132 |     *type = tstate->exc_type;
          |                     ^~~~~~~~
          |                     curexc_type
    netfilterqueue.c:7133:22: error: 'PyThreadState' {aka 'struct _ts'} has no member named 'exc_value'; did you mean 'curexc_value'?
     7133 |     *value = tstate->exc_value;
          |                      ^~~~~~~~~
          |                      curexc_value
    netfilterqueue.c:7134:19: error: 'PyThreadState' {aka 'struct _ts'} has no member named 'exc_traceback'; did you mean 'curexc_traceback'?
     7134 |     *tb = tstate->exc_traceback;
          |                   ^~~~~~~~~~~~~
          |                   curexc_traceback
    netfilterqueue.c: In function '__Pyx__ExceptionReset':
    netfilterqueue.c:7141:24: error: 'PyThreadState' {aka 'struct _ts'} has no member named 'exc_type'; did you mean 'curexc_type'?
     7141 |     tmp_type = tstate->exc_type;
          |                        ^~~~~~~~
          |                        curexc_type
    netfilterqueue.c:7142:25: error: 'PyThreadState' {aka 'struct _ts'} has no member named 'exc_value'; did you mean 'curexc_value'?
     7142 |     tmp_value = tstate->exc_value;
          |                         ^~~~~~~~~
          |                         curexc_value
    netfilterqueue.c:7143:22: error: 'PyThreadState' {aka 'struct _ts'} has no member named 'exc_traceback'; did you mean 'curexc_traceback'?
     7143 |     tmp_tb = tstate->exc_traceback;
          |                      ^~~~~~~~~~~~~
          |                      curexc_traceback
    netfilterqueue.c:7144:13: error: 'PyThreadState' {aka 'struct _ts'} has no member named 'exc_type'; did you mean 'curexc_type'?
     7144 |     tstate->exc_type = type;
          |             ^~~~~~~~
          |             curexc_type
    netfilterqueue.c:7145:13: error: 'PyThreadState' {aka 'struct _ts'} has no member named 'exc_value'; did you mean 'curexc_value'?
     7145 |     tstate->exc_value = value;
          |             ^~~~~~~~~
          |             curexc_value
    netfilterqueue.c:7146:13: error: 'PyThreadState' {aka 'struct _ts'} has no member named 'exc_traceback'; did you mean 'curexc_traceback'?
     7146 |     tstate->exc_traceback = tb;
          |             ^~~~~~~~~~~~~
          |             curexc_traceback
    netfilterqueue.c: In function '__Pyx__GetException':
    netfilterqueue.c:7201:24: error: 'PyThreadState' {aka 'struct _ts'} has no member named 'exc_type'; did you mean 'curexc_type'?
     7201 |     tmp_type = tstate->exc_type;
          |                        ^~~~~~~~
          |                        curexc_type
    netfilterqueue.c:7202:25: error: 'PyThreadState' {aka 'struct _ts'} has no member named 'exc_value'; did you mean 'curexc_value'?
     7202 |     tmp_value = tstate->exc_value;
          |                         ^~~~~~~~~
          |                         curexc_value
    netfilterqueue.c:7203:22: error: 'PyThreadState' {aka 'struct _ts'} has no member named 'exc_traceback'; did you mean 'curexc_traceback'?
     7203 |     tmp_tb = tstate->exc_traceback;
          |                      ^~~~~~~~~~~~~
          |                      curexc_traceback
    netfilterqueue.c:7204:13: error: 'PyThreadState' {aka 'struct _ts'} has no member named 'exc_type'; did you mean 'curexc_type'?
     7204 |     tstate->exc_type = local_type;
          |             ^~~~~~~~
          |             curexc_type
    netfilterqueue.c:7205:13: error: 'PyThreadState' {aka 'struct _ts'} has no member named 'exc_value'; did you mean 'curexc_value'?
     7205 |     tstate->exc_value = local_value;
          |             ^~~~~~~~~
          |             curexc_value
    netfilterqueue.c:7206:13: error: 'PyThreadState' {aka 'struct _ts'} has no member named 'exc_traceback'; did you mean 'curexc_traceback'?
     7206 |     tstate->exc_traceback = local_tb;
          |             ^~~~~~~~~~~~~
          |             curexc_traceback
    error: command 'x86_64-linux-gnu-gcc' failed with exit status 1

    ----------------------------------------
Command "/usr/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-install-evvln_9d/netfilterqueue/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-record-7hb6tfdl/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-install-evvln_9d/netfilterqueue/

After the error I have tried to run "pip uninstall netfilterqueue" and "pip3 uninstall netfilterqueue" and then "pip3 install netfilterqueue" again but I still get the same error.
How do I solve this?

A: It looks like NetfilterQueue package doesn't support python 3.7+. They don't provide such information on the site, but I tried building it and I got the same errors on 3.7, when it compiles fine for 3.6.
That would make sense because the pip package was released: Jan 31, 2017 and python3.7 on 2018.

A: hello first install netfilterqueue on your linux machine
sudo apt install libnfnetlink-dev libnetfilter-queue-dev

then you should know netfilterqueue for python3+ is named nfqp3 so install it with
pip3 install nfqp3

it is worth mentioning that when importing it in a python script you should import it as netfilterqueue not nfqp3

A: It worked after I installed this:

*

*sudo apt-get install build-essential python-dev libnetfilter-queue-dev

*pip install NetfilterQueue or pip3 install NetfilterQueue
My python3 version is 3.6.9

A: The project is abandoned but there are forks that fix this issue.
https://github.com/kti/python-netfilterqueue/pull/60 especially upgrades netfilterqueue to build on modern Cython, allowing it to support Python > 3.6. You can try using that branch
pip install https://github.com/johnteslade/python-netfilterqueue/archive/refs/heads/update-cython-code.zip

A: you will find the solution here :
https://github.com/kti/python-netfilterqueue/issues/53
Specially this answer :

pip3 install -U git+https://github.com/kti/python-netfilterqueue


text:
Q: Avro field default values I am running into some issues setting up default values for Avro fields. I have a simple schema as given below:
data.avsc:
{
 "namespace":"test",
 "type":"record",
 "name":"Data",
 "fields":[
    { "name": "id", "type": [ "long", "null" ] },
    { "name": "value", "type": [ "string", "null" ] },
    { "name": "raw", "type": [ "bytes", "null" ] }
 ]
}

I am using the avro-maven-plugin v1.7.6 to generate the Java model.
When I create an instance of the model using:
Data data = Data.newBuilder().build();, it fails with an exception:

org.apache.avro.AvroRuntimeException:
  org.apache.avro.AvroRuntimeException: Field id type:UNION pos:0 not
  set and has no default value.

But if I specify the "default" property,
{ "name": "id", "type": [ "long", "null" ], "default": "null" },

I do not get this error. I read in the documentation that first schema in the union becomes the default schema. So my question is, why do I still need to specify the "default" property? How else do I make a field optional?
And if I do need to specify the default values, how does that work for a union; do I need to specify default values for each schema in the union and how does that work in terms of order/syntax?
Thanks.

A: The default value of a union corresponds to the first schema of the union (Source). Your union is defined as ["long", "null"] therefor the default value must be a long number. null is not a long number that is why you are getting an error.
If you still want to define null as a default value then put null schema first, i.e. change the union to ["null", "long"] instead.

A: Its a bug at Avro's end which is marked as Not A Problem .
You need to add default attribute to mention default value.
{"name": "xxx", "type": ["null", "boolean"], "default": null}

Please refer AVRO-1803.

A: I think the problem is that you are using builder,
According to the documentation of the Java API:

using a builder requires setting all fields, even if they are null

A: You must provide "default": null not "default": "null" in the schema to get the builder method working

redpajama_set_name: RedPajamaStackExchange


text:
Q: Json Request failure using Alamofire in swift http://dev.alshmokh1.net/mobile/Login/?username=yasser&password=123
when I am calling this api am getting data from back end
[
    {
        "UserID": "yasser",
        "Username": null,
        "sysAdmin": "True",
        "UpdatePW": "True",
        "Name": "  selem yasser",
        "Email": "a@a/com",
        "iType": "2",
        "UserPW": "123",
        "Admin": "True",
        "Id_Bank": "5",
        "msg": "Success"
    }
]

I'm using alamofire to parse data from the api.
this is parsing code
func login()
   {

    let username = txtUserName.text!
     let password  = txtPassword.text!

    print("username\(username)  password \(password)")

    let params: [String: Any] = ["username": username, "password": password]

    let urlString = "http://dev.alshmokh1.net/mobile/Login/"
    guard let url = URL(string: urlString), var request = try? URLRequest(url: url, method: .post, headers: nil) else{
        //
        return
    }

    request.httpBody = params.map{ "\($0)=\($1)" }.joined(separator: "&").data(using: .utf8)
    Alamofire.request(request).responseJSON { response in

        print("response",response)
     }
    }

Result
[
    {
        "UserID": null,
        "Username": null,
        "sysAdmin": null,
        "UpdatePW": null,
        "Name": null,
        "Email": null,
        "iType": null,
        "UserPW": null,
        "Admin": null,
        "Id_Bank": null,
        "msg": "failure"
    }
]

how to parse data using alamofire where I did mistake

A: try this code because you need to append param in url
func login()
    {

        let username = txtUserName.text!
        let password  = txtPassword.text!

        print("username\(username)  password \(password)")

        let urlString = String(format:"http://dev.alshmokh1.net/mobile/Login?username=%@&password=%@",username,password)
        guard let url = URL(string: urlString), var request = try? URLRequest(url: url, method: .post, headers: nil) else{
            //
            return
        }

        Alamofire.request(request).responseJSON { response in

            print("response",response)
        }
    }

response
response SUCCESS: (
        {
        Admin = True;
        Email = "a@a/com";
        "Id_Bank" = 5;
        Name = "  selem yasser";
        UpdatePW = True;
        UserID = yasser;
        UserPW = 123;
        Username = "<null>";
        iType = 2;
        msg = Success;
        sysAdmin = True;
    }
)


text:
Q: Battery chargers that can recharge disposable batteries. How do they work and are they safe? A few years ago a product called SecondWind appeared, which claimed that it could recharge disposable batteries. To a layman like me that sounded like a great idea, but does such a product really work, and is it actually safe to use?
The labels on the batteries promise nothing but certain death if you try to recharge them, and a charger for disposable batteries seemed like something that might be potentially hazardous.

A: I had a low-stress application for reusing alkaline cells (low current, didn't necessarily need a full recharge), so I tried it myself [original research] although [this ain't Wikipedia].  The first thing I discovered was that the available information is so dead-set against trying this, that it is very difficult to determine what the proper terminating voltage would be.  I used a bench supply so I could limit both the current and the voltage.
On the first try, the results were good.  On the second try, the cell leaked.  After that, I intentionally kept the charge current to C/10 or less, using cells that had never been recharged, and that were not completely exhausted.  After some period of time, the cells began expelling gas and electrolyte.  The gas leaking was audible (as in, "What's that sound?", and "Oh, it's the cell I'm recharging")
As an aside, cells that are intended to be recharged often have mechanisms targeted at absorbing the gas, or at least safely venting it.  Not in this case.
Conclusion: The chemical reaction isn't necessarily "reversible" in an exact sense.  When run backwards you get other things like heat and gases.  Electrolytic reactions involve things like dissolving metal, and the resulting corrosion products don't automatically know where to go back to.   In the end, I quit trying to recharge these.  No deaths were reported.
I believe these results will vary with brand (manufacturer), so if it worked for you, you were just more lucky.  But this is an example of why it may not work.

A: Single-use alkalines aren't guaranteed to be rechargable.   Why not buy actual rechargable batteries which keep working even over a large number of recharge cycles?  It's much cheaper over the long term.
I've recharged lots of 9V alkalines for use in DVMs.   Trickle-charge 20mA with a cc power supply set to 9.5V max.   It doesn't work well with deeply-discharged batteries below about 7.5V.   But you can get some extra life from 9V alkalines if they've only been run down to 8V or 8.5V or so.   So, probably a commercial charger will accomplish this without tying up your bench supply.
Yes, sometimes a cell starts venting gas, little popping sounds.  I've only seen this on deep discharged ruined batteries where the voltage remains way low despite all "recharge."
There's one good application for all of this.   If you score a huge box of "dead" 9v alkalines, you can raise the voltage most of them.  Then hook them all in series and use them as woodburners, electrostatic kilovolt supply, carbon arclamp demos, etc.  Or just competing on YT/reddit for highest unwise 9V-bank voltage evar.   Get yours from indie theaters FM microphone discards, or office buildings replacing smoke detector batteries.
244 batteries in series
https://www.youtube.com/watch?v=8hwLHdBTQ7s
490 batteries in series
http://www.break.com/video/ugc/490-9v-batteries-351064
If you have some copper sulfate or copper chloride solution, you can demonstrate some issues behind "recharging."   Recharging is basically a form of electroplating, of converting the corrosion products back into solid battery plates.   Stick a couple of small copper electrodes into your bluegreen solution, then crank up the power supply to high current.  Fast-growing clots of black goo!  That's dendritic copper growing on the negative electrode; a forest of nanofilaments.  Perform the plating at much lower current and you instead get bulk copper metal.  Battery design has similar issues: the physical structures produced by the "corrosion" and the "plating" must not degrade over many cycles, and deep discharge (excessive 'corrosion') must not ruin the battery or reduce the number of charge cycles.

A: There is a blanket safety warning , but chargers with a limited capacity of C/10 would not likely result in overheating losses and take more than 10 hrs to trickle charge.   You might be lucky to get out 50% of charge put in up to 90% SOC on the 1st re-use , but this declines rapidly with temperature rise and cycle count on primary cells.  Using chargers >=1C charge rate could result in rapid temp rise should an internal short occur.  Monitoring battery temp. is safe if done in real-time.

A: What happens when you recharge any kind of battery?

*

*current flows into the + terminal

*a chemical reaction occurs inside the battery, more-or-less the opposite of the chemical reaction that occurred when the battery was discharged

*the chemical reaction recharges the battery and generates heat

What can go wrong?

*

*the battery can go into thermal runaway and overheat, sometimes explosively

*the battery can develop an internal short and draw excessive current, which can lead to thermal runaway or maybe just wreck your charger

*the battery can develop an internal open and become a paperweight

How to prevent the wrongness?

*

*monitor the battery temperature (internal if you can, otherwise external) and reduce current if the temp gets too high

*charge really slowly (trickle charge)

*do not overcharge

What else?
In order to "fully" recharge a battery, the charger must actually exceed the rated voltage of the battery (briefly, and at a low current). This overcomes the voltage drop in the internal resistance of the battery.
What do commercial chargers do?
Commercial chargers typically do some combination of constant-voltage and constant-current charging, the slightly fancier ones monitor temperature, and the really fancy ones may also monitor other things.
Why are they not recommended for alkaline batteries?
Each type of battery recharges slightly differently. Old ni-cad chargers may not work well for ni-mh rechargeables, and vice versa. You have to buy a special kind of charger for li-po batteries, lead-acid types, etc.
The real reason that alkaline rechargers are a niche item is that you don't gain much (in terms of recharge capacity or number of recharge cycles) from recharging alkaline batteries compared to other types.
The moral of the story is you can recharge most any kind of battery, but some are better at it than others.


text:
Q: WP doesn't show Array Custom Fields? I'm wondering why WordPress doesn't list PHP array() and any serialized data in Custom Fields in Admin Panel (for Pages, Posts etc.)? Only Custom Fields containing strings and numbers show up and can be edited by user manually.
Edit: Why aren't post meta values displayed if they are stored as a non-string value, meaning,  stored as either arrays or a serialized value ?
Example: If a post has a meta key 'custom-meta' with a string value as 'yes', it is displayed in the meta box, but if it has an array value like array('value' => 'yes'), it is not displayed in the meta box.
Can I enable this?

A: There is no filter to change that behavior, you would have to replace the entire metabox.
On the other hand: I think there is no really simple way to show and to save those arrays.
Example for a fictive meta key 'foo':
array (
    0 => 2,
    'hello' => array (
        0 => 2,
        'hello' => 'world'
    )
)

Creating a default interface for such an array would be very hard. This metabox is for simple fields, it should be easy to use. And you cannot just present the serialized string: editing that would probably break it. So I think it is a compromise. Better than nothing, but not perfect.

A: For those landing here, you could always just create a custom page template on a private page and then just throw something like this on the template page file:
/*Template Name: Test Post Meta */
$thisPostMeta = get_post_meta($yourPostId, 'meta_key');

//Check for type of value
if (is_array($thisPostMeta)) {
print_r($thisPostMeta);
} else {
echo $thisPostMeta;
}

Note: untested.

A: I think you can use serialize()
Example:
$value = array('value' => 'yes');
$new_value = serialize($value);
add_post_meta($post_id,'meta_key',$new_value);

Then, you can see the metabox in admin panel.


text:
Q: O que esse trecho de código com cast faz? código tirado do site Linux x86_64 execve Shellcode
#include<stdio.h>
#include<string.h>

unsigned char code[] = \
    "\x48\x89\xc6"                 // mov    %rax,%rsi
    "\x48\x89\xf2"                 // mov    %rsi,%rdx
    "\x49\xbc\x2f\x62\x69\x6e\x2f" // movabs $0x68732f6e69622f,%r12
    "\x73\x68\x00"
    "\x41\x54"                     // push   %r12
    "\x54"                         // push   %rsp
    "\x5f"                         // pop    %rdi
    "\xb0\x3b"                     // mov    $0x3b,%al
    "\x0f\x05"                     // syscall
;

main()
{

    printf("Shellcode Length:  %d\n", (int)strlen(code));

    int (*ret)() = (int(*)())code;

    ret();

}

o que essa linha de código esta fazendo?
int (*ret)() = (int(*)())code;

A: Isso é uma técnica para executar a função escrita em código de máquina ou outra forma onde não se sabe o nome da função, mas se sabe onde ela está.
Note que code é uma variável com o código de máquina montado a partir daquele código Assembly nos comentários. Como chamar isso através de C? As chamadas só podem ser através de funções. Então temos que interpretar esse array de bytes como se fosse uma função. C possui uma forma de se referenciar à funções de forma anônima.
Nesse caso terá uma variável chamada ret que é do tipo "função que retorna um inteiro". Os parenteses finais no nome da variável e o ponteiro (afinal toda função é um ponteiro para um código) é o que indica que no fundo é uma função.
O (int(*)()) é um cast para fazer com que esse array de bytes seja convertido para uma função. Não que seja feita uma conversão mesmo, apenas será interpretado assim pelo compilador. Isso é feito para compatibilizar com o que se espera na variável.
Assim você consegue executar um código arbitrário. Ele poderia vir até de fontes externas, o que pode ser um perigo. Em alguns casos o sistema operacional pode impedir a execução de códigos arbitrários.

A: int(*ret)()

É feita declaração de uma função ponteiro chamada ret, a função leva argumentos não especificados e retorna um inteiro.
(int(*)())code

Converte a array code para um ponteiro de uma função desse mesmo tipo.
Portanto converte o endereço da array code para um ponteiro de uma função, que, em seguida, permite que você chamá-lo e executar o código .
Tradução de:
What does int (ret)() = (int()())code mean?


text:
Q: In C#, what and how to pass IServiceProvider in ErrorListProvider(IServiceProvider isp)? I am creating a vsix project where I need to add some custom errors in Error List window. Now I am stuck in IServiceProvider. What it contains and why I need this and how I can get this? In my code, I need to initialize with a service provider. How can I do this? Following is code :
internal class ErrorListManager
{
    public static ErrorListProvider errorListProvider;

    public static void Initialize(IServiceProvider serviceProvider)
    {
        errorListProvider = new ErrorListProvider(serviceProvider);

    }

    public static void AddError(string errorMsg) {
        AddTask(errorMsg, TaskErrorCategory.Error);
    }

    private static void AddTask(string errorMsg, TaskErrorCategory category)
    {
        errorListProvider.Tasks.Add(new ErrorTask
        {
            Category = TaskCategory.User,
            ErrorCategory = category,
            Text = errorMsg
        });
    }
}

Please help. I am a beginner for C# and VSIX. Thanks!

A: Your package is a service provider. Its base class AsyncPackage derives from the Package class which implements OLE.Interop.IServiceProvider and System.IServiceProvider (yes, VSX is confusing and there are two IServiceProvider interfaces). So, from your package class you would call ErrorListManager.Initialize(this).
That said, you may want to use the new API of VS 2015 and higher for the ErrorList. The old approach that you are using doesn't allow you to add values to columns such as "Code", etc. See samples here:
VSSDK-Extensibility-Samples/ErrorList: https://github.com/microsoft/VSSDK-Extensibility-Samples/tree/master/ErrorList
madskristensen/WebAccessibilityChecker: https://github.com/madskristensen/WebAccessibilityChecker/tree/master/src/ErrorList
madskristensen/TaskOutputListener: https://github.com/madskristensen/TaskOutputListener/blob/master/src/ErrorListProvider/ErrorListProvider.cs

A: To write something in VS Error List you need to use ErrorListProvider. In my implementation, I inherit from ErrorListProvider and implement my own behavior for "ErrorWindowController". The code looks like this (read the code comments for more information):
public class ErrorWindowController : ErrorListProvider
{

#region Constructor

/// <summary>
/// Instance Constructor
/// </summary>
/// <param name="aServiceProvider"></param>
public ErrorWindowController(IServiceProvider aIServiceProvider) : base(aIServiceProvider)
{
}

#endregion

#region Public Methods

// Use this to add a collection of custom errors in VS Error List
public void AddErrors(IEnumerable<ErrorModel> aErrors)
{
    SuspendRefresh();

    foreach (ErrorModel error in aErrors)
    {
      ErrorTask errorTask = new ErrorTask
      {
        ErrorCategory = error.Category,
        Document = error.FilePath,
        Text = error.Description,
        Line = error.Line - 1,
        Column = error.Column,
        Category = TaskCategory.BuildCompile,
        Priority = TaskPriority.High,
        HierarchyItem = error.HierarchyItem
      };
      errorTask.Navigate += ErrorTaskNavigate;
      Tasks.Add(errorTask);
    }

    BringToFront();
    ResumeRefresh();
}

// Remove all the errors from Error List which are depending of a project and this specific project is closed
// Or remove all the errors from Error List when the VS solution is closed
public void RemoveErrors(IVsHierarchy aHierarchy)
{
    SuspendRefresh();

    for (int i = Tasks.Count - 1; i >= 0; --i)
    {
      var errorTask = Tasks[i] as ErrorTask;
      aHierarchy.GetCanonicalName(Microsoft.VisualStudio.VSConstants.VSITEMID_ROOT, out string nameInHierarchy);
      errorTask.HierarchyItem.GetCanonicalName(Microsoft.VisualStudio.VSConstants.VSITEMID_ROOT, out string nameErrorTaskHierarchy);
      if (nameInHierarchy == nameErrorTaskHierarchy)
      {
        errorTask.Navigate -= ErrorTaskNavigate;
        Tasks.Remove(errorTask);
      }
    }

    ResumeRefresh();
}

// Remove all the errors from the Error List
public void Clear()
{
    Tasks.Clear();
}

#endregion

#region Private Methods

// This is optional
// Add navigation for your errors.
private void ErrorTaskNavigate(object sender, EventArgs e)
{
  ErrorTask objErrorTask = (ErrorTask)sender;
  objErrorTask.Line += 1;
  bool bResult = Navigate(objErrorTask, new Guid(EnvDTE.Constants.vsViewKindCode));
  objErrorTask.Line -= 1;
}

#endregion
}

The ErrorModel is very simple:
public class ErrorModel
{
  #region Properties

  public string FilePath { get; set; }

  public int Line { get; set; }

  public int Column { get; set; }

  public TaskErrorCategory Category { get; set; }

  public string Description { get; set; }

  public IVsHierarchy HierarchyItem { get; set; }

  #endregion

}

Happy Codding!


text:
Q: Removing all spaces in text file with Python 3.x So I have this crazy long text file made by my crawler and it for some reason added some spaces inbetween the links, like this:
https://example.com/asdf.html                                (note the spaces)
https://example.com/johndoe.php                              (again)

I want to get rid of that, but keep the new line. Keep in mind that the text file is 4.000+ lines long. I tried to do it myself but figured that I have no idea how to loop through new lines in files.

A: You can open file and read line by line and remove white space -
Python 3.x:
with open('filename') as f:
    for line in f:
        print(line.strip())

Python 2.x:
with open('filename') as f:
    for line in f:
        print line.strip()

It will remove space from each line and print it.
Hope it helps!

A: Read text from file, remove spaces, write text to file:
with open('file.txt', 'r') as f:
    txt = f.read().replace(' ', '')

with open('file.txt', 'w') as f:
    f.write(txt)

In @Leonardo Chirivì's solution it's unnecessary to create a list to store file contents when a string is sufficient and more memory efficient.  The .replace(' ', '') operation is only called once on the string, which is more efficient than iterating through a list performing replace for each line individually.
To avoid opening the file twice:
with open('file.txt', 'r+') as f:
    txt = f.read().replace(' ', '')
    f.seek(0)
    f.write(txt)
    f.truncate()

It would be more efficient to only open the file once.  This requires moving the file pointer back to the start of the file after reading, as well as truncating any possibly remaining content left over after you write back to the file.  A drawback to this solution however is that is not as easily readable.

A: Seems like you can't directly edit a python file, so here is my suggestion:
# first get all lines from file
with open('file.txt', 'r') as f:
    lines = f.readlines()

# remove spaces
lines = [line.replace(' ', '') for line in lines]

# finally, write lines in the file
with open('file.txt', 'w') as f:
    f.writelines(lines)

A: I had something similar that I'd been dealing with.
This is what worked for me (Note: This converts from 2+ spaces into a comma, but if you read below the code block, I explain how you can get rid of ALL whitespaces):
import re

# read the file
with open('C:\\path\\to\\test_file.txt') as f:
    read_file = f.read()
    print(type(read_file)) # to confirm that it's a string

read_file = re.sub(r'\s{2,}', ',', read_file) # find/convert 2+ whitespace into ','

# write the file
with open('C:\\path\\to\\test_file.txt', 'w') as f:
    f.writelines('read_file')

This helped me then send the updated data to a CSV, which suited my need, but it can help for you as well, so instead of converting it to a comma (','), you can convert it to an empty string (''), and then [or] use a read_file.replace(' ', '') method if you don't need any whitespaces at all.

A: Lets not forget about adding back the \n to go to the next row.
The complete function would be :
with open(str_path, 'r') as file :
    str_lines = file.readlines()

# remove spaces
if bl_right is True:
    str_lines = [line.rstrip() + '\n' for line in str_lines]
elif bl_left is True:
    str_lines = [line.lstrip() + '\n' for line in str_lines]
else:
    str_lines = [line.strip() + '\n' for line in str_lines]

# Write the file out again
with open(str_path, 'w') as file:
    file.writelines(str_lines)


text:
Q: Two kinds of equation labels within one paper I have looked high and low for an answer to the following (including on this site, Google, etc.) without success, and I hope someone may be able to answer it (and if it is a repeat of something answered elsewhere, a link to that would be swell).
My question has to do with setting up two different equation-labeling environments within the same paper (produced via LaTeX using amsart).  I would like to have two distinct equation commands, say {equation} and {eqn}, so I can write things like
\numberwithin{equation}{subsection}

and
\numberwithin{eqn}{subsubsection}

in the topmatter so that by choosing either
\begin{equation}....\end{equation}

or
\begin{eqn}...\end{eqn}

I will have the flexibility to arrange that automated labels of a displayed expression will appear in the style (x.y.z) or (x.y.z.w) at my discretion.  How is this done (ideally with a minimum of fuss)?
For other kinds of environments, such as theorems, remarks, etc., I know one can use the {theoremstyle} framework to define distinct commands (such as {theorem}, {thm} as well as {remark}, {rem}, etc.) which one creates in such a way so as to have different levels of numerical labeling appear (e.g. Theorem x.y.z versus Theorem x.y.z.w).  But I cannot figure out how to do the same with the labeling of displayed expressions, since it seems the word equation is reserved in LaTeX in a way that the word theorem is not (unless I am overlooking something well-known, which is entirely possible).
Thanks in advance!

A: You could use the tag command defined by the ams bundle as follows
\newenvironment{eqn}{\refstepcounter{equation}\equation}{\tag{\thesubsection.\theequation}\endequation}

Here's a complete MWE to play with.
% arara: pdflatex
\documentclass{amsart}

\newenvironment{eqn}{\refstepcounter{equation}\equation}{\tag{\thesubsection.\theequation}\endequation}
\begin{document}

\subsection{test}
\begin{equation}
  y=mx+b
\end{equation}
\begin{eqn}
f(x)=x^2
\end{eqn}
\begin{equation}
  G(x)=\cos(x)
\end{equation}

\end{document}

A: It is a general idea, only for right equation numbers now. Some               deeper work is still needed. Additional LaTeX counter, called eqn, is defined.
You a suggesting a problems with labels' names. But they can be near arbitrary.
\documentclass[reqno]{amsart}

\begin{document}

\makeatletter
\@definecounter{eqn}
\def\eqn{$$\refstepcounter{eqn}}
\def\endeqn{\eqno \hbox{\@eqnNum}$$\@ignoretrue}
\def\@eqnNum{{\normalfont \normalcolor (\theeqn)}}
\makeatother

\section{First}

\numberwithin{equation}{subsection}

%and

\numberwithin{eqn}{subsubsection}

in the topmatter so that by choosing either

\begin{equation} ....\end{equation}

or

\begin{eqn}...\end{eqn}

\begin{equation} ....\end{equation}

or

\begin{eqn}...\end{eqn}

\end{document}


text:
Q: Decouple service complex query building from datastore We have a very large search service (written in golang if it matters) that runs on top of ElasticSearch, receive requests, builds the correspondent query, and returns the results (with some post-processing). The service handles thousands of requests per second and should be able to serve requests quickly and efficiently.
Since the service just READS from the database (writes are being handled outside of the service, asynchronous) and builds very complex queries who varies between users, requests and AB tests being run on production, most of the code in the service is code in charge of building the query.
Currently, the ElasticSearch query is being built mixing Business logic (AB tests running in production, classification of the user, etc..).
In classic OO application with relational databases I'd probably use a DAL, the receives a request and know how to parse it to SQL, and then converts the returned value to something that the BL knows how to handle.
Building such a mechanism (an abstraction of our query, an intermediate language between our domain language query to ES query language) feels like an overhead. Since all of our service is really coupled to ElasticSearch, takes into consideration lots of ES features in order to increase performance, it feels like we'll just build our own objects who are replicated ES objects, and then do the mapping.
On the other hand, we think of the possibility we'll want to replace the package querying ES, or we'll want to update ES version and it will go through breaking changes, and we'll have to change a lot of code, scattered through the whole service and not centralized.
Any advice or help would be appreciated. Thanks.

A: I also dont think that you need to decouple the two if your only concern is that ElasticSearch is updating the interface. If you have a decoupled layer then it should be more or less the same effort to change the code in the intermediate layer or in the coupled code.
A reason to decouple the code would be that you want to plug your BL to a new underlaying system such as (SolR, SQL,...) then you only would need to adapt the layer.
Alternatively, you could also look for an existing ElasticSearch Connector. There are connectors that could match to your BL. For example, you could use an SQL connector if your business layer is already writen in SQL.


text:
Q: Payment and Media I'm just curious on the Salesforce Partner front, is there any way to obtain physical media for local install (at a fee or otherwise) for any of the developer tools or is it strictly accessed through the development portal?
Also, when paying the revenue shares or other program fees (training etc) is that just done with CC or bank transfer?  Do they accept PayPal transfers?
Thanks!

A: SFDC doesn't install anywhere, it is a pure-play cloud solution.
You have several options to pay the fees, typically invoice/check or AppExchange Check Out are the solutions folks use.  To the best of my knowledge they do not accept paypal.
Do you have a partner user group in your area?  I am a co-leader for the one here in San Francisco, we have a meeting next week


text:
Q: After editing my wordpress website's footer copyright credites using My Custom Functions plugin, my site is down I am making a wordpress store using storefront theme named Pakoutfit.com.
I tried to edit its footer credentials using My Custom Functions plugin and using this plugin I run following code,
add-action( 'init' , 'custom_remove_footer_credit' , 10 );

function custom_remove_footer_credit(){
    remove_action( 'storefront_footer' , 'storefront_credit' , 20 );
    add_action( 'storefront_footer' , 'custom_storefront_credit' , 20 );
}

function custom_storefront_credit(){
    ?>
    <div class="site-info">
    © PakOutfit <?php echo get_the_date( 'Y' ); ?>
    </div>
    <?php
}

I do that following this youtube tutorial,
Now when I tried to open my site or even its wp-admin panel it says,

This page isn't working
  pakoutfit.com is currently unable to handle this request.
  HTTP ERROR 500

I dont know that in which file My custom Functions plugin make changes so that I can reverse them.
I am using godaddy domain name and hosting.
I am new in this field. Please help me to make my site live again. Thanks

A: Modification to your site should be made via a WordPress child theme. Do not edit core theme files: https://codex.wordpress.org/Child_Themes
Using your FTP or cPanel login, locate the file where you made the changes and remove them. That will restore your site.
Once you have your child theme installed and activated, and your function to the child theme functions.php file.
Be sure to change this:
add-action

To this:
add_action


text:
Q: How to perform IDP initated login in keycloak saml I have a spring boot application that is integrated to keycloak saml using the spring saml extension.
here is my security config class
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter implements     InitializingBean, DisposableBean {

private Timer backgroundTaskTimer;
@Autowired
private Environment env;
private MultiThreadedHttpConnectionManager multiThreadedHttpConnectionManager;

public void init() {
    this.backgroundTaskTimer = new Timer(true);
    this.multiThreadedHttpConnectionManager = new MultiThreadedHttpConnectionManager();
}

public void shutdown() {
    this.backgroundTaskTimer.purge();
    this.backgroundTaskTimer.cancel();
    this.multiThreadedHttpConnectionManager.shutdown();
}

@Autowired
private SAMLUserDetailsServiceImpl samlUserDetailsServiceImpl;

// Initialization of the velocity engine
@Bean
public VelocityEngine velocityEngine() {
    return VelocityFactory.getEngine();
}

// XML parser pool needed for OpenSAML parsing
@Bean(initMethod = "initialize")
public StaticBasicParserPool parserPool() {
    return new StaticBasicParserPool();
}

@Bean(name = "parserPoolHolder")
public ParserPoolHolder parserPoolHolder() {
    return new ParserPoolHolder();
}

// Bindings, encoders and decoders used for creating and parsing messages
@Bean
public HttpClient httpClient() {
    return new HttpClient(this.multiThreadedHttpConnectionManager);
}

// SAML Authentication Provider responsible for validating of received SAML
// messages
@Bean
public SAMLAuthenticationProvider samlAuthenticationProvider() {
    SAMLAuthenticationProvider samlAuthenticationProvider = new SAMLAuthenticationProvider();
    samlAuthenticationProvider.setUserDetails(samlUserDetailsServiceImpl);
    samlAuthenticationProvider.setForcePrincipalAsString(false);
    return samlAuthenticationProvider;
}

// Provider of default SAML Context
@Bean
public SAMLContextProviderImpl contextProvider() {
    return new SAMLContextProviderImpl();
}

// Initialization of OpenSAML library
@Bean
public static SAMLBootstrap sAMLBootstrap() {
    return new SAMLBootstrap();
}

// Logger for SAML messages and events
@Bean
public SAMLDefaultLogger samlLogger() {
    return new SAMLDefaultLogger();
}

// SAML 2.0 WebSSO Assertion Consumer
@Bean
public WebSSOProfileConsumer webSSOprofileConsumer() {
    return new WebSSOProfileConsumerImpl();
}

// SAML 2.0 Holder-of-Key WebSSO Assertion Consumer
@Bean
public WebSSOProfileConsumerHoKImpl hokWebSSOprofileConsumer() {
    return new WebSSOProfileConsumerHoKImpl();
}

// SAML 2.0 Web SSO profile
@Bean
public WebSSOProfile webSSOprofile() {
    return new WebSSOProfileImpl();
}

// SAML 2.0 Holder-of-Key Web SSO profile
@Bean
public WebSSOProfileConsumerHoKImpl hokWebSSOProfile() {
    return new WebSSOProfileConsumerHoKImpl();
}

// SAML 2.0 ECP profile
@Bean
public WebSSOProfileECPImpl ecpprofile() {
    return new WebSSOProfileECPImpl();
}

@Bean
public SingleLogoutProfile logoutprofile() {
    return new SingleLogoutProfileImpl();
}

// Central storage of cryptographic keys
@Bean
public KeyManager keyManager() {
    DefaultResourceLoader loader = new DefaultResourceLoader();
    Resource storeFile = loader
            .getResource("classpath:/saml/samlKeystore.jks_withoutcert");
    String storePass = "nalle123";
    Map<String, String> passwords = new HashMap<>();
    passwords.put("apollo", "nalle123");
    String defaultKey = "apollo";
    return new JKSKeyManager(storeFile, storePass, passwords, defaultKey);
}

@Bean
public WebSSOProfileOptions defaultWebSSOProfileOptions() {
    WebSSOProfileOptions webSSOProfileOptions = new WebSSOProfileOptions();
    webSSOProfileOptions.setIncludeScoping(false);
    return webSSOProfileOptions;
}

// Entry point to initialize authentication, default values taken from
// properties file
@Bean
public SAMLEntryPoint samlEntryPoint() {
    SAMLEntryPoint samlEntryPoint = new SAMLEntryPoint();
    samlEntryPoint.setDefaultProfileOptions(defaultWebSSOProfileOptions());
    return samlEntryPoint;
}

// Setup advanced info about metadata
@Bean
public ExtendedMetadata extendedMetadata() {
    ExtendedMetadata extendedMetadata = new ExtendedMetadata();
    extendedMetadata.setIdpDiscoveryEnabled(true);
    extendedMetadata.setSigningAlgorithm("http://www.w3.org/2001/04/xmldsig-more#rsa-sha256");
    extendedMetadata.setSignMetadata(true);
    extendedMetadata.setEcpEnabled(true);
    return extendedMetadata;
}

// IDP Discovery Service
@Bean
public SAMLDiscovery samlIDPDiscovery() {
    SAMLDiscovery idpDiscovery = new SAMLDiscovery();
    idpDiscovery.setIdpSelectionPath("/saml/discovery");
    return idpDiscovery;
}

@Bean
@Qualifier("idp-ssocircle")
public ExtendedMetadataDelegate ssoCircleExtendedMetadataProvider()
        throws MetadataProviderException {
    String idpSSOCircleMetadataURL = "https://idp.ssocircle.com/meta-idp.xml";
    HTTPMetadataProvider httpMetadataProvider = new HTTPMetadataProvider(
            this.backgroundTaskTimer, httpClient(), idpSSOCircleMetadataURL);
    httpMetadataProvider.setParserPool(parserPool());
    ExtendedMetadataDelegate extendedMetadataDelegate =
            new ExtendedMetadataDelegate(httpMetadataProvider, extendedMetadata());
    extendedMetadataDelegate.setMetadataTrustCheck(true);
    extendedMetadataDelegate.setMetadataRequireSignature(false);
    backgroundTaskTimer.purge();
    return extendedMetadataDelegate;
}
@Bean
@Qualifier("idp-keycloak")
public ExtendedMetadataDelegate keycloakExtendedMetadataProvider(Environment env)
        throws MetadataProviderException {
    String idpKeycloakMetadataURL = env.getProperty("keycloak.auth-server-url",String.class,"http://localhost:8081/auth/realms/demo") + "/protocol/saml/descriptor";
    HTTPMetadataProvider httpMetadataProvider = new HTTPMetadataProvider(
            this.backgroundTaskTimer, httpClient(), idpKeycloakMetadataURL);
    httpMetadataProvider.setParserPool(parserPool());
    ExtendedMetadataDelegate extendedMetadataDelegate =
            new ExtendedMetadataDelegate(httpMetadataProvider, extendedMetadata());
    extendedMetadataDelegate.setMetadataTrustCheck(true);
    extendedMetadataDelegate.setMetadataRequireSignature(false);
    backgroundTaskTimer.purge();
    return extendedMetadataDelegate;
}
// IDP Metadata configuration - paths to metadata of IDPs in circle of trust
// is here
// Do no forget to call iniitalize method on providers
@Bean
@Qualifier("metadata")
public CachingMetadataManager metadata() throws MetadataProviderException {
    List<MetadataProvider> providers = new ArrayList<>();
   // providers.add(ssoCircleExtendedMetadataProvider());
    providers.add(keycloakExtendedMetadataProvider(env));
    return new CachingMetadataManager(providers);
}

// Filter automatically generates default SP metadata
@Bean
public MetadataGenerator metadataGenerator() {
    MetadataGenerator metadataGenerator = new MetadataGenerator();
    metadataGenerator.setEntityId("com:vdenotaris:spring:sp");
    metadataGenerator.setExtendedMetadata(extendedMetadata());
    metadataGenerator.setIncludeDiscoveryExtension(false);
    metadataGenerator.setKeyManager(keyManager());
    return metadataGenerator;
}

// The filter is waiting for connections on URL suffixed with filterSuffix
// and presents SP metadata there
@Bean
public MetadataDisplayFilter metadataDisplayFilter() {
    return new MetadataDisplayFilter();
}

// Handler deciding where to redirect user after successful login
@Bean
public SavedRequestAwareAuthenticationSuccessHandler successRedirectHandler() {
    SavedRequestAwareAuthenticationSuccessHandler successRedirectHandler =
            new SavedRequestAwareAuthenticationSuccessHandler();
    successRedirectHandler.setDefaultTargetUrl("/landing");
    return successRedirectHandler;
}

// Handler deciding where to redirect user after failed login
@Bean
public SimpleUrlAuthenticationFailureHandler authenticationFailureHandler() {
        SimpleUrlAuthenticationFailureHandler failureHandler =
                new SimpleUrlAuthenticationFailureHandler();
        failureHandler.setUseForward(true);
        failureHandler.setDefaultFailureUrl("/error");
        return failureHandler;
}

@Bean
public SAMLWebSSOHoKProcessingFilter samlWebSSOHoKProcessingFilter() throws Exception {
    SAMLWebSSOHoKProcessingFilter samlWebSSOHoKProcessingFilter = new SAMLWebSSOHoKProcessingFilter();
    samlWebSSOHoKProcessingFilter.setAuthenticationSuccessHandler(successRedirectHandler());
    samlWebSSOHoKProcessingFilter.setAuthenticationManager(authenticationManager());
    samlWebSSOHoKProcessingFilter.setAuthenticationFailureHandler(authenticationFailureHandler());
    return samlWebSSOHoKProcessingFilter;
}

// Processing filter for WebSSO profile messages
@Bean
public SAMLProcessingFilter samlWebSSOProcessingFilter() throws Exception {
    SAMLProcessingFilter samlWebSSOProcessingFilter = new SAMLProcessingFilter();
    samlWebSSOProcessingFilter.setAuthenticationManager(authenticationManager());
    samlWebSSOProcessingFilter.setAuthenticationSuccessHandler(successRedirectHandler());
    samlWebSSOProcessingFilter.setAuthenticationFailureHandler(authenticationFailureHandler());
    return samlWebSSOProcessingFilter;
}

@Bean
public MetadataGeneratorFilter metadataGeneratorFilter() {
    return new MetadataGeneratorFilter(metadataGenerator());
}

// Handler for successful logout
@Bean
public SimpleUrlLogoutSuccessHandler successLogoutHandler() {
    SimpleUrlLogoutSuccessHandler successLogoutHandler = new SimpleUrlLogoutSuccessHandler();
    successLogoutHandler.setDefaultTargetUrl("/");
    return successLogoutHandler;
}

// Logout handler terminating local session
@Bean
public SecurityContextLogoutHandler logoutHandler() {
    SecurityContextLogoutHandler logoutHandler =
            new SecurityContextLogoutHandler();
    logoutHandler.setInvalidateHttpSession(true);
    logoutHandler.setClearAuthentication(true);
    return logoutHandler;
}

// Filter processing incoming logout messages
// First argument determines URL user will be redirected to after successful
// global logout
@Bean
public SAMLLogoutProcessingFilter samlLogoutProcessingFilter() {
    return new SAMLLogoutProcessingFilter(successLogoutHandler(),
            logoutHandler());
}

// Overrides default logout processing filter with the one processing SAML
// messages
@Bean
public SAMLLogoutFilter samlLogoutFilter() {
    return new SAMLLogoutFilter(successLogoutHandler(),
            new LogoutHandler[] { logoutHandler() },
            new LogoutHandler[] { logoutHandler() });
}

// Bindings
private ArtifactResolutionProfile artifactResolutionProfile() {
    final ArtifactResolutionProfileImpl artifactResolutionProfile =
            new ArtifactResolutionProfileImpl(httpClient());
    artifactResolutionProfile.setProcessor(new SAMLProcessorImpl(soapBinding()));
    return artifactResolutionProfile;
}

@Bean
public HTTPArtifactBinding artifactBinding(ParserPool parserPool, VelocityEngine velocityEngine) {
    return new HTTPArtifactBinding(parserPool, velocityEngine, artifactResolutionProfile());
}

@Bean
public HTTPSOAP11Binding soapBinding() {
    return new HTTPSOAP11Binding(parserPool());
}

@Bean
public HTTPPostBinding httpPostBinding() {
        return new HTTPPostBinding(parserPool(), velocityEngine());
}

@Bean
public HTTPRedirectDeflateBinding httpRedirectDeflateBinding() {
        return new HTTPRedirectDeflateBinding(parserPool());
}

@Bean
public HTTPSOAP11Binding httpSOAP11Binding() {
    return new HTTPSOAP11Binding(parserPool());
}

@Bean
public HTTPPAOS11Binding httpPAOS11Binding() {
        return new HTTPPAOS11Binding(parserPool());
}

// Processor
@Bean
public SAMLProcessorImpl processor() {
    Collection<SAMLBinding> bindings = new ArrayList<SAMLBinding>();
    bindings.add(httpRedirectDeflateBinding());
    bindings.add(httpPostBinding());
    bindings.add(artifactBinding(parserPool(), velocityEngine()));
    bindings.add(httpSOAP11Binding());
    bindings.add(httpPAOS11Binding());
    return new SAMLProcessorImpl(bindings);
}

/**
 * Define the security filter chain in order to support SSO Auth by using SAML 2.0
 *
 * @return Filter chain proxy
 * @throws Exception
 */
@Bean
public FilterChainProxy samlFilter() throws Exception {
    List<SecurityFilterChain> chains = new ArrayList<SecurityFilterChain>();
    chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/login/**"),
            samlEntryPoint()));
    chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/logout/**"),
            samlLogoutFilter()));
    chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/metadata/**"),
            metadataDisplayFilter()));
    chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/SSO/**"),
            samlWebSSOProcessingFilter()));
    chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/SSOHoK/**"),
            samlWebSSOHoKProcessingFilter()));
    chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/SingleLogout/**"),
            samlLogoutProcessingFilter()));
    chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/discovery/**"),
            samlIDPDiscovery()));
    return new FilterChainProxy(chains);
}

/**
 * Returns the authentication manager currently used by Spring.
 * It represents a bean definition with the aim allow wiring from
 * other classes performing the Inversion of Control (IoC).
 *
 * @throws  Exception
 */
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
}

/**
 * Defines the web based security configuration.
 *
 * @param   http It allows configuring web based security for specific http requests.
 * @throws  Exception
 */
@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .httpBasic()
            .authenticationEntryPoint(samlEntryPoint());
    http
            .addFilterBefore(metadataGeneratorFilter(), ChannelProcessingFilter.class)
            .addFilterAfter(samlFilter(), BasicAuthenticationFilter.class)
            .addFilterBefore(samlFilter(), CsrfFilter.class);
    http
        .authorizeRequests()
            .antMatchers("/").permitAll()
            .antMatchers("/saml/**").permitAll()
            .antMatchers("/css/**").permitAll()
            .antMatchers("/img/**").permitAll()
            .antMatchers("/js/**").permitAll()
            .anyRequest().authenticated();
    http
            .logout()
                .disable(); // The logout procedure is already handled by SAML filters.
}

/**
 * Sets a custom authentication provider.
 *
 * @param   auth SecurityBuilder used to create an AuthenticationManager.
 * @throws  Exception
 */
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth
        .authenticationProvider(samlAuthenticationProvider());
}

@Override
public void afterPropertiesSet() throws Exception {
    init();
}

@Override
public void destroy() throws Exception {
    shutdown();
}

}

With this im able to login to the application using the keycloak login

I think this is SP initiated login, I want to try IDP initiated login.
When I run http://localhost:8080/saml/metadata i get the below metadata file.

How do I configure the IDP initiated SSO in keycloak. Please help


text:
Q: Order of maven multi module is not maintained for eclipse plugins We have a bunch of eclipse plugin projects, features and update sites. We have created a master pom where we define the modules:
<modules>
    <module>bundles/b1</module>
    <module>features/f1</module>
    <module>p2/site1</module>
    <module>bundles/b2</module>
</modules>

We wanted to preserve this order and as per Guide to working with Multiple Modules
As per the link above we assumed that the order will be preserved as per the order in which the module elements were listed.
Our requirement:
site1 produces a site_assembly.zip. We wanted to take this zip file and wrap into around into a bundle which is what "b2" bundle does.
Our observation:

*

*Maven reactor order which is printed at the beginning of the multi-module build is proper, however the build for every module is forked.

*Because of (1) the bundle b2 get built before the site1 project is build and is able to produce a site assembly zip.

*We tried adding a dependency in "b2"'s pom.xml to site1 but the build failed as it tries to build b2 first which has dependency on site1 which has not been built till now.

*We observed the same behavior when we had unit test as osgi fragment. In the order we clearly specified that the host comes before the test fragment but when the maven build is invoked then it always built the fragment before the host and it used to fail.

Plugins that are defined in master pom:
 <plugin>
            <!-- enable tycho build extension -->
            <groupId>org.eclipse.tycho</groupId>
            <artifactId>tycho-maven-plugin</artifactId>
            <version>${tycho-version}</version>
            <extensions>true</extensions>
        </plugin>
        <plugin>
            <groupId>org.eclipse.tycho</groupId>
            <artifactId>target-platform-configuration</artifactId>
            <version>${tycho-version}</version>
            <configuration>
                <disableP2Mirrors>true</disableP2Mirrors>
                <resolver>p2</resolver>
                <target>
                    <artifact>
                        <groupId>com.x.y</groupId>
                        <artifactId>p2.build.target</artifactId>
                        <version>${project.version}</version>
                        <classifier>x</classifier>
                    </artifact>
                </target>
            </configuration>
        </plugin>

We are not sure if maven-tycho-plugin interferes with the reactor order, so any help would be appreciated.

A: Tycho resolves the dependencies from the Eclipse descriptor files (MANIFEST.MF, feature.xml, etc.) and re-orders the modules so that required artifacts are built first.


text:
Q: How to type a union of constants I would like to do the following:
from typing import Union, Literal
YES = 1
NO = 0
ValidResponse = Union[Literal[YES], Literal[NO]]

Of course, Python won't let me do this because YES and NO are considered to be variables, not literal numbers.
Obviously I can do ValidResponse = Union[Literal[1], Literal[0]], but as a programmer editing this file later, it seems odd that in order to change what constant YES used (for example YES = 'yes'), I would need to change it in two different places.
What's the best way to handle this scenario?

A: You should almost certainly just be using an enum instead:
import enum

class ValidResponse(enum.Enum):
    YES = 1
    NO = 0

Now you can use ValidResponse as an annotation:
def foo(response: ValidResponse) -> whatever:
    # do something with response

A: The enum solution is often the cleaner solution in these situations, but note that it is possible to do this kind of thing with typing.Literal. You have to explicitly annotate your variables as being of a "literal" type. The YesType and NoType aliases that I've introduced aren't strictly necessary, but may be helpful for clarity:
from typing import Union, Literal

YesType = Literal[1]
NoType = Literal[0]

YES: YesType = 1
NO: NoType = 0

ValidResponse = Union[YesType, NoType]


text:
Q: Windows Phone 8.1 Runtime - Image to byte[] and Vice Versa For my application, I am trying to convert an WriteableBitmap to byte[] to store in the database, and then from byte[] to BitmapImage to display back to the user.
My current methods that so far, produce no results:
public byte[] ConvertBitmapToByteArray(WriteableBitmap bitmap)
{
    using (Stream stream = bitmap.PixelBuffer.AsStream())
    using (MemoryStream memoryStream = new MemoryStream())
    {
        stream.CopyTo(memoryStream);
        return memoryStream.ToArray();
    }
}

To convert from byte array to BitmapImage, I use:
using (InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream())
{

    using (DataWriter writer = new DataWriter(ms.GetOutputStreamAt(0)))
    {
        writer.WriteBytes((byte[])buffer);
        writer.StoreAsync().GetResults();
    }

    var image = new BitmapImage();
    image.SetSource(ms);
    imageByteTest.Source = image;
}

There is good documentation for Silverlight applications I have found, but very little in the way for Windows Store Universal Runtime Applications.  Where are these methods going wrong?

A: You might want to take a look at the WriteableBitmapEx library which contains some extensions to WriteableBitmap, as well as some core features like your conversion of WriteableBitmap to byte array and vice versa.

A: I wrote a converter for ByteArrayToBitmapImage:
 public object Convert(object value, Type targetType, object parameter, string language)
    {
        var byteArray = value as byte[];
        var bitmapImage = new BitmapImage();
        Window.Current.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                using (var stream = new MemoryStream(byteArray))
                {
                    bitmapImage.SetSourceAsync(stream.AsRandomAccessStream());
                }
            });

        return bitmapImage;

    }

And byte[] -> WriteableBitmap
  public static WriteableBitmap PrepareWritableBitmap(Size size, byte[] pixels)
    {
        uint height = (uint)Math.Floor(size.Height);
        uint width = (uint)Math.Floor(size.Width);

        WriteableBitmap bmp = new WriteableBitmap((int)width, (int)height);
        Stream pixStream = bmp.PixelBuffer.AsStream();
        pixStream.Write(pixels, 0, (int)(width * height * 4));
        //4 is a channel number for RGBA, for RGB is 3 channels
        return bmp;
    }


text:
Q: Задача по системному программированию. (Массивы) [C++] Задача:

"Дан массив размером более 5000 элементов. Первый поток заполняет его случайными числами, второй поток - секундомер. Найти время заполнения массива."

Не знаю как сделать секундомер и подсчитать время заполнения...
Прошу помощи, желательно с комментариями и пояснениями.

A: Очень странная задача, я бы например показал что-то такое:
echo '
#include <stdio.h>
#define N 10000000
int a[N];
int main(){
  for (int i=0; i < N;i++)
    a[i] = rand();
  printf("%d", a[ rand() % N]);
  return 0;
}' | gcc -x c - -o 5 && time ./5


text:
Q: Conditionally independent versions of a random variable I have been going through some research papers related to information theory. Very often, I have come across this concept of independent versions and conditionally independent versions of a given random variable. I have some difficulty understanding this concept.
More precisely, say for a random variable $X$ and some measurable function $F$, $Z=F\left(X\right)$ be another random variable. What does it exactly mean when they say: "Let $X$ and $X'$ be two conditionally independent versions of $X$ given $Z$" ?
Though I understand what the above statement mathematically means, can anyone give me a more meaningful and intuitive interpretation of the above statement. Also I have the following doubt. How can we be sure that there exists such a version ?


text:
Q: INTERFACE target-link-libraries for shared libraries in macOS I'm creating some dynamic libraries (actually BLAS and LAPACK) with CMake. LAPACK uses functions from BLAS, but at least on Linux I don't need to specify this for building the libraries, and something like this seems to work:
add_library(blas ${BLAS_SOURCES})
add_library(lapack ${LAPACK_SOURCES})
# anything that links to lapack must link to blas too
target_link_libraries(lapack INTERFACE blas)

However, when I tried this on macOS I got undefined symbols when building lapack, which means I had to add:
target_link_libraries(lapack PRIVATE blas) # or "PUBLIC" and remove "INTERFACE"

Can this behavior be changed? Did the above work on Linux just by chance?
EDIT: This is a full simple example:
CMakeLists.txt
cmake_minimum_required(VERSION 2.8.12)
set (CMAKE_MACOSX_RPATH 0)
project (hello LANGUAGES Fortran)
add_library (bar SHARED bar.f90)
add_library (foo SHARED foo.f90)
target_link_libraries (foo INTERFACE bar)
add_executable (main main.f90)
target_link_libraries (main PUBLIC bar foo)

bar.f90
subroutine bar
write(6,*) "Hello, I'm bar"
end subroutine bar

foo.f90
subroutine foo
call bar()
end subroutine foo

main.f90
program main
call foo()
end program main


text:
Q: What is the meaning of the word "inriation"? I looked up the definition of the word elation in Webster's Revised Unabridged 1913 dictionary and found the following definition  (Page: 476):

Elation
E*la"tion (?), n. [L. elatio. See Elate.] A lifting up by success; exaltation; inriation with pride of prosperity. Felt the elation of triumph." Sir W. Scott."

I had never seen the word inriation before and my subsequent attempts to find a definition failed. It is not listed as a word in the 1913 dictionary, or any others that I've found.
Is there an example of this word in English literature? Is it made-up, a misspelling? I can infer the definition from context, but is there any dictionary where inriation is defined?

A: inflation with pride of prosperity
It is most likely an OCR error concerning an exotic fl ligature being interpreted as ri -> inflation.
This maybe due to poor inking of the top left quadrant of the ligature in the original, or poor thesholding during the OCR. In either case this would lose the upper branch of the f, but the dot being the f terminal serif would remain.
Reasoning:

*

*pride is something which is often said to be pumped up or otherwise swolen or aerated.

*I studied the OCR errors of noisy, hot-Lead typeset documents as part of my Computer Science doctorate.


text:
Q: Returning from only landscape view to portrait app I have an app that works only in portrait mode, however, there is one view that needs to support both portrait as well as landscape mode. Anytime I return from this view the rest of app mess up.
The view that needs to support both orientations contains webview that is used to play live stream.
Simple setting shouldAutorotateToInterfaceOrientation doesn't work. The trick with presenting modal view controller neither. The trick with removing and inserting root view doesn't work as well.
I am afraid to use [[UIDevice currentDevice] setOrientation:UIInterfaceOrientationPortrait] (that actually works) as it is private api.

A: I have an app that all works in portrait orientation and only one view with fullscreen photo supports landscape orientation. So i present this fullscreen view modally and in my FullscreenViewController.m
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return ([[UIApplication sharedApplication] statusBarOrientation]);
}

hope this can be useful

A: Actually the method with removing and inserting first view of window views as mentioned here does work!
iOS portrait only app returns from UIWebview youtube in landscape
I just need from some reason not to ask for first view in window subviews. I need to provide root view myself instead.
So my solution is to implement following methods in view controller that supports both orientations:
-(void)viewWillAppear:(BOOL)animated
{
    m_b_avoid_landscape_orinetation = NO;

    [super viewWillAppear:animated];
}

-(void)viewWillDisappear:(BOOL)animated
{
    m_b_avoid_landscape_orinetation = YES;

    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    [[self getTabBar].view removeFromSuperview];
    [window addSubview:[self getTabBar].view];

    [super viewWillDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
    if (m_b_avoid_landscape_orinetation)
        return (toInterfaceOrientation == UIInterfaceOrientationPortrait);
    else
        return YES;
}

Where [self getTabBar] provides my custom tab bar that works as first view in window's subviews.
Edit So with iOS 6 it doesn't work anymore. I used solution with inserting and removing modal dialog as mentioned elsewhere with new supportedInterfaceOrientations method.
-(void)goBack
{
    m_b_avoid_landscpae_orinetation = YES;

    UIViewController *viewController = [[UIViewController alloc] init];
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    [window.rootViewController presentViewController:viewController animated:NO completion:^{
        [viewController dismissModalViewControllerAnimated:NO];
    }];

    [self.navigationController popViewControllerAnimated:YES];
}

-(NSUInteger)supportedInterfaceOrientations
{
    if (m_b_avoid_landscpae_orinetation)
        return UIInterfaceOrientationMaskPortrait;

    return UIInterfaceOrientationMaskAllButUpsideDown;
}

A: You could use [[UIDevice currentDevice] setOrientation:orientation] in viewWillAppear: or viewDidAppear: to force app to rotate to desired orientation. But, that's private call, and not sure if Apple would approve your app :)(mine got approved). Good Luck!

A: //
//  ViewController.h
//  CustomNavigationController
//
//  Created by Durul Dalkanat on 11/05/15.
//  Copyright (c) 2015 Durul Dalkanat. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

- (IBAction)showLandscapeViewButtonClicked:(id)sender;

@end

//
//  ViewController.m
//  CustomNavigationController
//
//  Created by Durul Dalkanat on 11/05/15.
//  Copyright (c) 2015 Durul Dalkanat. All rights reserved.
//

#import "ViewController.h"
#import "LandscapeView.h"
#import "CustomNavigationControllerViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
  [super viewDidLoad];
  // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
  [super didReceiveMemoryWarning];
  // Dispose of any resources that can be recreated.
}

- (IBAction)showLandscapeViewButtonClicked:(id)sender {

  LandscapeView *landscape = [[LandscapeView alloc]initWithNibName:@"LandscapeView" bundle:nil];
  CustomNavigationControllerViewController *nav = [[CustomNavigationControllerViewController alloc]initWithRootViewController:landscape];
  nav.navigationBarHidden = true;
  [self presentViewController:nav animated:YES completion:^{

  }];

}

#pragma mark handeling rotation

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
  return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{
  return UIInterfaceOrientationPortrait;
}
- (BOOL)shouldAutorotate
{
  return NO;
}
- (NSUInteger)supportedInterfaceOrientations
{
  BOOL atLeastIOS6 = [[[UIDevice currentDevice] systemVersion] floatValue] >= 6.0;
  if(atLeastIOS6)
  {
    return UIInterfaceOrientationMaskPortrait;
  }
  else{
    return UIInterfaceOrientationPortrait;
  }
}

@end

And Insert a New ViewController with Xib. After please change freeform.

//
//  LandscapeView.h
//  CustomNavigationController
//
//  Created by Durul Dalkanat on 11/05/15.
//  Copyright (c) 2015 Durul Dalkanat. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface LandscapeView : UIViewController

@end
//
//  LandscapeView.m
//  CustomNavigationController
//
//  Created by Durul Dalkanat on 11/05/15.
//  Copyright (c) 2015 Durul Dalkanat. All rights reserved.
//

#import "LandscapeView.h"

@interface LandscapeView ()

@end

@implementation LandscapeView

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*

#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end

//
//  CustomNavigationControllerViewController.m
//
//
//  Created by Durul Dalkanat
//

#import <UIKit/UIKit.h>

@interface CustomNavigationControllerViewController : UINavigationController

@end

//
//  CustomNavigationControllerViewController.m
//
//
//  Created by Durul Dalkanat
//

#import "CustomNavigationControllerViewController.h"

@interface CustomNavigationControllerViewController ()

@end

@implementation CustomNavigationControllerViewController

- (NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskLandscape;

}

@end


text:
Q: accing dynamic element through jquery I want to achieve this
$("div1 input").attr('id');

where div1 is dynamically generated through php loop ( so i have like div1,div2,div3 etc )
in my jquery function i have $('#counter').val();which holds calues from 1 to 3 dynamically,
so this is what i am doing $("#div"+ $("#counter").val() +"input").attr('id')
above code should give me input attribute id,
for some reasons or may be due to some syntax problem i am not getting it, Have a look and point out my mistake . Thanks in advance

A: You missed the space before input, try this:
$("#div" + $("#counter").val() + " input").attr('id')

A: You need to use your code, AFTER you are generated your divs. So you need to put <script> after loop generation or on document ready event.
Try following:
$(function()
{
        var $el = $("#div"+ $("#counter").val() +" input");
        //or you can use alert($el.length) to see if $el created.
        if ($el.length)
        {
           var id =  $el.attr('id');
        }

});


text:
Q: OAuth2 Authorization Code in Cookie, good or bad? I can not seem to find a SIMPLE answer to the question on how to persist OAuth2 authentication... Let's take Google+ OAuth2 API as an example.

*

*User goes to page

*User is not authenticated, and gets redirected to authentication page where he logs in

*User logs in successfully and authorises my app

*User gets redirect to specified (by me) URI with Authorisation Code

*I use authorisation code to obtain a token in order to submit queries in the name of the user

All is good and well. My question is: how do you SECURELY know at step 2 that the user visiting the page is already logged in, without having to go through the whole process of redirecting him to all these pages.
I assume storing the Authorisation Code retrieved at step 4 in a cookie is not an option.
All of this will happen in a server-side (Go - if that matters) application.
Any help is much appreciated... I need a simple solution.
Thank you!

A: use server-side sessions to store any authentication state or even access tokens if you need them.
one solution is to use a database for session store (an encrypted cookie holds the session id)
and another is to use cookie sessions (encrypted cookies that hold the session data).
using encrypted cookies that only the server is able to decrypt should be safe enough.


text:
Q: Finding Patterns and Useful Information From Survey Text [xlsx] I want to find patters and extract useful information from a large amount of survey data. The data is sorted in an .xlsx spreadsheet with 4 columns corresponding to particular questions, with each row filled with a text response from the respondent.
How can I use python and openpyxl to extract patterns from the data, such as frequency of words or phrases, connections between answers across the four questions, or anything else I should look for?
I have limited experience in data/text mining, so if there is some documentation, useful tutorials, or another StackOverflow question I should look at, please let me know. I did a fair amount of searching here and elsewhere, but haven't found what I'm looking for.
So far I have taken a shot at word frequency based on the survey question, but it has proved difficult to navigate the openpyxl documentation to do something like this. Is there an easy way to do this in python?
Sample array [600x4]:
    [['this is an example of an answer to question 1 by respondent 1', 'answer to Q2 by R1', 'ans to Q3 by R1', 'ans to Q4 by R1']
    ['ans to Q1 by R2', 'ans to Q2 by R2', 'ans to Q3 by R2', 'ans to Q4 by R2']
    [etc, etc, etc, etc...]]

A: The Excel file format is not particularly suited to this kind of task. You would do much better to copy the data from the file into a tool more suited to the task such as a relational database with a full text search or maybe a specialised text engine.
openpyxl is library designed for manipulating the Excel files. So, in this case it can help you extract the data and pass it to another application.


text:
Q: Reducing unused space/arrow length for cytoscape js layouts I am using the cytoscape js library for displaying a hierarchy of images. I followed the example on http://jsbin.com/gist/aedff159b0df05ccfaa5?js,output and found that the breadthfirst layout is what I need.
However, I find the rendered result unsatisfactory due to too much unused space. The arrows are too long. Even the example (http://jsbin.com/gist/aedff159b0df05ccfaa5?js,output) has this issue. For this example, I tried the following

*

*Increase the "height/width" in .selector('node') .css({

*Muck around with the distanceX and distanceY (node spacing) variables in layout.breadthfirst.js (line 352).

I am unable to reduce the unused space or reduce the length of the arrows.

A: Ticket to follow: https://github.com/cytoscape/cytoscape.js/issues/737
If you want a new feature in future, please file a ticket.

A: For rushing Devs, try this layout option:
spacingFactor: 0

The manual says :
spacingFactor: 1.75, // positive spacing factor,
                     // larger => more space between nodes (N.B. n/a if causes overlap)

That's the result of the ticket https://github.com/cytoscape/cytoscape.js/issues/737 reported by maxkfranz.


text:
Q: JSF shows uninterpreted page when adding slash to path I have the problem, that JSF is showing the original source code page, when calling for exmaple ..../index.xhtml/ instead of the normal path .../index.xhtml
By adding the additional slash at the end of the path, it shows the unrendered page. How can I turn off this behaviour?
I use spring boot with JSF 2.2.13. I register JSF in my Spring Config with the following line.
ServletRegistrationBean registration = new ServletRegistrationBean(new FacesServlet(), "*.xhtml");

It's all working fine, we just discovered this odd behaviour when adding the additional slash.
Any suggestions how to avoid this?


text:
Q: how to specify generic types for a Dart static extension? I'm trying to create a static extension on Iterable like so:

extension IterableExtensions<T> on Iterable<T> {
  Iterable<E> mapIndexed<E, T>(E Function(int index, T item) f) sync* {
    var index = 0;

    for (final item in this) {
      yield f(index, item);
      index = index + 1;
    }
  }
}

but this gives me an error of:
The argument type 'T' can't be assigned to the parameter type 'T'.
Whereas if I cast the compiler is happy:
extension IterableExtensions on Iterable{
  Iterable<E> mapIndexed<E, T>(E Function(int index, T item) f) sync* {
    var index = 0;

    for (final item in this) {
      yield f(index, item as T);
      index = index + 1;
    }
  }
}

I'm not sure what I'm doing wrong here?

A: You actually shot yourself in the foot with the first example. The T defined in the method signature overrode the T in the extension signature. You can see what happened more clearly if you change one of them to something else:
extension IterableExtensions<U> on Iterable<U> {
  Iterable<E> mapIndexed<E, T>(E Function(int index, T item) f) sync* {
    var index = 0;

    for (final item in this) {
      yield f(index, item);
      index = index + 1;
    }
  }
}

// Error: The argument type 'U' can't be assigned to the parameter type 'T'.

The fix is to remove the T from the method signature:
extension IterableExtensions<T> on Iterable<T> {
  Iterable<E> mapIndexed<E>(E Function(int index, T item) f) sync* {
    var index = 0;

    for (final item in this) {
      yield f(index, item);
      index = index + 1;
    }
  }
}


text:
Q: Why does Laravel log out when I refresh the page after logging in? Everyone thanks. I fixed this problem. The source of the problem;
Çıkış Yap

this code line. Auth::logout() function. nobody clicks but this works. I will use the route.

I am using Laravel 7 library. I log in from the login page and go to the home page. However, when I refresh the page, it seems that the session has ended.
Because I use @auth and @guest in blade template. For the menu layout.
LoginController page;
class LoginController extends Controller
{

    use AuthenticatesUsers;

    protected $redirectTo = RouteServiceProvider::HOME;

    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }
}

HomeController
/**
 * Create a new controller instance.
 *
 * @return void
 */
public function __construct()
{
    //$this->middleware('auth');
}

/**
 * Show the application dashboard.
 *
 * @return \Illuminate\Contracts\Support\Renderable
 */
public function index()
{
    return view('home');
}

web.php
Auth::routes();

Route::get('/', 'HomeController@index')->name('home');

and this layout.app.blade page
@guest
    Giriş Yap
    Hizmet Ver
@endguest

@auth
    Profilim
    Çıkış Yap
@endauth

I hope you understand what I mean. I am logging in, yes the menu works correctly. But when the page is refreshed, it appears to be logged out.

A: You are calling Auth::logout() in href in second  tag at @auth block. When each time the page is refreshed, Auth::logout() is called and it is logging out from current session.
Please remove the Auth::logout() from there and add the logout URL. It will work.
@auth
    Profilim
    Çıkış Yap
@endauth


text:
Q: Uncaught InvalidStateError in JSON.stringify I've read this other thread and it was no good: Put data into JSON with Jquery
Whenever I try to JSON.stringify an object array I get an error saying:
Uncaught InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable.

Here is my JS:
            var responseItems = [];

            var keynoteContainer = $('div.keynote-questions');
            var eventQuestionContainer = $('div.event-questions');
            var sessionContainer = $('div.session-questions');
            var eventId = $('#Evaluation-Event-Id').val();

            keynoteContainer.children().each(function (index, el) {
                var element = $(el);

                var id = "-1";
                var parentId = element.find('input[type=hidden]').val();
                var parentType = "Keynote";
                var responseValue = element.find('.response-item-slider').slider("option", "value");
                var responseText = "";

                var response = { "Id": id, "EventId": eventId, "ParentId": parentId, "ParentType": parentType, "ResponseValue": responseValue, "ResponseText": responseText };
                responseItems.push(response);
            });

            eventQuestionContainer.children().each(function (index, el) {
                var element = $(el);

                var id = "-1";
                var parentId = element.find('input[type=hidden]').val();
                var parentType = "EventQuestion";
                var responseValue = element.find('.response-item-slider').slider("option", "value");
                var responseText = element.find('textarea').val();

                var response = { "Id": id, "EventId": eventId, "ParentId": parentId, "ParentType": parentType, "ResponseValue": responseValue, "ResponseText": responseText };
                responseItems.push(response);
            });

            sessionContainer.children().each(function (index, el) {
                var element = $(el);

                var id = "-1";
                var parentId = element.find('input[type=hidden]').val();
                var parentType = "Session";
                var responseValue = element.find('.response-item-slider').slider("option", "value");
                var responseText = "";

                var response = { "Id": id, "EventId": eventId, "ParentId": parentId, "ParentType": parentType, "ResponseValue": responseValue, "ResponseText": responseText };
                responseItems.push(response);
            });

            responseItems = JSON.stringify(responseItems);

I've tried to log everything and it only breaks at the last line where I stringify it.
How can I fix this? Any piece of advise or information would be highly appreciated.

A: I had the same error.  In my case, I had forgotten the .val() when I was setting one of the model properties.  There wasn't an error until I tried to JSON.stringify the model
        this.model.set(
        {
            customername: this.$("#customername").val(),
            jobtitle: this.$("#jobtitle"),  //This was the line causing the error
            testimonialtext: this.$("#testimonialtext").val()
        });

A: I had the same problem. In my case it was fixed casting my trouble variable toArray(). I mean something like this:
responseItems = responseItems.toArray();
I don't know why that variable looks like an Array but it isn't
after that you can call:
JSON.stringfy(responseItems);
without problems.

PD: sorry for my english I'm not native english speaker


text:
Q: C# Deleting a Row from AccessDatabase / Converting String to Int I'm a novice programmer trying to delete a row from an AccessDatabase using a "DELETE FROM " query. It requires converting a string to an Int which is where the problem occurs
Here's the Code I'm running :
private void BtnDelete_Click(object sender, EventArgs e)
{

    OleDbConnection Conn = new OleDbConnection();
    Conn.ConnectionString = @"Provider = Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\HoliPlanData.accdb;Persist Security Info=False";

    try
    {
         Conn.Open();
            String Query = "DELETE * FROM [Employee] WHERE PayrollNo = @PayrollNo";
            OleDbCommand DoDelete = new OleDbCommand(Query, Conn);
            String PayrollNo = PassPayrollNo;
            int PayRowNum = 0;
            bool isValid = int.TryParse(PassPayrollNo, out PayRowNum);
            if (isValid)
            {
                DoDelete.Parameters.AddWithValue("@PayrollNo", PayRowNum);
                DoDelete.ExecuteNonQuery();
                MessageBox.Show("Success");
                Conn.Close();
            }
            else
            {
                MessageBox.Show("Could not convert to string");
                Conn.Close();
            }

}

When I run this I get into the Else clause, so the conversion to string isn't working
What's going wrong? Why?
Any help would be greatly appreciated, thanks.

A: The problem is with your parameter @PayrollNo, you have to make sure the variable PassPayrollNo is the same type as the PayrollNo in your table. If you show the types you are using we can try to help you more.

A: Try with passing int type parameter:
int payrowNum = 0;
bool isValid = int.TryParse(PassPayrollNo, out payrowNum);
if(isValid)
{
     string sQuery = "DELETE * FROM [Employee] WHERE PayrollNo = @PayrollNo";
     OleDbCommand DoDelete = new OleDbCommand(sQuery, Conn);
     DoDelete.Parameters.AddWithValue("@PayrollNo", payrowNum);
     int rowsAffected = DoDelete.ExecuteNonQuery();
     if(rowsAffected>0)
     {
         MessageBox.Show("Success");
     }
     Conn.Close();

}


text:
Q: Using StructuralComparisons class for everything I had to compare equality of two two-dimensional arrays. I tried to use StructuralComparisons.StructuralEqualityComparer.Equals(obj1, obj2) and it works.
So now I wrote this method (in Helpers utility class):
public static bool Equals<T>(T obj1, T obj2)
{
    return StructuralComparisons.StructuralEqualityComparer.Equals(obj1, obj2);
}

And a question: Which method should I use when I don't know whether Type T is struct (i.e. array) or class? Object.Equals or this one?

A: The answer is yes.
In such situations we can use StructuralComparisons comparer because it checks whether first object implements IStructuralEquatable and if it really implements, then it uses IStructuredEquatable.Equals() method, otherwise it uses obj1.Equals(obj2).
The implementation of this method is listed below
public new bool Equals(Object x, Object y) {
    if (x != null) {

        IStructuralEquatable seObj = x as IStructuralEquatable;

        if (seObj != null){
            return seObj.Equals(y, this);
        }

        if (y != null) {
            return x.Equals(y);
        } else {
            return false;
        }
    }
    if (y != null) return false;
    return true;
}