Q: Django Ajax 'GET' newbie here. I am trying to get some data from my database using ajax.
In my views.py,
def getEvents(request):
    eventList = Events.objects.all()
    events=[]
    for event in eventList:
        events.append({"name": event.name, "start": event.start, "end": event.end})
    return HttpResponse(events, content_type="application/json")

Note that Events is the model that I am trying to parse. After I collect the data from this model, I want to return it to my template using the following ajax code:
            $.ajax({
                url: 'getEvents/',
                datatype: 'json',
                type: 'GET',
                sucess: function(data) {
                    alert(data.name);
                }
            });

In my urls.py:
url(r'^getEvents/', views.getEvents, name='getEvents'),

However, I think I am doing something wrong because it doesn't work. I have been stuck on this for hours...Any ideas?
EDIT:
Okay. When I append the getEvents to the url, I do see all the database objects together in a dict but it seems my ajax is not working. How do I parse this data? The data is in the form:
[{"start": "2017-02-06", "end": "2017-02-07", "name": "Capstone Meeting"},
{"start": "2017-02-07T0:00", "end": "2017-02-08", "name": "Capstone"},
{"start": "2017-01-31T0:00", "end": "2017-02-01", "name": "dasdsd"},
{"start": "2017-01-31", "end": "2017-02-01", "name": "hjb"}]

Here is what I have so far...
            $.ajax({
                url: 'getEvents/',
                datatype: 'json',
                type: 'GET',
                sucess: function(data) {
                    $.each(data, function(index, element) {
                        $('body').append($('<div>', {
                            text: element.name
                        }));
                    });
                }
            });

A: One of your errors is being caused by not using a JsonResponse in your view instead of an HttpResponse.  Here’s how to fix that issue:
from django.http import JsonResponse

def getEvents(request):
    eventList = Events.objects.all()
    events=[]
    for event in eventList:
        events.append({"name": event.name, "start": event.start, "end": event.end})
    return JsonResponse(events)

From the docs, the JsonResponse is

An HttpResponse subclass that helps to create a JSON-encoded response.

The reason that your regular HttpResponse didn’t work, is because you have to manually serialize the data to JSON when using an HttpResponse, e.g., something like:
import json

response_data = json.dumps(events)
return HttpResponse(response_data, content_type="application/json")

Otherwise, I think what will happen is that you will get a call to __repr__ on the events list which will get you python ast serialized data and not JSON serialized data.

A: First of all, there's a typo of your sucess function, it should be success.
Secondly, JSON response should be a dict object rather than a list, if you really want to get a JSON array response anyway, then you have to specify safe=False when you serializing the data by using JsonResponse(events, safe=False), otherwise you'll get a TypeError like TypeError: In order to allow non-dict objects to be serialized set the safe parameter to False.
So the code sample should be:
def getEvents(request):
    eventList = Events.objects.all().values("name", "start", "end")
    return JsonResponse({"events": eventList})

And for frontend:
        $.ajax({
            url: 'getEvents/',
            datatype: 'json',
            type: 'GET',
            success: function(data) {
                $.each(data.events, function(index, element) {
                    $('body').append($('<div>', {
                        text: element.name
                    }));
                });
            }
        });


Q: Influxdb howto update tag values I would like to do a query like this:
SELECT max(value) as value, "counter" = 'countergasconsumption'
INTO "home"."1month"."test"
FROM "telegraf"."autogen"."mqtt_consumer"
WHERE time > now() - 11d AND "topic" = '/utilitiesmonitor/countergasconsumption'
GROUP BY time(5m)

I already have data with the countergasconsumption tag (not the whole topic). I can't get it to work, tried different select into's and the docs are not really helpful on this topic. The old data is one measurement with a tag for the type of counter, the new data comes in on separate topics via Telegraf.


Q: Segmentation fault when writing to array of strings I am trying to copy some of the arguments passed in argv to an array of strings. Here is my program.
#include <string.h>
#include <stdlib.h>
#include <unistd.h>

int main (int argc, char * argv[]) {
    char **args = malloc(argc * sizeof(char *));
    for (int i = 0; i < argc - 1; ++i) {
        strcpy(*(args+i), argv[i+1]);
    }
}

I am getting a segmentation fault in the for loop. Why is this happening?

A: You get the segmentation fault because you are using uninitialized pointers.
In other words: *(args+i) is uninitialized.
Let's look at your memory:
char **args = malloc(argc * sizeof(char *));

This will give a local variable args that points to a dynamic allocated memory area consisting of argc pointers to char. Looks like this:

But the argc pointers to char are uninitialized (i.e. malloc doesn't initialized anything) so the real picture is:

That is - the argc pointers to char may point anywhere.
So when you do
strcpy(*(args+i), argv[i+1]);
       ^^^^^^^^^
       Read uninitialized pointer

you read the i'th uninitialized pointer and copy the string at argv[i+1] to that location. In other words - to a location that we can't know where is and most like doesn't belong to your program. This is likely to result in a seg fault.
So before you copy anything you want those char-pointers to point to some chars. Like:

So basically you need to do additional malloc.
Now one problem is: How many chars do you need to malloc?
Well, you can't know until you know the length of the input strings. So you need to put the malloc inside the loop. Like:
int main (int argc, char * argv[]) {
    char **args = malloc(argc * sizeof(char *));
    for (int i = 0; i < argc - 1; ++i) {
        *(args+i) = malloc(strlen(argv[i+1]) + 1);  // Allocate memory
        strcpy(*(args+i), argv[i+1]);
    }
}

Note:

*

*You don't need to write sizeof(char) as it is always 1

*You have to add 1 to the string length of the input string in order to reserve memory for the string termination.

*You should always check that malloc doesn't return NULL

*Instead of *(args+i) you can use the more readable form args[i]
So after a real execution the picture could be:

A: The problem lies in this part of your code:
malloc(argc * sizeof(char *));

Don't think that sizeof(char*) would give you the size of a string.
What is the size of a pointer?
Solution:
int main(int argc, char* argv[])

{
    char* copyOfArgv;

    copyOfArgv = strdup(argv[1]);
}

strdup() - what does it do in C?

A: The problem is you allocated memory for the pointers not for the string (arguments from argv itself) hence the strcpy is invalid - causing segmentation fault.
It would've been better to just:
Allocate memory for the pointers (as you have done) then make those pointers point to the arguments passed. Example:
 #include <string.h>
 #include <stdlib.h>
 #include <unistd.h>

 int main (int argc, char * argv[]) {
     char **args = malloc(argc*sizeof(char *)); //allocated memory for the pointers only
     int i=0;

     for(;i<argc;i++)
     {
         args[i]=argv[i];  //making the pointers POINT to the arguments including the 0th argument as well
         i++;
     }
     return 0;
 }

For using strcpy you should've allocated memory for the arguments itself and then copied those.


Q: Overriding timeout for database connection in properties file I was wondering if there is a specific way to override database connection timeout in the properties file in my Java web project? I am using Hibernate, Spring, and MySQL DB. I have tried several different property fields and reduced the timeout time to 1 millsecond, yet the connection is still completed with transactions still being processed properly.
These are the property fields I have used to no avail...

*

*spring.jpa.properties.javax.persistence.query.timeout=1

*spring.jdbc.template.query-timeout=1

*hibernate.c3p0.timeout=1
Is hibernate overriding this timeout value or am I just setting it improperly?
Thanks in advance!

A: Assuming that you're using Spring Boot you can try:
spring.transaction.defaultTimeout=1

This property sets defaultTimeout for transactions to 1 second.
(Looking at the source code of TransactionDefinition it seems that it is not possible to use anything more precise than seconds.)
See also: TransactionProperties

javax.persistence.query.timeout
This is  a hint for Query. It is supposed to work if you use it like this:
entityManager.createQuery("select e from SampleEntity e")
    .setHint(QueryHints.SPEC_HINT_TIMEOUT, 1)
    .getResultList();

See also QueryHints

spring.jdbc.template.query-timeout
Remember that according to the JdbcTemplate#setQueryTimeout javadoc:

Any timeout specified here will be overridden by the remaining transaction timeout when executing within a transaction that has a timeout specified at the transaction level.

hibernate.c3p0.timeout
I suspect that this property specifies timeout for getting from the connection pool, not for a query execution


Q: Functional Derivative of Fourier Transform Say I have a functional $F$ which depends on the Fourier transform of $g^{2}(x_{1},x_{2},x_{3})$: $$F[g] = \int \mathcal{F}(g^{2}) d^{3}x$$
The Fourier transform is given by:
$$\mathcal{F}(g^{2})=\int g^{2}e^{-i\vec{k}\vec{r}} d^{3}k$$
I was wondering if the following logic was sound and mathematically legal:
$$\frac{\delta F}{\delta g} = \frac{\partial \mathcal{F}(g^{2})}{\partial g}$$ by Euler Lagrange Equation
$$\frac{\partial \mathcal{F}(g^{2})}{\partial g}=\mathcal{F}(2g)$$
$$\frac{\delta F[g]}{\delta g} = \mathcal{F}(2g)$$

A: You have the functional
$$F[g] = \int \mathcal{F}\{g^{2}\}(k) \, d^{3}k$$
The functional derivative is a linear functional defined for some nice function $\phi$ as
$$
\left\langle \frac{\delta}{\delta g} F[g], \phi \right\rangle
= \left. \frac{d}{d\lambda} F[g+\lambda\phi] \right|_{\lambda=0}
= \left. \frac{d}{d\lambda} \int \mathcal{F}\{(g+\lambda\phi)^{2}\}(k) \, d^{3}k \right|_{\lambda=0} \\
$$
The Fourier transform is linear, so
$$
\mathcal{F}\{(g+\lambda\phi)^{2}\}
= \mathcal{F}\{g^2 + 2\lambda g \phi + \lambda^2 \phi^2\}
= \mathcal{F}\{g^2\} + 2\lambda \mathcal{F}\{g \phi\} + \lambda^2 \mathcal{F}\{\phi^2\}
$$
and therefore
$$
\int \mathcal{F}\{(g+\lambda\phi)^{2}\}(k) \, d^{3}k
= \int \left( \mathcal{F}\{g^2\}(k) + 2\lambda \mathcal{F}\{g \phi\}(k) + \lambda^2 \mathcal{F}\{\phi^2\}(k) \right) \, d^{3}k \\
= \int \mathcal{F}\{g^2\}(k) \, d^{3}k + 2\lambda \int \mathcal{F}\{g \phi\}(k) \, d^{3}k + \lambda^2 \int \mathcal{F}\{\phi^2\}(k) \, d^{3}k
$$
Taking the derivative w.r.t. $\lambda$ and then setting $\lambda=0$ gives us
$$
\left\langle \frac{\delta}{\delta g} F[g], \phi \right\rangle
= 2 \int \mathcal{F}\{g \phi\}(k) \, d^{3}k
$$
We insert the definition of $\mathcal F$:
$$
\left\langle \frac{\delta}{\delta g} F[g], \phi \right\rangle
= 2 \iint (g\phi)(x) e^{-i k \cdot r} \, d^3x \, d^{3}k
= 2 \iint g(x) \phi(x) e^{-i k \cdot r} \, d^3x \, d^{3}k
$$
Swapping the integrals (who cares if we may do it?) gives
$$
\left\langle \frac{\delta}{\delta g} F[g], \phi \right\rangle
= 2 \int g(x) \phi(x) \left( \int e^{-i k \cdot x} \, d^{3}k \right) \, d^3x \\
= 2 \int g(x) \phi(x) \, (2\pi)^3\delta(x) \, d^3x
= \langle 16 \pi^3 g(x) \delta(x), \phi(x) \rangle
$$
Thus,
$$\frac{\delta}{\delta g} F[g] = 16 \pi^3 g(x) \delta(x)$$


Q: quill error with Invalid Quill Container on Vuejs when used with vuetify tab Error on plugin quill occurred when i placed the editor in a tab container of Vuetify. It is created under the mounted hook.
The error in Console is

quill Invalid Quill container undefined
[Vue warn]: Error in mounted hook: "TypeError: Cannot read property
'on' of undefined"

Below is the vue file.

<template>
  <v-app class="panel" ref="panel">
    <v-tabs fixed-tabs v-model="tab">
      <v-tabs-slider></v-tabs-slider>
      <v-tab key="1" href="#tab1">
        Tab 1
      </v-tab>
      <v-tab key="2" href="#tab2">
        Tab 2
      </v-tab>
      <v-tabs-items v-model="tab">
        <v-tab-item key="1" value="tab1">

Edit text in tab 1

        </v-tab-item>
        <v-tab-item key="2" value="tab2">
          <v-card-text>This is tab 2</v-card-text>
        </v-tab-item>
      </v-tabs-items>
    </v-tabs>
  </v-app>
</template>

A: this is probably due to the fact that

 is inside a child component's slot v-tab-item which is conditionally rendered.
that means that the v-tab-item is mounted AFTER the parent's mounted() executes, so the content (including your refs) are not available.
If you can defer the initialization until the child has mounted then you can access the ref, but getting that to work is a complex endeavor.
Instead, I would opt to define a component that handles quill initialization and that can be nested in the tab.
ie:
<v-tab-item key="1" value="tab1">
    <MyQuillComponent v-model="value"/>
</v-tab-item>


Q: How to use coalesce to take sum Can I use sum() in coalesce()?
I want to use it in a stored function in Postgres.
For example
case (COALESCE(t3.Count3,0)+ COALESCE(t2.Count2,0) >= t4.Count4::float)
then ( select (t4.Count4::float/((t3.Count3::float)+(t2.Count2::float))) * 100 as Count5 )
else ''0''
end as Count5

A: It's hard to tell what you're trying to do here because there are multiple issues in the code. Also though your title mentions SUM your code doesn't include it (though you do have + but that's not the same).
If this is part of a SELECT statement, then I'm guessing what you want is:
SELECT
CASE
    WHEN COALESCE(t3.Count3,0)+ COALESCE(t2.Count2,0) >= t4.Count4::float
    THEN 100 * t4.Count4::float/(COALESCE(t3.Count3::float,0)+COALESCE(t2.Count2::float,0))
    ELSE 0
END as Count5
FROM MyTable


Q: Count 1's between the intersection of two binary arrays Given two binary arrays, how can one quickly find the number of 1's occurring between intersecting bits for both arrays?
For example, consider a pair of bitsets (i1, i2) and their intersection (i12):
i1  = [0001001000100100];
i2  = [0101000100010110];
i12 = [0001000000000100]; // (i1 & i2)

The intersecting bits are in position 3 and 13, so count the number of 1's in positions 0-2 and 4-12:
x1 = [0, 2] // results i1
x2 = [1, 2] // results for i2

Now generalize this idea to 32-bit integers. Toy example:
int i1[2] = {2719269390, 302235938};
int i2[2] = {2315436042, 570885266};

Toy example in binary:
i1      = [10100010 00010100 11000010 00001110, 00010010 00000011 11000001 00100010]
i2      = [10001010 00000010 11000000 00001010, 00100010 00000111 00000100 10010010]
i1 & i2 = [10000010 00000000 11000000 00001010, 00000010 00000011 00000000 00000010]

Expected results:
x1 = [2, 2, 0, 1, 1, 1, 0, 0, 4];
x2 = [2, 1, 0, 0, 0, 1, 1, 0, 3];

I can see a "brute-force" approach using __builtin_clz() to determine leading zeros in i1 & i2, shifting i1 and i2 right by that number, doing __builtin_popcount() for the shifted i1 and i2 results, and repeating the procedure until no intersections remain. My instinct suggests there may be a more elegant approach, as this involves a few temporaries, many instructions, and at least two logical branches.
C/C++ implementations are welcome, but I would be satisfied enough with conceptual perspectives.  Suffice it to say this approach intends to remove a critical bottleneck in a popular program.

A: std::popcount returns the number of active bits in a value. It is able to call intrinsic functions, if available.
constexpr auto get_popcount(auto list) {
    decltype(list) result;
    std::transform(list.begin(), list.end(), result.begin(), [](auto x) {
        return std::popcount(x);
    });
    return result;
}

int main() {
    constexpr auto i12 = std::array{
        0b10000010u, 0b00000000u, 0b11000000u, 0b00001010u,
        0b00000010u, 0b00000011u, 0b00000000u, 0b00000010u};

    static_assert(get_popcount(i12) == std::array{ 2u, 0u, 2u, 2u, 1u, 2u, 0u, 1u });
}

A: Can't test this right now but (I1 XOR I2) AND I1 should leave only the bits that you want to count, so:
constexpr auto get_popcount(auto i1, auto i2) {
    std::vector<std::pair(int,int)> res;
    std::transform (i1.begin(), i1.end(), i2.begin(), res.begin(), []
        (auto x, auto y){
            return std::tie(std::popcount((x^y)&x),std::popcount((x^y)&y));
    });
    return res;
}

Where the first item of the touple is the number of bits on I1 and the second on I2.

A: I'm dealing with a similar problem, where I have to count the
number of '1' bits from a run-time-determined range. Don't know how long your bit array is, but mine is millions to billions of bits.
For a very long bit arrays (say, millions of bits), you could build an auxiliary tree structure for each bit array. The root node counts all bits 0~N in the array, the left child node of root stores the partial sum of bits 0~N/2, the right child node store the partial sum of bits (N/2+1)~N, etc. etc. That way, when you want to count the number of '1' bits from an arbitrary range, you traverse the tree and add the partial sum values stored in appropriate nodes of the tree. The time complexity is O(log(N)). When your array is huge, this is going to be much more efficient than iterating over the entire array (complexity O(N)).
If your array is smaller, I would guess SSE/AVX instructions can result in higher throughput? Like Stack Danny has implied, intrinsic functions may already be the underlying implementation of popcount.
If you just use a for loop, GCC is able to vectorize your loop into SSE/AVX (e.g. if you got AVX2 on your CPU, add '-mavx2 -O3' to your compiler command). That works for summing elements of an integer array, but I never examined if looping on a bitarray can also result in vectorized code. https://gcc.gnu.org/projects/tree-ssa/vectorization.html

A: Use the AND operator for i1 and i2 to get only the intersecting bits. Then in a loop, SHIFT right checking each bit using the AND operator until the variable is zero.
Assuming the arrays are in packs of 4 bytes (unsigned long), this should work:
size_t getIntersecting(unsigned long* i1, unsigned long* i2, size_t nPacks) {
    size_t result = 0;
    unsigned long bitsec;
    for (size_t i = 0; i < nPacks; i++)
    {
        bitsec = i1[i] & i2[i];
        while (bitsec != 0) {
            if (bitsec & 1) {
                result++;
            }
            bitsec >>= 1;
        }
    }
    return result;
}

I'm not at my workstation to test it. Generally it should count intersecting bits.
EDIT:
After reexamination of your question, try something like this.
// Define the global vectors
vector<unsigned long> vector1;
vector<unsigned long> vector2;

// Define the function
void getIntersecting(unsigned long* pi1, unsigned long* pi2, size_t nPacks) {
    // Initialize the counters to 0
    unsigned long i1cnt = 0;
    unsigned long i2cnt = 0;
    // Local storage variables
    unsigned long i1, i2;
    // Loop through the pointers using nPacks as the counter
    for (size_t i = 0; i < nPacks; i++) {
        // Get values from the pointers
        i1 = pi1[i];
        i2 = pi2[i];
        // Perform the bitwise operations
        unsigned long i4 = i1 & i2;
        // Loop for each bit in the 4-byte pack
        for (int ibit = 0; ibit < 32; ibit++) {
            // Check the highest bit of i4
            if (!(i4 & 0x80000000)) {
                // Check the highest bit of i1
                if (i1 & 0x80000000) {
                    i1cnt++;
                }
                // Check the highest bit of i2
                if (i2 & 0x80000000) {
                    i2cnt++;
                }
            }
            else {
                // Push the counters to the global vectors
                vector1.push_back(i1cnt);
                vector2.push_back(i2cnt);
                // Reset counters
                i1cnt = 0;
                i2cnt = 0;
            }
            // Shift i4, i1, and i2 left by 1 bit
            i4 = i4 << 1;
            i1 = i1 << 1;
            i2 = i2 << 1;
        }
    }
}


Q: Direct Sum Decomposition of Hilbert space Let $H$ be a Hilbert space and $T: H \rightarrow H$ a bounded linear operator. Let $N = ker(T)$. It is well-known that $H = N \oplus N^{\perp}$.
Is it also true that $H = N \oplus M$, where $M$ is a closed linear subspace and $M$ is not necessarily $N^{\perp}$? What would such $M$ be?

A: Given a Hilbert space $H$ with inner $\langle\cdot,\cdot\rangle$, there are many topologically equivalent inner products $\langle \cdot,\cdot\rangle'$ that are not the same as the original. For any closed subspace $N$, there are corresponding orthogonal complements $N^{\perp}$ and $N^{\perp'}$, potentially leading to different direct sum decompositions that are not the same:
$$
           H=N\oplus N^{\perp} = N\oplus N^{\perp'}.
$$
Every such inner product $\langle \cdot,\cdot\rangle'$ can be written as
$$
              \langle x,y\rangle' = \langle Ax,y\rangle
$$
for a unique bounded selfadjoint $A$ on $H$ that is continuously invertible. Any such $A$ can be used to generate a topologically equivalent inner product, and some $A$ can lead to different decompositions.


Q: Want to make db layer generic and not tied to spring's JdbcDaoSupport Current I have a seperate maven module for my database access, all my DAO classes inherit from:
public class GenericDaoImpl<T> extends JdbcDaoSupport implements GenericDao<T> {
}

My maven module has a spring dependancy:
org.springframework spring-orm

So a typical Dao class looks like:
public class UserDaoImpl extends GenericDaoImpl<User> implements UserDao {

    @Override
    public void insert(User user) {
        getJdbcTemplate().update("insert into users(...)...");
    }
}

My Dao's get autowired with the dataSource bean.
Can I make this generic somehow so I can continue to use it in my spring MVC application, yet it will work if I need to use this library in a cron job service type environment?  (without having to bring in spring's application context into the picture).

A: I'd start to observe the following:

*

*You have a GenericDao<T> which means that you can have different implementations.

*Currently, you have GenericDaoImpl<T> extends JdbcDaoSupport which means that you cannot use in the other environment you described without any application context unless you prepare all the object in a manual fashion.

So my suggestion is:

*

*Allow GenericDao<T> extends org.springframework.jdbc.core.JdbcOperations

*Develop an AbstractGenericDao<T> implements GenericDao<T> to bring the abstract general functionality you need.

*Develop a MyEnvGenericDao<T> extends AbstractGenericDao<T> that is responsible to provide a data source and underlying implementation of different methods you need; could be using a direct Hibernate/OpenJPA implementation to directly executing the queries.

*Develop a SpringGenericDao<T> extends JdbcDaoSupport implements GenericDao<T> that comes is already with a getJdbcTemplate() to perform the operations you need and is delegated to Spring JDBC template. In this scenario, you need to delegate the operations to JdbcDaoSupport.getJdbcTemplate().

Related to Maven, then you can actually have different modules for MyEnv and Spring implementations but both with one parent to have access to GenericDao<T> interface.


Q: Css media print show additional data, how to avoid them not come in print I am working On a laravel project and used CSS media print in somewhere, It is good but it shows additional data in Chrome Print Dialog like the below image as I marked them, So I don't want them to display when I print it, how to avoid it?

this the HTML code:

مشخصات شاگرد

         نام
         تخلص
         نام پدر
         جنسیت
         سن
         تلیفون
         آدرس
         ایمیل
         حالت مدنی
         نمبر تذکره

          {{ $student->first_name }}
         {{ $student->last_name }}
          {{ $student->father_name }}
         {{ $student->gender }}
          {{ $student->age }}
         {{ $student->phone }}
          {{ $student->address }}
          {{ $student->email_address }}
          {{ $student->marital_status }}
          {{ $student->ssn_number }}

this my script code:

this is style for print:

A: use instead of every  tags from  tag.

مشخصات شاگرد

         نام
         تخلص
         نام پدر
         جنسیت
         سن
         تلیفون
         آدرس
         ایمیل
         حالت مدنی
         نمبر تذکره

          {{ $student->first_name }}
         {{ $student->last_name }}
          {{ $student->father_name }}
         {{ $student->gender }}
          {{ $student->age }}
         {{ $student->phone }}
          {{ $student->address }}
          {{ $student->email_address }}
          {{ $student->marital_status }}
          {{ $student->ssn_number }}


Q: Regex string must contain certain substrings only and separated by whitespace So, I've been trying to come up with a regexp in PHP which can pick out substrings like "XX-035" (or alternatively "XX035" or "XX35") from a larger string of words and character sequences - that's the easy part - with the added proviso that the required substrings must be separated by one or more whitespace characters from other substrings in the main string.
In addition the substrings must also start with a particular two-letter group like "AB","CG" or "MS", etc., followed by zero or one dashes, and then 1 to 4 numerals (again, that part is easy). So, I have tried many different regex's, with and without \b word-boundaries, with and without whitespace \s, the latest of which is as follows:
/\b(\s+[^\/a-zA-Z](AB|CG|MS|MT|NA|OQ|TS){1}[\-]?\d{1,4})\b/i

but I just can't seem to crack the whitespace requirement. I've gone through many iterations in https://regex101.com/ and still haven't managed to get it down.
Obviously, I'm no expert when it comes to regular expressions, so any help would be appreciated here.

A: You may use
(?<!\S)(?:AB|CG|MS|MT|NA|OQ|TS)-?\d{1,4}(?!\S)

See the regex demo
Details

*

*(?<!\S) - the previous char should be a whitespace or start of string

*(?:AB|CG|MS|MT|NA|OQ|TS) - one of the 2-letter alternative

*-? - an optional hyphen

*\d{1,4} - one to four digits

*(?!\S) - the next char should be a whitespace or end of string.

PHP:
if (preg_match_all('~(?<!\S)(?:AB|CG|MS|MT|NA|OQ|TS)-?\d{1,4}(?!\S)~', $s, $matches)) {
    print_r($matches[0]);
}


Q: Spring security jet always redirecting to "/" after successful auth I have made a Rest API project with Spring Boot 2. I have used jwt for authentication. I can generate tokens fine. But when I send the generated token in a header with a request, it always redirects me to "/" path instead of the requested path (in my case "/rest/hello").
This is my custom AuthenticationProvider
@Component
public class JwtAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {

    @Autowired
    private JwtValidator jwtValidator;
    @Override
    protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {

    }

    @Override
    protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
        JwtAuthenticationToken jwtAuthenticationToken = (JwtAuthenticationToken)authentication;
        String token = jwtAuthenticationToken.getToken();
        JwtUser jwtUser = jwtValidator.validate(token);
        if (jwtUser == null) {
            throw new RuntimeException("JWT Token not correct");
        }
        List<GrantedAuthority> grantedAuthorities = AuthorityUtils.commaSeparatedStringToAuthorityList(jwtUser.getRole());
        return new JwtUserDetails(jwtUser.getUserName(), jwtUser.getId(), grantedAuthorities, token);
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return JwtAuthenticationToken.class.isAssignableFrom(authentication);
    }
}

This is my custom Filter
public class JwtAuthenticationTokenFilter extends AbstractAuthenticationProcessingFilter {
    public  JwtAuthenticationTokenFilter() {
        super("/rest/**");
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        String header = request.getHeader("Authorization");
        if (header == null || !header.startsWith("Token ")) {
            throw new RuntimeException("JWT Token is missing");
        }
        String authenticationToken = header.substring(6);
        JwtAuthenticationToken token = new JwtAuthenticationToken(authenticationToken);
        return this.getAuthenticationManager().authenticate(token);
    }

    public void setAuthenticationManager(AuthenticationManager authenticationManager) {
        super.setAuthenticationManager(authenticationManager);
    }

    public void setAuthenticationSuccessHandler(JwtSuccessHandler jwtSuccessHandler) {
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
        super.successfulAuthentication(request, response, chain, authResult);
        chain.doFilter(request, response);
    }

}

This is my Security config
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class JwtSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtAuthenticationProvider authenticationProvider;
    @Autowired
    private JwtAuthenticationEntryPoint entryPoint;

    @Bean
    public AuthenticationManager authenticationManager() {
        return new ProviderManager(Collections.singletonList(authenticationProvider));
    }

    @Bean
    public JwtAuthenticationTokenFilter authenticationTokenFilter(){
        JwtAuthenticationTokenFilter filter = new JwtAuthenticationTokenFilter();
        filter.setAuthenticationManager(authenticationManager());
        filter.setAuthenticationSuccessHandler(new JwtSuccessHandler());
        return filter;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().authorizeRequests().antMatchers("/rest/**").authenticated().and().exceptionHandling().authenticationEntryPoint(entryPoint)
                .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        http.addFilterBefore(authenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);

        http.headers().cacheControl();
    }
}

I have custom classes for user details and token as well.


Q: Count of an NSMutable Array of Objects that is in an NSMutable Array of Objects returns 0 I have an array of NSObjects (mapArray), and the object being focused on is at position 0 (MAIN_MAP). In each NSObject, there is a NSMutableArray called moonGateArray (has @property and @synthesize) to which I add another NSObject called Moongate. However, I keep getting zero as the count for moonGateArray. Any answers for why that is?
Code:
for (int i = 0; i < 8; i++) {
    [[[mapArray objectAtIndex:MAIN_MAP] moonGateArray] addObject:[Moongate new]];
}
[[[[mapArray objectAtIndex:MAIN_MAP] moonGateArray] objectAtIndex:0] setPosition:9 :3];
[[[[mapArray objectAtIndex:MAIN_MAP] moonGateArray] objectAtIndex:1] setPosition:16 :8];
[[[[mapArray objectAtIndex:MAIN_MAP] moonGateArray] objectAtIndex:2] setPosition:11 :6];
[[[[mapArray objectAtIndex:MAIN_MAP] moonGateArray] objectAtIndex:3] setPosition:16 :13];
[[[[mapArray objectAtIndex:MAIN_MAP] moonGateArray] objectAtIndex:4] setPosition:13 :10];
[[[[mapArray objectAtIndex:MAIN_MAP] moonGateArray] objectAtIndex:5] setPosition:3 :1];
[[[[mapArray objectAtIndex:MAIN_MAP] moonGateArray] objectAtIndex:6] setPosition:3 :12];
[[[[mapArray objectAtIndex:MAIN_MAP] moonGateArray] objectAtIndex:7] setPosition:22 :17];
NSLog(@"%i",[[[mapArray objectAtIndex:MAIN_MAP] moonGateArray] count]);

A: You probably haven't initialized either mapArray or moonGateArray thats why you are getting 0 count. In objective-c calling count on nil object doest not give any exception but instead returns 0.
hope that helps!

A: However for your count=0, this is straight forward you missed to alloc/init any of the array you used.
Are you creating a 2D array or 3D array?
It is creating confusion to get your logic?
Edit:
if your MAIN_APP is always 0, why you need an array, a simple object or instead of storing in 2D array you could have used dictionary. However the entire logic I can guess.
And I would like to add one more thing about your naming conventions... Name suffix or prefix your variable with Array, Button etc. you can use "maps", "moonGates", all plural symbolizes its gonna to be an array.

A: Most likely you haven't properly initialize your arrays. Make your like easier and change your code a bit to make it easier to read and easier to debug. You don't get points for writing highly nested method calls. It makes your life harder. Split the code up to make things easier.
Change this:
for (int i = 0; i < 8; i++) {
    [[[mapArray objectAtIndex:MAIN_MAP] moonGateArray] addObject:[Moongate new]];
}

to this:
// replace "SomeMapClass" with your actual class name
SomeMapClass *mainMap = mapArray[MAIN_MAP];
NSMutableArray *moonArray = mainMap.moonGateArray;
for (int i = 0; i < 8; i++) {
    [moonArray addObject:[Moongate new]];
}

Now you can run this code in the debugger or add NSLog statements and verify each step of the process.
Is mapArray properly initialized?
Is moonArray property initialized?
Remember, simply defining a property doesn't actually create the object. You still need to initialize it.


Q: ReactNative nested render functions. Question regarding `this` between objects and functions Here is my confusion:
     constructor(props) {
    super(props);
  }

  hookNav(){
    console.log("work");
  }

  renderItem({ item, index }) {
    return (
      <TouchableOpacity style={{ margin: 9 }} onPress={this.hookNav}>
        <View
          style={{
            flex: 1,
            minWidth: 170,
            maxWidth: 223,
            height: 280,
            maxHeight: 280,
            borderRadius: 10,
          }}
        >
          <ImageBackground
            source={{
              uri: "https://picsum.photos/170/223",
            }}
            style={{ flex: 1 }}
            imageStyle={{ borderRadius: 10 }}
          >
            <Text
              style={{
                color: "white",
                position: "absolute",
                bottom: 20,
                right: 10,
                fontWeight: "bold",
                textShadowColor: "black",
                textShadowOffset: { width: -1, height: 1 },
                textShadowRadius: 10,
              }}
            >
              Topic
            </Text>
          </ImageBackground>
        </View>
      </TouchableOpacity>
    );
  }

  render(){
    return (
      <View style={{ marginBottom: 80, backgroundColor: "white" }}>
        <Header
          centerComponent={{ text: "test", style: { color: "orange" } }}
          rightComponent={{ icon: "add", color: "orange" }}
        />
        <FlatList
          numColumns={2}
          onEndReachedThreshold={0}
          onEndReached={({ distanceFromEnd }) => {
            console.debug("on end reached ", distanceFromEnd);
          }}
          contentContainerStyle={styles.list}
          data={[
            { key: "a" },
            { key: "b" },
            { key: "c" },
            { key: "d" },
            { key: "e" },
            { key: "f" },
          ]}
          renderItem={this.renderItem}
          ListHeaderComponent={
            <Text
              style={{ padding: 10, fontWeight: "bold" }}
            >
              Your Topics
            </Text>
          }
        />
      </View>
    );
  }
}

in this code above, when navigating to this page an error is immediately thrown that this.hookNav is undefined.
However, when I put the hookNav function inside of a state object, like so
constructor(props) {
    super(props);
    state = {
      hookNav : function() {
       console.log("work please");
      }
    }
  }

and in onPress inside of renderItem
const { hookNav} = this.state;
    return (
      <TouchableOpacity style={{ margin: 9 }} onPress={hookNav}>

This works as intended.
It is my understanding that render already has access to the component’s state via this. If renderItem can access the state object, through this, why can it not access this.hookNav() directly? Why does the function need to be encapsulated in an object for this to work?
Thanks.

A: It's because the value of this inside any Javascript function depends on how that function was called.
In your non-working example, this.hookNav is inside of the renderItem method. So it will adopt the this of that method - which, as I just said, depends on how it is called. Further inspecting your code shows that the renderItem method isn't called directly by your component but passed as a prop (called renderItem) of the FlatList component. Now I don't know how that component is implemented (I've never used React Native), but almost certainly it calls that function at some point - and when it does, it can't be in the context of your component. This is because FlatList can't possibly know where that function prop is coming from, and when it calls it, it will be treated as an "ordinary" function, not in the context of any particular object. So its this context won't be your component instance, as intended, but will simply be the global object - which doesn't have any hookNav method.
This problem doesn't happen in your second example because you simply access the function as part of this.state - there is no passing of a method, like the renderItem in the previous example, which depends on an internal this reference. Note that this won't be the case if your hookNav refers to this inside it.
Such problems with this context are very common in React, but fortunately there are two general solutions which will always fix this:

*

*Bind methods in your component's constructor. If the constructor, in the first example, includes the statement this.renderItem = this.renderItem.bind(this);, then it would work fine. (Note that this is recommended in the official React docs.) It's the "best" solution technically (performance is slightly better than in the other option) - but does involve quite a bit of boilerplate if you have lots of methods which need such binding.

*Use arrow functions to define the methods instead. Instead of renderItem({ item, index }) {...}, write it as renderItem = ({ item, index }) => {...}. This works because arrow functions adopt the this of their lexical scope, which will be the class itself - so in other words this will always refer to the component instance, as you almost always want.
Don't worry if this is confusing - the behaviour of the this keyword in JS is a common stumbling block for beginners to JS, and often enough for those more experienced too. There are a number of good explanations online which demystify it, of which I can especially recommend this one.

A: You have to bind the method in to this of your class. One way to do so will be like below.
constructor(props){
  super(props);
  this.renderItem = this.renderItem.bind(this);
}


Q: linux - Bash Terminal not allowing usage of scripts even if terminal is at current directory of script itself So,I had Fedora installed in my computer,since Windows gave me no choice last time.
Then after I installed Fedora,I learned that Fedora was actually Linux - only modified,and thus,I wanted to try out the programming language that it has - BASH.
And my search for tutorials went on,and I found one.And it tole me to do something like:
#!/bin/bash
echo Hello World.

Then,I wanted to try it out,so I saved it as testscript.sh and then,opened Terminal,and this happened.
[JRGarcia@localhost ~]$ ./testscript.sh
bash: ./testscript.sh : command not found

So,I thought to myself: "That just ain't right!"
And then,on went my rampant rage across my room,and everything I have is destroyed right now.
What do I have to do? I saw some videos on tutorials and that method worked fine for them.BTW,I saved the script in the /home/JRGarcia,which is what Terminal uses as a starting directory.

A: If you have the x permission on the script and cannot execute it, it may be because you mounted the current partition with the option noexec. See explanation in manpage of mount
You can verify this by running the mount command without any arguments.

A: $ cat > testscript.sh
#!/bin/bash
echo Hello World.
^D
$ chmod +x testscript.sh
$ ./testscript.sh         #=> Hello world.

Works fine.


Q: Error when adding ext.grid.panel into ext.form.panel I have this grid and form panels. I want to add a grid of data into the form panel and still have buttons from the form panel.
      myGrid= Ext.create('Ext.grid.Panel',{
            layout: {
                type: 'fit'
            },

            id: 'gridId',
            title: null,
            store: myDataStore,
            columns: [{
                header: 'header 1',
                dataIndex: 'index_1',
                width: 120
            }, {
                header: 'header 2',
                dataIndex: 'index_2',
                width: 120
            }, {
                header: 'header 3',
                dataIndex: 'index_3',
                width: 120
            }],
            stripeRows: true
        })

        formPanel= Ext.create('Ext.form.Panel',{
            id:'panelId',

            items:[myGrid],
            buttons: [{
                 // cancel, save, other buttons
            }]
        })

But I get this error
HierarchyRequestError: Node cannot be inserted at the specified point in the hierarchy

what do I do wrong?

A: You forgot semicolons after your Ext.create() config.
Seems to work just fine here. I made a fiddle
http://jsfiddle.net/WGgR8/1/


Q: Is there an [embed] alternative for Flash only (not flex)? Ok we all know that you can embed assets with Flex using the [embed] code.
But is there anyway to achieve something similar to this when working with only Flash?
For example:
I need to create a class (that contains certain assets) that needs to be used in the Flash IDE, but I don't want to have to drop all the assets into the library for every Flash file that happens to use the class.

A: Are you looking for this? http://adobe.com/devnet/flash/articles/embed_metadata.html

A: Hope this will helpful for you.
http://www.adobe.com/devnet/flex/articles/actionscript_blitting.html
http://blog.nightspade.com/2010/02/01/embedding-asset-at-compile-time-in-pure-as3-project/
http://www.bit-101.com/blog/?p=853


Q: How to set a cron expression of current date + 14 days I am looking for a cron expression which will help in setting the cron job for current date + 14 days. This is a repeated exercise which will take place whenever a new code is deployed into dev environment and then use the current date of dev will used to schedule the trigger for prod after 14 days.
Example : This a BAMBOO CLI Command to set scheduled triggers in a Bamboo Plan.
--action addEnvironmentTrigger  --deploymentProject "Deploy ZDEPLOY4774565-BASE"  --environment "QA"  --type "Scheduled"  --description "scheduled trigger"  --schedule "1 0 0 ? * *"
Now once the dev deployment is successfully completed , then it will create a scheduled trigger for prod to be deployed after 14 days .so every time dev is deployed . I need to use the current date of dev .

A: Following cron expression will run 14 days once
0 5 */14 * * /your/command/

If you like to run only once from current date  on 20th September 2018
0 0 20 9 ? 2018  /command

WARNING: The year column is not supported in standard/default implementations of cron.

A: Run a cron-job every 14 days starting from day X
If you want to do this, have a look at this answer.
Run a cron-job only ones 14 days after day X
If you want to do this, there are a few options you have. Assume that day X is today (2018-09-06), then I give you the following options:
# Example of job definition:
# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7)
# |  |  |  |  |
# *  *  *  *  *   command to be executed
  0  0  6  9  *   [[ `date '+\%Y'` == "2018" ]] && sleep 1209600 && command1
  0  0  20 9  *   [[ `date '+\%Y'` == "2018" ]] && command2
  0  0  *  *  *   /path/to/daytestcmd 14 && command3

*

*The first option here is simply checking if the year is correct. If so, sleep for 14 days and then execute command1

*The second option is by computing the day itself and execute the script on that day. Again, you have to check manually for the correct year.

The third option is much more flexible for your purpose. The idea is to create a script called daytestcmd which does the check for you. The advantage of this script is that you only need to update one line in the script to change the test and never change the cronjob. The script would look something like:
#/usr/bin/env bash
# Give reference day
reference_day="20180906"
# Give the number of days to await execution (defaults to zero)
delta_days="${1:-0}"
# compute execution day
execution_day=$(date -d "${reference_day} + $delta_days days" "+%F")

[[ $(date "+%F") == "$execution_day" ]]

So, the next time you want to wait 14 days, just update the script and change the variable reference_day.
note: the OP updated the question. The above script can also be adjusted where reference_day is obtained via a set of commands, for example to retrieve the day of dev deployment. Imagine get_dev_deployment_day is a command which returns that day, then you just need to update
reference_day=$(get_dev_deployment_day)


Q: Custom css for paging in codeigniter I need a little help here,
I want using paging CodeIgniter.
Here my piece code for showing the paging.
    $this->load->library("pagination");
    $config = array();
    $key = $this->input->get_post('qfront');
    $config["base_url"] = base_url() . "source/";
    $config["total_rows"] = $this->fetch_count($key)->count;
    $config["per_page"] = 10;
    $choice = $config["total_rows"] / $config["per_page"];
    $config["uri_segment"] = 2;
    $config["num_links"] = round($choice);
    $config['full_tag_open'] = '

';
    $config['full_tag_close'] = '

';

    $config['first_link'] = '« First';
    $config['first_tag_open'] = '
';
    $config['first_tag_close'] = '
';

    $config['last_link'] = 'Last »';
    $config['last_tag_open'] = '
';
    $config['last_tag_close'] = '
';

    $config['next_link'] = 'Next →';
    $config['next_tag_open'] = '
';
    $config['next_tag_close'] = '
';

    $config['prev_link'] = '← Previous';
    $config['prev_tag_open'] = '
';
    $config['prev_tag_close'] = '
';

    $config['cur_tag_open'] = '
';
    $config['cur_tag_close'] = '
';

    $config['num_tag_open'] = '
';
    $config['num_tag_close'] = '
';
    $this->pagination->initialize($config);
    $page = ($this->uri->segment(2)) ? $this->uri->segment(2) : 0;
    $data["results"] = $this->fetch_result($config["per_page"], $page, $key);
    $data["links"] = $this->pagination->create_links();
    $data["key"] = $key;
    $this->load->view("page", $data);

in my view :
<?php echo $links; ?>

And what I got is

How can I make like <-prev 1 2 3 4 5 . . . 200 next->
Is it possible? Or maybe a little nice css

A: In the $config array passed into the pagination initialize() method, you can set the number of links to display on either side of the current page with num_links:
$config['num_links'] = 2;

From the CI user guide:

The number of "digit" links you would like before and after the selected page number. For example, the number 2 will place two digits on either side, as in the example links at the very top of this page.

That should get you closer to exactly what you want. I don't know the exact HTML generated by this library, so if you post it maybe someone can give you a CSS solution. You could also look into extending the CI pagination library to suit you needs (check out "Extending Native Libraries").


Q: Clean map periodically I have a A class managing a map.
class A {
 public:
  A() {}
  void addElem(uint8_t a, const B& b) {
    std::lock_guard<std::mutex> lock(_mutex);
    auto result = _map.emplace_hint(_map.end(), a, b);
    _deque.push_back(std::make_pair(result, time(nullptr)));
  }
  void cleanMap() {
    std::lock_guard<std::mutex> lock(_mutex);
    _map.erase(_deque.front().first);
    _deque.pop_front();
  }
 private:
  std::map<uint8_t, B> _map;
  std::deque<std::pair<std::map<uint8_t, B>::iterator, time_t>> _deque;
  std::mutex _mutex;
};

As I add a lot of elements in my map, I want to periodically clean it by removing elements that were first inserted.
if (difftime(time(nullptr), _deque.front().second > EXPIRY)) {
  cleanMap();
}

The following code is crashing at some point when I try to pop element from deque:
double free or corruption (fasttop): 0x00007fffdc000900 ***

Is the above code makes sense ? If yes, where could be the error ? And if not, how can I clean periodically a map ?

A: You have problems when you add the elements with the same key.
When emplace_hint is called with the key which exists, you push on deque duplicated iterators (emplace_hint returns the iterator to already existing element map::emplace_hint).
When deque and map are cleared, you call map::erase but it accepts only valid and dereferenceable iterators. So when erase is called for the duplicated iterator (map::erase), the code crashes because this item was deleted in previous erase call.


Q: Uploadify onComplete not firing I am using Yii framework with uploadify. The upload works perfectly but the onComplete event gets not fired..
It seems that the main problem of most of the users is that the .php file does not return anything and so flash does not know when the .php script has finished. But my script does echo "OK" at the end, so this is not the problem.
My Code:
$('#element').uploadify({
    'uploader' : 'index.php?page=upload',
    'swf'      : 'javascript/uploadify.swf',
    onComplete : function(event, queueID, fileObj, response, data) {
        alert(event); alert(queueID); alert(fileObj); alert(response); alert(data);
    },
});

My PHP Code looks like:
//Upload things
echo 'OK';

The upload works perfectly, but the onComplete event is not fired. I tried to remove all upload things, so that the php file looks like:
echo 'OK';

but that also does not work.
Thanks for your help!


Q: Jinja2 template if/else statement In a jinja2 template file, I'm attempting to find a string in a server hostname, then apply the settings I want based on what it found. Here is what I have. This works, however, everything is getting the developmenthosts setting.
{% if 'dev' or 'tst' or 'test' or 'eng' in ansible_hostname %} {{ developmenthosts }} {% else %} {{ productionhosts }} {% endif %}
Any help would be great, and I'm fairly new using jinja2 templates.

A: Try the following, using regex_search the if/else can be written in shorter and cleaner format.
"{{ developmenthosts if ( ansible_hostname|regex_search('dev|tst|test|eng') ) else  productionhosts }}"

Example:
---

- name: Sample playbook
  connection: local
  #  gather_facts: false
  hosts: localhost
  vars:
   developmenthosts: MYDEVHOST
   productionhosts: MYPRODHOST
  tasks:
  - debug:
      msg: "{{ ansible_hostname }}"
  - debug:
      msg: "{{ developmenthosts if ( ansible_hostname |regex_search('dev|tst|test|eng') ) else  productionhosts }}"


Q: Upload ALAsset URL images to the server I am trying to access iPhone's photo album photo images through ALAssetsLibrary and upload(send) the images to my server. I am being successful accessing the photo album and get the asset URL of each images, via the following code:
    - (void)viewDidLoad
{
    [super viewDidLoad];

    void (^assetEnumerator)(struct ALAsset *, NSUInteger, BOOL *) = ^(ALAsset *result, NSUInteger index, BOOL *stop) {
        if(result != NULL) {
            NSLog(@"See Asset: %@", result);
            [assets addObject:result];
            // Here storing the asset's image URL's in NSMutable array urlStoreArr
            NSURL *url = [[result defaultRepresentation] url];
            [urlStoreArr addObject:url];
        }
    };

    void (^assetGroupEnumerator)(struct ALAssetsGroup *, BOOL *) =  ^(ALAssetsGroup *group, BOOL *stop)
    {

        if(group != nil) {
            [group enumerateAssetsUsingBlock:assetEnumerator];
        }
        [self.activity stopAnimating];
        [self.activity setHidden:YES];
    };
    assets = [[NSMutableArray alloc] init];
    library = [[ALAssetsLibrary alloc] init];
    [library enumerateGroupsWithTypes:ALAssetsGroupAlbum
                           usingBlock:assetGroupEnumerator
                         failureBlock: ^(NSError *error) {
                             NSLog(@"Failure");
                         }];

    urlStoreArr = [[NSMutableArray alloc] init];
}

    -(void) UploadImagesToServer
{

for (int i=0; i<[urlStoreArr count]; i++)

{

       // To get the each image URL here...

        NSString *str = [urlStoreArr objectAtIndex:i];
        NSLog(@"str: %@",str);

        // Need to upload the images to my server..

    }

}

I want to upload the images which i got from the device asset's URL to my server. Could someone please advise how can i program it for sending the images to the server using this case?
Thank you!

A: you could use the below SO post code for uploading images to server.
How can I upload a photo to a server with the iPhone?
upload image from iphone to the server folder


Q: Proving that every integer has a Fibonacci number multiple Show that for any positive integer, there exists a Fibonacci number N such that N is divisible by the integer.
I'm not really sure how to begin my approach to this problem, would really appreciate any help!

A: Modulo $n$ the Fibonacci sequence is periodic (because $F_k=F_{k-1}+F_{k-2}$ and there are only finitely many possibilities for what congruence classes $F_{k-1}$ and $F_{k-2}$ can belong to), and $F_0=0\equiv0$, which means there must be some later number $i$ for which $F_i\equiv 0$.

Edit: As the discussion in the comments have pointed out, the gaps in this "proof" are a bit too wide for comfort, here is a more thorough proof.

Lemma. For any natural number $n$ there are two distinct natural numbers $k\neq k'$ such that $F_k \equiv F_{k'}\pmod n$ and $F_{k-1} \equiv F_{k'-1}\pmod n$.

Proof: Make a list of all the possible pairs $(F_k, F_{k-1})$. This list is infinite, but reduced modulo $n$, there are only $n^2$ possible distinct pairs $(a, b)$. By the pidgeonhole principle, we must at some point get a pair $(F_k, F_{k-1})$ which represents the same pair as an earlier $(F_{k'}, F_{k'-1})$ when regarded modulo $n$ (we can even conclude immediately that $k, k' \leq n^2$, but that doesn't matter, really). This finishes the proof of the lemma.
Given a natural number $n$, and $k \neq k'$ as in the lemma, we see that $F_k\equiv F_{k'}$ and $F_{k-1}\equiv F_{k'-1}$ implies $F_{k-2} \equiv F_{k'-2}$ (all congruences are modulo $n$). This is because of the Fibonacci recurrence relation which states that $F_{j - 2} = F_j - F_{j+1}$ (after rearranging). If the right-hand side for index $k$ is congruent to the right-hand side with index $k'$, then the same must be true for the left-hand sides.
Therefore, if $k, k'$ are as in the lemma, then so are $k-1, k'-1$. This means that any time we have such a pair, we can subtract $1$ from each of them and get a new pair. This we can keep going until one of them reaches $0$, and the other one ends up being $|k-k'|$. That means that $0 = F_0 \equiv F_{|k-k'|}$, and since $k \neq k'$, we are finished.


Q: How to use socket.io and Express.js with IISNode I have setup a windows 2012 r2 server with IIS, IISNode and Rewrite module.
This all seems the work just fine, simple applications with Express also seem to work well.
But when I add socket.io to the application, I get stuck. I get following Error:
*

GET http://mywebsiteadress/socket.io/socket.io.js net::ERR_ABORTED

*
I use IIS version 8.5.96, express version 4.16.2 and socket.io version 2.0.4.
Server:
let app = require('express')(),
    server = require('http').Server(app),
    io = require('socket.io')(server);

server.listen(process.env.PORT);

app.get('/',(req,res)=>{
    res.sendFile(__dirname + '/index.html');
})

io.on('connection',socket=>{
    socket.emit('test','working');
});

EDIT:
I changed
io = require('socket.io')(server);

to:
io = require('socket.io')(server,{
        path: '/SocketIO/socket.io'
    });

And now i'm getting this error:
polling-xhr.js:264 GET http://mywebsiteadress/socket.io/?EIO=3&transport=polling&t=M6RHmTd 404 (Not Found)
i.create @ polling-xhr.js:264
i @ polling-xhr.js:165
o.request @ polling-xhr.js:92
o.doPoll @ polling-xhr.js:122
r.poll @ polling.js:118
r.doOpen @ polling.js:63
r.open @ transport.js:80
r.open @ socket.js:245
r @ socket.js:119
r @ socket.js:28
r.open.r.connect @ manager.js:226
r @ manager.js:69
r @ manager.js:37
r @ index.js:60
(anonymous) @ (index):12

Client:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Socket IO Test Page</title>
</head>
<body>
    <script src='socket.io/socket.io.js'></script>
    <script>
        let socket = io.connect()

        socket.on('test',data => {
            console.log(data);
        })
    </script>
</body>
</html>

Web.config:
<configuration>
    <system.webServer>

        <handlers>
            <add name="iisnode" path="index.js" verb="*" modules="iisnode" />
        </handlers>

        <rewrite>
            <rules>
                <rule name="LogFile" patternSyntax="ECMAScript">
                    <match url="socket.io"/>
                    <action type="Rewrite" url="index.js"/>
                </rule>
            </rules>
        </rewrite>

    <webSocket enabled="false"/>

    </system.webServer>
</configuration>

What am I doing wrong? I have searched the internet and this forum, and tried a lot of things, but none seem to solve it for me.
I can't seem to find documentation on setting up Socket.io with IISNode?
I hope someone can help me.
Kind regards

A: Looks like your rewrite rule is wrong. Did you forget to add ".+" after your url attribute?
 <rule name="SocketIO" patternSyntax="ECMAScript">
     <match url="socket.io.+"/>
     <action type="Rewrite" url="server.js"/>
 </rule>


Q: Select options won't display when parent div is shown after being hidden I have a select box that is nested inside three divs as such:

                   Name:
                   <select name="ddlName" id="ddlName">
                    <option value="Name1">Name1</option>
                    <option value="Name2">Name2</option>
                    <option value="Name3">Name3</option>
                   </select>

              ...

         ...

    ...

The CSS:
#entry
{
    position:absolute;
    width:527px;
    height:364px;
    left:69px;
    top:214px;
    z-index:2;
    display:none;
}

The following jquery code is to show/hide the entry div based on clicking certain buttons:
$("document").ready(function() {
    $("#addButton").live("click", function(event) {
        $("#entry").show();
    })
    $("#closeEntry").live("click", function(event) {
        $("#entry").hide();
    })
})

The problem is that when I first click the add button, it shows the entry div and the select box works fine. After I click the close button and click the add button again, the select box will not let me select another option. It works fine in firefox but not ie7.

A: Found that it has something to do with jQuery UI CSS file. When I exclude it, the works. When I added an effect to the hide() and show() function, then it worked properly.


Q: How do i break a number down into a percentage (0 - 100%)? Details inside I am using a JS progress bar that is set using a percentage: 0 to 100 (percent). I need the progress bar to reach 100% when 160,000 people have signed a certain form. I have the total number of signers set in a PHP variable but am lost on how to do the math to convert that into a percentage that fits within 1 - 100 (so that the progress bar actually reflects the goal of 160,000).
I may be missing something obvious here (i suck at anything number-related) so does anyone here have a clue as to how to do this?

A: Percentage calculation is basic mathematics:
$total = 160000;
$current = 12345;
$percentage = $current/$total * 100;

A: Just
percentage = number/160000 * 100

A: If N is the goal, and X is the number of people that have signed so far, then the percentage is (X/N)*100.

A: ...you can't convert a number to a percentage?
$percent = ($currentNumber / 160000) * 100;

If you don't want a float answer you can just cast or round it however you'd like.

A: 160,000/160,000 = 1 = 100%
160,000/2 = 0.5 = 50%
Given this, the calculation should be easy. The numerator is the number completed and the denominator is the "goal" -- the total to complete.
So once you are 80,000 you'd be 50% complete and your progress bar would render as such.
If you need to work with smaller numbers, divide everything by 100 or 1000 and you can reduce the size of the numbers in a relevant manor.
160,000 / 1000 = 160  160 would be your denominator.  So than 50% would be 80/160. Does this make sense?

A: Do it Microsoft style:
current = 12345
percentage = 100*(1-exp(-current/100000))


Q: How to import multiple shapefiles each with different source projections to postgis I have a couple thousand .zip files each with a .shp, .dbf, .shx, and .prj inside them that I want to load into postgis. The problem is, they have many different source projections (each defined in the .prj file).
Is there any way to load them all at once without having to manually set the projection for each file?


Q: Mutual information maximization with additive uniform noise Assume that we have a uniformly distributed $X \sim \mathcal{U}(-\alpha,\alpha)$ and a random variable $Y$ with a yet-to-be-determined distribution defined on the same interval as $X$, i.e. $[-\alpha,\alpha]$.
For Z = X + Y, which distribution of $Y$ maximizes the mutual information $I(Z;Y)$ if $X$ and $Y$ are assumed to be stochastically independent?
My attempts so far (exploiting that $X$ and $Y$ are independent):
$$
\begin{align}
I(Z;Y)&=H[Z]-H[Z|Y]\\
&=H[Z]-H[X+Y|Y]\\
&=H[Z]-H[X|Y]\\
&=H[Z]-H[X]\\
&=H[Z]-\log(2\alpha)
\end{align}
$$
Furthermore, the range of $Z$ is given by $[-2\alpha,2\alpha]$, enabling us to upper bound $H[Z]$ by the entropy of the uniform distribution $\mathcal{U}(-2\alpha,2\alpha)$, hence $H[Z] \leq \log(4\alpha)$ must hold. This, in turn, implies $I(Z;Y) \leq \log(4\alpha) - \log(2\alpha) = \log(2)$.

A: I found the solution. One has to define $f_Y$ as a linear combination of Dirac distributions placed at $-\alpha$ and $\alpha$. Then we can prove that $Z$ is a uniform RV on $[-2\alpha,2\alpha]$ by integrating ("convolution").


Q: Multitenancy and Partitaioning HI There,
i have to make my application SAAS compliant .For achieving multi tenancy , i was thing of partitioning the data , and each partition will be for a tenant. and this partitioning will be done dynamically .
has anybody done something like this ?
what do you think the better approach be ?
i am using SQL 2005
Regards
DEE

A: There is a limit of 1000 partitions per partition scheme and you can only partition on a single field, so if you intend to multi-tenant beyond 1000 instances you are going to have to jump through a lot more hoops. You can extend the limit by using a partitioned view on top of multiple partitioned tables, but this increases the management overhead. You can use the DMVs and create your own automated system that generates new partitions per client / tenant and manages the problem but it will be specific to your application and not generic.
At present there is no automatic dynamic partitioning in SQL Server, it was mentioned at the PDC09 in relation to the SQL Azure future roadmap, but I did not hear of it for SQL Server.
Your alternative choices are a database or SQL Instance per client, there are benefits to this approach in that you give yourself far more opportunity to scale out if the needed arises, and if you start looking at a larger data centre, you can start balancing the SQL Instances across a farm of servers etc. If you automatically have all the data in a single database.
Other things to take into consideration:
Security: Whilst you have the data in a single database with partitioning, you have no data protection. You risk exposing one client's data to another very trivially with any single bug in the code.
Upgrading: If all the clients access the same database, then the upgrades will be an all or nothing approach - you will not be able to easily migrate some users to a new version whilst leaving the others as they were.
Backups: You can make each partition occupy a separate file group and try manage the situation. Out of the box so to speak, every client's backups are mingled together. If a single client asks for a rollback to a given data you have to plan carefully in advance how that could be executed without affecting the other users of the system.


Q: Using pwelch to a set of signals: some questions (Matlab) I would like to use pwelch on a set of signals and I have some questions.
First, let's say that we have 32 (EEG) signals of 30 seconds duration. The sampling frequency is fs=256 samples/sec, and thus each signal has length 7680. I would like to use pwelch in order to estimate the power spectral density (PSD) of those signals.
Question 1:
Based on the pwelch's documentation,

pxx = pwelch(x) returns the power spectral density (PSD) estimate, pxx, of the input signal, x, found using Welch's overlapped segment averaging estimator. When x is a vector, it is treated as a single channel. When x is a matrix, the PSD is computed independently for each column and stored in the corresponding column of pxx.

However, if call pwelch as follows
% ch_signals: 7680x32; one channel signal per each column
[pxx,f] = pwelch(ch_signals);

the resulting pxx is of size 1025x1, not 1025x32 as I would expect, since the documentation states that if x is a matrix the PSD is computed independently for each column and stored in the corresponding column of pxx.
Question 2:
Let's say that I overcome this problem, and I compute the PSD of each signal independently (by applying pwelch to each column of ch_signals), I would like to know what is the best way of doing so. Granted that the signal is a 30-second signal in time with sampling frequency fs=256, how should I call pwelch (with what arguments?) such that the PSD is meaningful?
Question 3: If I need to split each of my 32 signals into windows and apply pwech to each one of those windows, what would be the best approach? Let's say that I would like to split each of my 30-second signals into windows of 3 seconds with an overlap of 2 seconds. How should I call pwelch for each one of those windows?

A: Here is an example, just like your case,
The results show that the algorithm indicates the signal frequencies just right.
Each column of matrix, y is a sinusoidal to check how it works.
The windows are 3 seconds with 2 seconds of overlapping,
Fs = 256;
T = 1/Fs;
t = (0:30*Fs-1)*T;
y = sin(2 * pi * repmat(linspace(1,100,32)',1,length(t)).*repmat(t,32,1))';
for i = 1 : 32
[pxx(:,i), freq] = pwelch(y(:,i),3*Fs,2*Fs,[],Fs); %#ok
end
plot(freq,pxx);
xlabel('Frequency (Hz)');
ylabel('Spectral Density (Hz^{-1})');


Q: Logging for Custom Code Written in Spark We are writing Scala code for Apache Spark and running the process in Yarn Mode (Yarn Client Mode) in cloudera 5.5. Spark version is 1.5
I need to do logging for this code and want to move logs in Specific Directory for Spark ,outside of noise in spark logs
We are using plain log4j. Dont have time for logging trait for now.
I have changed the default log4j file in ${spark_home} like this
# Set everything to be logged to the console
log4j.rootLogger=ERROR, console
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.target=System.err
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d{yy/MM/dd HH:mm:ss} %p %c{1}: %m%n

# Spark Logs

log4j.appender.aAppender=org.apache.log4j.RollingFileAppender
log4j.appender.aAppender.File=/var/log/aLogger.log
log4j.appender.aAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.aAppender.layout.ConversionPattern=[%p] %d %c %M - %m%n
log4j.appender.aAppender.maxFileSize=50MB
log4j.appender.aAppender.maxBackupIndex=5
log4j.appender.aAppender.encoding=UTF-8

# My custom logging goes to another file
log4j.logger.fsaLogger=ERROR, fsaAppender

This is my Code in scala
This is inside main method
val logger =LogManager.getLogger("aLogger")
 val jobName = "AData"
 logger.warn("jobName ::" +jobName +" Started at ::" +
+Calendar.getInstance().getTime())

  val sc = new SparkContext(conf)
  val sqlContext = new org.apache.spark.sql.hive.HiveContext(sc)
  val sourceDF = sqlContext.read
    .format("com.databricks.spark.avro")
    .load(pathToFiles)

 finalCSMDF.map { row =>
//To remove Serilizable Exception
 var loggers = org.apache.log4j.LogManager.getLogger("aLogger")
 loggers.error("Test Log")
 row
 }

logger.warn("jobName ::" +jobName +" completed at ::" +
+Calendar.getInstance().getTime())

My problem here is that when ever i run this in yarn mode , i find the lines jobName ::" +jobName started" etc in /var/log/aLogger.log but not the  loggers.error("Test Log") which is inside the closure. Basically everything in driver is going in closure but not the exceutioners closures
Please help


Q: Solution of $\large\binom{x}{n}+\binom{y}{n}=\binom{z}{n}$ with $n\geq 3$ I found this question in an old problem set. There's no hint or solution mentioned.

For $n \geq 3$, prove or disprove the existence of $(x,y,z) \in \mathbb N^3, \large\binom{x}{n}+\binom{y}{n}=\binom{z}{n}$ (of course $x\geq n$, $y\geq n$,$z\geq n$

I really have no clue of the answer, and I can't disprove it either...

A: $${10\choose3}+{16\choose3}={17\choose3},\qquad{132\choose4}+{190\choose4}={200\choose4}$$ and see the discussion at https://mathoverflow.net/questions/27305/a-binomial-generalization-of-the-flt-bombieris-napkin-problem


Q: Migrating from mongodb to firebase My app currently uses mongodb and I'm looking forward to migrating it to firebase instead.
How easy is it to do and are there things I have to watch out for.

A: Isn't Firebase stores all its data in MongoDB?
Update May 2016
Apparently a page where Firebase was mentioned in MongoDB's site was removed (http://www.mongodb.org/about/production-deployments/)
After some search on their site I've found another page in their blog
https://www.mongodb.com/post/45270275688/mongodbs-growing-ecosystem (mirror)
where they say:

it’s great to see so many companies building on MongoDB. Here are just a few:

*

*Modulus. A Node.js platform as a service (PaaS) offering, Modulus includes MongoDB as its default data store. This follows related offerings from Meteor and Firebase.

An alternative to MongoDB would be RethinkDB and recently the team behind RethinkDB released Horizon, an open-source backend platform on NodeJS and that is kind of a locally hosted Firebase. Here's a nice talk about Horizon.

A: Given that both MongoDB and Firebase are non-relational in nature, most of your data should map to Firebase cleanly. The Firebase REST endpoints support regular JSON, so getting your data in (and, back out if you choose) should also be easy. The main areas you need to keep watch for are:

*

*The Firebase API is realtime/asynchronous in nature; specifically, when clients are reading data. Migrating your backend request/response code to the client and using this approach will probably be the biggest area with regard to level of effort.

*There will also be a disparity in the feature set that MongoDB and Firebase provide; notable areas include Mongo's support for doing things like MapReduce, Cursors, and free-text queries (Firebase doesn't currently support these areas).

The other thing to keep in mind is that Firebase isn't an all-or-nothing type of undertaking. Apps can definitely take advantage of the realtime, scaling, and platform features piecemeal.

A: Not specifically answering the question, but if you find Firebase lacking a few features which you you are used to with Mongo -
I found a node package which will allow you to run both with Firebase as the master DB.
Firebase

*

*Security/Authentication

*Sockets

MongoDB

*

*querying

*indexing

*aggregation

https://www.npmjs.org/package/mongofb


Q: AngularJS : $watch vs. $observe when newValue === oldValue If this is already explained or discussed somewhere, I am very sorry, but I couldn't find this exact problem discussed anywhere.
So I have an angular directive with one data binding 'myvar' (= or @ makes no difference). The value from the data binding is used in the directive: scope.myvarStr = scope.myvar + 'somestring'. Then I bind myvarStr in the template.
Because scope.myvarStr must be modified when scope.myvar changes, I used $watch('myvar', function(...)) to watch the value and update scope.myVarStr when needed. In the watch function I put the classic if (newValue === oldValue) return;
The problems started the very first time $watch fired and the two values were equal; then the view was not updated. I could easily see that from console.log(scope.myvar) on the first line in the link function that scope.myvar was undefined (or '' dependent on binding type) to begin with and that the value had changed to something else when I did a console.log in the $watch.
I googled for an hour or so, and found this: https://github.com/angular/angular.js/issues/11565
However, this issue wasn't discussed anywhere else, so I looked googled more and  came across $observe AngularJS : Difference between the $observe and $watch methods
When I changed from $watch to $observe, all my problems went away and I can still use if(newValue === oldValue) return;.
(function(directives) {
'use strict';

directives.directive('someDir', [function() {
    return {
        restrict: 'E',
        scope: {
            myvar: '=' //or @ didn't matter at the time...
        },
        template: '
{{myvarStr}}
',
        link: function(scope, el, attrs) {

            function toString() {
                if (scope.myvar < 1000) {
                    scope.myvarStr = scope.myvar;
                } else {
                    scope.myvarStr = scope.myvar/1000 + 'k';
                }
            }
            toString();

            scope.$watch('myvar', function(newValue, oldValue) {
                console.log("changed", newValue, oldValue)
                if (newValue == oldValue) return;
                toString();
            },true);

            // When changing to $observe it works :)
            //attrs.$observe('myvar', function(newValue, oldValue) {
            //    console.log("changed", newValue, oldValue)
            //    if (newValue == oldValue) return;
            //    toString();
            //},true);

        }
    };
}]);
}(angular.module('myApp.directives')));

Suggestion: As far as I understand this issue occurs with $watch because the scope value is never changed. It takes a while for the directive to pick up the value, until then the binding is just an empty string or something and when the value is detected the $watch fires but the actual scope value has not changed (or as explained in the first link; the first watch fires when the value 'appears' in the directive).

A: I don't quite understand your suggestion/explanation, but I feel like things are much simpler than you make it appear.
You don't need the newValue === oldValue test, because your watch-action is idempotent and cheap. But even if you do, it only means you need to initialize the value yourself (e.g. by calling toString() manually), which you seem to be doing and thus your directive should work as expected. (In fact, I couldn't reproduce the problem you mention with your code.)
Anyway, here is a (much simpler) working version:
.directive('test', function testDirective() {
  return {
    restrict: 'E',
    template: '
{{ strVal }}
',
    scope: {
      val: '='
    },
    link: function testPostLink(scope) {
      scope.$watch('val', function prettify(newVal) {
        scope.strVal = (!newVal || (newVal < 1000)) ?
            newVal :
            (newVal / 1000) + 'K';
      });
    }
  };
})

BTW, since you are only trying to "format" some value for display, it seems like a filter is more appropriate (and clear imo), than a $watch (see the above demo):
.filter('prettyNum', prettyNumFilter)
.directive('test', testDirective)

function prettyNumFilter() {
  return function prettyNum(input) {
    return (!input || (input < 1000)) ? input : (input / 1000) + 'K';
  };
}

function testDirective() {
  return {
    template: '
{{ val | prettyNum }}
',
    scope: {val: '='}
  };
}


Q: Responsive dataTable is not working with Bootstrap 4.3.1 I have an issue with the responsive DataTable Plugin and Boostrap 4.3.1 in this specific scenario:
I have an extra large modal which display a table, this table have 3 collapsed columns with some contact information this work as expected:

However in mobile display the table dont collapse the other columns as I would expect, and the table is not wraped inside the modal:

I used the following example at Datatables.net and loaded basically the same files with the exception of Bootstrap which is the version 4.3.1 and not the 4.1.3.
My HTML:

Opciones:

                <button type="button" class="close" data-dismiss="modal">×</button>

                            id
                            Nombre
                            Apellido
                            Departamento
                            Puesto
                            Fecha Creado
                            Extension
                            Telefono
                            Celular
                            Email

                            id
                            Nombre
                            Apellido
                            Departamento
                            Puesto
                            Fecha Creado
                            Extension
                            Telefono
                            Celular
                            Email

                <button type="button" class="btn btn-outline-dark" data-dismiss="modal">Cerrar</button>

My Javascript:
$('#opciones-list').on('click', 'a' ,(e) => {
            $('#modalOpciones').modal('show');
            var tablaEditar=$('#tablaDirectorio').DataTable({
                "destroy": true,
                "responsive":/*{
                    "details": {
                        renderer: function ( api, rowIdx, columns ) {
                            var data = $.map( columns, function ( col, i ) {
                                return col.hidden ?
                                '
'+
                                ''+col.title+':'+'	 '+
                                ''+col.data+'	'+
                                '
' :
                                '';
                            } ).join('');

                            return data ?$('
').append( data ) :false;
                        }
                    }
                }*/true,
                "autoWidth": false,
                "ajax": {
                    "url": 'controller/controller.php',
                    "method": 'POST',
                    data:{accion:'getTabla'}
                },
                "columns": [
                    {"data": "directorio"},
                    {"data": "nombres"},
                    {"data": "apellidos"},
                    {"data": "departamento_nombre"},
                    {"data": "puesto"},
                    {"data": "fechacreado"},
                    {"data": "Extension"},
                    {"data": "Telefono"},
                    {"data": "Celular"},
                    {"data": "Email"}
                ],
                "language":idioma_spanol,
                "columnDefs": [
                    {"className": "dt-center", "targets": "_all"}
                ]
            });
        })

Hope someone can help me on this one !!
Thanks in advice

A: CAUSE
Your table is hidden initially which prevents jQuery DataTables from initializing the table correctly.
SOLUTION
Use the code below to recalculate column widths of all visible tables once modal becomes visible by using a combination of columns.adjust() and responsive.recalc() API methods.
$('#modal').on('shown.bs.modal', function(e){
   $($.fn.dataTable.tables(true)).DataTable()
      .columns.adjust()
      .responsive.recalc();
});

You can also adjust single table by using table ID, for example:
$('#modal').on('shown.bs.modal', function(e){
   $('#example').DataTable()
      .columns.adjust()
      .responsive.recalc();
});

LINKS

*

*jQuery DataTables: Column width issues with Bootstrap tabs - Responsive extension – Incorrect breakpoints.

*Datatable jquery - table header width not aligned with body width

A: Try to wrap the table inside a divand then give it the attribute overflow:auto;


Q: ImageMagick code neeeds to be edited..please CHECK OUT please check my imagemagick code where iam trying to add "size" variable ,but not getting where exactly we need to add size variable just like "color" ,"string"...
$animation = new Imagick();
$animation->setFormat( "gif" );
$color = new ImagickPixel( "blue" );
$color->setColor( "red" );
     $string = "kothi!";
$draw = new ImagickDraw();
$draw->setFont( "arial.ttf" );
for ( $i =0; $i <= 0; $i++ )
{
$part = substr( $string,100, $i);

$animation->newImage( 100, 50, $color);

$animation->annotateImage( $draw, 100, 100, 100, $part );
$animation->setImageDelay( 30 );
}
$draw->setFont( "arial.ttf" );
$animation->newImage( 100, 50, $color);
$animation->annotateImage( $draw, 10, 10, 0, $string );
$animation->setImageDelay( 120 );
header( "Content-Type: image/gif" );
echo $animation->getImagesBlob();

A: bool Imagick::setSize ( int $columns , int $rows )

Sets the size of the Imagick object. Set it before you read a raw image format such as RGB, GRAY, or CMYK.
--php.net


Q: How to pass variable from stimulus-js to view file of Rails? Facing problem
The order of things I want to do is

*

*Open modal from @posts partial

*Enter the posting deadline in the form on modal

*POST the contents of the form to rails action that updates the posting flag to true

When opening the modal in item 1 of above, it will be lost track of the partial post record information, so I'm getting the partial post.id with the stimulus getter, but I'm having trouble embedding that id in the url specified in the form.
Development Env
ruby 3.1.2
rails 7.0.3
importmap-rails 1.1.2
tailwindcss-rails 2.0.10
stimulus-rail 1.0.4
Related source code
_post.html.erb
 <button data-action="click->modal#open" data-modal-id-param=<%= post.id %> class="flex justify-center ml-1 py-2 px-4">
 </button>

modal_controller.js
import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  static targets = ["modal", "form"]

  open(event) {
    event.preventDefault();

    this.modalTarget.showModal();

    this.modalTarget.addEventListener('click', (e) => this.backdropClick(e));

    this.idValue = event.params

    console.log(this.idValue)

  }

  backdropClick(event) {
    event.target === this.modalTarget && this.close(event)
  }

  close(event) {
    event.preventDefault();

    this.modalTarget.close();

    if (this.hasFormTarget) {
      this.formTarget.reset();
    }
  }
}

_publish_limit_form.html.erb
<dialog class="bg-white shadow-xl w-4/5 md:w-2/5 backdrop:bg-gray-700 backdrop:bg-opacity-50 open:animate-fade-in open:backdrop:animate-fade-in" data-modal2-target="modal">
  <button type="button" data-action="modal#close" class="float-right">
    <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
    </svg>
  </button>
  <%= form_with url: start_to_publish_admin_post_path(????), method: :patch, data: { modal2_target: 'form2'} do |f| %>
// <- Above, I want to embed the id in the specified url by extracting post.id from stimulus.  advice please! ! ->

<%= t('.please_set_publish_limit')%>

      <%= f.datetime_select :publish_limit, { min: Time.zone.now, minute_step: 30, discard_year: true, discard_second: true, start_minite: 30, start_second: 0 }, { class: "leading-none rounded mt-2" } %>
      <%= t('.until') %>

    <%= f.hidden_field :publish_status, value: 'is_publishing' %>

      <%= f.submit 'OK', class: "mt-3 font-bold leading-normal text-white py-4 px-10 bg-blue-700 rounded hover:bg-blue-600 focus:ring-2 focus:ring-offset-2 focus:ring-blue-700 focus:outline-none" %>

  <% end %>
</dialog>

Any advice on what to do would be greatly appreciated.


Q: How do I have the serial monitor of the Arduino show a string a value but only the value is changing? I already have my code to work, I'm just trying to make it look nicer now. Just to give a really short summary on what my device does: Smart parking system that detects cars going in and out of a parking lot and displays how many vacant spots are available or not at the entrance. Right now the output looks like this:
Vacant Spots: 1
Vacant Spots: 1
Vacant Spots: 1
Vacant Spots: 1
Vacant Spots: 0
.
.
.
.
.

This is in the case of when a car is entering so it's decrementing by 1 and it increments when a car leaves since there's a added vacant spot available. What I'm trying to do is have the output look like this:
"
Vacant Spots: 1
"
The only thing I want to change is the numerical value. I don't want a continuous stream of
" Vacant Spots: 1 "s to show at the LCD display for the parking user to see. Is there a way to just clear the serial monitor after the loop ends without having it output a new value below it continuously? I've provided the code for the program. I have 3 xbees (1 coordinator and 2 routers). The two routers dont have code on them and are just sending data to the coordinator. The coordinator is where it receives the data. This is the code for the coordinator:
int readValue = 0;
void setup()
{
  Serial.begin(9600);
}
int vslots = 1;

void loop()
{

  if(Serial.available()>21)
  {
        if(Serial.read() == 0x7E)
        {
          for(int i=0;i<19;i++)
          {
          byte discard = Serial.read(); //Next 18 bytes, it's discarded
          }
          readValue = Serial.read();

            bool flagTrue = false;
            bool flagFalse = false;

            if((readValue == 0) && flagTrue == false ) //EXIT
              {
                flagTrue = true;
                flagFalse = false;
                Serial.print("Vacant Spots: ");
                Serial.println(vslots);
              }
              else if((readValue == 16 && flagFalse == false) && vslots >= 1)
//DECREMENT (CAR ENTERING)
              {
                flagTrue = false;
                flagFalse = true;
                vslots -= 1;
                Serial.print("Vacant Spots: ");
                Serial.println(vslots);
              }

             if((readValue == 18) && flagTrue == false )
              {
                flagTrue = true;
                flagFalse = false;
                Serial.print("Vacant Spots: ");
                Serial.println(vslots);
              }
               else if((readValue == 19 && flagFalse == false) && vslots <= 10)
//INCREMENT (CAR EXITING)
              {
                flagTrue = false;
                flagFalse = true;
                vslots += 1;
                Serial.print("Vacant Spots: ");
                Serial.println(vslots);
               }

         }
   }
}

A: First, you need to understand that Arduino serial terminal is not like a real terminal software It does not support a command sent on UART. So to achieve what you want you will require real terminal software such as putty. Which allows you to make changes by sending character bytes using UART communication.
//ADD these lines before printing on a serial terminal
  Serial.write(27);       // 27 is an ESC command for terminal
  Serial.print("[2J");    // this will clear screen
  Serial.write(27);       // 27 is an ESC command for terminal
  Serial.print("[H");     // move cursor to home
//now print what you want...
  Serial.print("Vacant Spots: ");
  Serial.println(vslots);

For more info and methods you can check this post here. But had tried everything and suggesting to go with putty.

A: The ln suffix in println stands for new line. That means println will "print" the value and a newline.
So as an initial solution you could change from using println to plain print:
Serial.print("Vacant Spots: ");
Serial.print(vslots);  // Note: not println

Then we have to solve the problem of going back to the beginning of the line. to overwrite the old text. This is typically done with the carriate-return character '\r'. If we add it to the beginning of the printout:
Serial.print("\rVacant Spots: ");  // Note initial cariage-return
Serial.print(vslots);  // Note: not println

Then each printout should go back to the beginning of the line, and overwrite the previous content on that line.
To make sure that each line is equally long, you could use e.g. sprintf to format the string first, and then write it to the serial port:
char buffer[32];
// - for left justification,
// 5 for width of value (padded with spaces)
sprintf(buffer, "\rVacant Spots: %-5d", vslots);
Serial.print(buffer);


Q: Can I develop a desktop app in VS2008 that can also run on Mac? What approach? Can I develop a desktop app in VS2008 that can also run on Mac?  What approach?
That is, if I am developing an application (thick client) that runs on a Windows XP/Vista PC, is there an approach to do this such that I could also run it on a Mac?  (e.g. silverlight?)
The kind of things my winforms type app needs includes:

*

*HttpWebRequest / HTTP calls

*Access to underlying Sqlite database (via ADO.net)

*Windows / Dialogs

*System Tray Presence

I'm currently working in VS2008 and using WinForms, so I'm not really across WPF / Silverlight etc.
Thanks

A: I would suggest using Mono for this project, since you're already in Windows Forms.  You'll have difficulty with the database requirement using Silverlight, and WPF will not work at all.

A: Agreed on the Mono front.  I would definitely check out Mono Develop - it's the cross platform Mono IDE.  It's been released for Mac so that may help you port your app (or even develop it!)

A: I would suggest looking into Silverlight 4.0. Beta version is already available. I expect to see release at Mix 2010 (which is March 15-17th).
From what you requested it already supports

*

*HttpWebRequest / HTTP calls

*Windows / Dialogs (kind of)

*System Tray Presence

As for access to underlying Sqlite database (via ADO.net) this can be achieved through RIA Services.
Silverlight supports out of browser mode, and runs both on Window and Mac. IDE is VS 2010, and (probably) Eclipse.


Q: Custom Calendar for sales data aggregated by weeks and months I am struggling with creating Custom Calendar that would allow me to use time intelligence function on data that is already aggregated by weeks and months. The original table with transactions contains over 20M rows, so for performance and space saving reasons the grouping is necessary and I perform it while querying the database in SQL Server. I want to create:

*

*Month vs Same Month Last Year

*Week vs Same Week Last Year

*Year-To-Date vs Last Year Year-To-Date (by Months)

*Year-To-Date vs Last Year Year-To-Date (by Weeks)
My idea was to assign some dummy dates to each row of data, and then create custom calendar that would have each of these dummy dates along with other details. I just cannot figure out the key (how to create dummy date having Year number Month number and Week number - please keep in mind that for example Week 5 of 2020 is  partially in January and partially in February)
Is it possible? Maybe I have to create 2 separate Calendars, one for Weeks and one for Months?

A: Add calculated table:
Calendar =
GENERATE (
    CALENDAR (
        DATE ( 2016,  1,  1 ),
        DATE ( 2020, 12, 31 )
    ),
    VAR VarDates = [Date]
    VAR VarDay = DAY ( VarDates )
    VAR VarMonth =  MONTH ( VarDates )
    VAR VarYear = YEAR ( VarDates )
    VAR YM_text = FORMAT ( [Date], "yyyy-MM" )
    VAR Y_week = YEAR ( VarDates ) & "." & WEEKNUM(VarDates)

    RETURN
        ROW (
            "day"     , VarDay,
            "month"   , VarMonth,
            "year"    , VarYear,
            "YM_text" , YM_text,
            "Y_week"  , Y_week
        )
)

You can customize it. In relation pane connect your Date field of FactTable (which is by week, as you say. This table can have missing dates and duplicate dates, to be precise) to the field Date of the Calendar table (which has unique Date, by day). Then, in all your visuals or measures always use the the Date field of the Calendar table. It is a good practice to hide the field Date in your FactTable.
More explanations here https://stackoverflow.com/a/54980662/1903793


Q: the result weka j48 classifyinstance is not correct I already build a tree to classify the instance. In my tree, there are 14 attributes. Each attribute is discretize by supervised discrete. When I created a new instance, I put the value in this instance and classify it in my tree, and I found the result is wrong. So I debug my program, and I found the value of the instance is not divided into the interval correctly. For example:
value of the instance:0.26879699248120303 is divided into '(-inf-0]'.
Why?

A: Problem solved.I didn't discretize the instance that was to be tested so that the weka didn't know the format of my instance.add the following code:
discretize.input(instance);//discretize is a filter
instance = discretize.output();


Q: continuity of a multivariable function2 I'm studying the continuity of the function
$$ f(x,y) = \left\{
   \begin{array}{l l}
     \frac{x^2y^2}{x^2+y^2} & \quad , \quad(x,y)\neq(0,0)\\
     0 & \quad , \quad(x,y)=(0,0)
   \end{array} \right.$$
in the point $(x,y)=(0,0)$.
It's clear to me that if a function is not continuous I have to find a case of discontinuity, but perhaps it's more difficult to prove the continuity in which I can't find a fault in the behaviour of the function.
In this case how can I show the limit
$ \lim_{(x,y)\rightarrow (0,0)}  f(x,y) = \lim_{(x,y)\rightarrow (0,0)}
     \frac{x^2y^2}{x^2+y^2} =0$?
It's simple to prove that on a line $y=mx$ through the origin $(0,0)$ but in the most general way?

A: You might consider a slightly more general case:

Claim. Let $\displaystyle f(x) = \frac{p(x)}{|x|^{r}}$ be an application of $\mathbb{R}^{n}$ to $\mathbb{R}$ (i.e, $x = (x_{1},...,x_{n}$)), with $p(x)$ a monomial in $m$ variables ($n\geq m$) such $\deg (p(x)) > r$. Then
  $$\lim_{x\to 0}f(x) = 0.$$

Proof. For each $i = 1,...,m$ we have $x_{i}^{2} \leq |x|^2$ and so $(x_{i}^{k})^{2} \leq |x|^{2k}$. Thus
$$(x_{1}^{s_{1}}\cdot \ldots \cdot x_{m}^{s_{m}})^{2} \leq (|x|^{s_{m}}\cdot \ldots \cdot |x|^{s_{m}})^{2} = |x|^{2ms_{m}} \Longrightarrow \frac{(x_{1}^{s_{m}}\cdot \ldots \cdot x_{m}^{s_{m}})^{2}}{|x|^{2r}}\leq |x|^{2(ms_{m}-r)}$$
and, since $\deg (p(x)) > r$, so $ms_{m}-r\geq0$ (suppose $s_{m} = \max s_{i}$), then
$$\frac{(x_{1}^{s_{m}}\cdot \ldots \cdot x_{m}^{s_{m}})^{2}}{|x|^{2r}}\leq |x|^{2(ms_{m}-r)} \Longrightarrow |f(x)| \leq |x|^{ms_{m}-r}.$$
Therefore
$$\lim_{x \to 0}|f(x)| \leq \lim_{x \to 0}|x|^{ms_{m}-r} = 0.$$

In your case, $p(x)=x^2 y^2$ has degree $4$ and if $z = (x,y)$, so $x^2 + y^2 = (\sqrt{x^2 + y^2})^{2} = |z|^{2}$ and $\deg(p(x)) = 4 > r = 2$.

I think this works.

A: For $x=0$ or $y=0$, it is clear that the fraction equals $0$, so we may, without loss of generality, assume that we approach the origin through a path where $x,y\neq0$. Then we can apply AM-GM to observe that $x^2+y^2\geq2\sqrt{x^2y^2}=2|xy|$. This yields $$\lim_{(x,y)\rightarrow (0,0)}
     \left|\frac{x^2y^2}{x^2+y^2}\right|\leq\lim_{(x,y)\rightarrow (0,0)}
     \left|\frac{x^2y^2}{2|xy|}\right|=\lim_{(x,y)\rightarrow (0,0)}\frac{|xy|}{2}=0.$$
This is just a nice trick that often works. It can be done way simpler in this case, however: $$\lim_{(x,y)\rightarrow (0,0)}
     \left|\frac{x^2y^2}{x^2+y^2}\right|\leq\lim_{(x,y)\rightarrow (0,0)}
     \left|\frac{x^2y^2}{x^2}\right|=\lim_{(x,y)\rightarrow (0,0)}
     |y^2|=0.$$
There are many strategies to tackle these problems, and it is probably best to try the second approach first. AM-GM is a nice trick that often works.
It is really important, however, that the fact that the iterated limit, for an $m\in\mathbb{R}$ $$\lim_{x\to0}\lim_{y\to mx}f(x,y)=L,$$ does not imply the limit exists. For example, the limit of $f(x,y)=\frac{x^2y}{x^4+y^2}$ as $(x,y)\to(0,0)$ exists along every straight line approaching the origin but not along the parabola $y=x^2$.

A: Consider $\varepsilon>0$. for $x,y)\neq (0,0)$
$$ f(x,y) = \frac{x^2y^2}{\|\vec x\|^2} \leq \frac{\|\vec x\|^4}{\|\vec x\|^2} = \|\vec x\|^2. $$
Thus, for any $0<\delta^2 <\varepsilon$
$$
\sqrt{x^2+y^2}<\delta \Longrightarrow |f(x,y)|\leq \delta^2<\varepsilon .
$$

A: An option:
$x=r\cos t$ ; $y =r\sin t$, $r$ , real, positive; and $0 \le t <2π.$
$F(r,t):= \dfrac{r^4\sin ^2 t \cos^2 t}{r^2}=$
$r^2 \sin^2 t \cos^2 t=(1/4)r^2 \sin ^2 (2t).$
Now consider the limit $ r \rightarrow 0$.