text:
Q: Awkward sentence
*

*A clause having a subject beginning with preposition is used occasionally.

Does this sentence make any sense? I think this sentence means that a clause has a subject phrase that was started with preposition, and such kind of clause is used occasionally.
Please say what you think. I want better way to rewrite the sentence stated above.

A: Is a more natural sounding sentence is

A clause having a subject beginning with a preposition is used occasionally.

without the a you will sound non-native.
This sentence is fine:

Does this sentence make any sense?

As per @Subjunctive:

I think this sentence means that a clause has a subject phrase that begins with a preposition

because you are asking about a collection (of types of clauses):

and such types of clauses are used occasionally

Since you are wondering about how to improve your sentence:

I would like a better way rewriting this sentence, please suggest any improvements.

Although what you wrote is understandable:

Please say what you think.

is asking for an opinion, whereas you are asking for suggestions, and again the a:

I want a better way to rewrite the sentence stated above

without which to a native ear will signal you as a non-native speaker


text:
Q: How to identify when Vuetify's v-autocomplete reaches last scrolled item I have a Vuetify v-autocomplete that I want to know when the user scrolled to its last item, so I can load more items (without him having to type for search):
// component.vue
<template>
  <v-autocomplete
    ref="myAutocomplete"
    v-model="selectedItem"
    autocomplete="off"
    :items="items"
    no-filter
    :label="$t('unit')"
    rounded
    outlined
    item-text="name"
    return-object
  />
</template>

I don't see any available prop and/or event that could help me do that.

A: My solution was to listen to scroll events on inner v-automplete's v-menu__content element:
// component.vue
export default {
  ...,
  // at mounted hook we set the listener
  mounted() {
    const component = this.$refs.myAutocomplete;
    component.onScroll = this.onScroll(component);
  },

  // and our method should look like:
  methods: {
    onScroll(component) {
      // recursively will search for the specified child
      const findChildren = (elem, name) => {
        if (elem.$el.className.includes(name)) return elem.$el;
        let i = 0;
        let children;
        for (i; !children && i < elem.$children.length; i++) {
          children = findChildren(elem.$children[i], name);
        }
        return children;
      }

      // searchs for 'v-menu--content' element inside v-autocomplete
      const vMenuContent = findChildren(component, 'v-menu__content');

      // take its scroll values
      const a = vMenuContent.scrollTop;
      const b = vMenuContent.scrollHeight;
      const c = vMenuContent.clientHeight;

      // check if it is 100% scrolled
      const isScrolled = (a / (b - c)) === 1;
      if (!isScrolled) return
      // reached the last item: load more items...
    },
  },

redpajama_set_name: RedPajamaStackExchange


text:
Q: Lebesgue measure 0 set which is not Borel Let $A$ be an uncountable Borel subset of $\mathbb{R}^n$, and consider the Lebesgue measure on $\mathbb{R}^n$.
Assume the axiom of choice (if you need it). Does there exist a Lebesgue measurable set $B \subset A$, which has zero Lebesgue measure and is not Borel?
I have no idea of the answer. I know Lebsegue measure theory, and more generally, abstract measure theory, but not the the theory of Polish spaces and analytic sets (the so called descriptive set theory, which could be the key to answer the question). Any help is welcome.

A: Yes, by a simple counting argument:

*

*If $B$ is Borel and uncountable, it has cardinality $2^{\aleph_0}$. EDIT: see below.

*The number of subsets of $B$ is therefore $2^{2^{\aleph_0}}$.

*"Most" of those will not be Borel, since there are only continuum-many Borel sets.

*However, if $B$ is null, all of them will be measurable.
So the result follows since every uncountable Borel set contains an uncountable null Borel set.

A proof of that last claim, that every uncountable Borel set has an uncountable null Borel subset: Every uncountable Borel set has a perfect subset (https://en.wikipedia.org/wiki/Perfect_set_property), so we might as well assume our $A$ is perfect: that is, closed and without isolated points. (Actually, all we need is that $A$ be closed.)
Since $A$ is perfect, it's easy to show that there is a sequence $\{S_i\}$ of finite sets of disjoint closed intervals such that

*

*$S_1$ contains a single interval, $S_2$ contains two, . . . , $S_n$ consists of $2^{n-1}$-many intervals.

*Each $I\in S_n$ contains exactly two $J_0, J_1\in S_{n+1}$.

*Every interval in $S_n$ has length at most $2^{-2^n}$.

*For each $I\in S_n$, the intersection $I\cap A$ is uncountable.
Now consider the "limit set" $X=\bigcap_{i\in\mathbb{N}} (\bigcup S_i)$. It's a good exercise to show that $X$ is a closed uncountable subset of $A$ with measure zero.

EDIT: Based on the comments below, I think I should probably explain the first bullet point above: that every uncountable Borel set has cardinality continuum. (One way this is phrased is "the Continuum Hypothesis holds for Borel sets.") Of course, on the face of it this seems to need CH (the statement $\vert\mathbb{R}\vert=\aleph_1$); so the whole point is that there's something special about Borel sets which prevents "weird" behavior.
Although don't put too much faith in the Borel sets! Weird behavior is still possible, especially in the absence of the axiom of choice: see this paper by Arnold Miller, which constructs a Dedekind-finite infinite Borel set, and also this question.
First off, it's worth proving the much simpler claim that every uncountable closed set has size continuum. While this is fairly easy, it's not trivial; and even pushing it up to the next level of the Borel hierarchy ($G_\delta$ - countable intersections of open sets) is somewhat hard. So proving it for all Borel sets is a daunting task.
The solution is via games, specifically the perfect set game. For a set $A\subseteq\mathbb{R}$, the game $PSG(A)$ is defined as follows:

*

*It's a game of perfect information between two players, Large (I) and Small (II).

*On turn $n$, player I plays a pair of disjoint intervals $I_{n, 0}$ and $I_{n, 1}$; player II then picks one of them (which becomes $J_n$).

*We demand that $I_{n+1, i}\subseteq J_n$, that is, the intervals are nested appropriately.

*After $\omega$-many turns, we've defined a sequence of intervals $J_0\supseteq J_1\supseteq...$. Let their intersection be $J$. Player I wins iff $J\cap A\not=\emptyset$.
We can prove that

*

*Player I has a winning strategy iff $A$ contains a perfect subset, and

*Player II has a winning strategy iff $A$ is countable.
So the goal is to show:

*

*If $A$ is Borel, then $PSG(A)$ is determined: one player or the other has a winning strategy.

This is a consequence, for instance, of Borel determinacy (see https://en.wikipedia.org/wiki/Borel_determinacy_theorem), but that proof is very hard. In particular, this wasn't how the result was originally proved. Instead, the original proof is to "unfold" the game $PSG(A)$ for $A$ Borel into an open game on a certain set $X$; then by Gale-Stewart, that game is determined, so we are done. Note that this is actually how the proof of full Borel determinacy goes, too - but that unfolding process is much harder. This argument actually proves that analytic sets have the perfect set property; I'm not aware of any proof that the Borel sets have the perfect set property which doesn't immediately apply to analytic sets too (besides the argument via full Borel determinacy, which I mean come on that's just silly).
I'm not going to include this whole argument, although it's really cool, since it's pretty long - see the "Games people play" section in Kechris' book for a great exposition. But hopefully the above gives some context for the result.

A: I fill the gaps in the proof sketched by Noah Schweber that every uncountable Borel set of $\mathbb{R}^n$ has an uncountable null Borel subset (since the proof is too long I can't post it as a comment). As Noah noted, since very analytic set has the perfect set property, we can assume that $A$ is a perfect set.
More generally, I will prove that if $A$ is a closed and uncountable subset of $\mathbb{R}^n$, then we can find $X \subseteq A$, with $X$ perfect set of zero Lebesgue measure.
I call a cell a set which is defined, for some $a_i \leq b_i$ for $i=1, \dots, n$, as consisting of all $x=(x_1, \dots, x_n) \in \mathbb{R}^n$, with $a_i \leq x_i \leq b_i$ for all $i=1, \dots, n$.
First, we claim there exists a sequence $(S_i)$, where each $S_i$ is a finite family of pairwise disjoint cells such that:

*

*each $S_k$ contains $2^{k-1}$ cells;

*each $I \in S_k$ contains exactly two elements $J_0, J_1$ of $S_{k+1}$;

*every $I \in S_k$ has sides whose length is at most $2^{-2^k}$;

*for each $I \in S_k$, the set $I \cap A$ is uncountable.
To prove this, for every $v=(v_1, \dots, v_n)$, with $v_1, \dots, v_n\in \mathbb{Z}$, and every nonnegative integer m, let $I_{m,v}$ the dyadic cell consisting of all $x=(x_1, \dots, x_n) \in \mathbb{R}^n$ such that for all $i=1, \dots, n$ we have
\begin{equation}
2^{-m}v_i \leq x_i \leq 2^{-m}(v_i + 1).
\end{equation}
Assume that for some $m$ and $v$, the set $I_{m,v} \cap A$ is uncountable. Then we claim that there are infinitely many integers $p > m$ such that, for each such $p$ there are $s, t \in \mathbb{Z}^n$, such that $I_{p,s}$ and $I_{p,t}$ are disjoint, both contained in $I_{m,v}$, and such that both $I_{p,s} \cap A$ and $I_{p,t} \cap A$ are uncountable. If not, there would exist some integer $N$ such that, for all $p > N$, there exists a dyadic cell $C_p$ of side of length $3 \times2^{-p}$ which contains all the cells of side $2^{-p}$ which have an uncountable intersection with $A$. We would get a sequence of compact sets $(C_p)_{p > N}$, with $C_{p+1} \subset C_p$, so that $\bigcap_{p>N} C_p$ contains exactly one point. But then $A$ would be countable, a contradiction.
From the property just proved, we can easily construct our sequence $(S_i)$.
Now, define $X= \bigcap_{i \in \mathbb{N}} (\bigcup S_i)$. Clearly $X$ is closed, since each $\bigcup S_i$ is. Moreover, if $x \in X$, then for each $k$, $x$ belongs to some $I \in S_k$. Since each point $y \in S_k$ has a distance from $x$ which is not greater than $n \times 2^{-2^k}$, $x$ turns out to be a limit point of a sequence of points of $A$, and since $A$ is closed, we conclude that $x \in A$. Finally, let $J_0, J_1$ be the elements of $S_{k+1}$ contained in $I$, and $x \in J_0$. Then there is some $y \in J_1 \cap X$ (since a decreasing sequence of compact sets has nonempty intersection). The distance between $x$ and $y$ is not greater than $n \times 2^{-2^{k}}$. We conclude that $x$ is a limit point of $X$, so that $X$ is perfect. To see that $X$ has zero Lebesgue measure just note that each $S_k$ has measure at most $2^{k-1} \times 2^{-n 2^k}$. QED


text:
Q: how detect the software the presence of a VM I am beginners in the world of virtual machines and have a small question. if a software is running on a VM (eg. VMware Player) how does it know that it is installed on a VM? Does the software get the information from the operating system or is there a direct communication between the software and the hardware (VMware Player)? thank you in advance

A: Unfortunately there is not an unique answer. Each virtual machine has a sort of bridge you can use but you have to write specific checks for each VM you want to detect (examples are VC++ specific but you can easily adapt them to your compiler). Note that in theory you should not be able to determine if you're running under a VM or not.
VMWare
VMWare uses IN instruction to handle guest to host communication. Normally this instruction is not available in user-mode and it throws an exception but VM handles it. If we catch the exception then we know we are not running under VMWare (or we are privileges to execute IN instruction). Second test to determine if we have privileges or we are running under WMWare is almost useless but that's standard detect code and I write it here for completeness (we just check for an expected string VMXh in EBX register, note we had to initialize some registers with required values.)
bool IsRunningInsideVmWare()
{
    bool flag = true;

    __try
    {
        __asm
        {
            push    edx
            push    ecx
            push    ebx

            mov     eax, 'VMXh'
            mov     ebx, 0
            mov     ecx, 10
            mov     edx, 'VX'

            in      eax, dx
            cmp     ebx, 'VMXh'
            setz    [flag]

            pop     ebx
            pop     ecx
            pop     edx
        }
    }
    __except(EXCEPTION_EXECUTE_HANDLER)
    {
        flag = false;
    }

    return flag;
}

Virtual PC
Guests can use a non-existing instruction 0f3f070b to communicate with host, what you can do is then emit such instruction, VM will correctly interpret it but physical CPUs will throw an exception (which you can catch and jump over offending instruction). In this example we set EBX to a known value in the exception handler and then we can detect this scenario.
DWORD __forceinline VpcExceptionFilter(LPEXCEPTION_POINTERS ep)
{
    ep->ContextRecord->ctx->Ebx = -1;
    ep->ContextRecord->ctx->Eip += 4;

    return EXCEPTION_CONTINUE_EXECUTION;
}

bool IsRunningInsideVpc()
{
    bool flag = false;

    __try
    {
        _asm
        {
            push    ebx

            mov     eax, 1
            mov     ebx, 0

            __emit  0Fh
            __emit  3Fh
            __emit  07h
            __emit  0Bh

            test    ebx, ebx
            setz    [flag]

            pop     ebx
        }
    }
    __except(VpcExceptionFilter(GetExceptionInformation()))
    {
    }

    return flag;
}

VirtualBox
To detect VirtualBox is extremely simple, you just need to check if a pseudo-device \\.\VBoxMiniRdrDN exists:
bool IsRunningInsideVirtualBox()
{
    HANDLE handle = CreateFile("\\\\.\\VBoxMiniRdrDN", GENERIC_READ, FILE_SHARE_READ,
        NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

    if (handle != INVALID_HANDLE_VALUE)
    {
        CloseHandle(handle);
        return true;
    }

    return false;
}

Something little bit more generic can be done (assumption: you're running on Windows) using WMI and the following queries:

*

*In Win32_BaseBoard matchName against (?i)(Hyper-V|Virtual Machine|Microsoft|VMware|VirtualBox|Parallels Virtual).

*In Win32_ComputerSystem match Model and Manufacturer against (?i)(Hyper-V|Virtual Machine|VMware|VirtualBox).

*In Win32_VideoController match Name against (?i)Hyper-V.

CPUID instructions can also help you (when those values are supported).
With EAX set to 0 (Get vendor ID) you get in EBX, EDX and ECX an ASCII string with CPU vendor name (see Wikipedia for list). Of course a VM can return a false name or it may be an unknown VM.
With EAX set to 1 (Processor Info and Feature Bits) bit 31 of ECX (hypervisor) is set to 1 if you're running under a VM. Again a VM may return a false result (and some VMs don't honor this bit).

When I had to play with this issue I tried also to check for hardware tricks/features which are not supported in a VM (for example to USB Legacy support) but I found it's not reliable enough to be used in production.

In comment you said you're running on Android. That's a completely different story but common techniques are similar to what I said about WMI (or a combination of the above). A common way is to check the device name string for well-known emulators, from Android 7 there is a specific flag ro.kernel.qemu.
Can you fake those values? Yes, see for example Is there a way to set ro.kernel.qemu to 0 in a emulator?. Note that any decent application which cares to stop you to use it under emulation will also use multiple detection techniques (see also Android: Get Hardware Information Programmatically).

A: I don't think that it does matter for the software where it is running as long as it works properly.
If you really want to check if you are running (or if your self-written code) is running on VM. In Windows case it is possible to check the hardware in device manager (Windows case), because VM apps create some virtual hardware. For example VMWare will create some hardware named VMware... devices.


text:
Q: Windows 7 BigSQL packaged PostGIS ST_Transformation queries not working we've recently migrated from the EnterpriseDB packaged PostgreSQL 9.5/PostGIS 2.3 to the BigSQL verision (9.6/2.3), PostGIS was installed via PGC.  Platform is Windows 7 64bit and data migration was via a database dump.
Unfortunately this has resulted in the PostGIS ST_Transform queries no longer functioning. Previously this would work -
"UPDATE secure.lp_long_mx SET nztm_geom = ST_Transform(nzmg_geom, 2193) WHERE lp_long_mx.cc_x >=2000000 AND lp_long_mx.nztm_geom IS NULL;"

Now it throws the error of -

NOTICE:  PostGIS was unable to transform the point because either no
  grid shift files were found, or the point does not lie within the
  range for which the grid shift is defined. Refer to the ST_Transform()
  section of the PostGIS manual for details on how to config
ERROR:  transform: couldn't project point (2.67867e+006 6.45903e+006
  0): failed to load datum shift file (-38)

If I run the same query on a Linux box where I dumped the same database it runs no problem.
"SELECT PostGIS_Full_Version();" results are these
Windows 7 64bit -
"POSTGIS="2.3.2 r15302" GEOS="3.5.0-CAPI-1.9.0 r4084" PROJ="Rel.
4.9.2, 08 September 2015" GDAL="GDAL 2.0.3, released 2016/07/01" LIBXML="2.9.4" RASTER"

Ubuntu 16.04 64bit -
"POSTGIS="2.3.2 r15302" GEOS="3.5.1-CAPI-1.9.1 r4246" PROJ="Rel. 4.9.2, 08 September 2015" GDAL="GDAL 1.11.3, released 2015/09/16" LIBXML="2.9.3" LIBJSON="0.11.99" RASTER"

Windows spatial_ref_sys on database also seems fine when I run
"select * from spatial_ref_sys where srid in (2193,27200);"

I had a hunt around for other similar problems and saw some references to file locations and checked PostGIS has correctly set the Windows GDAL_DATA Environment Variable (C:\PostgreSQL\gdal-data).
Anyone have any ideas on how to resolve or better diagnose - I'm more a GIS than database persons so am clueless on the debugging side. I'm also stuck on Windows 7 so the Linux box isn't a solution. Seems (naively) to me an issue with the BigSQL PostGIS installation.

A: geometry does not use GDAL so has nothing to do with that setting. There is a proj folder containing the nad shift files.  I have to check if BigSQL is distributing those.  They might not be.  I think there is some hard-coding in PostGIS code to try to look for those in share/contrib/postgis-2.3.
I haven't checked to see how that plays with BigSQL.  You could try copying the files from:
http://postgis.net/windows_downloads/   (look in the winnie section, vor your PostgreSQL version/ PostGIS version.
Try to copy the files in share/contrib/postgis-2.3/proj to your share\postgresql\contrib\postgis-2.3\proj
of your bigsql install.
If that doesn't work, put in a ticket in our tracker: http://postgis.net/support/
The paths of BigSQL are a little different, so might have to make some changes to accommodate or let them know what variable they need to set.
Also provide a specific geometry so I can test it.

A: Thanks for helping out on this issue Regina!
Ronald, we will include the proj folder in our next release. We have recently begun to support PostGIS in our distributions in an effort to help GISers across all platforms. Thanks for helping us make our distribution better - and feel free to provide feedback to https://www.bigsql.org/forum if you find any other issues or have suggestions for improvements.
Best,
Holly Orr
Senior Technical Manager
OpenSCG

A: Hi Ronald and Regina -
Proj datum shift files have been included in the new binaries postgis23-pg96-2.3.3-1 across all the platforms. They are located in bigsql/pg96/share/postgresql/contrib/postgis-2.3/proj.
Look at this blog post for instructions for installing the BigSQL distribution and/or updating to the latest release: https://www.openscg.com/2017/07/postgis-2-3-3-is-now-available/
Please tell us if you have any further issues or questions!


text:
Q: How to return the values of dictionary key that has gained new values in a different dictionary I have question a bit similar to:Replacing the value of a Python dictionary with the value of another dictionary that matches the other dictionaries key
However in my case I got two dictionaries
dict1 = {'foo' : ['val1' , 'val2' , 'val3'] , 'bar' : ['val4' , 'val5']}

dict2 = {'foo' : ['val2', 'val10', 'val11'] , 'bar' : ['val1' , 'val4']}

What I want to return is
dict3 = {'foo' : ['val10', 'val11'] , 'bar' : ['val1']}

and the opposite which is
dict4 = {'foo' : ['val1', 'val3'] , 'bar' : ['val5']}

where dict3 returns a dictionary of the values the keys 'foo' and 'bar' has gained in dict2 and the dict4 is a dictionary of the values the keys 'foo' and 'bar' has lost in dict2
One way I have tried solving this is to:
 iterate over both dictionaries then
    if key of dict1 == key of dict2
       return the values of the key in dict1 and compare with the values in dict2
       return the values that aren't in both
       as a dictionary of the key and those values

This idea isn't working and obviously highly inefficient. I was hoping there is a more efficient working way to do this

A: Two dict comprehensions will do the trick:
dict3 = {k: [x for x in v if x not in dict1[k]] for k, v in dict2.items()}
print(dict3)
# {'foo': ['val10', 'val11'], 'bar': ['val1']}

dict4 = {k: [x for x in v if x not in dict2[k]] for k, v in dict1.items()}
print(dict4)
# {'foo': ['val1', 'val3'], 'bar': ['val5']}

The above two comprehensions basically filter out the values from key that don't exist in the other dictionary, which is done both ways.
You can also do this without dict comprehensions:
dict3 = {}
for k,v in dict2.items():
    dict3[k] = [x for x in v if x not in dict1[k]]

print(dict3)
# {'foo': ['val10', 'val11'], 'bar': ['val1']}

dict4 = {}
for k,v in dict1.items():
    dict4[k] = [x for x in v if x not in dict2[k]]

print(dict4)
# {'foo': ['val1', 'val3'], 'bar': ['val5']}


text:
Q: Most effective pathway to compare geographic locations? solutions pls Say I have a location A, with IP address, and a geolocator API with latitude and longitude. Now I want to find all instances that are within a 25-mile radius of location A. How can I compute this with the least amount of steps?
solution A: I can compute all distances between location A and all instances in the database, and display instances within 25 radius. (way too slow especially if I want a dynamic location, with a large database of locations)
solution B: I can group all instances in terms of zip code in addition to IP, and (lat, long). so that fewer distances between location A and instances needed to be computed. (better, but what if the IP address is at the border of another zip code, this will add to the amount of needed computation)
solution C: I can use trigonometry. using the latitude and longitude of location A. i can find each instance with in the 25 mile radius.
Can someone please describe a better way of comparing distances? ideas and suggestions are much appreciated (if further explanation is needed, pls ask) Thanks.

A: I'd use a combination of your proposed solutions a and c. You can query your database directly using a filter that only selects the locations within a 25 miles radius (or any other radius). Calculating the longitudinal difference in miles is a little tricky because the mileage of one degree in longitude differs with latitude. Kudos go out to this explanation: https://gis.stackexchange.com/questions/142326/calculating-longitude-length-in-miles#142327
Assuming you have the following DB schema with existing locations (only latitude and longitude as columns):
CREATE TABLE location (
    lat REAL,
    lon REAL
);

You're able to filter only the locations within a 25 mile radius using this query:
query = """
    SELECT (lat - ?) AS difflat,
           (lon - ?) AS difflon
    FROM location
    WHERE POWER(POWER(difflat * 69.172, 2) + POWER(difflon * COS(lat*3.14/180.) * 69.172, 2), 0.5) < ?;
    """

Using the query then like this:
radius = 25 #miles
cursor.execute(query, (querylocation['lat'], querylocation['lat'], radius))

SQLite3 unfortunately doesn't support basic mathematical functions like COS and POWER but they can easily be created:
import math
con = sqlite3.connect(db_path)
con.create_function('POWER', 2, math.pow)
con.create_function('COS', 1, math.cos)


text:
Q: How to get Minitest to test in Parallel? I have tried adding this to minitest: parallelize(workers: :number_of_processors, with: :threads) but it doesn't seem to do anything.  I have some very back stock CRUD tests and they take 2-3 minutes each for just a single controller:
Running 7 tests in a single process (parallelization threshold is 50)
Started with run options --seed 2895

  7/7: [=======================================================================================================================================================================] 100% Time: 00:03:06, Time: 00:03:06

Finished in 186.22311s
7 tests, 11 assertions, 0 failures, 0 errors, 0 skips

This seems to be a LONG time for some basic test.  I added parallelize_me! to my tests and they ran instantly then I realized that they were passing 100% of the tests even if there were underlying failures.  The documentation on this seems week and I am not finding much from searching etc.
I can't even see where you set that parallelization threshold?

A: The parallelization threshold is 50 but this test contains only 7 tests so it will not parallelize. You can lower the threshold:
parallelize(workers: :number_of_processors, threshold: 5)


text:
Q: nginx 499 errors with node upstream and http2 Recently we've switched apache to nginx with http2 support for our web application, and we're seeing quite a lot of 499 errors.
Our setup:

*

*Ubuntu machine running on Amazon AWS

*Nginx/1.9.12 acting as proxy (and ssl offload) for node application (same machine)

*Single Page App on the client side

My initial thought was that clients simply close their browsers, but from the logs, i see that ~95% clients are alive, and there are requests after getting 499.
55% of 499 errors occur for http2 and 45% for http1.1 version, so no trend here.
80% of the requests come from mobile devices (bad connection?)
But of particular worry there is one endpoint which might take 5-15 seconds to complete (PUT request). For that endpoint:

*

*~95% of the 499 errors are for http2 version

*~95% of the request are from mobile devices

*almost all clients are alive (we see that from logs because after failed request client side javascript issues another request to different endpoint)

*There is no time pattern - sometimes client gets 499 after just 0.1 second, sometimes 3-9 seconds

*Logs don't indicate any problems on the node upstream, and this happens regularly, and there is no heavy load.

I've tried adding keepalive to upstream, and enabling proxy_ignore_client_abort, but that does not seem to help.
Any hints how to troubleshoot this?

A: I was reading this unanswered question which suggests that one potential source is from impatient clients hitting the refresh button.
This seems to be consistent with your observation that clients are alive, and there are requests after getting 499.


text:
Q: How can I fix a 'Undefined control sequence' error in order to convert a JupyterNotebook to PDF?
Hello everyone,
since this is my first post here (even though not my first time, because I've spent hours reading some of your brilliant answers over time), I hope you guys will forgive me initial mistakes, when it comes to writing a proper post.
I have a problem when trying to convert a JupyterNotebook, that runs on AWS SageMaker to PDF using nbconvert.
I am using the following command via the terminal:
jupyter nbconvert --to pdf MyNotebook.ipynb

And instead of the notebook converting into a PDF, I'll end up with the following error:
! Undefined control sequence.
\AfterEndPreamble ->\AddToHook
                               {begindocument/end}
l.158 \AfterEndPreamble
                       {%
?
! Emergency stop.
\AfterEndPreamble ->\AddToHook
                               {begindocument/end}
l.158 \AfterEndPreamble
                       {%
No pages of output.

Converting it to a .tex file, however, works without any problems.
Now I've spend the last hour, trying to solve this issue by searching the web and looking at similar problems, but for the first time I couldn't find any solution to my specific issue yet.
So I hope, some of you will be able to help me with it.
Appreciate it!


text:
Q: Application_End Not Running I'm new to C#, so please bear with me.
I have a function that runs in the Application_Start function in the Global.asax.cs file, and this works fine when I start debugging.
But when I stop debugging, the function I have in the Application_End function doesn't seem to fire off.  I'm wondering if this has to do with debugging, or is just an error in my code.

A: I guess the application never ended. While you are debugging (using Cassandra or IIS Express) or running an installation on IIS itself the application doesn't end when your debugging session ends.
On IIS it ends when the worker process stops. This happens automatically after some time, depending on your application pool settings.
In Cassandra and IIS Express it will happen when the process ends gracefully. I wonder if they get ever called on a regular basis on those installations.

A: I had a similar issue where Application_End was not called because there were threads running when the application was asked to stop, and because this method is only called after everything has stopped fine.
Then, I discovered Application_Disposed. From http://www.techrepublic.com/article/working-with-the-aspnet-globalasax-file/5771721/ :

Application_Disposed: Fired just before an application is destroyed. This is the ideal location for cleaning up previously used resources.

A: Its in general not a good idea to put a lot of code in Application_End that you need to rely on firing.  Consider that an ApplicationInstance is started to each thread of the work process that will be serving your application, you will run into scenarios where your Application_End will be called frequently on a busy site as traffic ebbs and flows.
You may find it easier to use a Cache object with a sliding expiration and a callback function when the object expires from Cache to ensure that your clean up code is called properly when you need it.
http://msdn.microsoft.com/en-us/library/05kd8d77(v=vs.110).aspx


text:
Q: Fix a div using position:fixed for a particular direction Is there a way to fix a div using position:fixed in only top to bottom direction; i.e when I scroll from left to right the div should not be fixed. It should behave as a absolute positioned element. It should be fixed only when I scroll from top to bottom. Is it possible?

A: It's not possible, because it's not supposed to be.
The action of "scrolling" may be very different from a browser to an other... from a device to an other... So it's not predictable.

A: If you want pure good solution then, I would recommend you use jQuery.
If you will implement it using CSS then it may not be smooth.


text: Q: Is there anything similar to hashlimit for mac address? The hashlimit module works basically like 'limit' but can be used with source IP, destination port, destination IP and source port, thanks to the –-hashlimit-mode option. Is there anything similar that allows to use the mac address as well (something like "–-hashlimit-mode srcmac,dstmac")?


text:
Q: Does can Zabbix send log in mail after fail restart service I have one question about Zabbix Action functions.
I configured some trigger, example for MySQL down. For this trigger I created Zabbix Action with 2 Steps.
Step 1. Zabbix run remote script to restart MySQL service. After 1 minutes if service still down zabbix run the second step.
Step 2. Zabbix send email.
My question is:
Can I add the last 15 rows of mysql-error.log in that mail?

A: You need change the default zabbix email by customs scripts. This script will read the last 15 lines of log file and then append this lines in the email.
Access Zabbix with a admin account and then Administration, Media Types, Create Media Type choose type = script.
In "Script Name" put the name of the script ou create do send email. This script must be in ZABBIX_HOME/alertscripts.
Configure your action to use this media type.
The docs are always your friend


text:
Q: How to update huge sql data in asp .net application using c# I am doing web application using c# .net and sql server 2008 as back end. Where application read data from excel and insert into sql table. For this mechanism I have used SQLBulkCopy function which work very well. Sql table has 50 fields from which system_error and mannual_error are two fields. After inserting records in 48 columns I need to re-ckeck all this records and update above mentioned two columns by specific errors e.g. Name filed have number, qty Not specified etc. For this I have to check each column by fetching in datatable and using for loop.
Its work very well when record numbers are 1000 to 5000. But it took huge time say 50 minutes when records are around 100,000 or more than this.
Initially I have used simple SQL Update Query then I had used stored procedure but both requires same time.
How to increase the performance of application? What are other ways when dealing with huge data to update? Do suggestions.

A: I hope this is why people use mongodb and no SQL systems. You can update huge data setsby optimizing your query. Read more here:
http://www.sqlservergeeks.com/blogs/AhmadOsama/personal/450/sql-server-optimizing-update-queries-for-large-data-volumes
Also check:Best practices for inserting/updating large amount of data in SQL Server 2008

A: One thing to consider is that iterating over a database table row by row, rather than performing set based update operations would incur a significant performance hit.
If you are in fact performing set based updates on your data and still have significant performance problems you should look at the execution plan of your queries so that you can workout where and why they are performing so badly.


text:
Q: I am converting a Bootstrap theme into Wordpress but I cannot get my scripts to load in and run Here is my repos on GitHub for the theme: https://github.com/RyanChrist4/ryanstrap
What I have done is removed the script tags from the head and put them into the functions.php file using the wp_register_script function and the wp_enqueue_script function. I have looked at the answers for other peoples similair questions and tried formatting it like them but I still cant get the scripts to run. I am new to web development and new to Wordpress. Also, in the header, there is a script tag that is calling multiple function but I get an error in the console that says "Uncaught Reference error.
Here is my the code in my functions.php file:
    <?php
//jQuery Insert From Google
if (!is_admin()) add_action("wp_enqueue_scripts", "my_jquery_enqueue");
function my_jquery_enqueue() {
   wp_deregister_script('jquery');
   wp_register_script('jquery', "http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js", false, null);
   wp_enqueue_script('jquery');
}
//Launches all of the scripts below
add_action("wp_enqueue_scripts", "launch_scripts");
function launch_scripts() {
    wp_enqueue_script('the-flexslider', get_template_directory_uri() . '/assets/js/jquery.flexslider-min.js');
    wp_enqueue_script('the-fitvids', get_template_directory_uri() . '/assets/js/jquery.fitvids.js');
    wp_enqueue_script('the-smoothscroll', get_template_directory_uri() . '/assets/js/jquery.smooth-scroll.min.js');
    wp_enqueue_script('the-backstretch', get_template_directory_uri() . '/assets/js/jquery.backstretch.min.js');
    wp_enqueue_script('the-bootstrap', get_template_directory_uri() . '/assets/js/bootstrap.js');
    wp_enqueue_script('the-bootstrapmin', get_template_directory_uri() . '/assets/js/bootstrap.min.js');
    wp_enqueue_script( 'the-gmaps', get_template_directory_uri() . '/http://maps.google.com/maps/api/js', array(), '20120206', true );
    wp_enqueue_script('the-mgmaps', get_template_directory_uri() . '/assets/js/gmaps.js');
    wp_enqueue_script('the-script', get_template_directory_uri() . '/assets/js/script.js');
}
?>

Here is the content of my header.php file:
    <!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
        <title><?php bloginfo( 'title' ); ?></title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta name="description" content="A very good admin theme" />
        <meta name="author" content="AHthemes" />

        <link rel="stylesheet" type="text/css" href="<?php bloginfo('stylesheet_url'); ?>"media="screen" />

        <link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/ico/apple-touch-icon-144-precomposed.png">
        <link rel="apple-touch-icon-precomposed" sizes="114x114" href="assets/ico/apple-touch-icon-114-precomposed.png">
        <link rel="apple-touch-icon-precomposed" sizes="72x72" href="assets/ico/apple-touch-icon-72-precomposed.png">
        <link rel="apple-touch-icon-precomposed" href="assets/ico/apple-touch-icon-57-precomposed.png">
        <link rel="shortcut icon" href="assets/ico/favicon.png">
<?php
  wp_head();
?>

Home

About

Work

Contact

A: If I can believe the documentation, you don't need to register the script first:

wp_enqueue_script - Registers the script if $src provided (does NOT overwrite), and enqueues it.

Read more here.
<?php
//jQuery Insert From Google
if (!is_admin()) add_action("wp_enqueue_scripts", "my_jquery_enqueue");
function my_jquery_enqueue() {
   wp_deregister_script('jquery');
   wp_register_script('jquery', "http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js", false, null);
   wp_enqueue_script('jquery');
}
//Launches all of the scripts below
add_action("wp_enqueue_scripts", "launch_scripts");
function launch_scripts() {
    wp_enqueue_script('the-flexslider', get_template_directory_uri() . '/assets/js/jquery.flexslider-min.js');
    wp_enqueue_script('the-fitvids', get_template_directory_uri() . '/assets/js/jquery.fitvids.js');
    wp_enqueue_script('the-smoothscroll', get_template_directory_uri() . '/assets/js/jquery.smooth-scroll.min.js');
    wp_enqueue_script('the-backstretch', get_template_directory_uri() . '/assets/js/jquery.backstretch.min.js');
    wp_enqueue_script('the-bootstrap', get_template_directory_uri() . '/assets/js/bootstrap.js');
    wp_enqueue_script('the-bootstrapmin', get_template_directory_uri() . '/assets/js/bootstrap.min.js');
    wp_enqueue_script( 'the-gmaps', '//maps.google.com/maps/api/js');
    wp_enqueue_script('the-mgmaps', get_template_directory_uri() . '/assets/js/gmaps.js');
    wp_enqueue_script('the-script', get_template_directory_uri() . '/assets/js/script.js');
}
?>

A: please try this line
wp_enqueue_script( 'the-gmaps', get_template_directory_uri() . '/http://maps.google.com/maps/api/js', array(), '20120206', true );

A: This sounds like a JavaScript issue, compounded by WordPress.
Generally, when someone mentions "Uncaught reference error" it has to do with your scripts depending on something, and that thing not being loaded yet.
That's my hunch.
To do that, your code should be changed to the following -- I cleaned up your code :-)
Also fixed some code errors, you have one of your external scripts being loaded in badly (the gmap thing).
<?php

    // Replace Core jQuery version with 1.7.1 (Bootstrap Theme Requirement)
    // WordPress 4.5 includes 1.12.3
    // Only do this when we are not within the Administration area of WordPress.
    if (!is_admin()) {
        add_action("wp_enqueue_scripts", "replace_jquery");
    }

    function replace_jquery() {
        wp_deregister_script('jquery');
        wp_register_script('jquery', "//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js", false, '1.7.1', false);
        wp_enqueue_script('jquery');
    }

    // Load all of the scripts below, on every single page. :-\
    add_action("wp_enqueue_scripts", "launch_scripts");
    function launch_scripts() {
        $internal_path = get_template_directory_uri() . '/assets/js/';
        wp_enqueue_script('the-flexslider', $internal_path . 'jquery.flexslider-min.js', array('jquery'));
        wp_enqueue_script('the-fitvids', $internal_path . 'jquery.fitvids.js', array('jquery'));
        wp_enqueue_script('the-smoothscroll', $internal_path . 'jquery.smooth-scroll.min.js', array('jquery'));
        wp_enqueue_script('the-backstretch', $internal_path . 'jquery.backstretch.min.js', array('jquery'));
        wp_enqueue_script('the-bootstrap', $internal_path . 'bootstrap.js', array('jquery'));
        wp_enqueue_script('the-bootstrapmin', $internal_path . 'bootstrap.min.js', array('jquery'));
        wp_enqueue_script('the-gmaps', '//maps.google.com/maps/api/js', array('jquery'), '20120206', true);
        wp_enqueue_script('the-mgmaps', $internal_path . 'gmaps.js', array('jquery'));
        wp_enqueue_script('the-script', $internal_path . 'script.js', array('jquery'));
    }
?>


text:
Q: Transform a JsonProperty in another Type based on the Property value I have this JsonProperty defined in my object to serialize to JSON:
[JsonProperty(PropertyName = "client_state")]
public Boolean IsRunning { get; set; }

What I want to achieve is to transform the JSON "client_state" so that the JSON property will be a string containing the text "isrunning" when the IsRunning property is true and "notrunning" when the IsRunning property is false.
How can I define this transformation during JSON serialization?

A: You could add an intermediate property to perform the serialization and ignore the original one
[JsonProperty(PropertyName = "client_state")]
public string ClientState => IsRunning ? "isrunning" : "notrunning";

[JsonIgnore]
public Boolean IsRunning { get; set; }


text:
Q: JHipster, spring rest service with MultiPart and JSON, swagger/curl error I am having problems with JHipster to publish a rest spring service.
The service includes a MultipartFile, parameters and a JSON object. To my knowledge, I should be able to publish as follows:
public @ResponseBody
    ResponseEntity<DocumentId> addDoc(@RequestPart(required = true) MultipartFile file, @RequestPart(required = false) String folder, @RequestPart(required = true) MetadataDoc metadata)

The swagger api does not recognize the parameter "metadata" declaring it as "undefined"data type. And when I try to make a curl request, I get the following error:
2016-09-30 13:27:15.174  WARN 30451 --- [ XNIO-2 task-12] .m.m.a.ExceptionHandlerExceptionResolver : Resolved exception caused by Handler execution: org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'text/plain;charset=UTF-8' not supported
2016-09-30 13:27:15.298 DEBUG 30451 --- [ XNIO-2 task-14] c.q.smartgov.aop.logging.LoggingAspect   : Enter: com.queres.smartgov.web.rest.errors.ExceptionTranslator.processRuntimeException() with argument[s] = [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'text/plain;charset=UTF-8' not supported]
2016-09-30 13:27:15.298 DEBUG 30451 --- [ XNIO-2 task-14] c.q.smartgov.aop.logging.LoggingAspect   : Exit: com.queres.smartgov.web.rest.errors.ExceptionTranslator.processRuntimeException() with result = <500 Internal Server Error,com.queres.smartgov.web.rest.errors.ErrorVM@3d872331,{}>

The curl request:
curl -X POST --header 'Content-Type: multipart/form-data' --header 'Accept: application/json' --header 'Authorization: Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsImF1dGgiOiJST0xFX0FETUlOLFJPTEVfVVNFUiIsImV4cCI6MTQ3Njk3NjY3N30.82FRMRSrrniEQcIhI6DtHEFf5ln3OSjS_6OWy-1d8h3Cp5MjRuxo04IuIxAX_WC8YJJ1QyLrq7loLUSQ8RV_Gw' -F file=@"result.txt" -F folder=folde -F metadata={"clave":"2","valor":"1"}  'http://127.0.0.1:8080/sd_api/api/almacen/addDoc'

I have tried a lot of things, any suggestion?
Thanks in advance!

A: Finally I took the solution of declare JSON parameter as a String, an parse it by myself.
If anybody knows how to publish the parameter as JSON Object I will appreciate any clue.
 ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.readValue(stringValue, mapper.getTypeFactory().constructCollectionType(List.class, MetadataDoc.class));
        } catch (IOException ex) {
            //throw exception
        }


text:
Q: Преобразовать byte[] в объект На входе есть строка, которую необходимо преобразовать в объект. Делаю так
byte[] file = System.Text.Encoding.UTF8.GetBytes(sign);
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf
= new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
MemoryStream ms = new MemoryStream(file);
ms.Position = 0;
object obj = bf.Deserialize(ms);

Получаю ошибку

Недопустимый двоичный формат входного потока. Начало содержимого (в
  байтах):

Если сохраняю в файл
File(System.Text.Encoding.UTF8.GetBytes(sign), "application/text", name)

то получаю файл, который проходит проверку без ошибок.


text:
Q: O if do codigo php não executa só o else <form method="GET">
    salário: <input type="number" name="salario">

    tempo de serviço (em meses): <input type="number" name="tds">

    n° reclamações: <input type="number" name="rec">

    <input type="submit" name="calcular">
</form>

<?php
if (!empty($_GET["salario"]) && !empty($_GET["tds"]) && !empty($_GET["rec"])) {

    $salario=$_GET["salario"];
    $tds=$_GET["tds"];
    $rec=$_GET["rec"];

    $nsal=($salario*0.2);

    if (($salario > 1000) && ($tds > 12) && ($rec == 0)) {

        echo "Você foi promovido, parabéns.";
        echo "E ganhou um aumento de salário. Seu novo salário é: $nsal";

    } else{
        echo "Sem novidades, volte depois.";
    }
 }

?>

A: O problema é que você está usando o empty() para o rec, se o valor for 0, o PHP considera com vazio. Troque o empty() por isset() que vai funcionar.
Veja o exemplo:
if (isset($_GET["salario"]) && isset($_GET["tds"]) && isset($_GET["rec"])) {
  // lógica aqui
}

Espero ter ajudado.


text:
Q: XML files to dataframe - Brazilian Senate Good afternoon, everyone!
I am relatively new to R and during my experience, I have had never had to deal with XML files. However, I am currently on a project in which I need to open the nominal votes for the Brazilian Senate (you can find the data here: https://www12.senado.leg.br/dados-abertos/legislativo/plenario/votacoes-nominais) from 1991 to 2019 and all the files are XML.
I have already done the same process for the Brazilian Congress but files were csv. The data frame that I am trying to get needs to has the following parameters:
CodigoSessao; SiglaCasa; CodigoSessaoLegislativa; TipoSessao; NumeroSessao; DataSessao;
HoraInicio; CodigoSessaoVotacao; SequencialSessao; Secreta; DescricaoVotacao; Resultado; VotoParlamentar; CodigoParlamentar; NomeParlamentar; SexoParlamentar; SiglaPartido; SiglaUF; Voto;
I would really apreciate any guidance on how to deal with these data. Also, if you have any problems with all the Portuguese, please send me a message here or even an e-mail (gbrogim@hotmail.com). I will respond as soon as possible and help you with the translation (I want to help you help me :)
Thank you for your attention.


text:
Q: Fast import whole SQL table (using cache?) I use DBI and RMySQL package to import the whole table from the database. The code works as expected. I would like to know is there a faster way to import the same table multiple times? For example, I import the table, do some calculations, close the R session, and then import the same table again tomorrow. Is there a way to somehow cache that table and import the same table in a faster way?
The code example (working as expected):
library(RMySQL)
library(DBI)

# coonect to database
connection <- function() {
  con <- DBI::dbConnect(RMySQL::MySQL(),
                        host = "91.234.xx.xxx",
                        port = 3306L,
                        dbname = "xxxx",
                        username = "xxxx",
                        password = "xxxx",
                        Trusted_Connection = "True")
}

# imoprt
db <- connection()
vix <- DBI::dbGetQuery(db, 'SELECT * FROM VIX')
invisible(dbDisconnect(db))


text: Q: How can I tell what is dirty in my modal form? In my  ABP 4.2 Angular project I've added got a modal with two form groups in it. When you save the modal I'm firing the data off via my service proxy and I want the form to remain open so the user can continue editing. To achieve this I've removed the default tap(() => this.hideForm()) that ABP adds by default. I'm calling this.form1.markAsPristine() and this.form2.markAsPristine() but when I click the Cancel button after the Save has completed I still get the Confirmation modal telling me I've got unsaved changes. How can I tell what is causing this Confirmation modal to fire? How can I find out what pending changes I still have in the modal?


text:
Q: A minor point in Serre's Representation Theory Let $R$ be a commutative ring of characteristic zero, $G$ a finite group. For each conjugacy class $[x]$ in $G$, define $e_{[x]} = \sum_{s\in[x]}s$. It is easily checked that these $\{e_{[x]}\}_{x\in G}$ form a basis for $Z(\mathbb{C}[G])$. Serre makes the claim that

"... each product $e_{[x]}e_{[y]}$ is a linear combination with integer coefficients of the $e_{[z]}$."

While I can see how these $e_{[x]}$'s form a basis for $Z(\mathbb{C}[G])$, for some reason I can't see this fact as easily. In fact, I can't even intuit why $e_{[x]}e_{[y]}$ should also be an element of $Z(\mathbb{C}[G])$ when written out as
$$
e_{[x]}e_{[y]} = \left(\sum_{g\in G}gxg^{-1}\right)\left(\sum_{h\in G}hyh^{-1}\right) = \sum_{g,h\in G}gxg^{-1}hyh^{-1}
$$
To me it's not clear at all that the above double sum is "a linear combination with integer coefficients of the $e_{[z]}$." Can someone provide some insight?

A: Well, since $e_{[x]}$ and $e_{[y]}$ are both in $Z(\mathbb{C}[G])$, so is their product.  Moreover, it is clear that $e_{[x]}e_{[y]}$ is an integer linear combination of elements of $G$ (since it is just some sum of elements of $G$).  But since it is in $Z(\mathbb{C}[G])$, the coefficients must be constant on each conjugacy class, and so it is in fact an integer linear combination of $e_{[z]}$'s.
To see this more explicitly from the expression $$e_{[x]}e_{[y]} = \sum_{g,h\in G}gxg^{-1}hyh^{-1},$$ note that $$k(gxg^{-1}hyh^{-1})k^{-1}=(kg)x(kg)^{-1}(kh)y(kh)^{-1}.$$ So, this sum is unchanged if you conjugate by $k$: the terms just get permuted, with the term indexed by $(g,h)$ becoming the term indexed by $(kg,kh)$.

A: If $z=gxg^{-1}hyh^{-1}\in[x][y]$ and $\gamma\in G$ we have
$$
\gamma z\gamma^{-1}=(\gamma g)x(g^{-1}\gamma^{-1})(\gamma h)y(h^{-1}\gamma^{-1})\in[x][y]
$$
so that $[x][y]$ is a union of conjugacy classes.
The coefficient of $z\in G$ is the cardinality of the set
$$
P_z=\{(g,h)\in G\times G\,|\, z=gxg^{-1}hyh^{-1}\}.
$$
The same formula above says that multiplication by $\gamma$ embedded diagonally in $G\times G$ gives a bijection between $P_z$ ad $P_{\gamma z\gamma^{-1}}$ so that the coefficients are the same for all the elements in the same conjugacy class.


text:
Q: Is there a faster alternative to Map in Haxe when transpiling to php Haxe
public var bonus:Map<Int,Int>;

if (bonus.exists(id))
    score += bonus.get(id);

Compiles to the following php
if($bonus->exists($id))
    $score += $bonus->get($id);

Ideally I'd like haxe to generate
if(isset($bonus[$id]))
    $score += $bonus[$id];

I suspect it would be possible using dynamic however I'd like to avoid using dynamic as it is not recommended.  Exists is unnecessary in php but will not compile for our as3 target.  Current profiling shows exists (50% of execution time) and get (30%) are quite expensive.  I'd hope that it would be possible to either use the built in array type or at least inline the exists and get calls.  Can anyone tell me how or recommend a better way of doing this?
Thanks

A: For PHP's isset(), you may simply compare the variable with null, ie. "myVar != null".
if(bonus[id] != null)
    score += bonus[id];

or with ternary operator
score += (bonus[id] != null) ?: bonus[id];

Sidenote:
I believe, you could also try a PHP in_array() solution by using Lambda.has(arrayOrMap, "key");. But i don't know exactly if Lambda.has works on Maps.
But still, the != would be faster than a call to in_array().


text:
Q: How can I draw the histogram of date values group by month in each year in Python? I wrote this code to draw the histogram of date values in each month. It shows the number of dates for each month in the whole dataset. But I want the histogram to be for each month in each year.That is, for example, I should have January through December for year1, and then January through December for year2 and so on.
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

pd.options.display.mpl_style = 'default'

sns.set_context("talk")

df = pd.read_csv("data.csv", names=['lender','loan','country','sector','amount','date'],header=None)
date=df['date']
df.date = date.astype("datetime64")
df.groupby(df.date.dt.month).count().plot(kind="bar")

A: According to the docstring the groupby docstring, the by parameter is:

list of column names. Called on each element of the object index to determine the groups. If a dict or Series is passed, the Series or dict VALUES will be used to determine the groups

So your code simply becomes:
df = pd.read_csv(...)
df['date'] = df['date'].astype("datetime64")
df['year'] = df['date'].dt.year
df['month'] = df['date'].dt.month
df.groupby(by=['month', 'year']).count().plot(kind="bar")

But I would write this as:
ax = (
    pandas.read_csv(...)
        .assign(date=lambda df: df['date'].astype("datetime64"))
        .assign(year=lambda df: df['date'].dt.year)
        .assign(month=lambda df: df['date'].dt.month)
        .groupby(by=['year', 'month'])
        .count()
        .plot(kind="bar")
)

And now you have a matplotlib axes object that you can use to modify the tick labels (e.g., matplotlib x-axis ticks dates formatting and locations)


text:
Q: Creating a Yii webapp without command line? To install the Yii Framework, after unpack the file the tutorial always told me to enter text in command line like this : -
yiic webapp testing01

Is there anyway to do it not by the command line ?

Edit :
I wonder why this is off-topic.
ok, here is something for refence  :
In the book "Agile Web Application Development with Yii1.1 and PHP5" (by Jeffrey Winesett) in Chapter 2: Getting Started. Page 23.

To create a new application, we are going to use a little powerhouse of a tool known as yiic that comes packaged with the framework. This is a command-line tool that one can use to quickly jumpstart a brand new Yii application. It is not mandatory to use this tool, but it saves a lot of time and guarantees that the proper folder and file structure is in place.

It said "It is not mandatory to use this tool", which means there is some way to create a yii webapp without yiic (which is the command line way I mention).
so here my question again : How to Creating a Yii webapp without using the 'command line' tool, yiic ?

A: You can use some IDE.
For example Netbeans. There is Yii plugin installed there(if not installed, then install it). Simply creat new Project step by step. At the end there would be "select framework" option. chouse Yii framework. if everything is ok with settings of PHP it will install yii automatically. (It may ask base yii file, if so you can point to yiic.php)


text:
Q: PRIMARY key must be unique (Code 19) Android, Unable to overwrite table record I'm trying to import .CSV file into a table but it returns error as mention below

CSV import error:
PRIMARY key must be unique (Code 19)
"2","Aortic",".","1","0","3","","0","0","","0"

I'm using a Android application called aSQlite Manager ( Google Play store) to export and import .CSV files.
Database file belongs to   MyWordBook [by Frozened,  com.frozenarts.mynotebook ] , An App i use to build  my vocab words. This application  has very nice user interface but it lacks IMPORT word list feature, i'm trying to manually import my word list, developer won't respond and there is no good alternative app i can find.
It has IMPORT/EXPORT database feature though.
Mynotebook.db and mots.csv in .zip
'Mots' is  name of the table where word list data is stored. You can do it one by one, no problem but will take months for me.
I've tried importing and exporting .csv file without any edits(identical) ,it still throws an error. What is going wrong here? How to solve it?
PS: My word list has over 4000 words

A: There are one or more entries in your CSV file with the same primary key. In your case the word Aortic has an ID of "2" which already exists in your database.


text:
Q: Use variable as role name in function postgresql Can't use variable as role name
I tried to create function with trigger on insert, witch perform some grant statements for given id's. I declared some variable with id value and have to use it as role name.
CREATE OR REPLACE FUNCTION permissions() RETURNS trigger
    LANGUAGE plpgsql
    AS $permissions$
    DECLARE
        id varchar  := NEW."id"; --this variable will contain user name ex. "valid.user"
    BEGIN
        GRANT USAGE ON SCHEMA zakupy TO id;
        RETURN NEW;
    END;
$permissions$;

CREATE TRIGGER permissions_insert AFTER INSERT ON public.permissions FOR EACH ROW EXECUTE PROCEDURE permissions();

When I add new row i have error message  ERROR:  role "id" does not exist.
If I replace id to "valid.user":
GRANT USAGE ON SCHEMA zakupy TO "valid.user"

statement works perfectly.

A: try this :
CREATE OR REPLACE FUNCTION permissions() RETURNS trigger
LANGUAGE plpgsql
AS $permissions$
DECLARE
    id varchar  := NEW."id"; --this variable will contain user name ex. "valid.user"
BEGIN
    execute 'GRANT USAGE ON SCHEMA zakupy TO "'||id||'"';
    RETURN NEW;
END;
$permissions$;


text:
Q: Setting my RSS Feed on ROMETOOL with spring boot app I'm looking for a way to set my RSS Feed with ROMETools. I have a spring boot blog web app. want to embed the RSS feed URL into an email marketing app to read that feed.
The problem is I couldn't find anywhere in the net setting the feed items automatically, for example, everyone setting the URL and description manually like "hi this my description" and also they have the post URL entered manually like "www.domain.postId?id=20"! what I need is the blog URL detected automatically with title, body, etc... Any ideas, anyone has implemented that earlier would be a big favourite. Thanks in advance.
What I have learned is:
1- embed the dependency in POM:
<dependency>
   <groupId>com.rometools</groupId>
    <artifactId>rome</artifactId>
    <version>1.12.2</version>
</dependency>

2-Expose the RSS Feed URL:
@RestController
public class RssFeedRestController {
    @Autowired
    private RssFeedView view;

    @GetMapping("/rss")
    public View getFeed() {
        return view;
    }
}

3-Extend the AbstractRssFeedView as a @Component
@Component
public class RssFeedView extends AbstractRssFeedView {

    @Override
    protected void buildFeedMetadata(Map<String, Object> model, Channel channel, HttpServletRequest request) {
        channel.setTitle("Title"); //Here is my Concern
        channel.setDescription("Description"); //Here is my Concern
        channel.setLink("www.mydomain.com"); //Here is my Concern
        channel.setUri("www.mydomain.com"); //Here is my Concern
    }

    @Override
    protected List<Item> buildFeedItems(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) {

        Item item = new Item();
        Date postDate = new Date();
        item.setTitle("title"); //Here is my Concern
        item.setLink("www.mydomain.com/"); //Here is my Concern
        item.setUri("/www.mydomain.com/"); //Here is my Concern
        item.setPubDate(postDate);
        item.setAuthor("Me");
        Description description = new Description();
        description.setValue("Description"); //Here is my Concern
        item.setDescription(description);

        return Arrays.asList(item);
    }
}


text:
Q: InitWithCoder, [super init] or [super initWithCoder]? Can I ask which version I should be using, in my older apps I seem to be using "B" but when I look at a lot of examples online I am seeing a lot of versions that look like "A".
// A
- (id)initWithCoder:(NSCoder *)decoder {
    self=[super initWithCoder:decoder];
    if(self) {
        ...

OR
// B
- (id)initWithCoder:(NSCoder *)decoder {
    self=[super init];
    if(self) {
        ...

A: Depends on whether the superclass conforms to the NSCoding protocol or not. If it does, you must call [super initWithCoder:decoder]. If it does not, you must call the superclass' designated initializer.
For example, if your class is a direct subclass of NSObject, you would call [super init], NSObject's designated initializer, since NSObject does not conform to the NSCoding protocol.

A: If the superclass adopts NSCoding (which is likely albeit not always the case), always call
[super initWithCoder:decoder]

Otherwise call its designated initializer.


text:
Q: Is there a way to count unsaved column cells in ASP.NET mvc telerik then create a pop up window when the user hasnt saved after 10 rows Currently I am trying to count the number of unsaved columns a user has edited so that a pop up window will remind them to save or periodically produce the pop up message again.
My problem is i cant seem to get it to work lol, I can create the pop up window and it loads on open or refresh but it doesnt open when i have over 10 like the code is asking. Infact I havent been able to get any console.logs to the console window to debug if its even working and frankly im looking for some help with solving
<script>

    function onClose() {
        //$("#showDialogBtn").fadeIn();

    }

    function onOpen() {
       // $("#showDialogBtn").fadeOut();

    }

    function showDialog() {
        /*
    The general idea here is that you count the total number of
    unsaved columns before you release the show dialog
    */
        $('#dialog').data("kendoDialog").open();

        var ucc; // create total unsaved column count
        var grid = $('#Grid').data("kendoGrid");
        var gridData = grid.dataSource.view();

        for (var i = 0; i < gridData.length; i++) {
            (ucc += gridData[i].eTmfCompletenessComment);
        }
        if (ucc >= 10) {
            $('#dialog').data("kendoDialog").open();
            // $("#showDialogBtn").fadeOut();
        }
        else {
            kendoConsole.log(ucc)
        }

    }

</script>

A: This is how you would register unsaved changes and then alert if there are any
<script type="text/javascript">
    window.addEventListener("beforeunload", function (e) {
        var confirmationMessage = 'It looks like you have been editing something. '
            + 'If you leave before saving, your changes will be lost.';

        (e || window.event).returnValue = confirmationMessage; //Gecko + IE
        return confirmationMessage; //Gecko + Webkit, Safari, Chrome etc.
    });
</script>


text:
Q: Inheriting object and auto populate When I want to extend an existing Object I create my own and use inherits clause, and works fantastic... problem is when I want to use this new Object instead of the original, the populate part is a "pain".
is there any AUTO POPULATE way of doing this?
Original Object: Customer
My Object: CustomerWithGroup
public class CustomerWithGroup : Customer
{
    public CustomerWithGroup() { }
    public string GroupName { get; set; }
    public string Fullname
    {
        get
        {
            return string.Format("{0} {1} {2}", firstname, middlename, lastname).Replace("  ", " ");
        }
    }
}

and I'm populating it like this:
customerswithgroup = new List<CustomerWithGroup>();
string groupname;
foreach (Customer c in customers)
{
    groupname = customergroup.Find(x => x.customer_group_id == c.group_id).customer_group_code;

    customerswithgroups.Add(
        new CustomerWithGroup {
            GroupName = groupname,
            created_at = c.created_at, customer_id = c.customer_id, default_billing = c.default_billing, default_shipping = c.default_shipping, email = c.email, firstname = c.firstname, group_id = c.group_id, increment_id = c.increment_id, lastname = c.lastname, middlename = c.middlename, password_hash = c.password_hash, prefix = c.prefix, store_id = c.store_id, suffix = c.suffix, taxvat = c.taxvat, updated_at = c.updated_at, website_id = c.website_id });
}

It's a bunch of code! and you can imagine doing this for really big objects!
Ins't there a way of telling, like

Hei object, please load all the base members from this Object!

newCG = new CustomerWithGroup().LoadFromBase(c);
newCG.groupName = "my group";
customerswithgroup.Add( newCG );

Is there any trick we can use?

A: No, there is no easy way. You could use reflection and write a bunch of code to do that, but it would be a lot of work.
In my opinion you should rethink your design. Inheritance is not a good solution in this case, composition here is better, like so:
public class CustomerWithGroups
{
    public CustomerWithGroups(Customer c) { Customer = c; }

    public Customer Customer { get; private set; }

    public string GroupName { get; set; }
    public string Fullname
    {
        get
        {
            return string.Format("{0} {1} {2}", Customer.firstname, Customer.middlename, Customer.lastname).Replace("  ", " ");
        }
    }
}

A: You cannot easily do this automatically.
You could make a constructor or method in the derived class that takes an instance of the base class and copies all of the properties.  (You'd still need to write it by hand, but you'd only need to write it once)
If you really want to do it automatically, you could use reflection to loop through the properties and make an expression tree that copies them from an original.
However, the best way is to use a has-a relationship, making CustomerWithGroups not inherit Customer and instead have a read-only Customer property of type Customer.


text:
Q: Custom Icon in gtk toggle_action I have the following code which adds a toolbar icon "gtk-info" (from stock) to a python Gtk+ window. I would like to have a custom icon instead. How would I do that?
    self.action = ('ActivateSqueezeboxMode','gtk-info', _('SqueezeboxTools'),
                    None, _('Activate Squeezebox mode'),
                    self.activate_button_press, True)
    self.action_group = gtk.ActionGroup('SqueezeboxPluginActions')
    self.action_group.add_toggle_actions([self.action])
    uim = self.shell.get_ui_manager()
    uim.insert_action_group (self.action_group, 0)
    self.ui_id = uim.add_ui_from_string(context_ui)
    uim.ensure_update()

A: Try this:
self.action = ('ActivateSqueezeboxMode', None, _('SqueezeboxTools'),
                None, _('Activate Squeezebox mode'),
                self.activate_button_press, True)
self.action_group = gtk.ActionGroup('SqueezeboxPluginActions')
self.action_group.add_toggle_actions([self.action])
# now get your action back out of the action group so you can modify it
action = self.action_group.get_action('ActivateSqueezeboxMode')
action.set_icon_name('my-custom-icon')

to use a named icon, or
action.set_gicon(my_custom_gicon)

as the last line to use a gio.Icon (see for example gio.FileIcon.)


text:
Q: Can "modality" mean "having modes?" A widget has one button. This button performs different functions depending on the widget's mode at the time the button is pressed.
Can this be said to have modality, or a modal design?

A: This quote from Jeff Raskin's book, The Humane Interface (courtesy of wikipedia) gives a good definition for "modal" in this context:

An human-machine interface is modal
  with respect to a given gesture when
  (1) the current state of the interface
  is not the user's locus of attention
  and (2) the interface will execute one
  among several different responses to
  the gesture, depending on the system's
  current state.

In your case, the "gesture" is "clicking on the widget's button", so the word "modal" is applicable here.
In general English usage the word "modality" means "having or related to modes" (for instance one might refer to "the modality of the music" about modal music), so your example would technically be correct. However, since the word "modality" has a specific different meaning within the context of user interface design, you might be advised to express yourself differently avoid confusion.

A: In computing a mode is "a way of operating or using a system," so if your widget has different ways of operating, which apparently it does, then it could be said to have a modal design.

A: In my experience, there are only two recognised uses of modality in computing:

*

*Modal Dialogs/Windows - These force interaction from the user; that is, the user must interact with the dialog (and ultimately dismiss it) in order to continue with other operation - http://en.wikipedia.org/wiki/Modal_window

*Human Computer Interaction (HCI) - Modality is the means of communication between the user and the computer (e.g. audio, visual, tactile)

Neither of these fit your scenario. That's not to say it is entirely wrong - model does mean 'pertaining to mode or form' - but at best, its use in this context might be unclear
Instead, I would say the button on your widget is multi-functional, context-sensitive or mode-sensitive/mode-dependent - I think mode-sensitive would be my preference.

A: I prefer to use modal design, even if modality means also modal quality.
The phrase modal dialog, though, could be understood to have a different meaning, as it is normally used to mean a dialog window that blocks its parent window until it is open. If you think that modal design can be confused with that, then I would use modality.


text:
Q: If A = BC and B is invertible why must null(A) = null(C) Hey I'm reviewing for my linear exam and on the review sheet my teacher asks me...
  Suppose A = BC where B is an invertible matrix, then null(A) = null(C).

I see that the answer is "true" in the solutions but I really have no clue why. is it just that for any vector v s.t. Av = 0, and knowing that A = BC, BCv must also be zero and we can reduce to Cv = 0 to by multiplying by B^-1? I'm just suspicious and while my explanation might be right I really have no conceptual understanding of what is going on here.
Thanks :)


text:
Q: Is there an easy or built-in way to say "when I do nothing" in Cucumber? So I have been writing some Cucumber tests.
For example, I have test:
Given I have a category page "Art"
When I create a subcategory page "Painting"
Then the subcategory page "Painting" should be created

The test has been written, and it's passing.
Now to make sure my test is working as expected, I want to try
Given I have a category page "Art"
When I do nothing
Then the subcategory page "Painting" should be created

Now, the test should fail.
Is there some easy, built-in Cucumber way to express "I do nothing" without
my having to define this step explicitly, which would be just
When(/^I do nothing$/) do
end

Thanks

A: Fortunately, (note: I did not say unfortunately) that seems to be the only way. Because having that empty step definition establishes/proves that you are doing nothing there.


text:
Q: Got a Black screen by changing activity i am creating a app and got a annoying bug.
When I start my second Activity my screen (on device) turns randomly black and app stucks and sometimes it changes to the 2nd activity and works fine. There are no errors ...
Please help I ve no idea how to fix that.

A: Use
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

while creating your Intent.
Like this :
Intent intent = new Intent(this, SecondActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);


text:
Q: What's the maximum number of steps in a non-loopy maze? I've written an maze-solving algorithm in 2D (with a robot) that does the following:
At first, the robot will explore (keep going down one path, avoiding walls). When it encounters a junction that it's already come across before, if reverses direction and backtracks.
If the robot encounters a junction with an unexplored exit while backtracking, it randomly chooses one of these exits and explores down it.
If the robot encounters a junction with no unexplored exits while backtracking it backtracks in the direction from which it came when it first reached the junction.
Given this, is there a (least upper bound) for the maximum number of steps the robot will take to navigate the maze?

A: If the distance between junctions is always 1 (if necessary, introduce "dummy" 2-way junctions 1 unit apart along longer passageways) then the maximum distance that the robot travels to solve the maze is $2n-1$ where $n$ is the number of junctions.
We can see this is an upper bound on the maximum because the robot does not travel along any passage more than twice, and it only travels along the final passage (with the goal/exit at the end) once.
And this upper bound is actually attained if we have a maze where there the goal is 1 unit away from the junction at the entrance, but there are other branches from this junction, and the robot chooses and fully explores each of these other branches before it chooses the exit branch.

A: The best upper bound is around $2n,$ where $n$ is the number of junctions. Essentially, one could search the 'wrong' part of the array and have to backtrack complete. Think of the path graph with vertices $1,2,\dots,n,$ where the exit is at 1, and you start at 2 and start searching $3,4,\dots.$
If you want a more precise number, such as $2n-3,$ you'll need to give a slightly more formal description of the problem.


text:
Q: Any way to set span directly to spanable text? This may be a blunder,But I need to know... :)
Iam develeoping an android application,In in I want to display two type face in a single textview and found this One very useful,A custom typeface span that extends typeface span,
As per my understanding , we are creating a spannable as follows using two words
String firstWord = "first ";
String secondWord = "second";
// Create a new spannable with the two strings
Spannable spannable = new SpannableString(firstWord+secondWord);

then sets two type face to that words using our custom span  like this
// Set the custom typeface to span over a section of the spannable object
spannable.setSpan( new CustomTypefaceSpan("sans-serif",CUSTOM_TYPEFACE), 0,
firstWord.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spannable.setSpan( new CustomTypefaceSpan("sans-serif",SECOND_CUSTOM_TYPEFACE),   rstWord.length(), secondWord.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

Now my question, I have a large amount of text so If i am able to put the spans directly in my text its will be a more easy for us ,is that possible to put spans directly to the text like we put <b>bold </b> as my need is to use my custom typeface span  like <typeface1> sample </typeface1> <typeface2> Doc </typeface2>.
WHAT I NEED IS,  DIRECTLY APPLY THE CHANGE TO TEXT WHAT THE SET SPAN DO TO THE TEXT
Is that possible, if possible what i need to write as span in my text,How can I achieve this.. or am i compleatly wrong ?
Thank you for all

A: Very late answer but what you asked for is pretty easy.
For instance, lets say we want to change everything between quotation marks into italic font.
    String s =  "\"Hello my name is Edward\" Hola, my nombre es Edward";
    Pattern p = Pattern.compile("\"([^\"]*)\"");
    Matcher m = p.matcher(text);
    Spannable spannable = new SpannableString(s);
    while (m.find()) {
      int textLocation = text.indexOf(m.group(1));

      // Set the custom typeface to span over a section of the spannable object
       spannable.setSpan( new CustomTypefaceSpan("sans-serif",my_italic_font),
       textLocation-1, textLocation + m.group(1).length(),spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

      // Set the text of a textView with the spannable object
      TextView textbox = (TextView) v.findViewById(R.id.cardtextbox);

    }
    textbox.setText( spannable );

Result of s would be
"Hello my name is Edward" Hola, my nombre es Edward
Now instead of quotation marks you would use a regex pattern for tags like <b>bold </b>;
And you could also remove the tags afterwards with a simple .replace();


text:
Q: How to insert a pdf file in a MySQL database and then read it in php? I have a PHP code that allows me to send a pdf file by email with SendGrid and to insert this file as a BLOB in a MySQL database.
Everything works fine but the file inserted in the database is always a [BLOB - 20,0 kio] file, I can't figure out if it is inserted correctly and how to retrieve it from the database...

Thanks for your help
<?php

 $filename2 = 'test.pdf';

 $file_encoded = base64_encode(file_get_contents("C:/wamp64/www/final/API_label/PDF/$filename2"));
 $email->addAttachment($file_encoded, "application/pdf", "$filename2", "attachment");

 $sendgrid = new \SendGrid('SG.Ebi-CnMATfeehrmw89O5CuSNfPk');
 try {
     // $response = $sendgrid->send($email);
     // print $response->statusCode() . "\n";
     // print_r($response->headers());
     // print $response->body() . "\n";
 } catch (Exception $e) {
     // echo 'Caught exception: ' .  $e->getMessage() . "\n";/
 }

      //Insertion of the values in the database
      try {
         // Connect to db
         $db = new db('mysql:dbname=jotform; host=localhost', 'root', '');
         $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

         // Set SQL
         $sql = 'INSERT INTO DHL (submission_id, formID, identite, email, adresse, telephone, label, commercial_invoice)
         VALUES (:submission_id, :formID, :NOM, :EMAIL, :ADRESSE, :TELEPHONE, :file_encoded, :COMMERCIAL_INVOICE)';

         // Prepare query
         $query = $db->prepare($sql);
         $query->bindParam(':file_encoded', $file_encoded, PDO::PARAM_LOB);

         // Execute query
         $query->execute(array(':submission_id' => $submission_id, ':formID' => $formID, ':NOM' => $NOM, ':EMAIL' => $EMAIL, ':ADRESSE' => $ADRESSE, ':TELEPHONE' => $TELEPHONE,
         ':file_encoded' => $file_encoded, ':COMMERCIAL_INVOICE' => $COMMERCIAL_INVOICE));
     } catch (PDOException $e) {
         echo 'Error: ' . $e->getMessage();
     }

}

?>

Code to dowload:
    //PDO PART
include '../include/classe_PDO.php';

 try {
  // Connect to db
  $db = new db('mysql:dbname=jotform; host=localhost', 'root', '');
  $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  // Set SQL
  $sql = "SELECT * FROM `dhl` WHERE `submission_id` = '5094071540419221255'";

  foreach  ($db->query($sql) as $row) {

          $filedata = $row['label']; //get base64 data from query result
          $decoded = base64_decode($filedata); //decode base64 to binary

          //set suitable HTTP response headers
          header('Content-Description: File Transfer');
          header('Content-Type: application/octet-stream');
          header('Content-Disposition: attachment; filename="label.pdf"');
          header('Expires: 0');
          header('Cache-Control: must-revalidate');
          header('Pragma: public');
          //output the binary file data in the body of the response
          echo $decoded;
          exit;
}

} catch (PDOException $e) {
  echo 'Error: ' . $e->getMessage();
}

?>

A: You need to

*

*Store the data in a TEXT column in MySQL, not BLOB, because a base64 string is text, not binary data.

*Query that field from your database to get the base64 data

*Decode the base64 data to get the original binary data.

*Send that data for download, setting the appropriate headers for your browser to understand that it's a file download rather than a web page.
You seem to have the SQL part sorted now, judging by the update to your questions, so here I'll just show a simpler way to download the data, without needing to write a file to the server disk first (which you'd then need to clean up later).
$filedata = $row['label']; //get base64 data from query result
$decoded = base64_decode($filedata); //decode base64 to binary

//set suitable HTTP response headers
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="test.pdf"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
//output the binary file data in the body of the response
echo $decoded;
exit;


text:
Q: How to use two databases at a time and update simultaneously in two different locations How to use two databases at a time? They are placed at different networks. Is it possible in .net?

A: If you want a Transaction that spans multiple databases you can use a TransactionScope.
using (TransactionScope t = new TransactionScope())
{
    // Execute code
    t.Commit();
}

The Transaction will be promoted to a distributed transaction when necessary. You need to make sure that the Distributed Transaction Coordinator is installed and then everything will work without further configuration.

A: Use DataMirroring concept in Sqlserver.


text:
Q: OpenGL - circle not being drawn smooth I am drawing a circle using OpenGL, with the set of calls being:
float delta_theta = 0.001;
glBegin(GL_POLYGON); // OR GL_LINE_LOOP

glEnable( GL_LINE_SMOOTH );
glHint( GL_LINE_SMOOTH_HINT, GL_NICEST );
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

for (angle = 0; angle < 2*3.1415; angle += delta_theta)
   glVertex3f( radius*cos(angle), radius*sin(angle), 0 );

glEnd();

The problem is that the circle is not smooth. I am moving (translating) the circle along axes; at some points it becomes smooth, but mostly, it's like a blot, please see the attached screenshot.
Any suggestions as to what I could do to smoothen the circle?

A: I would suggest you not try to implement this with lines or a filled polygon for one thing.
Use a single GL_POINT and enable GL_POINT_SMOOTH. That will rasterize the point as a filled circle instead of the normal square. It will be much more efficient, provided you use a point size your implementation supports for anti-aliased points (often up to ~ 63.5 on NV implementations, more on others).


text:
Q: Fullcalendar and Scheduler Issues with versions I've a problem with FullCalendar (FC) and it's plugin Scheduler (S).
Since some some months I use the version 1.2.0 (S) together with 2.6.0 (FC).
It's ok, but a new request from our users (enable/disable grouping of resources) would be greatly satisfied using the feature 'get / set options dynamically'. So I've downloaded the new versions of the libraries, 1.4.0 (S) and 3.0.1 (FC).
Here come the problems: with the normal scheduler day view it works great. But, when I open a new page, where I use the weekly view, no data is show.
I've tried everything:

*

*changed the versions, using the 2.7.3 (FC) with 1.3.2 (S).

*used the version of (FC) packed in the zip together with (S).

*having made some changes, I've deleted them, but the fault seems to lie in the way the libraries operate together.

I would post some code, but it's a bit complex... The scheduler is encapsulated inside a "class" and is activated using events. The whole infrastructure is part of a kind of framework and I cannot simply take a part of the code. What I'm sure is that the whole works with the older version, but no way with the new.
Up to now the only working solution is to use two versions, one for each page. But, of course, this is a kind of hack, not nice and not good for maintenance.
Here is the code used to generate the scheduler. _schedulerType is used to crate a daily or weekly view. Two "containers", _schedulerOptions and _schedulerServices are created outside and used to define how the scheduler is created.
_schedulerContainer.fullCalendar({
    local (or lang): _schedulerOptions.language,
    allDaySlot: false,
    now: _currentDay,
    selectable: true,
    editable: false,
    aspectRatio: _schedulerOptions.aspectRatio,
    scrollTime: '07:30',
    slotDuration: '00:15:00',
    slotLabelInterval: '01:00:00',
    slotLabelFormat: _schedulerOptions.slotLabelFormat,
    slotWidth: _schedulerOptions.slotWidth,
    nowIndicator: true,
    customButtons: (_schedulerServices.schedulerHeader !== null) ?
        _schedulerServices.schedulerHeader.createCustomButtons() :
        null,
    header: (_schedulerServices.schedulerHeader !== null) ?
        _schedulerServices.schedulerHeader.createHeader() :
        false,
    defaultView: _schedulerType,
    -------------------REMOVE-----------------------------------------
    resourceLabelText: 'Rooms',
    resourceGroupField: _defaultOptions.groupBy,
    resourceOrder: _defaultOptions.orderBy,
    resources:
      function (callback) {
        if (_schedulerServices.rscCallback !== null) {
          if (log) {
              console.log("reload resources inside scheduler");
          }

          callback(_schedulerServices.rscCallback.getResources());
        }
      },
    ------------------------------------------------------------------
    events:
      function (start, end, timezone, callback) {
        if (_schedulerServices.evtCallback !== null) {
          if (log) {
            console.log("reload events inside scheduler");
          }
         callback(_schedulerServices.evtCallback.getEvents());
        }
      },
    -------------------REMOVE-----------------------------------------
    resourceRender:
      function (resourceObj, element) {
        if (_schedulerServices.rscViewManager !== null) {
          return _schedulerServices.rscViewManager.requestRender(resourceObj, element);
        }
      },
    ------------------------------------------------------------------
    eventRender:
      function (eventObj, element) {
        if (_schedulerServices.evtViewManager !== null) {
          return _schedulerServices.evtViewManager.requestRender(eventObj, element);
        }
      }
    });

Any help would be appreciated!
Thanks

Solved!!!
After version 2.6.0, the unused options fields of the options should not be used. In my case, removing all the fields related to Resources solved the problem.


text:
Q: Video and Audio Sychronization issue I am saving frames to H264 format and I saved audio to aac format. Then I concatenate of these format to creating mp4 format using ffmpeg player in android but When I concatenate Audio and Video, audio getting back of video they aren't playing at synchronous mode,how can I played video and audio at syncronous mode? H264 video format is 6 second, audio format is 8 second When I concatenate of these getting 8 second and audio coming longer and occuring asyncronous.
Recording Audio to AAC format
    recorder = new MediaRecorder();

    recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
    recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
    recorder.setAudioEncodingBitRate(48000);//48000
    recorder.setAudioSamplingRate(720);//16000
    recorder.setOutputFile(path2);
    try {
        recorder.prepare();
    } catch (IOException e) {
        e.printStackTrace();
    }
    recorder.start();

Saving Video to H264 format
        MediaFormat mediaFormat = MediaFormat.createVideoFormat("video/avc",
                1280,
                720);
        mediaFormat.setInteger(MediaFormat.KEY_COLOR_FORMAT,
                MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Planar);
        mediaFormat.setInteger(MediaFormat.KEY_BIT_RATE, 6000000);
        mediaFormat.setInteger(MediaFormat.KEY_FRAME_RATE, 720); //video second

        mediaFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 5);
        try {
            mMediaCodec = MediaCodec.createEncoderByType("video/avc");
        } catch (IOException e) {
            e.printStackTrace();
        }
        mMediaCodec.configure(mediaFormat,
                null,
                null,
                MediaCodec.CONFIGURE_FLAG_ENCODE);

        mMediaCodec.start();

//Video format H264
private synchronized void encode(byte[] data) {

    ByteBuffer[]  inputBuffers = mMediaCodec.getInputBuffers();
    ByteBuffer[]  outputBuffers = mMediaCodec.getOutputBuffers();

    int inputBufferIndex = mMediaCodec.dequeueInputBuffer(-1);
    if (inputBufferIndex >= 0) {
        ByteBuffer inputBuffer = inputBuffers[inputBufferIndex];
        inputBuffer.capacity();
        inputBuffer.clear();
        inputBuffer.put(data);
        mMediaCodec.queueInputBuffer(inputBufferIndex, 0, data.length, 0, 0);

    } else {
        return;
    }

    MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo();
    int outputBufferIndex = mMediaCodec.dequeueOutputBuffer(bufferInfo, 0);
    Log.i(TAG, "outputBufferIndex-->" + outputBufferIndex);
    do {
        if (outputBufferIndex >= 0) {
            ByteBuffer outBuffer = outputBuffers[outputBufferIndex];
            System.out.println("buffer info-->" + bufferInfo.offset + "--"
                    + bufferInfo.size + "--" + bufferInfo.flags + "--"
                    + bufferInfo.presentationTimeUs);
            byte[] outData = new byte[bufferInfo.size];
            outBuffer.get(outData);
            try {
                if (bufferInfo.offset != 0) {
                    fos.write(outData, bufferInfo.offset, outData.length
                            - bufferInfo.offset);
                } else {
                    fos.write(outData, 0, outData.length);
                }
                fos.flush();
                Log.i(TAG, "out data -- > " + outData.length);
                mMediaCodec.releaseOutputBuffer(outputBufferIndex, false);
                outputBufferIndex = mMediaCodec.dequeueOutputBuffer(bufferInfo,
                        0);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else if (outputBufferIndex == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) {
            outputBuffers = mMediaCodec.getOutputBuffers();
        } else if (outputBufferIndex == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
            MediaFormat format = mMediaCodec.getOutputFormat();
        }
    } while (outputBufferIndex >= 0);
}

Concatenate Video and Audio with using ffmpeg
String[] cmd = {"-i", h264_video_path, "-i", aac_audio_path, "-c", "copy", "-map","0:v:0","-map","1:a:0", outpath_mp4};

    try {
                    //FFMPEG execute command
                    executeCommand(cmd);
                } catch (FFmpegCommandAlreadyRunningException e) {
                    e.printStackTrace();
                }


text:
Q: What's the Best Way to Measure Memory Use from a Program? I've been trying to optimize the Windows program I am developing, trying to find the best data structures that will minimize memory use. It loads large blocks of data, so with huge files, it can use a large amount of RAM.
For memory measurement, I have been using GlobalMemoryStatusEx. See: http://msdn.microsoft.com/en-us/library/aa366589(VS.85).aspx
I believe this works for most flavors of Windows, from Windows 2000 right up to and including Windows Vista.
Is this the preferred way to measure memory use from within a program, or is there another, better way?

Addenum:  Found the Stackoverflow question: How to get memory usage under Windows in C++ which references GetProcessMemoryInfo
I'll try that one out.

A: If you are trying to optimize your own program memory-wise, I suggest you use a memory profiler tool for that.
There are many out there...some are free, some are not..you will surely find the one you need.
Those tools are written specifically for what you need (and also for memory leaks search) so...it will be hard to compare with them and do something like that on your own from your own program :)

A: See the addenum in my question.

A: I use valgrind to track memory usage, as well as to profile code and detect memory leaks.  The massif tool, I believe, tracks memory usage on the stack and heap.


text:
Q: SMPP connection using TLV I would like to send commands to the device using Open Smpp protocol.
    API people provided me ProgramID, but i didn't find any method which is accepting programId in open smpp api.
So i thought to add it in setExtraOptional(TLV tlv)
but i am not able to set TLV parameter.
I have below values,

tag = 0x1234,
programId = 12345

How can i build the TLV from above values?

Thanks in advance for your help.

A: You can simple add request.setExtraOptional((short) 0x1400, new ByteBuffer("programId:12345,String,5".getBytes())); as an extraParameter to Send SM request


text:
Q: Algorithm for enumerating grid points by distance from given point I'm trying to devise an algorithm for enumerating all points on a 2D grid in order of their Euclidean distance to a given target point.  I know I could just get a bunch of them that are close to the target and then sort them, but that's not what I want.  I want something that will output every point, out to infinity, in order of their distance to the target.
At the bare minimum, I need something that works if the target point is also a grid point.  But ideally, I want something that works for any target, even non-grid points.  Ideally ideally, I want something that works for grids of an uneven x-y scale.
Any ideas on where to start with this?

A: Except for the corners of the square your target is in, every grid point has a neighbor that is closer to the target. So you can use a modified breadth-first search:
Maintain a priority queue of points that you have not printed yet but are neighbors to something you have printed, ordered by (squared) distance to the target. Keep taking out the closest point and adding those of its remoter neighbors that are not already in the queue.
This uses $O(\sqrt n)$ space to print $n$ points, and it takes $O(\log n)$ work to print point number $n$.


text:
Q: disable a specific warning in QtCreator I installed the new QtCreator which comes with the new clang language model and provides lots of useful warnings. However one of them annoys me: Winconsistent-missing-destructor-override. How to disable this one and keep the other warnings?
UPDATE: I am talking about the warnings which I get as in-line warnings in the text editor in Qt Creator IDE (which uses Clang toolchain). I am not talking about the warnings produced when compiling the project (which is for example MSVC in my case).

A: To disable specific warning annotations in the Qt IDE:
Go to Tools -> Options -> C++ -> Code Model
Click Manage next to Diagnostic Configuration
Select Clang-only checks for almost everything[built-in]
Click Copy on the upper right corner
Go to the copied version of the Diagnostics Configuration and append -Wno-inconsistent-missing-destructor-override in the text field under the Clang tab.
You can read more about configuring the Clang Code Model here.


text:
Q: phpmyadmin - Unable to import spreadsheet "#1005 - Can't create table `database_name`.`table_name` (errno: 185 "Too many columns")" I am trying to import a spreadsheet into my database but I am running into the following error:

Unable to import spreadsheet "#1005 - Can't create table database_name.table_name (errno: 185 "Too many columns")"

I looked this error up and my spreadsheet is well below the maximum column count of mysql (it only has 7) so I am not sure why I am experiencing this error. I thought maybe it had to do with some formulas I had on the table so I copied the cells data to another column, then copied those values back to the original column and I am still having the same error. I am importing the spreadsheet as a .ods file.
Update 1: I converted my spreadsheet from .ods to .csv and I was able to now import my data without any issues. While my problem is now fixed I would still like to know how to fix the original problem I was having without having to convert the file type.


text:
Q: VBA Finding Unique Distinct Values based on Multiple Dynamic Criteria It's not too easy to explain this but basically I have a data set that pulls through information to the dashboard.
I am looking to find the unique distinct amount of managers matched to 5 simultaneous criteria.
The data set looks like this:

The dashboard has an option to chose criteria to search this database with which looks like this
My Question is - Say I search the entire database for jobs by a certain Principal (using the * wildcard for all other criteria). How do I then find out the distinct number of managers and consultants working on these jobs?
Sorry I couldn't attach the figures as figures rather than a photo - not sure how to do it.

A: Just wanted to demonstrate how you could approuch this:
My sample data...

Formula in J1:
=SUM(--(FREQUENCY(IF((A2:A10=I1),MATCH(F2:F10,F2:F10,0)),ROW(F2:F10)-ROW(F2)+1)>0))

Formula in J2:
=SUM(--(FREQUENCY(IF((A2:A10=I1)*(B2:B10=I2),MATCH(F2:F10,F2:F10,0)),ROW(F2:F10)-ROW(F2)+1)>0))

Formula in J3:
=SUM(--(FREQUENCY(IF((A2:A10=I1)*(B2:B10=I2)*(C2:C10=I3),MATCH(F2:F10,F2:F10,0)),ROW(F2:F10)-ROW(F2)+1)>0))

All these formula need to be entered through CtrlShiftEnter
Unfortunately IF(.. doesn't support wildcards, so that's why I do it like this.
Append on this for the 4th and 5th criteria....


text:
Q: Standard include Paths entries for GCC with Eclipse Kepler on Linux Ubuntu 13.10 I am using Eclipse Kepler (Service Release 2) on Linux Ubuntu 13.10.
Trying to build a "hello world" project (created using File->New->C++Project->HelloWorldC++Project) results in
unresolved inclusion: < iostream >
Under Project Properties:
C/C++ General -> Paths and Symbols
I see that there is no include directory given under any of "Assembly", "GNU C" or "GNU C++".
Setting/deleting the checkmark at "Show built-in values" doesn't help.
Also not helping is trying to clear the discovery entries under Project Properties -> C/C++ Build -> Discovery Options.
I would be very pleased if anyone could tell me either
- how to get Eclipse auto-setting the necessary standard include paths
or
- tell me which paths I actualy need to set myself to get a simple hello-World C++ project running
Thanks in advance.
Steve