text:
Q: What is the purpose of `boolean` type in JVM? As it said in JVMS8:

Although the Java Virtual Machine defines a boolean type, it only provides
very limited support for it. There are no Java Virtual Machine instructions solely
dedicated to operations on boolean values. Instead, expressions in the Java
programming language that operate on boolean values are compiled to use values
of the Java Virtual Machine int data type.

Indeed, these two methods:
boolean expr1(boolean a, boolean b) {
    return a || b;
}

int expr2(int a, int b) {
    return ((a != 0) || (b != 0)) ? 1 : 0;
}

will produce the same byte code (except the method signatures)
  boolean expr1(boolean, boolean);
    Signature: (ZZ)Z
    Code:
       0: iload_1
       1: ifne          8
       4: iload_2
       5: ifeq          12
       8: iconst_1
       9: goto          13
      12: iconst_0
      13: ireturn

  int expr2(int, int);
    Signature: (II)I
    Code:
       0: iload_1
       1: ifne          8
       4: iload_2
       5: ifeq          12
       8: iconst_1
       9: goto          13
      12: iconst_0
      13: ireturn

So, I do not understand why JVM needs boolean type. Is it just for the runtime check of method signatures?

A: As minimum it is needed to support methods overloading. Say, we have two methods in the same class
boolean a(boolean x) {...}
and
boolean a(int x) {...}
They can have different internal logic, so in the byte code they should be distinguished by their signatures.


text:
Q: How to properly rename a wagtail page model I have two models in a wagtail app, PageType and NewPageType, and need to replace PageType with NewPageType.
I thought I could remove PageType from my models.py and then run a migration to remove it, and then rename NewPageType to PageType and run a second migration.
However, I'm running into errors when I do this:
[2019-01-22 23:20:26,344] [ERROR] Internal Server Error: /cms/
Traceback (most recent call last):
  File "/.../python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner
    response = get_response(request)
  File "/.../python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  [...snip...]
  File "/.../python3.6/site-packages/django/db/models/query.py", line 1121, in _fetch_all
    self._result_cache = list(self._iterable_class(self))
  File "/.../python3.6/site-packages/wagtail/core/query.py", line 397, in specific_iterator
    yield pages_by_type[content_type][pk]
KeyError: 278

It seems like something didn't get updated automatically by Django's built-in migration handling. I couldn't tell what steps I'm missing here so would love to get some help. Thanks!

A: That's because Wagtail pages uses Multi-table inheritance and part of your deleted PageType pages are still around.
Let's take a look at a fresh install of Wagtail (i.e. wagtail start mysite) which comes with a home.HomePage model and creates one HomePage by default. We can have a look at the database and confirm that there is indeed an entry in the database:
sqlite> SELECT * FROM home_homepage;
page_ptr_id
3

However it's rather empty. There's no title, no path, nothing but a page_ptr_id. This is because the HomePage inherit from the Page model which isn't abstract. Therefore, there is a database table for that Page model as well (this is how Multi-table inheritance works with Django). Let's have a look at the corresponding table (voluntarily ommitting some columns) :
sqlite> SELECT id, path, title, slug, url_path, content_type_id FROM wagtailcore_page;
id|path    |title|slug|url_path|content_type_id
1 |0001    |Root |root|/       |1
3 |00010001|Home |home|/home/  |2

Here it is!
Similarly, in your case, there is the wagtailcore_page, the myapp_pagetype and myapp_newpagetype tables. By deleting the PageType model, django created a migration which then deleted the myapp_pagetype but left the entry in the wagtailcore_page table. Therefore now, when you load the admin interface, Wagtail tries to load the page #3 but fail to do so.
For that reason, before deleting a Page model, you need to delete all the pages first. You can achieve this by adding a RunPython step to your migration.
You would still be left with renaming your second model though which can be difficult with Django, although if you're lucky, renaming it in your models.py file and runing makemigrations might be enough for Django to detect that it should rename the model. If not, or if you have relationships which need to be renamed to, it might be more involed, see 1 and 2.

A: To recover from it and be able to load admin again, do the following:
Delete the reference:
import django
django.setup()
from wagtail.core.models import PageRevision
PageRevision.objects.filter(page_id= 278).delete()
exit()

Then delete the page.
django-admin dbshell
DELETE FROM wagtailcore_page WHERE id=278;

Hope that helps.

A: I'm new to wagtail, but I had no issues renaming the model and the correlating template, then running
python manage.py makemigrations
python manage.py migrate

That being said, I was not reusing an old name like OP. I might recommend anyone having this issue to come up with a new name for the model and make it a descriptive one.

redpajama_set_name: RedPajamaStackExchange


text:
Q: react native: state updates do not have effect on transform I want to have a component that gets bigger when pressed on, and gets smaller when released. I am trying to use onPressIn and onPressOut handlers to update state which updates the transform value:
const ExampleScreen = () => {
  const [pressed, setPressed] = useState(false);
  const scale = pressed === true ? 2 : 1;
  console.log('rendering with scale ', scale);
  return (
    <View
      style={{
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
      }}>
      <TouchableWithoutFeedback
        onPressIn={() => setPressed(true)}
          onPressOut={() => setPressed(false)}>
        <View
          style={[
            {
              backgroundColor: 'lightblue',
              width: 100,
              height: 100,
            },
            {transform: [{scale: scale}]},
          ]}>
          <Text>Press me</Text>
        </View>
      </TouchableWithoutFeedback>
    </View>
  );
};

I can see in the console that the state changes:
[Thu Jun 18 2020 19:36:14.483]  LOG      rendering with scale  1
[Thu Jun 18 2020 19:36:14.780]  LOG      rendering with scale  2
[Thu Jun 18 2020 19:36:15.124]  LOG      rendering with scale  1

but the square on the screen does not change its scale. Why is that, and how to fix it?

A: Try this!
Put this code outside your component like this
if (Platform.OS === 'android') {
  if (UIManager.setLayoutAnimationEnabledExperimental) {
    UIManager.setLayoutAnimationEnabledExperimental(true);
  }
}

const ExampleScreen = () => {/* your component */}

Then add this right before you update the state:
LayoutAnimation.configureNext(LayoutAnimation.Presets.spring);

//Example
<TouchableWithoutFeedback
        onPressIn={() => {
                    LayoutAnimation.configureNext(LayoutAnimation.Presets.spring);
                    setPressed(true);
                  }}>

For more info on LayoutAnimation go here: LayoutAnimation


text:
Q: flutter slider image use Carousel problem I tried to use carousel to realize slider images, but I got some error.
first when I running the app I got Cannot run with sound null safety, because the following dependencies don't support null safety, So i tried to use this methods to solve flutter run --no-sound-null-safety I not sure is it normal methods??
Second, I got this error type 'List<dynamin>' is not a subtype of type 'String'
this is my code
campsite_screen.dart
body: StreamBuilder(
        stream: FirebaseFirestore.instance
            .collection('Campsite')
            //.orderBy('ServerTimeStamp', descending: true) //倒序開啟
            .snapshots(),
        builder: (context,
            AsyncSnapshot<QuerySnapshot<Map<String, dynamic>>> snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Center(
              child: CircularProgressIndicator(),
            );
          }
          return ListView.builder(
            itemCount: snapshot.data!.docs.length,
            itemBuilder: (context, index) => Container(
              margin: EdgeInsets.symmetric(
                  horizontal: width > webScreenSize ? width * 0.3 : 0,
                  vertical: width > webScreenSize ? 15 : 0),
              child: CampsiteCard(
                snap: snapshot.data!.docs[index],
              ),
            ),
          );
        },
      ),

CampsiteCard
GestureDetector(
            child: Stack(
              alignment: Alignment.center,
              children: [
                SizedBox(
                  height: MediaQuery.of(context).size.height * 0.35,
                  width: double.infinity,
                  child: Carousel(
                    dotSize: 6.0,
                    dotSpacing: 15.0,
                    dotPosition: DotPosition.bottomCenter,
                    images: [
                      Image.network(
                        widget.snap[
                            'CamperSiteImages'],
                        fit: BoxFit.cover,
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),

This is my database dot

Do I miss somethings?


text:
Q: Does $z^0$ Have Multiple Solutions? While playing around with complex numbers, I stumbled upon a result that implies $z^0$ has infinitely many values (where $z$ is any complex number).  This struck  me as odd since I've never come across it before in my studies (and I think it violates the Fundamental Theorem of Algebra). I assume I made a mistake somewhere in my derivation but I cannot find it. Could someone please look through the steps below and help me understand where my error is?
I started by solving $z^i$:
Assume $z^i=w$
$$z^i=w$$
$$\ln(z^i)=\ln(w)$$
$$i\ln(z)=\ln(w)$$
Express $z$ in its polar form:
$$z=||z||e^{i(arg(z) + 2\pi n)}$$ where n is an integer that accounts for periodicity of the argument of z
Substitute in the polar expression for $z$ and simplify the logarithm:
$$i\ln(||z||e^{i(arg(z) + 2\pi n)})=i\ln(||z||))+i\ln(e^{i(arg(z) + 2\pi n)})=\ln(w)$$
$$i\ln(||z||))+i^2(arg(z) + 2\pi n)=\ln(w)$$
$$i\ln(||z||))-arg(z) - 2\pi n=\ln(w)$$
Invert the natural logarithm:
$$w = e^{i\ln(||z||))}e^{-arg(z) - 2\pi n}$$
$$z^i = ||z||^ie^{-arg(z) - 2\pi n}$$
Next I solved $z^{-i}$ using the same process with $m$ as the periodicity constant:
$$z^{-i}=w$$
$$\ln(z^{-i})=\ln(w)$$
$$-i\ln(z)=\ln(w)$$
Substitute in the polar expression for $z$ and simplify the logarithm:
$$-i\ln(||z||e^{i(arg(z) + 2\pi m)})=-i\ln(||z||))-i\ln(e^{i(arg(z) + 2\pi m)})=\ln(w)$$
$$-i\ln(||z||))-i^2(arg(z) + 2\pi m)=\ln(w)$$
$$-i\ln(||z||))+arg(z) + 2\pi m=\ln(w)$$
Invert the natural logarithm:
$$w = e^{-i\ln(||z||))}e^{arg(z) + 2\pi m}$$
$$z^{-i} = ||z||^{-i}e^{arg(z) + 2\pi m}$$
Now multiply the $z^i$ and $z^{-i}$ results together:
$$z^iz^{-i} = z^0$$
$$\left(||z||^ie^{-arg(z) - 2\pi n}\right)\left(||z||^{-i}e^{arg(z) + 2\pi m}\right) = z^0$$
$$\left(||z||^i*||z||^{-i}\right)\left(e^{-arg(z) - 2\pi n}*e^{arg(z) + 2\pi m}\right)=z^0$$
$$e^{- 2\pi n + 2\pi m}=z^0$$
Since $m$ and $n$ are just integers, you can just group them into one constant.
$$e^{2\pi n}=z^0$$
where $n$ is any integer.
Does anyone see where I went wrong?

A: Choose for instance: $z = i$
$i^i = \exp(i \ln i) = \exp \bigg[i^2 \bigg(\cfrac{\pi}{2} + 2\pi \mathbb{Z}\bigg)\bigg] = e^{-\cfrac{\pi}{2}} e^{2\pi\mathbb{Z}} = A$
$i^{-i} = \exp(-i \ln i) = \exp \bigg[-i^2 \bigg(\cfrac{\pi}{2} + 2\pi \mathbb{Z}\bigg)\bigg] = e^{+\cfrac{\pi}{2}} e^{2\pi\mathbb{Z}} = B$
Set A times set B:
$A \cdot B = e^0 \exp({2\pi \mathbb{Z} + 2\pi \mathbb{Z}}) = 1 \exp (2\pi \mathbb{Z}) = \{\exp 0, \exp ± 2\pi, \exp ± 4\pi, \cdots \}$
Therefore $i^i \cdot i^{-i} \neq \{1\}$


text:
Q: How to take the average for percent error? I have roughly 39 data points that are values for % error. I have been researching and found that it is not correct to simply take the average of the % errors. Is this correct? If so, what is the correct way to take the average for % error values? All of the data values are weighted the same. Thanks!

A: You certainly can average the percent error values.  That is a well defined operation.  As Dilbert says, you can multiply them, too.  Whether or not it expresses what you want can be very subtle.  You are probably remembering the fact that averaging the percentage errors will not give the same result as dividing the average error by the average true value.  If you explain carefully what you want to express, it will lead to the correct way to compute it.

A: I assume that you have given the errors in one direction and not the absolute error.
Let $r_i$ the deviation from the real data point in decimal notation.
Then the average deviation is
$$d=\sqrt[n]{(1+r_1)\cdot (1+r_2)\cdot (1+r_3)\cdot \ldots\cdot (1+r_n)}-1$$
$r_i$ can be negative and positive. For instance, if the real value is 120 and the deviation is $-12$, then $r_1=\frac{-12}{120}=-0.1$ and consequently $1+r_1=0.9$.
To get the value in percentage you have to multiply $d$ by $100\%$.


text:
Q: location.href not changing iframe src I need to check an iframe src for changes from the parent page.
$('myiframe').attr('src');

works fine, but when I change the hash of the url via javascript from within the iframe
location.href += '#hash';

I can see it changed from the iframe inspecting location.href, but from the parent document, src doesn't seem to change. Any help?
EDIT
Since the containing page and the iframe are on different domains, I have to inspect it with the src attribute and I can't access the iframe location.href property.

A: the hash-parameter isn't in the property location.href, try
location.hash = 'hash';

A: I doubt whether you can do it simply from parent javascript.
Because then I can:

*

*create a page, with a hidden iframe. (say http://mysite.com/fake)

*In the iframe, open some intermediate page within the login process of some website (something similar to https://accounts.google.com/redirlogin)

*if the cookie for child is present & of there is not enough care taken, the page within the frame will redirect to actual website, with user logged in.

*From parent page, I can check all the intermediate urls it gone through, which can essentially contain some session IDs.

NOTE: I had done something similar in orkut days & that 'intermediate login page' used to redirect to orkut. This was done for an autologin feature I wanted to implement. However, I could not get any information in parent page.
Notes:

*

*I may be completely wrong, but I feel that from security perspective, this will not be possible from pure parent side code. Child should inform the parent.

*It may indeed work for intra-domain sites.

A: Cross-domain frames are allowed to set, but not read, each other's locations. (Why? Well, reading each other's locations would violate the same origin policy, potentially leaking sensitive information that appears in URLs. I'm not exactly sure why setting them is allowed though. Historically sites used the ability to navigate the parent page to framebust, but that isn't so relevant anymore.)
So, if you are trying to use hash fragments for cross-domain frame communication (and you can't use postMessage for some reason), then the way to do it is to have the inner frame change the hash fragment of its parent's location, using window.top.location.href. The parent page should then check every so often for changes to its hash fragment.
Here is a demo I found.

A: This snippet works for youtube clips, pdfs and html pages (unless frames are deliberately blocked by the targeted website)
The link will render the document 'htp://someurl' into an anonymous iframe within div id="someID"
`<a href="htp://someurl" onclick="renderLink('someID');return false;" title="Click to view external document">view external document</a>`

`function renderLink() {`
    `if (!e) var e = window.event;`
    `var pdfsrc = e.srcElement.getAttribute('href');`
    `var $pdfdiv = document.getElementById('someID');`
    `var $pdfTarget = $pdfdiv.getElementsByTagName("iframe")[0];`
    `$pdfTarget.src = pdfsrc;`
   `}`


text:
Q: What governs switching of refresh rate in "Pro Motion" iPads? A major new feature in the latest generation of iPad Pro is the automatic adaptation of screen refresh rate.
I haven't found any documentation of the level at which this is controlled, whether it is something that it is possible (or even desirable) to explicitly specify from a running app, or indeed if there might be costs associated with frequently switching, for example in cases where a high refresh rate is desired only intermittently as the user is interacting.
As of this writing, I don't have such a device to test with, and am also not sure of what information the developer tools - Energy Gauges or Time Profiler - convey about how these states switch during runtime and the resulting energy consumption, whether it is handled automatically by iOS or not.


text:
Q: Can we cascade multiple MapReduce jobs in Hadoop Streaming (lang: Python) I am using Python and have to work on following scenario using Hadoop Streaming:
a) Map1->Reduce1->Map2->Reduce2
b) I dont want to store intermediate files
c) I dont want to install packages like Cascading, Yelp, Oozie. I have kept them as last option.
I already went through the same kind of discussion on SO and elsewhere but could not find an answer wrt Python. Can you please suggest.

A:
b) I dont want to store intermediate files
c) I dont want to install packages like Cascading, Yelp, Oozie.

Any reason why? Based on the response, a better solution could be provided.
Intermediates files cannot be avoided, because the o/p of the previous Hadoop job cannot be streamed as i/p to the next job.  Create a script like this

run streaming job1
if job1 is not success then exit
run streaming job2
if job2 is success them remove o/p of job1 else exit
run streaming job3
if job3 is succcess them remove o/p of job2 else exit

A: Why not using MapReduce frameworks for python streaming, like Dumbo https://github.com/klbostee/dumbo/wiki/Short-tutorial, or MRJob http://packages.python.org/mrjob/
For example, with dumbo, your pipe would be:
job.add_iter(Mapper1, Reducer1)
job.add_iter(Mapper2, Reducer2)


text:
Q: How can I get rid of divider on android.support.v7.widget.Toolbar? How can I get rid of divider on android.support.v7.widget.Toolbar?

I have LinearLayout below android.support.v7.widget.Toolbar. They both have  the same color. How can I get rid of devider between them?


text:
Q: APC fragmention woes on Apache AWS EC2 Small instance with WordPress and W3TC AWS EC2 Small instance, Apache 2 running WordPress and W3TC. Within an hour, my APC fragmentation hits 100%.
My APC settings are:
apc.enabled = 1
apc.shm_segments = 1
apc.shm_size = 100M
apc.optimization = 0
apc.num_files_hint = 512
apc.user_entries_hint = 1024
apc.ttl = 7200
apc.user_ttl = 7200
apc.gc_ttl = 3600
apc.cache_by_default = 1
apc.use_request_time = 1
apc.filters = "apc\.php$"
apc.mmap_file_mask = "/tmp/apc.XXXXXX"
apc.slam_defense = 0
apc.file_update_protection = 2
apc.enable_cli = 0
apc.max_file_size = 2M
apc.stat = 1
apc.write_lock = 1
apc.report_autofilter = 0
apc.include_once_override = 0
apc.rfc1867 = 0
apc.rfc1867_prefix = "upload_"
apc.rfc1867_name = "APC_UPLOAD_PROGRESS"
apc.rfc1867_freq = 0
apc.localcache = 0
apc.localcache.size = 256M
apc.coredump_unmap = 0
apc.stat_ctime = 0
apc.canonicalize = 1
apc.lazy_functions = 0
apc.lazy_classes = 0
/etc/php.d/apc.ini

More poop can be seen here.
Mostly cribed settings from here. The shm was meant to be whittled down from such a high value after some observation, but apparently such a large value isn't even high enough....
I found an similar question/answer here. I do have some virtual hosts setup, but they aren't being touched much at all. Having users logged into the admin panel of WP does make things worse, but that's certainly not the main culprit. The question asker seems to suggest that it turns out W3TC is probably causing the problem, which the plugin author seems to agree with, but there aren't any helpful details beyond that. Why is it causing the problem?
Do I just take it for now and turn off object caching with APC? Is there nothing I can do? Does having it turned on without being used for object caching actually help anything? Would memcache be an ok substitute just for object caching here? Finally, maybe I just shouldn't worry so much about the fragmentation?

A: Cached variables: 3562 ( 14.3 MBytes)
This is what's causing your fragmentation. GC is cleaning them up and chances are they're getting placed in a new 'slice' when they're regenerated.
You could try to up the GC TTL on user variables - but if the code for your APC usage is manually handling the TTL's that may be a part of the problem.
3500+ vars is quite a bit for what I'm seeing (only 500 files cached, 100MB SHM); APC may not be leveraged correctly.
Edit:
Hits   19195
Misses 13830
Insert Rate    1312.99 cache requests/second <-- This leads me to think something isn't configured correctly. Technically, this is telling me that your caching is largely ineffective as 33% of your cached variables are generated every second.


text:
Q: Why is my SQL MsAccess query so slow? Basically I have an SQL query which is an union of 10 queries like the one below. Why is this query so slow? It is taking me more than a minute to run, and it crashes my form when i use a textbox with DCount on this query.
SELECT
ESP_Fisico.ESP_SubTipo_ID,
ESP_Fisico.ESP_Unidade_ID,
ESP_Facturacao.Item_TAG,
MIN(ESP_Facturacao.[1a_MesAno]) AS Data,
MIN(ESP_Facturacao.[1a_Faturado]) AS Valor,
'1 a' AS Tarefa,
'1' AS Control,
min(ESP_Administrativas.Novo_Pos_2010),
min(ESP_SubTipo.Descrição) AS SubTipo,
min(ESP_Unidade.Descricao) AS Unidade,
min(ESP_Facturacao.ID)
FROM ESP_Unidade INNER JOIN (((ESP_TAG LEFT JOIN ESP_Facturacao ON ESP_TAG.ID = ESP_Facturacao.ESP_Tag_ID) INNER JOIN (ESP_SubTipo INNER JOIN ESP_Fisico ON ESP_SubTipo.ID = ESP_Fisico.ESP_SubTipo_ID) ON ESP_TAG.ID = ESP_Fisico.ESP_Tag_ID) INNER JOIN ESP_Administrativas ON ESP_TAG.ID = ESP_Administrativas.ESP_Tag_ID) ON ESP_Unidade.ID = ESP_Fisico.ESP_Unidade_ID
WHERE (((ESP_Facturacao.Item_TAG) Not In
(SELECT ESP_Facturacao.Item_TAG
FROM ESP_Facturacao
WHERE (((ESP_Facturacao.[1a_MesAno]) Is Not Null))))
AND ((ESP_Administrativas.Data_Aut_Funcion) Is Null))
Group By ESP_Facturacao.Item_TAG, ESP_Fisico.ESP_SubTipo_ID, ESP_Fisico.ESP_Unidade_ID, ESP_Facturacao.Item_TAG

A: You are already selecting data from ESP_Facturacao, querying the same table again for the Where clause is implemented in Access (as in most other RDBMS's) in an inefficient way. You should therefor create an alias on the table name in the Inner query: SELECT AA.Item_TAG FROM ESP_Facturacao As AA WHERE (((AA.[1a_MesAno]) Is Not Null)):
SELECT
ESP_Fisico.ESP_SubTipo_ID,
ESP_Fisico.ESP_Unidade_ID,
ESP_Facturacao.Item_TAG,
MIN(ESP_Facturacao.[1a_MesAno]) AS Data,
MIN(ESP_Facturacao.[1a_Faturado]) AS Valor,
'1 a' AS Tarefa,
'1' AS Control,
min(ESP_Administrativas.Novo_Pos_2010),
min(ESP_SubTipo.Descrição) AS SubTipo,
min(ESP_Unidade.Descricao) AS Unidade,
min(ESP_Facturacao.ID)
FROM ESP_Unidade INNER JOIN (((ESP_TAG LEFT JOIN ESP_Facturacao ON ESP_TAG.ID = ESP_Facturacao.ESP_Tag_ID) INNER JOIN (ESP_SubTipo INNER JOIN ESP_Fisico ON ESP_SubTipo.ID = ESP_Fisico.ESP_SubTipo_ID) ON ESP_TAG.ID = ESP_Fisico.ESP_Tag_ID) INNER JOIN ESP_Administrativas ON ESP_TAG.ID = ESP_Administrativas.ESP_Tag_ID) ON ESP_Unidade.ID = ESP_Fisico.ESP_Unidade_ID
WHERE (((ESP_Facturacao.Item_TAG) Not In
(SELECT AA.Item_TAG FROM ESP_Facturacao As AA
WHERE (((AA.[1a_MesAno]) Is Not Null))))
AND ((ESP_Administrativas.Data_Aut_Funcion) Is Null))
Group By ESP_Facturacao.Item_TAG, ESP_Fisico.ESP_SubTipo_ID, ESP_Fisico.ESP_Unidade_ID, ESP_Facturacao.Item_TAG


text:
Q: "Never say die?" What's the deal with this idiom? I know what it means, but cannot wrap my head around its grammar structure. The sentence structure of

"Never say die"

looks like that of

"Never admit defeat"

but it does not make the same grammatical+semantical sense.
Is it an archaic use? Is it a contraction of a longer phrase? Was it originally misspoken by someone of note and survived memetically? What are its roots?
Edit: Well, the comments made me realize that I worded my question poorly. I'm not saying I think this phrase is ungrammatical. I'm asking how the heck "saying 'die'" came to mean what it means.

A: The expression "never say die" has been around since at least the early 1800s, but I think OP is attempting to over-analyse the grammar.
It just means don't use the word "die" (as in "We're all going to die!") because that would imply you've given up hope, which might become a self-fulfilling prophecy. It's much the same as "Where there's life there's hope"

As @Edwin comments, there's also Never say never. Add to that a couple of thousand written instances of Never say can't (and a couple of dozen Never say hopeless, for example) and I think one could reasonably say this is a "productive" construction even today.

A: According to Concise Oxford English Dictionary, one says "never say die … to encourage someone not to give up hope".
It functions literally as a reply to a statement such as "we are all going to die", expressing hopelessness in the face of a deadly situation.
It is also used idiomatically as a reply to similar statements of hopelessness not containing the word die, or when the speaker anticipates such a statement and wants to forestall it, or when the speaker is struggling with feelings of hopelessness and wants to banish them.
The earliest published example I found is from "The-Man-of-War's-Man, Chapter XVI" (evidently part of a novel serialization) printed in Blackwood's Magazine, Volume 18 (1825):

Cheer up then, and never say die, for the devil a morsel of good it will do.

To uncover more examples, you can use the Google Ngram Viewer: search for [ never say die,Never say die ]; click through the various date ranges beneath the chart to view the source texts using Google Book Search.

A: I agree that it is a strange construction. So I thought maybe searching for why you might use the phrase "say die" (instead of "never say die") might shed some light on the origin of the phrase. The earliest publication I could find, in which the phrase "say die" was included, is a play called, "The Faithful Shepherd." The play was published in 1590, written in Italian by Giovanni Battista Guarini. The English translation wasn't published until 1647. In a 1736 edition of a book entitled The faithful shepherd:
A pastoral tragi-comedy, written in Italian by the celebrated Signor Baptista Guarini, there are these lines (pages 102 and 103):

"Let those fair amiable Eyes release
My Life, now bitter, which once made it sweet;
And those bright Stars, which my Love's Torches li't,
Light too my Funeral Tapers, and fore-run,
As once my rising, now my setting Sun.
But thou more hard than 'ere thou wert before,
Feel'st yet no Spark of Pity, but art more
Deaf to my Pray'rs. Must I then talk alone?
Wretch that I am, discourse I to a Stone!
Say die, at least, if nothing else thou' It say,
And thou shalt see me die..."

Within the next century, for whatever reason, the phrase "Never say die." becomes quite common. (I'm not saying it's a result of the play, by any means, in case anyone mistakenly thinks I'm implying that.) MetaEd mentions one citation in his answer, but there are many citations from the 1800s in which the phrase is used, including a flowery poem attributed to J.F. Waller, reprinted in Oddfellows' magazine, Vol. 13, 1881, page 91:

Never say die—never say die;
Life's worth the living, if we only try;
The hand and the brain
Were not given in vain.
We've a battle to gain,
And so—never say die.
Never say die—never say die;
If earnings be low and if living be high,
'Tis reason the more
Not to faint or give o'er,
Better days are in store,
And so—never say die.
Never say die—never say die—
When night is at darkest the morning is nigh;
Whether far off or near,
In God's time will appear
Some blessing to cheer,
And so never say die.
Never say die—never say die;
The soul that is steadfast may fortune defy;
In labour and art
Let the hand and the heart
Each do its own part,
And so—never say die.
Never say die—never say die;
When cowards despair, be this our reply—
All that's noble and human
In constant and true man,
In brave patient woman,
Cries—never say die.
Never say die—never say die;
Life is God's gift that we may not lay by;
Whatever befall,
'Tis the duty of all'
Till he gives the call
To say—never say die.


text:
Q: Flutter: Tap delay with GestureDetector in a Tile of a GridView Normally, the below behavior is quick in nature. However, inside a GridView (or any ScrollView I assume (tried ListView, too)) the performance seems to be very poor. When I tap on the screen the opacity of the Container increases, but after a delay. Any idea what I am missing?
import "package:flutter/material.dart";
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
  @override
    Widget build(BuildContext context) {
      return MaterialApp(
        home: Scaffold(
          body: MyWidget()
        )
      );
    }
}
class MyWidgetState extends State<MyWidget> {
  double opacity = 0.2;
  @override
    Widget build(BuildContext context) {
      return GridView.builder(
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 3
        ),
        itemBuilder: (context, index) {
          return GestureDetector(
            onTap: () {
              setState(() {
                opacity = 0.2;
              });
            },
            onTapDown: (details) {
              setState(() {
                opacity = 1.0;
              });
            },
            child: Container(
              color: Colors.red.withAlpha((255 * opacity).toInt())
            )
          );
        },
      );
    }
}
class MyWidget extends StatefulWidget {
  @override
    State<StatefulWidget> createState() {
      return MyWidgetState();
    }
}

A: Maybe Listener would be faster in your case
Listener(
      onPointerDown: (PointerDownEvent event) {
        setState(() {
          opacity = 1.0;
        });
      },
      onPointerUp: (PointerUpEvent event) {
        setState(() {
          opacity = 0.2;
        });
      },
      child: Container(
          color: Colors.red.withAlpha((255 * opacity).toInt())
      ),
    )


text:
Q: Export 100000 rows to CSV in Javascript I have 100 000 lines and i want to export them to CSV, i did manage to export it for few lines but many thousands of lines return network error to my browser and i cannot download it.
        let csvContent = "data:text/csv;charset=utf-8,";
        csvContent += [
            Object.keys(payload[0]).join(";"),
            ...payload.map(item => Object.values(item).join(";"))
        ]
            .join("\n")
            .replace(/(^\[)|(\]$)/gm, "");

        const data = encodeURI(csvContent);
        const link = document.createElement("a");
        link.setAttribute("href", data);
        link.setAttribute("download", "export.csv");
        link.click();

A: You can not encodeURI with 100000 rows
Use FileSaver.js
var blob = new Blob([csvContent], {type: "text/plain;charset=utf-8"});
saveAs(blob, "export.csv");

Maybe also split the string with Blob.slice() and save several chunks.


text:
Q: How to Find Dominant colors in an image in c++ and percentage of each cluster? I am able to  get the dominant color from image, but I am not able to get the percentage of color.
This is my code to get the dominant color from a image:
cv::Matsource_img=cv::imread("detect.bmp",1); // Read image from path

// Serialize, float
cv::Mat data = source_img.reshape(1, source_img.total());
data.convertTo(data, CV_32F);
// Perform k-Means
int k = 10;
std::vector<int> labels;
cv::Mat3f centers;
cv::kmeans(data, k, labels, cv::TermCriteria(), 1, cv::KMEANS_PP_CENTERS,   centers);

// Make a poster! (Clustering)
for (int i = 0; i < (int)labels.size(); ++i) {
    data.at<float>(i, 0) = centers.at<float>(labels[i], 0);
    data.at<float>(i, 1) = centers.at<float>(labels[i], 1);
    data.at<float>(i, 2) = centers.at<float>(labels[i], 2);
   // qDebug()<<labels.size();
}
// Un-Serialize, un-float
cv::Mat destination = data.reshape(3, source_img.rows);
destination.convertTo(source_img, CV_8UC3);
std::sort(centers.begin(), centers.end(),
        [](const cv::Vec3f &a, const cv::Vec3f &b) -> bool
        { return a[0] + a[1] + a[2] > b[0] + b[1] + b[2]; }
    );
// Paint!
QLabel *palette[6] = {ui->b_1, ui->b_2, ui->b_3, ui->b_4, ui->b_5, ui->b_6};
const int p = 0; // Offset
for(int i = 0; i < 6; ++i) {
    // Set back color of label. Lazy ass way to show the colors
    std::stringstream back_clr;
    back_clr << centers.at<float>(i + p, 2) << "," << centers.at<float>(i + p, 1) << "," << centers.at<float>(i + p, 0);
    palette[i]->setStyleSheet(QString::fromStdString("background-color:rgb(" + back_clr.str() + ");"));
    qInfo()<< QString::fromStdString(back_clr.str() );
}

This is my output:
Screenshot from 2021-04-09 16-51-30.png

"238.594,229.237,205.951"
"213.832,204.984,180.845"
"216.373,190.585,84.8002"
"218.931,132.845,105.804"
"138.95,143.804,118.714"
"198.743,110.853,46.7355"

But I want the output like this:
[238.59435545 229.23386034 205.94674433] 29.34%
[213.67154468 204.84374578 180.77144429] 21.07%
[198.76836914 110.87256368 46.76773957] 7.76%
[39.94140346 42.37245936 36.42510903] 7.68%
[216.17736047 190.52489076 84.93423309] 7.36%
[ 83.247557 108.82634188 70.66370203] 7.15%
[82.05183941 60.05586475 55.07991179] 5.87%
[218.7735931 132.99684942 105.99257623] 5.62%
[ 41.73549837 87.24996989 139.9000843 ] 5.07%
[132.72742222 139.51450372 113.63158587] 3.09%

A: You want to count how often each individual label occurs in labels, i.e. label 0 occurs 29.34% in labels. That's just a std::count divided by labels.size()


text:
Q: How would I use a SQL query for the following result I have a database with the following entities:

I also have an employee entity not shown here that has an id and name field that I would like to include in my query.
I need to create a query that if given a survey ID would return a list of results that look like this:
Survey.name  |  Survey.submitter_id  |  Survey.subject_id | question.text | survey_questions.answer_value |survey_questions.anonymous

A: I can't test the query but i think you will get the idea:
SELECT s.name, sq.submitter_id, s.subject_id, q.text, sq.answer_value, sq.anonymous FROM surveys AS s
JOIN survey_questions AS sq ON sq.survey_id = s.id
JOIN questions AS q ON sq.question_id = q.id
WHERE s.id = <your_value>


text:
Q: Runtime error on realloc() | inorder traversal I am trying to implement an inorder traversal that returns an array with the traversed values. In my recursive approach, I am trying to use realloc() function to modify the size of the array and store the result. However, I am getting the following error:
realloc(): invalid next size.
Following is my code:
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
};

void inorder(struct TreeNode *root, int *res, int *returnSize)
{
    if(root == NULL)
        return;

    //if left node present, traverse left
    inorder(root->left,res,returnSize);

    // add node to array
    res[(*returnSize)]=root->val;
    (*returnSize)++;
    int *temp = realloc(res,sizeof(int)*(*returnSize));
    res = temp;

    //if right node present, traverse right
    inorder(root->right,res,returnSize);
}

/**
 * Return an array of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* inorderTraversal(struct TreeNode* root, int* returnSize)
{
    //check if root == null
    if(root == NULL)
    {
        return root;
    }

    //malloc result array to return
    int *res = (int *)malloc(sizeof(int)*(*returnSize));

    //start inorder parsing
    inorder(root, res, returnSize);

    return res;
}

A: There are multiple problems:

*

*the reallocated value for res is not passed back to the caller. You should pass a pointer to res instead of its value or return the newly allocated pointer.

*returnSize is an output variable, you should initialize it to 1, or better to 0 and reallocate the array before storing the node value.

*you should handle potential memory allocation failures.

Here is a corrected version:
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
};

int *inorder(struct TreeNode *root, int *res, int *returnSize) {
    if (root != NULL) {
        //traverse the left tree
        res = inorder(root->left, res, returnSize);

        if (returnSize >= 0) {
            // add node to array
            int *temp = realloc(res, sizeof(int) * (*returnSize) + 1);
            if (temp == NULL) {
                free(res);
                *returnSize = -1;
                res = NULL;
            } else {
                res = temp;
                res[(*returnSize)++] = root->val;

                //traverse the right tree
                res = inorder(root->right, res, returnSize);
            }
        }
    }
    return res;
}

/**
 * Return an array of size *returnSize.
 * Return NULL and *returnSize=0 for an empty tree.
 * Return NULL and *returnSize<0 for memory allocation failure.
 * Note: The returned array is malloced, the caller must call free().
 */
int *inorderTraversal(struct TreeNode *root, int *returnSize) {
    int *res = NULL;

    *returnSize = 0;
    return inorder(root, res, returnSize);
}

A: You almost certainly have memory corruption elsewhere in your code--this code looks good to me (well, apart from not testing the return from realloc() for NULL, but that would just cause you to lose data, not get the error you are seeing).  If you can run valgrind on your program it will probably point you to the problem.


text:
Q: Best practice on implementing a load more in meteor I would like to have a list with 10 items, at the bottom of the list there should be a load more button. When clicked it adds another ten items to the list.
I already came up with a session that keeps track of the limit property.. But the problem is that meteor then reloads the full list instead of just adding another 10..
I would be very thankful for an elegant solution.

A: This smart package provides an easy way to do pagination:
https://github.com/tmeasday/meteor-paginated-subscription

A: For future reference, the most complete solution for paging in Meteor looks to be meteor-pages:
https://github.com/alethes/meteor-pages
It provides UI components and iron router integration as well. If you are only looking for infinite scroll without page navigation the simpler meteor-paginated-subscription might suit you well enough though:
https://github.com/tmeasday/meteor-paginated-subscription

A: Have you looked at preserve? That should do it.
http://docs.meteor.com/#template_preserve


text:
Q: python pandas sorting by group Each row in my DataFrame is a user vote entry for a restaurant. The data look like
id   cuisine
91   american
3    american
91   american
233  cuban
233  cuban
2    cuban

where id refers to the restaurant.
I want to get something like the following
american  91   100
          3    30
          12   10
cuban     233  80
          2    33
mexican   22   99
          8    98
          21   82

where the 2nd column is the id, and the 3rd column is the number of rows in the DataFrame for that id.  In other words, sort by the number of rows, but group by cuisine. I tried
g = df.groupby(['cuisine', 'id'])
c = g.size().sort_values(ascending=False)

But the order of the cuisines is mixed.

A: is that what you want?
In [2]: df
Out[2]:
    id   cuisine
0   91  american
1    3  american
2   91  american
3  233     cuban
4  233     cuban
5    2     cuban

In [3]: df.groupby(['cuisine', 'id']).size()
Out[3]:
cuisine   id
american  3      1
          91     2
cuban     2      1
          233    2
dtype: int64

or as a data frame:
In [10]: df.groupby(['cuisine', 'id']).size().reset_index(name='count').sort_values(['cuisine', 'count'], ascending=[1,0])
Out[10]:
    cuisine   id  count
1  american   91      2
0  american    3      1
3     cuban  233      2
2     cuban    2      1

A: use value_counts after group_by followed by sort_index
# ascending=[1, 0] says True for level[0], False for level[1]
df.groupby('cuisine').id.value_counts().sort_index(ascending=[1, 0])

cuisine   id
american  91     2
          3      1
cuban     233    2
          2      1
Name: id, dtype: int64


text:
Q: Ensure that an argument can be iterated twice Suppose I have the following function:
def print_twice(x):
    for i in x: print(i)
    for i in x: print(i)

When I run:
print_twice([1,2,3])

or:
print_twice((1,2,3))

I get the expected result: the numbers 1,2,3 are printed twice.
But when I run:
print_twice(zip([1,2,3],[4,5,6]))

the pairs (1,4),(2,5),(3,6) are printed only once. Probably, this is because the zip returns a generator that terminates after one pass.
How can I modify the function print_twice such that it will correctly handle all inputs?
I could insert a line at the beginning of the function: x = list(x). But this might be inefficient in case x is already a list, a tuple, a range, or any other iterator that can be iterated more than once. Is there a more efficient solution?

A: A simple test to see if x will be consumed when you iterate over it is iter(x) is x. This is reliable, since it's specified as part of the iterator protocol (docs):

Iterators are required to have an __iter__() method that returns the iterator object itself

Conversely, if iter(x) returns x itself then x must be an iterator, since it was returned by the iter function.
Some checks:
def is_iterator(x):
    return iter(x) is x

for obj in [
    # not iterators
    [1, 2, 3],
    (1, 2, 3),
    {1: 2, 3: 4},
    range(3),
    # iterators
    (x for x in range(3)),
    iter([1, 2, 3]),
    zip([1, 2], [3, 4]),
    filter(lambda x: x % 2 == 0, [1, 2, 3]),
    map(lambda x: 2 * x, [1, 2, 3]),
]:
    name = type(obj).__name__
    if is_iterator(obj):
        print(name, 'is an iterator')
    else:
        print(name, 'is not an iterator')

Results:
list is not an iterator
tuple is not an iterator
dict is not an iterator
range is not an iterator
generator is an iterator
list_iterator is an iterator
zip is an iterator
filter is an iterator
map is an iterator

So, to ensure that x can be iterated multiple times, without making an unnecessary copy if it already can be, you can write something like:
if iter(x) is x:
    x = list(x)

A:
I could insert a line at the beginning of the function: x = list(x). But this might be inefficient in case x is already a list, a tuple, a range, or any other iterator that can be iterated more than once. Is there a more efficient solution?

Copying single-use iterables to a list is perfectly adequate, and reasonably efficient even for multi-use iterables.
The list (and to some extend tuple) type is one of the most optimised data structures in Python. Common operations such as copying a list or tuple to a list are internally optimised;1 even for iterables that are not special-cased, copying them to a list is significantly faster than any realistic work done by two (or more) loops.
def print_twice(x):
    x = list(x)
    for i in x: print(i)
    for i in x: print(i)

Copying indiscriminately can also be advantageous in the context of concurrency, when the iterable may be modified while the function is running. Common cases are threading and weakref collections.

In case one wants to avoid needless copies, checking whether the iterable is a Collection is a reasonable guard.
from collections.abc import Collection

x = list(x) if not isinstance(x, Collection) else x

Alternatively, one can check whether the iterable is in fact an iterator, since this implies statefulness and thus single-use.
from collections.abc import Iterator

x = list(x) if isinstance(x, Iterator) else x
x = list(x) if iter(x) is x else x

Notably, the builtins zip, filter, map, ... and generators all are iterators.

1Copying a list of 128 items is roughly as fast as checking whether it is a Collection.

A: zip will return an iterator. Once unpacked, it cannot be unpacked again, it gets exhausted.
Maybe if you want to make sure that only zip objects get converted to list as you said it would work but it would not be efficient, you can check for it type:
if isinstance(x, zip):
  x = list(x)

A: Modify your print_twice function
def print_twice(x):
    val = x
    for i in range(2):
        for i in val: print(i)


text:
Q: How create a react-native custom view with typescript I want to create a custom view with react-native-modal in my custom view:
type Props = {isVisible: boolean;setVisible: void }
<Modal isVisible={props.visible}......>
<Button title="colse" onPress={()=> props.setVisible}>

Then in my page:
const [isVisible,setVisible]= React.useState(false)
const onClick= () =>{setVisible(!isVisible)}
<MyView visible={isVisible} setVisible={onClick}/>

But when I click the button, nothing happens and there is no error.
If I change the code like this:
const [isVisible,setVisible]= React.useState(true)

the dialog will be shown at first, but cannot close.
I hope someone can give me an example of how to do that.

A: Try this way
<Button title="colse" onPress={()=> props.setVisible()}>

const [isVisible,setVisible] = React.useState(false)
const onClick= () => {setVisible(!isVisible)}
<MyView visible={isVisible} setVisible={onClick}/>

A: Have a try by updating the state based on the previous state.
like:
const onClick = () => {setVisible(prevState => !prevState)}


text:
Q: mysql Length() for different languages returns different size select

length('abcdefg') english,
length('가나다라마바사') korean

from dual

This returns below.
english korean
7       21

Is there any function returning the count of character not character bytes?
I mean what I need is
english korean
7       7

A: use :

CHAR_LENGTH()

(the number of characters)
reference :
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_char-length

A: See the manual:

Returns the length of the string str, measured in bytes. A multi-byte character counts as multiple bytes. This means that for a string containing five 2-byte characters, LENGTH() returns 10, whereas CHAR_LENGTH() returns 5.

CHAR_LENGTH() will do what you want.


text:
Q: How to update typings.json and typing files? My typings.json is like this:
{
  "globalDependencies": {
    "aws-sdk": "registry:dt/aws-sdk#0.0.0+20160606153210"
  },
  "dependencies": {
    "lodash": "registry:npm/lodash#4.0.0+20160416211519"
  }
}

Right now when I want to update, I need run all typings install XXX --save again.
Any other way to update typings.json and typing files?
Is there something like typings update?

A: TypeScript 2.x solves the issue. TypeScript 2.x installs typings through npm, for example:
npm install --save-dev @types/node

So now the typings files are all in package.json with version like below, instead of typings.json.
"@types/node": "4.0.30"

Now you can update your typings like other npm packages.

A: There is no typings update, but typings install XXX --save should do the job


text:
Q: Apostrophes are being saved as ' using Gravity Forms on Wordpress I am using Gravity Forms (Wordpress) and when saving words with apostrophes, it saves it like that: '
Example:
today's needs
How to to fix this?

A: In Gravity Forms plugin fields files
(wp-content/plugins/gravityforms/includes/fields) find $value and wrap it with  html_entity_decode()
$value = html_entity_decode($value);


text:
Q: Google Place Api Prediction class cast to Position or something equivalent I'm working on a Xamarin Forms project. I have a very simple page where a job seeker searches job posts by entering a location(ex. New York) and a radius(picker). I have the following code in my PageViewModel:
public class SearchPageViewModel : BaseViewModel

    {

        private readonly INavigation _navigation;

        private readonly GooglePlacesApiService _api;

        private IEnumerable<JobPost> Posts;
        public int RadiusIndex {get;set;}

        public SearchPageViewModel (INavigation navigation, IEnumerable<JobPost> posts)

        {

            _navigation = navigation;
            var settings = GoogleApiSettings.Builder.WithApiKey("MY_API_KEY").Build();
            _api = new GooglePlacesApiService(settings);
            this.posts =posts;

        }

        public ICommand DoSearchCommand

        => new Command(async () => await DoSearchAsync().ConfigureAwait(false), () => CanSearch);

        public ICommand SelectItemCommand

        => new Command<Prediction>(async (prediction) =>

        {

             //!!!Filter jobposts based on position and radius to be able to display it!!!

            _api.ResetSessionToken();

        });

        private string _searchText;

        public string SearchText
        {

            get => _searchText;

            set
            {
                if (SetProperty(ref _searchText, value))

                    OnPropertyChanged("CanSearch");
            }

        }

        private List<Prediction> _results;

        public List<Prediction> Results

        {

            get => _results;

            set => SetProperty(ref _results, value);

        }

        public bool CanSearch => !string.IsNullOrWhiteSpace(SearchText) && SearchText.Length > 2;

        private async Task DoSearchAsync()

        {

            var results = await _api.GetPredictionsAsync(SearchText)

                                    .ConfigureAwait(false);

            if(results != null && results.Status.Equals("OK"))

            {

                ResultCount = results.Items.Count;

                Results = results.Items;

                OnPropertyChanged("HasResults");

            }

        }

    }

public class JobPost
{
    public Position Location {get;set;}
}

Ok, so far it works well. Once the search button is clicked the job seeker get a list of predictions and picks a place. But the problem is now, how do I get the positioning(longitude and latitude) of the picked prediction, so I can filter the job posts so I can dsiplay the result to the job seeker.
Thanks in advance.

A: use the Essentials GeoCoding plugin
var address =  "New York";
var locations = await Geocoding.GetLocationsAsync(address);

locations will be a list of potential matches, each with a lat/long
var location = locations?.FirstOrDefault();
if (location != null)
{
    Console.WriteLine($"Latitude: {location.Latitude}, Longitude: {location.Longitude}, Altitude: {location.Altitude}");
}


text:
Q: NSUserDefaults crashes with setInteger I used this part of code in my Application for a while and it worked as expected. But now, it crashes on the line with setInteger:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
int selEvent = [defaults integerForKey:@"selected_event"];
/*
 * Do Something with selEvent
 * New ID is in NSNumber event_id
 */
[defaults setInteger:[event_id intValue] forKey:@"selected_event"]; //Crashes on this line
[defaults synchronize];

Working in Xcode 4.5.1 and iPad 6.0 Simulator.
I'm getting a EXC_BAD_ACCESS.
Whats the cause of my problem?

A: I had the same problem. I traced it back to something else:
I stored integers in NSUserDefaults just fine with code like:
[[NSUserDefaults standardUserDefaults] setInteger:_currentBannerIndex forKey:@"currentBannerIndex"];

After a certain period it crashed at the same point, writing the same value.
The cause was that after this period I registered for changes in the NSUserdefaults with code like:
[[NSNotificationCenter defaultCenter] addObserver:self selector: @selector(userDefaultsChanged) name:NSUserDefaultsDidChangeNotification object:nil];

This was done in an importer at initialization. After the importer was deallocaed, a new write to the user defaults was triggering the observer for an object that was gone. Boom. Crash.
The solution was of course to remove the observer in the dealloc of my importer.

A: For me, I would say problem is at [event_id intValue]
event_id is NSString & its getting released and hence this error is occurring.

A: Found my Problem:
NSDictionary *defaultUserDefaults = [NSDictionary dictionaryWithObjectsAndKeys:
                                     [NSNumber numberWithInt:0], @"selected_event",
                                     nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:defaultUserDefaults];

This worked before with setInteger:
Changed all setIntegers with setObject .

A:    [[NSUserDefaults standardUserDefaults] setInteger:1 forKey:@"KeyName"];


text:
Q: XML to XSL what do I do wrong I'm trying to publish some data from an XML report from our firewalls on a webpage. Since the data in the XML will be updated from time till time I can't just publish the data static.
Now I have spent some time to look into the XML and on the web but I can't figure out what I'm doing wrong.
a part of the XML code:
 <?xml version="1.0"?>
 <?xml-stylesheet href="test.xsl"
    type="text/css"?>
 <report reportname="top-application-categories">
   <result name="Top application categories" logtype="appstat" start="2017/02/08 00:00:00" start-epoch="1486508400" delta="86400" slabbed-     start="2017/02/08 00:00:00" end="2017/02/08 23:59:59" end-epoch="1486594799" slabbed-end="2017/02/08 23:59:59" generated-at="2017/02/09 00:00:16" generated-at-epoch="1486594816" range="Wednesday, February 08, 2017">
<entry>
  <category-of-name>general-internet</category-of-name>
  <nsess>14765605</nsess>
  <nbytes>81973979657</nbytes>
</entry>
<entry>
  <category-of-name>business-systems</category-of-name>
  <nsess>8449911</nsess>
  <nbytes>2747818255111</nbytes>
</entry>
<entry>
  <category-of-name>networking</category-of-name>
  <nsess>7673706</nsess>
  <nbytes>172508825988</nbytes>
</entry>

Now I tried to create an XSL which makes sure only the Category-of-name, Nsess and Nbytes are shown on the page.
<?xml version="1.0"?>
<xsl:stylesheet
version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:msxsl="urn:schemas-microsoft-com:xslt"
>
<xsl:strip-space elements="*"/>
<xsl:output method="xml"
   omit-xml-declaration="yes"
   indent="yes"
   standalone="yes" />

<xsl:template match="/">
  <xsl:for-each select="report">
     <xsl:element name="report">
     <xsl:for-each select="result">
     <xsl:element name="result">
        <xsl:for-each select="entry">
           <xsl:element name="entry">
              <xsl:attribute name="category-of-name">
                 <xsl:value-of select="category-of-name"/>
              </xsl:attribute>
              <xsl:attribute name="nsess">
                 <xsl:value-of select="nsess"/>
              </xsl:attribute>
              <xsl:attribute name="nbytes">
                 <xsl:value-of select="nbytes"/>
              </xsl:attribute>
           </xsl:element>
           </xsl:for-each>
        </xsl:for-each>
     </xsl:element>
  </xsl:for-each>

I found this example on the WWW at MSDN. It explained how to use XML and display the data on an webpage created in Visual Web developer.
Still tried that been there same result, or an error or it just displays nothing at all.
Hopefully someone can steer me in the right direction :)

A: Look at line 5. In your result name="Top application categories" tag there's an an unsetted slabbed- attribute.
It leads you to an not well formed XML error. You can use http://codebeautify.org/xmlvalidator in order to check if it's well formed and valid online.
I hope that It helps you ;)


text:
Q: Google App Engine Python Datastore Basically what Im trying to make is a data structure where it has the users name, id, and datejoined. Then i want a "sub-structure" where it has the users "text" and the date it was modified. and the user will have multiple instances of this text.
class User(db.Model):
    ID = db.IntegerProperty()
    name = db.StringProperty()
    datejoined = db.DateTimeProperty(auto_now_add=True)

class Content(db.Model):
    text = db.StringProperty()
    datemod= db.DateTimeProperty(auto_now_add = True)

Is the code set up correctly?

A: One problem you will have is that making User.ID unique will be non-trivial.  The problem is that two writes to the database could occur on different shards, both check at about the same time for existing entries that match the uniqueness constraint and find none, then both create identical entries (with regard to the unique property) and then you have an invalid database state.  To solve this, appengine provides a means of ensuring that certain datastore entities are always placed on the same physical machine.
To do this, you make use of the entity keys to tell google how to organize the entities.  Lets assume you want the username to be unique.  Change User to look like this:
class User(db.Model):
    datejoined = db.DateTimeProperty(auto_now_add=True)

Yes, that's really it.  There's no username since that's going to be used in the key, so it doesn't need to appear separately.  If you like, you can do this...
class User(db.Model):
    datejoined = db.DateTimeProperty(auto_now_add=True)

    @property
    def name(self):
        return self.key().name()

To create an instance of a User, you now need to do something a little different, you need to specify a key_name in the init method.
someuser = User(key_name='john_doe')
...
someuser.save()

Well, really you want to make sure that users don't overwrite each other, so you need to wrap the user creation in a transaction.  First define a function that does the neccesary check:
def create_user(username):
    checkeduser = User.get_by_key_name(username)
    if checkeduser is not None:
        raise db.Rollback, 'User already exists!'
    newuser = User(key_name=username)
    # more code
    newuser.put()

Then, invoke it in this way
db.run_in_transaction(create_user, 'john_doe')

To find a user, you just do this:
someuser = User.get_by_key_name('john_doe')

Next, you need some way to associate the content to its user, and visa versa.  One solution is to put the content into the same entity group as the user by declaring the user as a parent of the content.  To do this, you don't need to change the content at all, but you create it a little differently (much like you did with User):
somecontent = Content(parent=User.get_by_key_name('john_doe'))

So, given a content item, you can look up the user by examining its key:
someuser = User.get(somecontent.key().parent())

Going in reverse, looking up all of the content for a particular user is only a little trickier.
allcontent = Content.gql('where ancestor is :user', user=someuser).fetch(10)

A: Yes, and if you need more documentation, you can check here for database types and here for more info about your model classes.

A: An alternative solution you may see is using referenceproperty.
    class User(db.Model):
        name = db.StringProperty()
        datejoined = db.DateTimeProperty(auto_now_add=True)

    class Content(db.Model):
        user = db.ReferenceProperty(User,collection_name='matched_content')
        text = db.StringProperty()
        datemod= db.DateTimeProperty(auto_now_add = True)

    content = db.get(content_key)
    user_name = content.user.name

    #looking up all of the content for a particular user
    user_content = content.user.matched_content

    #create new content for a user
    new_content = Content(reference=content.user)


text:
Q: What is the correct way to detect new Microsoft Edge v80 (Blink) via Javascript? As latest version of Microsoft Edge is out and uses Blink - what is the correct way to differentiate Old Edge from New Edge one with javascript?

Currently I plan to look into navigator.userAgent to check for older versions of Edge (up to 18)
const isOldEdge = /edge\/([0-1][0-8]|[0-9]\D)/.test(navigator.userAgent.toLowerCase());

Is this correct way to detect it?

A: I suggest you use window.navigator userAgent to check whether the browser is Microsoft Chromium Edge or MS edge (EdgeHtml).
The Edge (EdgeHtml) browser userAgent:

mozilla/5.0 (windows nt 10.0; win64; x64) applewebkit/537.36 (khtml,
  like gecko) chrome/70.0.3538.102 safari/537.36 edge/18.18362

The Microsoft Chromium Edge userAgent:

mozilla/5.0 (windows nt 10.0; win64; x64) applewebkit/537.36 (khtml,
  like gecko) chrome/80.0.3987.87 safari/537.36 edg/80.0.361.50

Sample code:

<!doctype html>

<title>Test demo</title>

Output in MS edge (EdgeHtml) browser:

Output in MS edge Chromium browser:

Reference:
How to detect Microsoft Chromium Edge (chredge , edgium) in Javascript


text:
Q: blank screen when i execute simple Kivy code I am new to kivy and using some tutorials but i only get black screen while on the videos developers get their widget on the screen.
import kivy
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.uix.textinput import TextInput

class MyGrid(GridLayout):
    def __int__(self, **kwargs):
        super(MyGrid, self).__int__(**kwargs)
        self.cols = 2
        self.add_widget(Label(text="Name: "))
        self.name = TextInput(multiline=False)
        self.add_widget(self.name)

        self.add_widget(Label(text="last name : "))
        self.lastName = TextInput(multiline=False)
        self.add_widget(self.lastname)

        self.add_widget(Label(text="email: "))
        self.emailName = TextInput(multiline=False)
        self.add_widget(self.emailname)

class MyApp(App):
    def build(self):
        return MyGrid()

if __name__ == "__main__":
    MyApp().run()

A: You have some spelling errors in the code.
The first is about the __init__ function that you spelled __int__
You also use a different variable to assign a widget and a similar one (but different) for adding it (e.g. self.lastName = TextInput(multiline=False) and self.add_widget(self.lastname))
This code should work:
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.uix.textinput import TextInput

class MyGrid(GridLayout):
    def __init__(self, **kwargs):
        super(MyGrid, self).__init__(**kwargs)
        self.cols = 2
        self.add_widget(Label(text="Name: "))
        self.name = TextInput(multiline=False)
        self.add_widget(self.name)

        self.add_widget(Label(text="last name : "))
        self.lastName = TextInput(multiline=False)
        self.add_widget(self.lastName)

        self.add_widget(Label(text="email: "))
        self.emailName = TextInput(multiline=False)
        self.add_widget(self.emailName)

class MyApp(App):
    def build(self):
        return MyGrid()

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


text:
Q: error message on change password code using php I used a script for my user to change their password when logged in and when I tested it I showed this error message

Notice: Undefined index: username in
  /home/www/sitename/directory/changepw.php on line 8 Notice: Undefined
  index: pin in /home/www/sitename/directory/changepw.php on line 9
  Notice: Undefined index: newpassword in
  /home/www/sitename/directory/changepw.php on line 10 Notice: Undefined
  index: repeatnewpassword in /home/www/sitename/directory/changepw.php
  on line 11

This is what I have in line 8,9,10and 11
 $username = $_POST['username'];
 $pin = $_POST['pin'];
 $newpassword = $_POST['newpassword'];
 $repeatnewpassword = $_POST['repeatnewpassword'];

this is my HTML Code below

<form name="form1" method="post" action="changepw.php">

Change password

Username:

<? echo    "{$_SESSION['username']}"; ?>

    <input name="username" type="text" id="username" value="<? echo   "{$_SESSION['username']}"; ?>">

Password:
<input name="pin" type="password"  id="pin" class="invulbalkje">

New Password:
<input name="newpassword" type="password" id="newpassword" class="invulbalkje">

Repeat New Password:
<input name="repeatnewpassword" type="password" id="repeatnewpassword" class="invulbalkje">

    <input type="submit" name="Submit" value="Change" class="button">
  LOGOUT
</form>

This is my php code below
<?php
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
    session_start();
    include 'db.php';

    $username = $_POST['username'];
    $pin = $_POST['pin'];
    $newpassword = $_POST['newpassword'];
    $repeatnewpassword = $_POST['repeatnewpassword'];

    $encrypted_password=md5($pin);
    $encrypted_newpassword=md5($newpassword);
    $wtbusers = '`wtbusers`';//this should be defined (change this to your whatever table name)

    $result = mysql_query("SELECT pin FROM $wtbusers WHERE     username='$username' and pin = '$pin'");
    if(!$result)
    {
        echo""; }
        if(mysql_num_rows($result) != 0){
            if($newpassword == $repeatnewpassword){
            $sql=mysql_query("UPDATE $wtbusers SET pin='$pin' where  username='$username'");
            if($sql)
            {
                echo"";
            }
            else
            {

                echo"";
            }
        } else {

          echo"";
    }
} else {

    echo"";
}

?>

Thank You.

A: All the other problems aside and addressing your actual question; There is no checking to see if a POST is being made that I can tell, so adding an @ symbol to those, like $username = @$_POST['username']; in your context is the fastest fix to get rid of them but I would recommend checking for a post first. isset is pretty good for that.
Alternatively you can turn off error reporting for notices by doing this
error_reporting(E_ALL & ~E_NOTICE);

See error_reporting

A: That is not how you assign the value to a text field using sessions in PHP. It has syntactical error:
<input name="username" type="text" id="username" value="<? echo "{$_SESSION['username']}"; ?>">

I hope you have written session_start(); in the beginning of your code (in every file you're using sessions in) or all of this (related to sessions) will be of no use.
Try this instead:
<?php
 session_start();
 $_SESSION['username'] = "mk";
 ?>
  <input name="username" type="text" id="username" value="<?php echo $_SESSION['username'];?>">

Now, you must use isset in a way so it doesn't run the php if it doesn't come from the form.
<?php
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
    session_start();
    include 'db.php'; // you might want to make corresponding changes here

if(isset($_POST['Submit'])){
    $username = $_POST['username'];
    $pin = $_POST['pin'];
    $newpassword = $_POST['newpassword'];
    $repeatnewpassword = $_POST['repeatnewpassword'];

    $encrypted_password=md5($pin);
    $encrypted_newpassword=md5($newpassword);
  // the rest of your code

   }
?>

EDIT:
Moving forward from the comments, this is the simplified/minor bugs fixed code:
<?php
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
    session_start();
    include 'db.php';

$servername = "localhost";
$username = "your_user_name_here";
$password = "your_pass_here";
$dbname = "your_db_name_here";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

if(isset($_POST['Submit'])){
    $username = $_POST['username'];
    $pin = $_POST['pin'];
    $newpassword = $_POST['newpassword'];
    $repeatnewpassword = $_POST['repeatnewpassword'];

    $encrypted_password=md5($pin);
    $encrypted_newpassword=md5($newpassword);

   $wtbusers = '`your_table_name_here`';       //this should be defined (change this to your whatever table name)

    $result = mysqli_query($conn, "SELECT pin FROM $wtbusers WHERE username= '$username' and pin = '$pin'");
    if(!$result)

        echo"";

        if(mysqli_num_rows($result) > 0){
            if($newpassword == $repeatnewpassword){
            $sql=mysqli_query($conn, "UPDATE $wtbusers SET pin= '$pin' WHERE username='$username'");
            if($sql)
                echo"";
            else
                echo"";
        }
        else
          echo"";
}
else
    echo"";

?>


text:
Q: xsl not rendering results I have to make an xsl for an xml output exported from a database. The name tags in xml have a prefix bib followed by a colon (as in bib:), and it was defined in xml. But I still got an xsl compiler error saying bib: is not declared. So I added the declaration in xsl. this time the error went away, but the result comes out zero, and I checked the path that is correct. I also tried to exclude "bib:" prefix in xsl after declaration but got the same zero result. I am new to xsl so I don't know what is wrong here. These are my files. Thanks very much.
XML:
<?xml version="1.0" encoding="UTF-8"?>
<embasexmllist>
<cards items="1">
  <bib:card items="0" xmlns:bib="http://elsevier.co.uk/namespaces/2001/bibliotek">-
    <bib:cardfields>
      <bib:Fulltext>
        <bib:DOI>10.1371/journal.pone.0068303</bib:DOI>
      </bib:Fulltext>
      <bib:Title>Mesothelin Virus-Like Particle Immunization Controls Pancreatic Cancer Growth through CD8+ T Cell Induction and Reduction in the Frequency of CD4+foxp3+ICOS- Regulatory T Cells
      </bib:Title>
    </bib:cardfields>
  </bib:card>
</cards>
</embasexmllist>

XSL
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
     xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
     xmlns:bib="http://www.bib.com/xml">

  <xsl:output indent="yes" omit-xml-declaration="no"
       media-type="application/xml" encoding="UTF-8" />

  <xsl:template match="/">
    <searchresult>
      <xsl:apply-templates
        select="/embasexmllist/cards/bib:card/bib:cardfields" />
    </searchresult>
  </xsl:template>

  <xsl:template match="bib:cardfields">
    <document>
      <title><xsl:value-of select="bib:Title" /></title>
      <snippet>
        <xsl:value-of select="bib:Title" />
      </snippet>
      <url>
        <xsl:variable name="doi" select="bib:Fulltext/bib:DOI"/>
        <xsl:value-of
          select="concat('http://dx.doi.org/', $doi)" />
      </url>
    </document>
  </xsl:template>
</xsl:stylesheet>

A: The prefix defines a namespace for the XML elements.
For your stylesheet to work, the namespace declaration needs to match that in your input XML. Replace
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:bib="http://www.bib.com/xml">

with
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:bib="http://elsevier.co.uk/namespaces/2001/bibliotek">

This results in the following output XML:
<?xml version="1.0" encoding="utf-8"?>
<searchresult xmlns:bib="http://elsevier.co.uk/namespaces/2001/bibliotek">
  <document>
    <title>
          Mesothelin Virus-Like Particle Immunization Controls Pancreatic Cancer Growth through CD8+ T Cell Induction and Reduction in the Frequency of CD4+foxp3+ICOS- Regulatory T Cells
        </title>
    <snippet>
      Mesothelin Virus-Like Particle Immunization Controls Pancreatic Cancer Growth through CD8+ T Cell Induction and Reduction in the Frequency of CD4+foxp3+ICOS- Regulatory T Cells
        </snippet>
    <url>http://dx.doi.org/10.1371/journal.pone.0068303</url>
  </document>
</searchresult>


text:
Q: How can I determine what is referencing Microsoft.VC90.DebugCRT? I have a large web application project, including code in C#, C++, and C, with many references (project references, DLL references) and I am making a release build. Testing my program in a virtual machine I get the following error:
Could not load file or assembly <MyAssembly.DLL> or one of its dependencies.
The application has failed to start because its side-by-side configuration is incorrect.
Please see the application event log or use the command-line sxstrace.exe tool for more detail.

So I check the event log, and I find this:
Activation context generation failed for "C:\Windows\Microsoft.NET\Framework\...\MyAssembly.DLL".
Dependent Assembly Microsoft.VC90.DebugCRT,processorArchitecture="x86",
publicKeyToken="1fc8b3b9a1e18e3b",type="win32",version="9.0.21022.8"
could not be found. Please use sxstrace.exe for detailed diagnosis.

I also used sxstrace as suggested and simply ended up with a file that says:
ERROR: Cannot resolve reference Microsoft.VC90.DebugCRT,processorArchitecture="x86",
publicKeyToken="1fc8b3b9a1e18e3b",type="win32",version="9.0.21022.8"

I checked the configuration for my projects and they are all set to build in release. Why is MyAssembly referencing Microsoft.VC90.DebugCRT? And how can I fix it?
Note that I did install x86 and x64 MSVC++ redistributables on my virtual machine.
EDIT
I also ran dependency walker on MyAssembly.dll, and I got a bunch of entries that say "Error opening file. The system cannot find the file specified":
API-MS-WIN-... (4x)
EXT-MS-WIN-...
MSVCM90D.DLL
MSVCR90.DLL
MSVCR90D.DLL
IESHIMS.DLL
MFPLAT.DLL
SETTINGSYNPOLICY.DLL
WLANAPI.DLL

A: As mentioned in some comments, a solution is to use dependency walker.
Indeed MyAssembly.dll was being built with Debug configuration even though I chose Release in Visual Studio. The reason was that I was running a post-build event that called msbuild on target WebPublish, but it didn't explicitly specify Release configuration for that, so it decided to use Debug.


text:
Q: Why can't I add objects to this array? For some reason when I make an NSMutableArray it won't add SKLabelNodes. I add them in my code, but when I ask for the count it gives me 0. Am I doing something wrong? Or is something that should work not working? I honestly have no idea
self.titleLabels = [[SKNode alloc]init];
self.titleLabels.position = CGPointMake(CGRectGetMidX(self.frame),  700);

self.titleLabelsArray = [[NSMutableArray alloc]initWithCapacity:5];

SKLabelNode *label1 = [SKLabelNode labelNodeWithFontNamed:@"Code-Pro-Demo"];
label1.text = @"0";
label1.fontSize = 90;
label1.fontColor = [SKColor colorWithRed:90/255.0f green:197/255.0f blue:198/255.0f alpha:1];
label1.position = CGPointMake(-150, 100);
label1.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:label1.frame.size];
label1.physicsBody.dynamic = NO;

SKLabelNode *label2 = [SKLabelNode labelNodeWithFontNamed:@"Code-Pro-Demo"];
label2.text = @"1";
label2.fontSize = 90;
label2.fontColor = [SKColor colorWithRed:1 green:1 blue:1 alpha:1];
label2.position = CGPointMake(-30, 100);
label2.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:label2.frame.size];
label2.physicsBody.dynamic = NO;

SKLabelNode *label3 = [SKLabelNode labelNodeWithFontNamed:@"Code-Pro-Demo"];
label3.text = @"2";
label3.fontSize = 90;
label3.fontColor = [SKColor colorWithRed:1 green:1 blue:1 alpha:1];
label3.position = CGPointMake(150, 100);
label3.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:label3.frame.size];
label3.physicsBody.dynamic = NO;

SKLabelNode *label4 = [SKLabelNode labelNodeWithFontNamed:@"Code-Pro-Demo"];
label4.text = @"3";
label4.fontSize = 90;
label4.fontColor = [SKColor colorWithRed:1 green:1 blue:1 alpha:1];
label4.position = CGPointMake(-150, 0);
label4.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:label4.frame.size];
label4.physicsBody.dynamic = NO;

SKLabelNode *label5 = [SKLabelNode labelNodeWithFontNamed:@"Code-Pro-Demo"];
label5.text = @"4";
label5.fontSize = 120;
label5.fontColor = [SKColor colorWithRed:228/255.0f green:70/255.0f blue:38/255.0f alpha:1];
label5.position = CGPointMake(10, -1);
label5.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:label5.frame.size];
label5.physicsBody.dynamic = NO;

[self.titleLabels addChild:label1];
[self.titleLabels addChild:label2];
[self.titleLabels addChild:label3];
[self.titleLabels addChild:label4];
[self.titleLabels addChild:label5];

[self addChild:self.titleLabels];

[self.titleLabelsArray addObject:label1];
[self.titleLabelsArray addObject:label2];
[self.titleLabelsArray addObject:label3];
[self.titleLabelsArray addObject:label4];
[self.titleLabelsArray addObject:label5];
NSLog(@"%i",self.titleLabelsArray.count);

A: As you noted in your own answer, in this case there is no need to add the 5 SKLabelNode(s) to a distinct array, infact you can iterate them using self.titleLabels.children.
However I tried to understand why your original code does not work as expected, infact your last line of code should indeed print the number 5.
Step 1
The compiler does not like this line
NSLog(@"%i",self.titleLabelsArray.count);

because values of type NSUInteger should not be used as format arguments. Use this instead:
NSLog(@"%lu",(unsigned long)self.titleLabelsArray.count);

Step 2
The code does work properly (and does print 5) IF the property titleLabelsArray is NOT declared as weak.
E.g. this is a correct declaration:
@property NSMutableArray * titleLabelsArray;

And this is the output:
2015-03-29 16:09:31.919 MyProject[1231:695366] 5

On the other hand this is a wrong declaration for this case:
@property (weak) NSMutableArray * titleLabelsArray;

and now you get this output:
2015-03-29 16:10:59.713 MyProject[1275:699690] 0

So my question: how are you declaring the property titleLabelsArray?
Step 3
Finally I would suggest you to use an instance variable instead of a property when there is no need to make the variable public.
You can declare it this way
@implementation YourSuperCoolClass
{
    NSMutableArray * titleLabelsArray;
}

And then you access it without the self. prefix:
[titleLabelsArray addObject:label1];
[titleLabelsArray addObject:label2];
[titleLabelsArray addObject:label3];
[titleLabelsArray addObject:label4];
[titleLabelsArray addObject:label5];

NSLog(@"%lu",(unsigned long)titleLabelsArray.count);

A: Use this:
self.titleLabels.children

It's a built in array for the childnodes


text:
Q: Error: $injector:unpr Unknown Provider in AngularJS I'm trying to do test app on AngularJS but stuck on few days on one place
with this error:
angular.js:38 Uncaught Error: [$injector:unpr] http://errors.angularjs.org/1.4.1/$injector/unpr?p0=AuthtokenProvider%20%3C…terceptor%20%3C-%20%24http%20%3C-%20%24templateRequest%20%3C-%20%24compile

as I could understand, I did a mistake somewhere in the references:
can you show me where my code below
mainController.js:
angular.module('mainController', [])

.controller('MainController', function($rootScope, $location, Auth) {

        var vm = this;

        vm.LoggedIn = Auth.isLoggedIn();

        $rootScope.$on('$routeChangeStart', function () {
            vm.LoggedIn = Auth.isLoggedIn();

            Auth.getUser()
                .then(function (data) {
                    vm.user = data.data;
                });
        });

        vm.doLogin = function () {

            vm.processing = true;

            vm.error = '';

            Auth.login(vm.loginData.username, vm.loginData.password)
                .success(function (data) {
                    vm.processing = false;

                    Auth.getUser()
                        .then(function (data) {
                            vm.user = data.data;
                        });

                    if (data.success)
                        $location.path('/');
                    else
                        vm.error = data.message;

                });
        }

        vm.doLogout = function () {
            Auth.logout();
            $location.path('/logout');
        }
    });

userController.js:
    angular.module('userController', ['userService'])

.controller('UserController', function(User){

    var vm = this;

    User.all()
        .success(function (data) {
            vm.users = data
        })
})

.controller('UserCreateController', function(User, $location, $window){

        var vm = this;

        vm.signupUser = function () {
            vm.message = '';

            User.create(vm.userData)
                .then(function(response){
                    vm.userData = {};
                    vm.message = response.data.message;

                    $window.localStorage.setItem('token', response.data.token);
                    $location.path('/');
                })
        }
    })

authService.js:
angular.module('authService', [])

.factory('Auth', function($http, $q, AuthToken) {

        var  authFactory = {};

        authFactory.login = function(username, password){

            return $http.post('/api/login', {

                username: username,
                password: password
            })
                .success(function(data){
                    AuthToken.setToken(data.token);
                    return data;
                })
        }

        authFactory.logout = function(){
            AuthToken.setToken();
        }

        authFactory.isLoggedIn = function(){
            if(AuthToken.getToken())
                return true;
            else
                return false;
        }

        authFactory.getUser = function(){
            if(AuthToken.getToken())
            return $http.get('/api/me');
            else
            return $q.reject({ message: "User has no token"});
        }

        return authFactory;
    })

.factory('AuthToken', function($window){

        var  authTokenFactory = {};

        authTokenFactory.getToken = function(){
            return $window.localStorage.getItem('token');
        }

        authTokenFactory.setToken = function (token) {
            if(token)
            $window.localStorage.setItem('token', token);
            else
            $window.localStorage.removeItem('token');
        }

        return authTokenFactory;
    })

.factory('AuthInterceptor', function ($q, $location, Authtoken) {

        var interceptorFactory = {};

        interceptorFactory.request = function(config){

            var token = Authtoken.getToken();

            if(token){
                config.headers['x-access-token'] = token;
            }

            return config
        };

        interceptorFactory.responseError = function (response) {
            if(response.status == 403)
            $location.path('/login');

            return $q.reject(response);
        }

        return interceptorFactory;
    });

userService.js:
angular.module('userService', [])

.factory('User', function($http){

        var userFactory = {};

        userFactory.create = function(userData){
            return $http.post('/api/signup', userData);
        }

        userFactory.all = function(){
            return $http.get('/api/users');
        }

        return userFactory;
    });

app.js:
angular.module('MyApp', ['appRoutes', 'mainController', 'authService', 'userController', 'userService'])

.config(function($httpProvider){

        $httpProvider.interceptors.push('AuthInterceptor');
    });

app.routes.js:
angular.module('appRoutes', ['ngRoute'])

.config(function ($routeProvider, $locationProvider) {

        $routeProvider

            .when('/', {
                templateUrl: 'app/views/pages/home.html'
            })
            .when('/login',{
                templateUrl: 'app/views/pages/login.html'
            })
            .when('/signup', {
                templateUrl: 'app/views/pages/signup.html'
            });

        //$locationProvider.html5Mode(true);
        $locationProvider.html5Mode({
            enabled: true,
            requireBase: false
        });
    });

A: You need to inject your authService into your mainController to make it available since you are using Auth in mainController:
angular.module('mainController', ['authService']);

Everytime you pass in the 2nd argument to module (the array) it creates a new module that doesn't have access to other modules that have been created. So you have to make them available to each other this way.
You can read about loading dependencies here

A: Maybe the problem is referencing the name of the module in different files. I read in another post here that this makes the module to load the number of times it is repetead. So asign a name to a variable and then use the variable in the rest of the files instead of naming it again.
Example of the forum.


text:
Q: LEM Sensor's output for current polarity change I have a project where I'm trying to build a DC Drive, using just analog circuits. I'm expected to show the operation of the drive in forward and reverse motoring, and I'm trying to pick between the following two sensors, and I'm having trouble understanding the differences between them. Ideally I want a current sensor that can give me a positive voltage (4-5V) for +5A and -4 or -5 V for -5A. A dc offset is okay.
Not sure which one to pick.
HX 05-P
https://www.lem.com/en/product-list/hx-05p
https://www.lem.com/sites/default/files/products_datasheets/hx_03_50-p_ver15.pdf
HX 05-P/SP2
https://www.lem.com/en/product-list/hx-05psp2
https://www.lem.com/sites/default/files/products_datasheets/hx%203_50-p_sp2_e%20v07.pdf
Thanks in advance !

A: The -P/SP2 part uses a single positive supply; its output is offset 2.5V, and its output "gain" (transresistance, actually) is 0.625 V at nominal current.  The -P part requires a positive and negative supply.  Its output has no offset, gain is 4V at nominal current.
Which one to choose probably depends mainly on whether or not you have a negative supply voltage available


text:
Q: How to obtain the local bound on the length of the Morse function? This is a follow-up of the question
Is there a bound on the length of the longest Morse trajectory?.
Consider the following setup. Let $(M,g)$ be a (complete) Riemannian Hilbert manifold and $f$ a Palais-Smale Morse function which is bounded below. In the cited question Pietro Majer essentially states that: Let $a$ be a real number. Then, for every critical point $x$ of $f$  there is a neighborhood $U_x$ of $x$ and a constant $C,$ s.t. whenever $\gamma:[0,T]\rightarrow M$ is a Morse trajectory (i.e. $\dot{\gamma}(t)=-\nabla f(\gamma(t))$) with $f(\gamma(0))\leq a$ and $\gamma([0,T])\subseteq U_x$, then the length of $\gamma$ is bounded by $C$.
When Pietro's answer came online, I thought I had a proof for the statement above. Unfortunately I found a gap in my argument which I could not fix. Any ideas?

A: It's quite a standard fact, not difficult though a bit technical. Of course it comes from the hyperbolic structure of the flow near its equilibrium points, and from the existence of a Lyapounov function for the flow (the function itself), which in turn this gives the existence of an isolating neighborhood (in the language of Conley theory). You may find it useful to check this, a paper of some years ago where I myself needed these length estimates (see section 5.1)
http://onlinelibrary.wiley.com/doi/10.1002/cpa.1012/pdf
You may also find interesting these lectures.


text:
Q: Escaping arrays using mysqli escape string I need to escape array's, I am using array_map with mysqli_real_escape_string.
I have multiple arrays like
$_post['countries'];
$_post['categories'];
.
.

How do I perform escaping on these arrays
I am doing this way
$countries=array_map('mysqli_real_escape_string', $_POST['countries']);
$categories=array_map('mysqli_real_escape_string', $_POST['categories']);
.
.

but it shows me error as Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1 given in
also doing
$categories=mysqli_real_escape_string($connection, $_POST['categories']);

gives error as
Warning: mysqli_real_escape_string() expects parameter 2 to be string, array given in

Please see and suggest a way or another better way to do this.
Thanks

A: You need to wrap mysqli_real_escape_string() call with an anonymous function to use within array_map() like this:
// $connection_object is a mysqli object declared somewhere above

$countries = array_map(function($item) use($connection_object) {
  return mysqli_real_escape_string($connection_object, $item);
}, $_POST['countries']);

A: You have a lot of solutions here.
Considering you wanna stick to mysqli (PDO is now the recommanded way, but still a choice) and you want to keep using array_map on this context, you have to check the array_map prototype: http://php.net/array_map

array array_map ( callable $callback , array $array1 [, array $... ] )

So:

*

*Using dynamic arguments of array_map
Note : this solution is a bad one, and was mistaken.
Original answer : $myArray = array_map('mysqli_real_escape_string', $db, $myArray);
Updated answer : $myArray = array_map('mysqli_real_escape_string', $myArray, array_fill(0, count($myArray), $db)); and that's a bad idea with mysqli object.

*Using array callable
Because mysqli_real_escape_string is also a method of mysqli...
$myArray = array_map(array($db, 'real_escape_string'), $myArray);

*Using closure
$myArray = array_map(function($e) use($db) { return mysqli_escape_string($db, $e); }, $myArray);
or
$myArray = array_map(function($e) use($db) { return $db->real_escape_string($e); }, $myArray);


text:
Q: Restore one table from a database in PostgreSQL and save it with plain/text data format I have a table (tst2) in a database (tweets) in PostgreSQL  and I need to have a plain/text format file out of it, I was wondering if there is any possible solution with pg_dump ? something like :
pg_dump -t tst2 tweets -f plain >...

also if I am in a wrong way please let me know?!

A: pg_dump works for me, though there is some clutter before and after the table (after all, dumps are supposed to be used to fill up the table at recovery time).
I'm not sure what you use the > operator for; the dump goes to the file `plane'.
Your error message would help, of course.
On the other hand, what's wrong with using psql with a .pgpass password file and setting the PGDATABASE, PGHOST, PGPORT, and PGUSER anvironment variables, e.g.:
export PGDATABASE=tweet
# PGHOST, PGPORT, and PGUSER as per your setup
psql -c 'select * from tst2'

A: There are a couple of ways to dump a table into a text file.
First, you can use pg_dump, as you intended. In that case you'll get a SQL script to restore the tables. Just fix your command a bit:
pg_dump -t tst2 -t tweets -F plain >...

Second, you can dump contents of a table with copy command. There are either SQL version of the command (files will be created on the server):
copy tst2 to 'tst2.txt';
copy tweets to 'tweets.txt';

Or client-side psql version (files will be created on your client computer):
\copy tst2 to 'tst2.txt';
\copy tweets to 'tweets.txt';


text:
Q: python argsparse data types I am running into a weird problem with args.parse in python 3.4 and I need some help. I am just starting with python, so it may be something stupid.
I am passing an argument
parser.add_argument('-solr', type=str, default='http://localhost:8983/solr/', nargs='+', help='Address of Solr server (ex: http://192.168.137.128:8983/solr/)')

It should be just one argument, all the time. If I actually pass the argument, it will get stored as an array and I will need to access it via args.solr[0]. However, if I don't pass any arguments to it, the default value will be used, but it will be stored as string, thus, args.solr[0] will be 'h'.
What gives? I've tried to play around with nargs, but even setting it to 1 doesn't seem to change anything.
Thanks in advance

A: Use nargs = '?'. It stopped taking the input as an array.
parser.add_argument('--solr', type=str, default='http://localhost:8983/solr/',nargs='?',help='Address of Solr server (ex: http://192.168.137.128:8983/solr/)')

A: Since your argument is flagged (name starts with -) you don't need to set nargs at all - use its default None.  It is optional (not required) unless you use the flag string.
parser.add_argument('--solr', default='http://localhost:8983/solr/',
    help='Address of Solr server (ex: %(default)s)')

With this, sample inputs produce:
In [51]: parser.parse_args([])
Out[51]: Namespace(solr='http://localhost:8983/solr/')

In [52]: parser.parse_args(['--solr','test'])
Out[52]: Namespace(solr='test')

In [50]: parser.print_help()
usage: ipython [-h] [--solr SOLR]

optional arguments:
  -h, --help   show this help message and exit
  --solr SOLR  Address of Solr server (ex: http://localhost:8983/solr/)

With longer optional names, a -- is better than -.  The default type is str, so you don't need to specify that.  I've added %(default)s to the help, so you don't have to repeat the default value.
If you do want the result to be a list, e.g. ['test'], use nargs=1 and put the default in a list as well, e.g. default=['http...'].


text:
Q: What is optimal API to scan Google Cloud BigTable data in Python? I see there are 2 hbase table-scanning APIs in Google Cloud's sample code:
1) using google.cloud module bigtable object
https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/bigtable/hello/main.py
from google.cloud import bigtable
client = bigtable.Client(project=project_id, admin=True)
instance = client.instance(instance_id)
table = instance.table(table_id)
partial_rows = table.read_rows(...)
partial_rows.consume_all()
for row_key, row in partial_rows.rows.items():

2) using google.cloud module bigtable and happybase objects
https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/bigtable/hello_happybase/main.py
from google.cloud import bigtable
from google.cloud import happybase
client = bigtable.Client(project=project_id, admin=True)
instance = client.instance(instance_id)
connection = happybase.Connection(instance=instance)
table = connection.table(table_name)
for key, row in table.scan():

Which of these 2 mechanisms is the recommended approach for scanning BigTable?
Also, are they suitable for using from PySpark ?

A: Either one of these libraries can be made to work with PySpark, however we generally recommend our native API (the first example) rather than HappyBase, if you are building a new application.
We provide the HappyBase adapter for Google Cloud Bigtable as a convenience for developers looking for an easier path to migrate existing workloads using HappyBase from an HBase deployment over to Google Cloud Bigtable.


text:
Q: Can set some type for FormControl value? Framework which I use (Angular 7).
I want set some type for FormControl like this.
    startDate: FormControl<NgbDate>;
    endDate: FormControl<NgbDate>;

Do you have any experience with it or it is not posible in angular?

A: For now it's not possibile. Check this issue to Angular GitHub Reactive forms are not strongly typed

A: It is available in angular 14 ,

startDate: FormControl<Date | null>(null);
endDate: FormControl<Date | null>(null);


text:
Q: Unable to drag Element/Item into the Drop Area/Container Unable to drag Element/Item into the Drop Area/Container
Tech/Softwares used:

*

*IDE: Eclipse

*Framework for testing: Selenium

*Language: Java

*Browser: Microsoft Edge - Version 85.0.564.51

Issue:

*

*I'm unable to drag the given Element/Item into the Drop Area/Container (See Images)

*I've also used different Xpaths/Selectors i.e. By-CSS,By-Xpath or By-Class

*It seems that the Element/Item is selected and moved a pixel or two after which the Element/Item freezes and is not dragged to the Drop Area/Container below

My Attempt:

*

*So i've tried different drag and drop functions such as the ones below:-
  Actions action = new Actions(drv);
  //Source
  WebElement sourceLocator = drv.findElement(By.className(Item));
 //Destination
  WebElement targetLocator = drv.findElement(By.cssSelector(DropArea));
 //Click -> Hold -> Drag -> Drop
  action.clickAndHold(sourceLocator).moveToElement(targetLocator)
  .release()
  .build()
  .perform();

*I've also tried using 'dragAndDrop instead of clickAndHold'
   `action.dragAndDrop(sourceLocator, targetLocator).build().perform();`

Like I said earlier, The item/element is selected -> Moves a pixel or two then it freezes just above the container (The container pops-up from below as per functionality)
Green box is the item/element to be dragged and droped - Red box is the area where the item/element should be droped
As you can see, the item/element is stuck/frozen right above the drop area
Outcome that is expected - Element has been dragged and dropped (Done manually) in the picture

A: You should try to do it by JavaScript, use the JavaExecutor class from selenium execute the scripts that are in this post, it could work for you
Why drag and drop is not working in Selenium Webdriver?


text: Q: Mapping MIDI keyboard as C++ input I'm doing a GUI that allows you to play sounds as you put input in the MIDI keyboard, using RtMidi,how can i separete inputs to differenciate keys in the keyboard an put them as input?