text:
Q: Why we can't call methods of Date() class without new operator Suppose I define a variable like this
var today = Date();
console.log(today.getMonth()); // Throw Error

while other class like Error class call their methods without new operator.
function factorial(x) {
 if(x <= 1)
   throw Error("x must not be negative");
 return x*factorial(x-1);
}

Also wrapper objects (number, boolean, string) can call their methods without new operator.
So, Is this the only class which require new operator or any object creation technique before calling their methods.
Edit: As Date() is a string type, so it should be call their methods without creating objects. Because string type behave as if they are objects. So why not?
Edit 2: I think this is the only core function which cannot be same as new Date() like other functions (Array(), String(), Error() etc). So, it's also the hidden feature of this language or ECMAScript mistake.

A: It is perfectly valid for a JavaScript constructor function to act differently when called with new or without. This is the case of the Date function which returns the date as a string when called without new and as a full fledged object when called with new.

A: ECMAScript Language Specification
According to the ECMAScript specification (on which Javascript is based):

When Date is called as a function rather than as a constructor, it
  returns a String representing the current time (UTC).
NOTE The function call Date(…) is not equivalent to the object
  creation expression new Date(…) with the same arguments.

Reference: http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.2
Calling Constructor vs Calling Function
You need the new because you are creating a new Date object.
Calling simply Date() , means calling a function that returns the Date() as a string.
See: http://www.javascripture.com/Date
Date() : String
Returns a string representation of the current date and time.

In the case of other types such as Array or Error, the functions are factory functions that create a new object and return them.
See:

*

*http://www.javascripture.com/Error

*http://www.javascripture.com/Array
Error(message : String) : Error
Creates a new Error with the specified message that describes the error.
new Error(message : String) : Error
Same as Error(message)

A: The point in using new is to create an instance inheriting from Date's prototype.
That's what makes possible that the object can be the receiver of Date's functions.
When you use Date() (which is in my opinion a useless function), you're really getting a string which is the equivalent of (new Date()).toString(). Of course this object only has string functions, not the one of Date.


text:
Q: windows7 laptop computer. cup intelD425-1.80G It says reboot and select proper  boot device or insert Boot Media in selected Boot device and press a key. how should  I do this?

A: Sounds like your hard drive is dead or you have a device that your system is trying to load first.
A D425 is ~5 years old. Hard drives often last roughly that long.
Bad news is if you don't have backups, any data that was on the drive including the recovery partition is gone, and well, you may need to reinstall.
Troubleshooting steps, in order would be

*

*Disconnect any external device. Remove any SD cards, CDs... ANYTHING that could be bootable other than any HDD

*Check if the hard drive is detected in bios.

*Try reseating the hard drive if it is not

*Boot from a known good liveusb install of linux (I favour lubuntu or xubuntu) to check if the system is able to boot. If the drive is detected, install gsmartctrl and use that to check if the drive is clearly unhealthy. Run a short smart test from gsmartctrl to make sure there's no errors.

*If the drive is detected and you want to attempt to do data recovery, try imaging the drive with gddrescue and mount it with kpartx. Dosen't seem likely here.

*Purchase a new drive, install it, and reinstall your OS.

A: This message means that the BIOS is not able to locate the boot device on your machine.
It possibly means that the hard drive is dead, or the Windows boot partition on it.
Another possibility is that the boot order setuped in the BIOS configuration does not list the device containting the boot partition.
It can happen if a hard drive is added and if this ones replaces the old one containing Windows in the BIOS boot order list.

*

*First, check if your hard drive is detected in the BIOS.

*Second, check the boot order device list

*Third, try to boot to a rescue CD
(LiveCD Linux or else) to check the hard drive sanity.

A: Like other answers, the hard drive may be dead if you can't boot from it.
What you can try:

*

*Check to see if there is a clicking sound (Hard Drive is most likely dead then)

*If the Hard Drive is accessible, make sure it is properly connected and screwed in

*Check the BIOS and see if your hard drive is detected in the BIOS Setup. If it is, then you'll need to use a rescue disk to try and recover or get a copy of Windows and reinstall.

You might want to look into getting a SSD if you need a replacement. They are much faster then Hard Drives but don't last as long.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is it possible to save a NSManagedObjectModel? I have the following requirement: create and populate a SQLite database with data from a .xml file, this file can have a different structure any time so I cannot create the NSManagedObjectModel with Xcode, it must be at runtime. I've successfully created a NSManagedObjectModel programmatically, created the persistent store and populated the sqlite file with data from the .xml . However, the next time I use the app the persistent store is not compatible with the NSManagedObjectModel (I don't want to recreate the Model every time I run the app, just the first time). Is there any way to save the model I created programmatically and load it the next time it is needed? All I can see in the examples are models being loaded from the NSBundle.

A:
Is there any way to save the model I created programmatically and load it the next time it is needed?

Yes. NSManagedObjectModel conforms to NSCoding, which means that you can easily convert it to/from NSData, and saving and reading NSData is easy.
To save a model:
NSString *modelPath = // path where you want to save
NSData *modelData = [NSKeyedArchiver archivedDataWithRootObject:self.managedObjectModel];
[modelData writeToFile:modelPath atomically:YES];

To read a saved model:
if ([[NSFileManager defaultManager] fileExistsAtPath:modelPath]) {
    NSData *savedModelData = [NSData dataWithContentsOfFile:modelPath];
    NSManagedObjectModel *savedModel = [NSKeyedUnarchiver unarchiveObjectWithData:savedModelData];
}

A: I'm not sure if you are saying that the data in the xml file is changing each time or what. It sounds like you are referring to the data, not the data model. I can't answer specifically, but I would take the approach as follows.
If the data in the xml file is structured the same or close to the same each time, I would create a data model to match that.
Then I would write some sort of parser class that would read the xml and parse it into the Core Data data store according to you "ManagedObjectModel" or data model.
I have seen the error you are talking about when you change the datastore outside of Core Data. You need to let Core Data handle all the reading and writing to the data store or else Core Data will tell you basically that "Your Persistent Store was created or altered by something other than your ManagedObjectModel".  I think this is what is happening.
I know I am not using the terminology exactly as Core Data puts it, but Core Data is confusing and I'm trying to convey the message and understanding.
I would also look in to using MagicalRecord. It Drastically makes Core Data easier to work with and there is a great tutorial on www.raywenderlich.com which you can find Here
I really hope this helps you out some. If not, please post some sample code or maybe an example of that xml you are referring to.
Good Luck


text:
Q: Another way to write, ''Why now''? When people know it is good, but are suspicious of the timing) Another way to write, ''Why now''? (When people know it is good, but are suspicious of the timing)

A: One approach that I've seen writers take is to identify the fortuitous event, spell out its benefits to the public (voters, employees, or whoever else), and note any advantage that its occurring at this particular moment might have for people in positions of decision-making power (incumbent politicians, embattled corporate executives, or others who may have a vested interest in the outcome)—and then conclude with the one-word question, "Coincidence?"
Here is a fictitious example:

After months of delays in responding to demands by citizens for street repairs, Mayor Blaine Blintz today announced authorization of large-scale repairs on several important roadways. Construction, which should be complete approximately three weeks before scheduled municipal elections take place, will include resurfacing of major thoroughfares running through several neighborhoods where allies of the mayor are in close contests for reelection. Coincidence?


text:
Q: Proof of Hausdorff's moment theorem using Fourier's series Let $f \in \mathcal{C}^0([0,2\pi])$ such that : $\forall n \in \mathbb{N}\ $, $\displaystyle \int_{0}^{2\pi}t^nf(t)\mathrm{d}t=0$.
I have to show that : $\forall n \in \mathbb{Z}, \ \displaystyle \int_{0}^{2\pi}f(t)\exp(-int)\mathrm{d}t=0$ and $f\equiv 0$.
Here is the beginning :
Let define $\widetilde{f}$ the $2\pi$-periodic, even, continuous function on $\mathbb{R}$ which fits with $f$ on $]0,2\pi]$.
Moreover the Fourier's coefficients give : $\forall n\in \mathbb{Z}$ : $c_n(\widetilde{f})=\displaystyle \frac{1}{2\pi}\int_{0}^{2\pi}f(t)\exp(-int)\mathrm{d}t$.
Then we can notice that : $\exp(-int)=\displaystyle \sum \limits_{k\ge 0}\frac{(-int)^k}{k!}$.
So $c_n(\widetilde{f})=\displaystyle\frac{1}{2\pi}\int_{0}^{2\pi}\left(\sum \limits_{k\ge 0}f(t)\frac{(-int)^k}{k!}\right)\mathrm{d}t$.
Let's try to exchange $\displaystyle \sum$ and $\displaystyle \int$ :
Fix $n\in \mathbb{N}$.
-For all $k\ge 0$, the functions $t\mapsto f(t)\dfrac{(-int)^k}{k!}$ are continuous on $[0,2\pi]$.
-For all $t\in [0,2\pi]$ : $\Big\vert f(t)\dfrac{(-int)^k}{k!} \Big \vert \le \vert f(t)\vert \Big\vert\dfrac{(-int)^k}{k!}\Big\vert \le M\dfrac{\vert-int\vert^k}{k!}=M\dfrac{(2\pi n)^k}{k!}$.
That last term is the general term of a convergent series (of sum $M\exp(2\pi n)$) so we can deduce that the series converges uniformly on $[0,2\pi]$.
Hence : $c_n(\widetilde{f})=\displaystyle\frac{1}{2\pi}\int_{0}^{2\pi}\left(\sum \limits_{k\ge 0}f(t)\frac{(-int)^k}{k!}\right)\mathrm{d}t = \displaystyle \frac{1}{2\pi} \sum \limits_{k\ge 0}\int_{0}^{2\pi}f(t)\frac{(-int)^k}{k!}\mathrm{d}t = \displaystyle \sum \limits_{k\ge 0} \frac{(-in)^k}{2\pi (k!)} \int_{0}^{2\pi}f(t)t^k\mathrm{d}t =0.$
We can conclude using Parseval's formula (for $f \in \mathcal{C}^0([0,2\pi])$) :
$\displaystyle \int_{0}^{2\pi} \vert f(t) \vert^2\mathrm{d}t = \sum \limits_{n\in\mathbb{Z}} \vert c_n(\widetilde{f})\vert^2 = 0$ hence $f \equiv 0$.
At the end we want $[a,b]$ instead of $[0,2\pi]$ but the variable change $u=a+t\left(\dfrac{b-a}{2\pi}\right)$ seems to work no ?
Is the general reasoning correct ?
Thanks in advance !

A: You do not need Fourier series to prove that if $f\in C^0([0,2\pi])$ and $\int_{0}^{2\pi}x^n f(x)\,dx = 0$, then $f\equiv 0$ on $[0,2\pi]$ (so $\int_{0}^{2\pi}f(x) e^{\pm in x}\,dx$ is obviously zero). By the Weierstrass approximation theorem, for any $\varepsilon >0$ there is a polynomial $p(x)$ such that $\left|f(x)-p(x)\right|\leq \varepsilon $ for any $x\in[0,2\pi]$. By the assumptions
$$ \int_{0}^{2\pi} p(x)\,f(x)\,dx = 0 $$
hence $\int_{0}^{2\pi} f(x)^2\,dx $ is arbitrarily close to zero. Since $f$ is continuous on $[0,2\pi]$, $f\equiv 0$.


text:
Q: Dense data set of locations for flow analysis I want to do some analysis on real world data related to crowd flows and now I am looking for a publicly available (or at least available to academia) data set of trackings in a crowd. The data set does not neccesarilly have to be from humans, eg. locations of kettle's would also work. The required features are:

*

*Dense in the sense of many tracklets on a relatively small area during the same time window, the more the merrier

*Individuals/tracklets have to be identifiable (ie. it must be possible to link all locations added by one individual to some kind of id) at least for some time periods

*Bonus for underlying ground truth (eg. a fair going on)

I have searched the webs for about 4 hours now but couldn't find anything that fits at least the first two requirements, any ideas are very welcome.


text:
Q: Github Visual Studio Pull : Will it include the Project's references? Github Visual Studio 2022 Git Pull : Will it include the Project's references?
Using Visual Studio 2022 with Git. When pulling from a hosted repository into my local machine, will that also automatically set the same project references in my local machine as it is in the hosted repositories?
What should be the expected behaviour?
Thank you
I tried but I see other references than other users on other machines.

A: The project references should be defined in the .csproj file (or .vbproj, etc).  This file should be included in ones source control repository.
You may need to perform a nuget restore if the references are fetched from a package manager (i.e. https://nuget.org), especially if someone else modified the references and pushed them to your remote in GitHub
For example, someone else on your project updates a reference to a newer version and pushes it up to GitHub.  You then perform a git pull on the branch that these changes were made on, and suddenly you have new references or possibly see errors all over your code.  When this happens, you almost certainly need to perform a nuget restore to get the new package references.


text:
Q: C socket API is thread safe? I'm using both Linux and Win32 socket APIs. In my program, multiple threads share a socket handle. In particular, multiple threads call send with the shared socket handle (i.e., the same port). In this case, do I have to put a lock for thread safety? I was unable to find the answer. I may do a test, but want to hear your experiences.
EDIT: I know that such sending data via socket isn't atomic operation at all. Definitely we have to use a mutex for thread safety. However, I was wondering whether the system API could have their own internal lock. If so, we can omit putting our own lock.
This question may be applicable to fprintf function as well. I'm wondering such system APIs would have their own locks. In my experience, calling fprintf from multiple threads didn't kill my program although there was races on a file or stdout (i.e., inconsistent or unpredictable outputs, but the program was not crashed), which implied fprintf had a lock to protect their internal data structure.

A: I find multiple socket close() file descriptor calls extremely dangerous in concurrent environment.
Usually multiple calls are ignored, but in case other thread opens another file descriptor, quite often it gets previous file descriptor, and nightmare starts.

A: Sockets are not part of C++ Standard so it depends on implementation. Generally they are not thread safe since send is not an atomic operation. Check this discussion for additional information.
EDIT: OS could have or couldn't have internal lock for protecting internal structures. It depends on implementation. So you should not count on it.

A: Sending data via a socket is not a atomic transaction - any non-atomic transaction will require a lock/synchronisation. This is independent of the platform.

A: No, the variable created with accept does not need to be mutex. Any data used by threads should at least be semaphores.
sem_t* sem_data;


text:
Q: Passing a lambda function as a parameter I'm trying to create an equivalent to Javascript's Array#map in Java.
I have been able to do it with
ArrayList<String> data = myList.stream().map(e -> {
    return "test "+e;
}).collect(Collectors.toCollection(ArrayList::new));

Here, myList is the initial ArrayList and data is the resulting ArrayList.
However, I find it very tedious to do that every time.
So I tried to create a generic function that would make my life easier :
public static ArrayList<?> map(ArrayList<?> list, Function<? super Object,?> callback){
    return list.stream().map(callback).collect(Collectors.toCollection(ArrayList::new));
}

And then calling it with:
ArrayList<String> data = DEF.map(myList,e -> {
    return "test "+e;
});

But I get the error

[Java] The method map(ArrayList, Function) in the
  type DEF is not applicable for the arguments (List, (
  e) -> {})

How can I edit my generic function to accept the lambda I'm using?

A: You should define your method with two generic type parameters - the element type of the source list, and the element type of the target list :
public static <S,T> ArrayList<T> map(ArrayList<S> list, Function<S,T> callback)
{
    return list.stream().map(callback).collect(Collectors.toCollection(ArrayList::new));
}

It would also be better to use the List interface instead of ArrayList:
public static <S,T> List<T> map(List<S> list, Function<S,T> callback)
{
    return list.stream().map(callback).collect(Collectors.toList());
}

Example of usage:
List<Integer> myList = Arrays.asList (1,2,3,4);
List<String> datai = map(myList ,e -> "test " + e);

Output:
[test 1, test 2, test 3, test 4]


text:
Q: Other than when used as a name, is there any evidence of the word "puck" before Hockey Was trying to search history on the word puck, but couldn't find what I was looking for. It seems that before 1870 there are only instances of "puck" when used as a name. Some sources, like Etymonline, indicate it originated from "poke", which referred to the hitting or striking of the object. Was wondering if there were any other potential sources of this word as we often refer to other similarly shaped object as "pucks".

A: The OED's first example of the word "puck" in the modern sense comes from the Boston Daily Globe in 1866:

In hockey a flat piece of rubber, say four inches long by three wide
  and about an inch thick, called a 'puck', is used.

There's a much older definition of the word:

An evil, malicious, or mischievous spirit or demon of popular belief.

The OED has examples of this definition going back to 1378. According to the etymology, this meaning is even older:

Probably cognate with Old Icelandic púki mischievous demon, the Devil

You are correct in thinking that the use of the name "puck" for the small rubber disc likely came from the verb "poke." Around the same time that the black biscuit got its name, the verb "to puck" had been developed as an offshoot of "to poke." Here's how the OED defines that infinitive version of "puck":

To hit or strike; to butt; to box.


text:
Q: How I authentificate my android app requests to my server? I have an Android app that connects to a external server for receiving/setting data. The problem that the server reply to request of everyone. How can I make it reply only from the request of my application.
Thanks in advance!


text:
Q: Count Dates which a specific Customer does not have a Shop in it Here is an example Data Table:
ID    Amount     Date
--------------------------
1      3.000     2016/1/1
2      4.000     2016/1/1
1      6.000     2017/1/1
1      3.000     2018/1/1
3      2.000     2019/1/1

I need to count Dates which a specific Customers does not have a Shop in it.
for example ID 2 does not have a shop in 2017/1/1 and 2018/1/1, so the count will be 2. and the count for customer ID 3 will be 3 because He does not have a shop in 2016/1/1 and 2017/1/1 and 2018/1/1
I think I should use grouping but do not know how to count which I want for a specific ID!
orders.GroupBy(x => x.Date)......???

A: Assuming you have list of objects:
// number of all different dates
var datesCount = list.Select(i => i.Date).Distinct().Count();

int customerId = 2;

//number of dates with customer shopping
var customerDatesCount = list.Where(i => i.ID == customerId).Select(i => i.Date).Distinct().Count();

var nonShoppingDatesCount = datesCount - customerDatesCount;

A: You need two steps here.

*

*Get all distinct order dates
var allDates = orders.Select(o => o.Date).Distinct();

*Find those dates which customer don't have. Except operation will do that
var missingDates = allDates.Except(orders.Where(o => o.ID == 2).Select(o => o.Date));
If you need just number of missing dates, then use missingDates.Count() or (better) use solution by @Roma


text:
Q: How to agregate queries results from dynamic table queries To begin I am far from being an expert and I would like to have some guidance on the following subject :

*

*I am trying to get a query result from several table without having the table names on the query but coming as a result of another table.

I have all the table names from 1 table :
Tables names from U5WOMA
What I would like to get is something as this as a result :
Union results from Tables stored in U5WOMA
select description, actif, code from U5WOCO
union
select description, actif, code from u5wowo
union
select description, actif, code from U5woeq;

Except that I would like this result without having to put the table names in the query but rather having them dynamically from the U5WOMA table since I will not know how many tables that I would have neither their names.
I did some research and I get the feeling that the response is in dynamic SQL but I am unable to find something even close to works.
I am using Oracle database.
If you have any suggestion, tutorial or advice that could help me to move to the right direction, it would be very appreciated.
Thank you,

A: Here's one option - create a function which composes a "long" select statement based on contents of the u5woma table and uses it as a source for the refcursor.
Sample data:
SQL> select * from u5woco;

DESCRIPTI ACTIF            CODE
--------- ---------- ----------
MANAGER   CLARK            7782
PRESIDENT KING             7839
CLERK     MILLER           7934

SQL> select * from u5wowo;

DESCRIPTI ACTIF            CODE
--------- ---------- ----------
CLERK     SMITH            7369
MANAGER   JONES            7566
ANALYST   SCOTT            7788
CLERK     ADAMS            7876
ANALYST   FORD             7902

SQL> select * from u5woeq;

DESCRIPTI ACTIF            CODE
--------- ---------- ----------
SALESMAN  ALLEN            7499
SALESMAN  WARD             7521
SALESMAN  MARTIN           7654
MANAGER   BLAKE            7698
SALESMAN  TURNER           7844
CLERK     JAMES            7900

6 rows selected.

The u5woma table that contains list of all tables involved in query:
SQL> select * from u5woma;

TABLE_
------
U5WOCO
U5WOWO
U5WOEQ

Function: in order for union to work, all select statements must return the same number of columns and they must match in datatype. Your example shows that all tables share the same column list (which simplifies the task):
SQL> create or replace function f_u5
  2    return sys_refcursor
  3  is
  4    l_str varchar2(2000);
  5    l_rc  sys_refcursor;
  6  begin
  7    for cur_r in (select table_name from u5woma) loop
  8      l_str := l_str || ' select description, actif, code from ' || cur_r.table_name
  9                     || ' union all';
 10    end loop;
 11
 12    l_str := rtrim(l_str, ' union all');
 13    open l_rc for l_str;
 14    return l_rc;
 15  end;
 16  /

Function created.

SQL>

Testing:
SQL> select f_u5 from dual;

F_U5
--------------------
CURSOR STATEMENT : 1

CURSOR STATEMENT : 1

DESCRIPTI ACTIF            CODE
--------- ---------- ----------
MANAGER   CLARK            7782
PRESIDENT KING             7839
CLERK     MILLER           7934
CLERK     SMITH            7369
MANAGER   JONES            7566
ANALYST   SCOTT            7788
CLERK     ADAMS            7876
ANALYST   FORD             7902
SALESMAN  ALLEN            7499
SALESMAN  WARD             7521
SALESMAN  MARTIN           7654
MANAGER   BLAKE            7698
SALESMAN  TURNER           7844
CLERK     JAMES            7900

14 rows selected.

SQL>

There are other possibilities as well (for example, you could return a collection; or use a pipelined function; or ...), but the main principle remains the same.

A: thank you for your help, it is a very interesting way of managing it and it is very helpfull.
If I understand correctly all the results are stored in one variable. So as long as there is less than 2000 characters I will be fine but if there are more, it will be trunqued ?
When I call the funtion directly, I have the following result :
SQL>
{<DESCRIPTION=Commande 2,ACTIF=-,CODE=1001>,<DESCRIPTION=Commande 1,ACTIF=+,CODE=1000>,<DESCRIPTION=OT 1,ACTIF=+,CODE=1000>,<DESCRIPTION=OT 2,ACTIF=-,CODE=1001>,<DESCRIPTION=Actif 1,ACTIF=+,CODE=1000>,<DESCRIPTION=Actif 2,ACTIF=-,CODE=1001>,<DESCRIPTION=Actif 3,ACTIF=+,CODE=1003>,}
SQL>

Since the results are all in one line I have to split them in several lines to be able to use them.
I should be able to do it when I call the function f_u5 but is it possible to store the date directly on the function in order to get as many lines as I have results ?
Thank you,

A: I finally did it a little differently :
I first created a new table :
SQL>
 create table SG_u5woma(description varchar2(80), actif varchar2(1), code varchar2(30));
SQL>

Then a stored procedure :
SQL>
create or replace procedure P_u5
  as
   begin
   delete from SG_u5woma;
     for cur_r in (select table_name from u5woma) loop

     execute immediate 'insert into SG_u5woma (description, actif,code) select description, actif, code from ' || cur_r.table_name ;
     end loop;

   end;
   /
SQL>

The I execute the procedure :
SQL>
 exec P_u5();
SQL>

And the result is the data in the table :
SQL>
 select * from SG_u5woma;

Commande 2  -   1001
Commande 2  +   1003
Commande 1  +   1000
OT 1    +   1000
OT 2    -   1001
Actif 1 +   1000
Actif 2 -   1001
Actif 3 +   1003
SQL>

Anyway, thank you for the help, it was very helpfull.


text:
Q: Charging on Free Tier of AWS RDS? I´m trying to find out more on the possibilities with GeoClouding and PostGIS.
I was experimenting with AWS RDS feature with an Free Tier account, and now I´ve been charged a large amount of money. I might misunderstood something here. I´ve been charged for theese RDS-services (which i thought was inlcuded in the 750 free hours per month):
Amazon RDS Service for PostgreSQL ($0.910 per RDS Second Gen Extra Large Multi-AZ Instance hour (or partial hour) running PostgreSQL)
Amazon RDS Service Storage ($0.238 per IOPS-month of Multi-AZ Provisioned IOPS and $0.298 per GB-month of Multi-AZ Provisioned IOPS Storage)
These were tested in 2 regions: EU (Frankfurt) and US West (Oregon) Region.
I´ve only set up an empty  DB-instance,  and now they wanna charge me around 700 dollars.
So the question is: Did I misunderstood/didn´t understand the "contract" well enough or do I have any chance to avoid this? The bill hasn´t been charged from my card yet. It might be my own fault, but it´s jungle of texts and if you´re not from a country with english as your main language, then it´s confusing.

A: The free usage tier for RDS does include 750 hours of usage per month, but it's for single-AZ Micro instance hours, not any of the larger instances. The micro instance normally costs $0.025/hour.
The included storage is single-AZ without provisioned IOPs.
The AWS web site is pretty clear on what is included in the free tier.
If you haven't tried contacting AWS support, you should, They may be able to help you.

A: I had exact situation of 700$ and even after suspending my account I was being billed hourly as I had not terminated the RDS instances, but I called up aws customer support at 1 (888) 280-3321
and explained the scenario and it was an honest unintended mistake from my side as I had used extra large multi A Z RDS instance instead single with free tier.
Amazon was kind enough to wave off as gesture of good will and provided me video tutorials which would help me understand better.


text:
Q: JSON, compressing it on client and server side Anybody knows of any utility that will compress JSON server side (C#), and re-constitute it into JSON on the client side and vice versa. My whole page view model is in json, and need to find a way to reduce size of it. I found cJSON, and RISON, but I don't see C# implementations.
Any ideas?
Clarification: On server side, I need to take a JSON string and register client side variable that is encoded/compressed to reduce the size. On the client side I need a utility that I can call from JavaScript to decode/uncompress it. Also need this in reverse order too.
Reference links:
cJson
http://stevehanov.ca/blog/index.php?id=104
Rison
http://mjtemplate.org/examples/rison.html

A: Why not use HTTP compression and allow the browser/web server to handle the compression of the requests?

A: I'd second Llyod's answer and also add that you're not considering the client-side decompression overhead.
Deflate and gzip are worthwhile largely because browsers handle decompression in native code.  If you implement a custom JSON compression scheme, you'll have to decompress it using JavaScript, which will be significantly slower.  Unless you're doing that in a browser that supports Web Workers (i.e no versions of IE), that really isn't viable.  Either way, the JavaScript-based decompression would almost certainly add more latency than the compression would save.


text:
Q: python, Django added new celery task i'm new to python celery, and thus my question, i added recently 3 new tasks that looks like this :
@shared_task(name="3rd-task",acks_late=True, autoretry_for=(Exception,), retry_backoff=True)

when i run it from console, everything is fin, but when i try to run via periodic_task in Django i get this error
AttributeError at /admin/django_celery_beat/periodictask/

'NoneType' object has no attribute 'delay'

Request Method:     POST
Request URL:    http://localhostadmin/django_celery_beat/periodictask/
Django Version:     2.0.4
Exception Type:     AttributeError
Exception Value:

'NoneType' object has no attribute 'delay'

Exception Location:     /usr/local/lib/python3.5/dist-packages/django_celery_beat/admin.py in <listcomp>, line 184

i think, problem is that i didn't register it somewhere
[EDIT]

def run_tasks(self, request, queryset):
        self.celery_app.loader.import_default_modules()
        print("asdasd")
        tasks = [(self.celery_app.tasks.get(task.task),
                loads(task.args),
                loads(task.kwargs))
                for task in queryset]
        task_ids = [task.delay(*args, **kwargs) <-- here is error
                    for task, args, kwargs in tasks]
        tasks_run = len(task_ids)
        self.message_user(
            request,
            _('{0} task{1} {2} successfully run').format(
                tasks_run,
                pluralize(tasks_run),
                pluralize(tasks_run, _('was,were')),
            ),
        )


text:
Q: CloudFormation EventBusPolicy: The relative-id "event-bus/bus_name" is invalid for ARN According to this doc, I try:
  ebMailPolicy:
    Type: AWS::Events::EventBusPolicy
    Properties:
      EventBusName: !Ref ebMail
      StatementId: AllowForOrg
      Statement:
        Effect: Allow
        Action: events:PutEvents
        Condition:
          StringEquals:
            "aws:PrincipalOrgID": !Ref OrgId
        Principal: "*"

The error is:
The relative-id "event-bus/bus_name" is invalid for ARN "arn:aws:events:eu-central-1:acc_id:event-bus/bus_name"
What am I doing wrong?

A: The doc is wrong. Correct version:
  ebMailPolicy:
    Type: AWS::Events::EventBusPolicy
    Properties:
      EventBusName: !Ref ebMail
      StatementId: CrossAccSendEvents
      Action: events:PutEvents
      Principal: "*"
      Condition:
        Type: StringEquals
        Key: aws:PrincipalOrgID
        Value: !Ref OrgId

A: The AWS document does not explicitly state it but this is what we have working
EventBusPolicy:
    Type: AWS::Events::EventBusPolicy
    DependsOn: CustomEventBridgeBus
    Properties:
      StatementId: "AllowSameAWSAccount"
      EventBusName: !Ref CustomEventBridgeBus
      Statement:
        Effect: "Allow"
        Principal:
          AWS: !ImportValue IntanceRoleArn
        Action: "events:PutEvents"
        Resource: !GetAtt CustomEventBridgeBus.Arn


text:
Q: WP_Query doesn't return some child pages even though the database shows them I have several pages all under one parent like this
ParentPage (ID 24)

*

*ChildPage A

*ChildPage B

*ChildPage C

*ChildPage D

*ChildPage E

*ChildPage F

I am using WP_Query to return all the child pages but only some are coming back. In the DB all the child pages have the same parent ID of 24.
// args
$args = array(
    'numberposts'   => -1,
    'post_type'     => 'page',
    'post_parent' => 24
);

// query
$the_query = new WP_Query( $args );

// loop through posts
if( $the_query->have_posts() ): ?>
    <?php while( $the_query->have_posts() ) : $the_query->the_post();?>
        <a href="<?php the_permalink(); ?>"><?php the_title(); ?>
    <?php endwhile; ?>
<?php endif; ?>

Let's say B & C don't return. I tried assigning it to a new parent (ID25) and modify the query to return child pages of parent 25 - and the missing pages display fine.
I have virtually no plugins other than ACF PRO, which -- prior to making some new pages and fields for said pages recently -- was working fine.

A: Red faced - but happy to share the results and save someone else the pain. I have been chasing a ghost for the last two days, there is a default number of posts the wp_query returns which is page specific. It seems to be set to 10 posts on the page I am on.
All you have to do is specify the number of posts you want to override the default values. In my case I wanted them all so I added the following to the query args.
'posts_per_page' => -1

I really hope this helps someone, dark couple of days and I was starting to incorrectly point fingers at plugins that were behaving just fine.
Found this out at wp query to get child pages of current page


text:
Q: DatagridView Selected Row Error What is wrong w/my code?
this.comboBox1.SelectedIndex = _f3.dataGridView2.SelectedRows[0].Index;

my datagrid is in form3 and my combobox is in form 2. HOW could I implement something like this?

A: Instead, you declare one public integer in form2 and when you want to get the selected row index of the datagridview you can use the CurrentRowIndex property to get the index of the datagridview selected row like, in form3 you get the selectedindex global varaible from form2 and assign the CurrentRowIndex, or declare a public method which should return the selected row index when ever required
In form2 you write something like
  private int selectedindex {get; set;}
    selectedindex = _f3.GetSelectedIndex();
    this.comboBox1.SelectedIndex = selectedindex;

In form3 you write the method like
 public int GetSelectedIndex()
    {
         int selectedIndex = 0;
         try
         {
           if(dataGridView2.SelectedRows.Count > 0)
           {
              selectedIndex = dataGridView2.CurrentRow.Index;
           }
         }
         catch
         {
          return 0;
         }
      return selectedIndex;
    }

EDIT:
You can use instead
dataGridview2.CurrentRow.Index

In form3 under the SelectionChanged event of datagridview you do the following thing
    private void dataGridView2_SelectionChanged(object sender, EventArgs e)
    {
        selectedindex = dataGridView2.CurrentRow.Index;
    }

and also declare the selectedindex as an integer as a public variable like
public int selectedindex {get; set;}

and in form2 directly get the selectedindex by using the global variable like below,
this.comboBox1.SelectedIndex = _f3.selectedindex;

get the selectedindex when ever required.

A: Change the Modifiers property of datagridview2 to Public


text:
Q: H.264 auxiliary picture = alpha channel? H.264 standard (ITU-T Rec. H.264 (02/2014) Advanced video coding) describe "Auxiliary Pictures" which  are optional for decoding and can be used for such purposes as alpha blending.
Also, at document "7.4.2.1.2 Sequence parameter set extension RBSP semantics" has a alpha_transparent_value can be set.
And I found QuickTime Movie support alpha setting.
But what I know is H.264 is not support alpha channel. What is this "Auxiliary Picture"? For alpha channel? If it's yes, how H.264 compress it? Do it have some samples?

A: The H.264 standard describes alpha channel encoding through auxiliary picture. But I have never seen a decoder or encoder supporting it.
So to my knowledge - yes there is standard for H.264 with alpha but to me there is no known implementation.
So you would have to implement or modify existing H.264 decoder/encoder which is a substantial task.
I think the situation is even worse - I don't know of any popular cross platform video format with alpha. On Apple I'd use Apple ProRes 4444 - but you may have a hard time creating ProRes files on anything but macOS.
Currently HAP is gaining traction - https://hap.video/ which has alpha support.


text:
Q: Error when trying to return promise from mongoose save I am using mongoose and express within node.
I am running into a problem with a nested promise and can't figure out why this is happening.
Route - /loans
router.post('/problems/add', (req, res, next) => {
// error checking
  req.headers.api = 'true';

  let required = ['loan', 'item', 'type', 'quantity', 'description'];
  let problems = [];

  required.forEach(r => {
    if (!req.body[r]){
      problems.push(`Field '${r}' was not supplied`);
    }
  });

  if (problems.length > 0){
    res.json({success: false, message: `Couldn't create problem:\n${problems.join('\n')}`});
  } else {

// Important part
    loanController.addProblem(req.body)
    .then((newProblem) => { // line 118 mentioned in error message
      res.json({success: true, problem: newProblem});
    })
    .catch(err => {
      return next(err);
    })
  }

});

Controller - loanController
exports.addProblem = (body) => {

  Loan.findById(mongoose.Types.ObjectId(body.loan)).exec()
  .then(foundLoan => {

    if (!foundLoan){
      throw new Error('loan not found');
    }

    let newProblem = new Problem({
      loan: foundLoan._id,
      item: mongoose.Types.ObjectId(body.item),
      type: body.type,
      quantity: body.quantity,
      status: 'new',
      text: body.description
    });

    return newProblem.save(); // newProblem is a valid mongoose document
  })
  .catch(err => {
    return Promise.reject(err);
  });

}

I'm getting the error below, it's not getting caught by any of these catch blocks and is coming from my general error trapping:

"TypeError: Cannot read property 'then' of undefined    at router.post (c:\dev....\loans.js:118:5)

Now when I put a breakpoint at newProblem.save(), it shows newProblem being a valid Mongoose document, these documents are being saved correctly.
I'm even able to call newProblem.save().then() from the debug command line.
I assume I've made an error somewhere but this is structured similarly to other objects and they work fine.
Can anyone spot the error I've made or suggest a way to investigate further?


text:
Q: Предпоказ из формы Есть форма. В ней несколько полей и загрузка картинки.
Требуется вывод преподказа из формы после нажатия кнопки Добавить.
т.е
Нажал кнопку добавить, внизу формы вышло то, что сделали. Опять нажал добавить, рядом еще появилось и так много раз. + возможность удалить(отменить добавление).
После нажатия кнопки  Продолжить, данные отправятся PHP, там уже знаю как сделать.
После выходит опять форма и все, что было добавлено - вывелось. и для них требуется возможность удалить(отменить добавление).
Есть ли что-то подобное уже в готовом виде?)


text:
Q: Request processing failed; nested exception is java.lang.NumberFormatException: For input string: "" org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NumberFormatException: For input string: ""
I'm trying to build a web app using only annotations, java, JSPs, spring data, spring mvc, and mongo db.
I've got things mostly working, however when I tried to create a JSP form with multi select lists, I'm getting the title error.
I'm trying to create an agent object and save it to the mongodb database.  The multi select boxes are passing back string IDs for the objects that were selected.  The agent object has lists that need to be populated with the multi select lists.
Here is the response data from chrome dev tools:
id: name:Test1 type:MOB
attributeList[]:687a1964-4179-4631-832b-e23b34300840
personalityTraitList[]:8b321f3c-6398-4bc4-afc6-e6c7e4a6a3e3
skillList[]:53090226-0f54-4121-90c0-4d3a188aa5f8
triggerList[]:923048ef-7a4d-42e3-8691-2d2e9603e79b
behaviorTreeList[]:84966b7a-fb53-4f64-be2a-203ae3743250

Here is the html for the first multi select box. They are all the same.
<td align="left">
    <select size="10" id="selectedAttributes" multiple="multiple" name="attributeList[${attribute.id}]" style="width: 130px;"></select>
</td>

Here is the controller save request mapping:
@RequestMapping(value = "/AgentManager/save", method = RequestMethod.POST)
public View createAgent(@ModelAttribute Agent agent, ModelMap model)
{
    if(StringUtils.hasText(agent.getId()))
    {
        agentService.updateAgent(agent);
    } else
    {
        agentService.addAgent(agent);
    }

    return new RedirectView("/MotherNatureEmulator/AgentManager");
}

The agent service will create a random UUID if the ID field is empty when going to save the agent.
Here is the stack trace:

java.lang.NumberFormatException: For input string: ""
      java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
      java.lang.Integer.parseInt(Integer.java:504)
      java.lang.Integer.parseInt(Integer.java:527)
      org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:969)
      org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:902)
      org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:75)
      org.springframework.validation.DataBinder.applyPropertyValues(DataBinder.java:740)
      org.springframework.validation.DataBinder.doBind(DataBinder.java:636)
      org.springframework.web.bind.WebDataBinder.doBind(WebDataBinder.java:191)
      org.springframework.web.bind.ServletRequestDataBinder.bind(ServletRequestDataBinder.java:112)
      org.springframework.web.servlet.mvc.method.annotation.ServletModelAttributeMethodProcessor.bindRequestParameters(ServletModelAttributeMethodProcessor.java:153)
      org.springframework.web.method.annotation.ModelAttributeMethodProcessor.resolveArgument(ModelAttributeMethodProcessor.java:106)
      org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:77)
      org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:162)
      org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:123)
      org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
      org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
      org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
      org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
      org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
      org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
      org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
      org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:838)
      javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
      org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
      javax.servlet.http.HttpServlet.service(HttpServlet.java:728)

I tried creating a custom data binder, but that didn't help.
Could anyone direct me to the right way to do these things?  This is the first time I'm trying to make a web app by myself.
Here is the Agent class:
@Document(collection = "AgentCollection")
public class Agent
{
@Id
private String _id;

private String _name;
private String _type;
private ArrayList<String> _actionList;
private ArrayList<String> _attributeList;
private ArrayList<String> _behaviorTreeList;
private ArrayList<String> _itemList;
private ArrayList<String> _personalityTraitList;
private ArrayList<String> _skillList;
private ArrayList<String> _triggerList;

public String getId()
{
    return _id;
}

public void setId(String id)
{
    _id = id;
}

public String getName()
{
    return _name;
}

public void setName(String name)
{
    _name = name;
}

public String getType()
{
    return _type;
}

public void setType(String type)
{
    _type = type;
}

public ArrayList<String> getAttributeList()
{
    return _attributeList;
}

public void setAttributeList(final ArrayList<String> attributeList)
{
    _attributeList = attributeList;
}

public ArrayList<String> getPresonalityTraitList()
{
    return _personalityTraitList;
}

public void setPersonalityTraitList(final ArrayList<String> personalityTraitList)
{
    _personalityTraitList = personalityTraitList;
}

public ArrayList<String> getSkillList()
{
    return _skillList;
}

public void setSkillList(final ArrayList<String> skillList)
{
    _skillList = skillList;
}

public ArrayList<String> getActionList()
{
    return _actionList;
}

public void setActionList(final ArrayList<String> actionList)
{
    _actionList = actionList;
}

public ArrayList<String> getTriggerList()
{
    return _triggerList;
}

public void setTriggerList(final ArrayList<String> triggerList)
{
    _triggerList = triggerList;
}

public ArrayList<String> getItemList()
{
    return _itemList;
}

public void setItemList(final ArrayList<String> itemList)
{
    _itemList = itemList;
}

public ArrayList<String> getBehaviorTreeList()
{
    return _behaviorTreeList;
}

public void setBehaviorTreeList(final ArrayList<String> behaviorTreeList)
{
    _behaviorTreeList = behaviorTreeList;
}
}

Thanks,
Matt

A: Spring doesn't handle empty square bracket. To summarize you can use

*

*?myarray[0]=aa&myarray[1]=bb

*?myarray=aa&myarray=bb

but not

*

*?myarray[]=aa&myarray[]=bb

I created the ticket https://jira.springsource.org/browse/SPR-11214


text:
Q: How to execute thread synchronize from a separate unit I have the following problem/question.
I have a unit named "myGlobalFunctions.pas".
Inside this unit I have implemented multiple procedures/functions that are used by several projects.
project 1 use this unit
project 3 use this unit
project 6 use this unit
etc
inside "project 1" there is a thread that use functions inside the "global function" unit.
inside project 3 there is no thread but the functions are used.
so far this thread (project1) provide almost no update of the application interface and the update was made AFTER or BEFORE calling a function from "myGlobalFunctions.pas"
like "before start function1"
... the calling
"after function1".
this way I can know what the program is doing.
However now I want to implement inside the "function1" update of the application interface (with synchronize).
I want to reflect in the application interface "processing step1 ... xx records". (there is a while loop there for a dataset).
using Synchronize for "project1" and with normal label1.caption = 'message'; application.process messages for any other project.
is it possible?
how can I do such a thing.
can be Thread Safe ?
tks a lot
Razvan
here is some code to understand better
THREAD UNIT

procedure TThreadSyncronizeProcess.SignalStart;
begin
  frmMain.sbMain.Panels[2].Text := 'Syncronizare in desfasurare...'; -- exist all the time
  if Assigned(frmSyncronize) then begin     -- check if exist this
    frmSyncronize.logMain.WriteFeedBackMessage('Pornire syncronizare...', '', EVENTLOG_INFORMATION_TYPE, True);
  end;
end;

procedure TThreadSyncronizeProcess.Execute;
var ..... declarations
begin
  Synchronize(SignalStart); -- this is normal call within thread update interface
  try
    try
      workSession        := TIB_Session.Create(nil);
      workDatabase       := TIB_Database.Create(workSession);
        ... creating more components and setup them ...

      uSyncronizareFunctions.SetupDatabase(workDatabase, workSession, transactionWrite, transactionRead);
      uSyncronizareFunctions.SetupDataSnapConnection(workConnectionRead, providerRead);
      if Assigned(frmSyncronize) then begin
        uSyncronizareFunctions.SetupFeedBack(frmSyncronize.logMain);
      end;

      try
          Synchronize(SignalMessage);
          // this next function is from the "global unit"
          isAllOk := uSyncronizareFunctions.ImportOperatoriAutorizati(workImage, workLabelProgress, True);
          isAllOk := isAllOk and uSyncronizareFunctions.ImportJudete;
          isAllOk := isAllOk and uSyncronizareFunctions.ImportLocalitati;
          isAllOk := isAllOk and uSyncronizareFunctions.ImportUM;
          isAllOk := isAllOk and uSyncronizareFunctions.ImportFurnizori;
          isAllOk := isAllOk and uSyncronizareFunctions.ImportClasificari;
      except
        on e : Exception do begin
          raise Exception.Create(dmMain.GetDataSnapExceptionMessage(e.Message));
        end;
      end;
    except
      on e : Exception do begin
        baseMessage := e.Message;
        Synchronize(SignalMessage);
      end;
    end;
  finally
    workDatabase.ForceDisconnect;
    FreeAndNil(transactionRead);
        ... etc
  end;
  Synchronize(SignalFinish);
end;

global function unit
unit uSyncronizareFunctions;

function  ImportOperatoriAutorizati(imgDone : TImage; labelProgress : TLabel; isThread : Boolean) : Boolean;
var workQuery  : TIB_Query;
    serverData : TClientDataSet;
begin
  Result := True;
  try
    ... create all that we need

    serverData.Close;
    serverData.CommandText := 'SELECT * FROM OPERATORI_AUTORIZATI WHERE REC_VERSION > :ARECVERSION ORDER BY REC_VERSION, ID';
    serverData.Params.Clear;
    serverData.Params.CreateParam(ftInteger, 'ARECVERSION', ptInput);
    serverData.Params.ParamByName('ARECVERSION').AsInteger := lastVersion;
    serverData.Active := True;

        ...... I want here to signal start

    while not serverData.Eof do begin
      try
        globalInsert_Tran.StartTransaction;

        workQuery.Close;
        workQuery.ParamByName('AIDGLOBAL').AsString := serverData.FieldByName('IDGLOBAL').AsString;
        workQuery.Open;
        if workQuery.IsEmpty then begin
          workQuery.Insert;
          workQuery.FieldByName('IDGLOBAL').AsString   := serverData.FieldByName('IDGLOBAL').AsString;
        end else begin
          workQuery.Edit;
        end;
        workQuery.FieldByName('NUME').AsString           := serverData.FieldByName('NUME').AsString;
        workQuery.FieldByName('COD_AUTORIZARE').AsString := serverData.FieldByName('COD_AUTORIZARE').AsString;
        workQuery.FieldByName('OTHER_INFO').AsString     := serverData.FieldByName('OTHER_INFO').AsString;
        workQuery.FieldByName('DATASTERGERE').AsVariant  := GetValueDate(serverData.FieldByName('DATASTERGERE').AsDateTime);
        workQuery.FieldByName('REC_VERSION').AsInteger   := serverData.FieldByName('REC_VERSION').AsInteger;
        workQuery.Post;

        MarkRecordAsDirtyFalse(workQuery);
        globalInsert_Tran.Commit;

        ...... I want here to signal progress and to see in the application interface "processing record xx/100" or any other message

      except
        on e : Exception do begin
          Result := False;
          globalInsert_Tran.Rollback;
        end;
      end;

      serverData.Next;
    end;
  finally
    FreeAndNil(serverData);
    FreeAndNil(workQuery);
  end;
end;

A: It looks like you would like your global function to execute a callback.  You might try an approach like this:
unit MyGlobalMethods;

interface
  uses
    System.SysUtils;
  type
    // define a method signature for your callback
    TSomeCallback = procedure(progress : integer) of object;

  // add a callback argument to your function (initializing to nil will make
  // the parameter optional and will not break your previous implementations)
  function GlobalFunction(arg1 : integer;
                          AMethodCallback : TSomeCallback = nil) : boolean;

implementation

function GlobalFunction(arg1 : integer;
                        AMethodCallback : TSomeCallback) : boolean;
var i : integer;
begin
  for i := 0 to arg1 do begin
    sleep(10);  // Do some work
    // report progress by executing the callback method
    // only do this if a method has been passed as argument
    if (i mod 100 = 0) and (Assigned(AMethodCallback)) then AMethodCallback(i);
  end;
  result := true;
end;

end.

Adding a method callback as an argument allows you to pass in any function you like to have the method execute.  For example  :
  TForm1 = class(TForm)
    Button1: TButton;
    Label1: TLabel;
    procedure Button1Click(Sender: TObject);
  private
    procedure UpdateProgress(progress : integer);
  end;

  TSomeThread = class(TThread)
    private
      FProgressCallback : TSomeCallback;
      FProgress : integer;
      procedure SynchronizeCallback(progress : integer);
      procedure DoCallback;
    public
      procedure Execute; override;
      property OnFunctionProgress : TSomeCallback
                               read FProgressCallback write FProgressCallback;
  end;

implement as :
procedure TSomeThread.Execute;
begin
  GlobalFunction(1000, SynchronizeCallback);
end;

procedure TSomeThread.SynchronizeCallback(progress: Integer);
begin
  FProgress := progress;
  Synchronize(DoCallback);
end;

procedure TSomeThread.DoCallback;
begin
  if Assigned(FProgressCallback) then FProgressCallback(FProgress);
end;

You haven't told us what version of Delphi you are using.  If you are using D2009 or newer you can bundle the above two calls into one using anonymous methods (and get rid of FProgress) :
procedure TSomeThread.SynchronizeCallback(progress: Integer);
begin
  Synchronize(procedure
              begin
                if Assigned(FProgressCallback) then FProgressCallback(progress);
              end;);
end;

Where in your form you would do :
procedure TForm1.UpdateProgress(progress: Integer);
begin
  label1.Caption := IntToStr(progress);
end;

procedure TForm1.Button1Click(Sender: TObject);
var someThread : TSomeThread;
begin
  someThread := TSomeThread.Create(true);
  someThread.FreeOnTerminate := true;
  someThread.OnFunctionProgress := UpdateProgress;
  someThread.Start;
end;

This nicely separates the responsibilities.  The main form passes an update method to the thread (a method, in this case, to update a label).  The thread is responsible for synchronizing the call and the global function, therefore, does not need to care whether or not the callback it is executing originates from the main thread or from any other thread.  The thread knows it needs to synchronize the method so it should take that responsibility.


text:
Q: PinchToZoom not working with multiple activities in Android I am trying to implement pinch to zoom, in my project i have used multiple activities which interconnect them. Initially when i had my complete project in one activity it was performing zoom, however it is not the case with multiple activities.
CODE: AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.kmay.calculatephase">
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:debuggable="true"
    android:theme="@style/AppTheme" >
    <activity android:name=".MainActivity" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".LoadImage" >
    </activity>
    <activity android:name=".Phase" >
    </activity>
    <activity android:name=".ColorGray" >
    </activity>
    <activity android:name=".Information" >
    </activity>
</application>

CODE: MainActivity.java
package com.example.stiwari.myappli;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;

public class MainActivity extends AppCompatActivity {
    Button btn1;Bitmap imgb;Bitmap operation;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn1 = (Button) findViewById(R.id.btn1);
        Bitmap bmp;
        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent rawIntent = new Intent(Intent.ACTION_PICK);
                File pictureDirectory =  Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
                String pictureDirectoryPath = pictureDirectory.getPath();
                Uri data = Uri.parse(pictureDirectoryPath);
                rawIntent.setDataAndType(data, "image/*");
                startActivityForResult(rawIntent, 10);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode==RESULT_OK){
            if(requestCode==10){
                final float red = (float) 0.299;
                final float green = (float) 0.587;
                final float blue = (float) 0.114;
                final Uri imagef = data.getData();
                InputStream streamI;
                try {
                    streamI = getContentResolver().openInputStream(imagef);
                    //Create bitmap from selected image
                    imgb = BitmapFactory.decodeStream(streamI);
                    //Define rows and columns of selected image
                    int rows = imgb.getHeight();int cols = imgb.getWidth();
                    operation = Bitmap.createBitmap(cols, rows, imgb.getConfig());
                    //Convert original image to Gray Image
                    for (int i=0;i<cols;i++){
                        for(int j=0;j<rows;j++){
                            int p = imgb.getPixel(i,j);
                            int r = Color.red(p);
                            int g = Color.green(p);
                            int b = Color.blue(p);
                            r = (int) (red*r);
                            g = (int) (green*g);
                            b = (int) (blue*b);
                            int gray = (int) (r*0.299+g*0.587+b*0.114);
                            operation.setPixel(i, j, Color.argb(Color.alpha(p), gray, gray, gray));
                        }
                    }
                } catch (FileNotFoundException e) {
                    e.printStackTrace();}
            }
            //Use Intent property to send data to Main2Activity.class
            Intent i = new Intent(this,Main2Activity.class);
            ByteArrayOutputStream bs = new ByteArrayOutputStream();
            operation.compress(Bitmap.CompressFormat.PNG, 50, bs);
            i.putExtra("byteArray", bs.toByteArray());
            startActivity(i);
        }
    }
}

CODE: activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Next Page"
    android:id="@+id/btn1"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true" />

CODE:Main2Activity.java
package com.example.stiwari.myappli;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.widget.ImageView;
public class Main2Activity extends AppCompatActivity {
    Bitmap imgb;
    ImageView imageView1;float scaleFactor;View view;
    ScaleGestureDetector detector;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        imageView1 = (ImageView) findViewById(R.id.imageView1);
        detector = new ScaleGestureDetector(this, new ScaleListener());

    if (getIntent().hasExtra("byteArray")) {
        //ImageView previewThumbnail = new ImageView(this);
        imgb = BitmapFactory.decodeByteArray(
                getIntent().getByteArrayExtra("byteArray"), 0, getIntent().getByteArrayExtra("byteArray").length);
        //previewThumbnail.setImageBitmap(imgb);
    }imageView1.setImageBitmap(imgb);

    imageView1.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            Main2Activity.this.view = v;
            detector.onTouchEvent(event);
            return false;
        }
    });
}

CODE: activity_main2.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="com.example.stiwari.myappli.Main2Activity">

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/imageView1"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true" />

A: Use the below code for Pinch Zoom.
ScaleGestureDetector detector = new ScaleGestureDetector(this, new ScaleListener());

private class ScaleListener extends
        ScaleGestureDetector.SimpleOnScaleGestureListener {
    @Override
    public boolean onScale(ScaleGestureDetector detector) {
        scaleFactor *= detector.getScaleFactor();
        scaleFactor = (scaleFactor < 1 ? 1 : scaleFactor);
        scaleFactor = ((float) ((int) (scaleFactor * 100))) / 100;
        view.setScaleX(scaleFactor);
        view.setScaleY(scaleFactor);
        return true;
    }
}

Also,Setup a touchListener to you view on onCreate(The one which you want to zoom).
example
(YOUR_VIEW).setClickable(true);

 (YOUR_VIEW).setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                    MainActivity.this.view = v;
                    detector.onTouchEvent(event);

                return false;

        });

Hope this will help :)
UPDATE 1:
Based on your code.change condition like this
imageView1.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
             if (event.getAction() == MotionEvent.ACTION_UP) {
                } else {
                     Main2Activity.this.view = v;
            detector.onTouchEvent(event);
                }
            return false;
        }
    });


text:
Q: C# BackgroundWorker update UI from DoWork event I know that the UI can only be updated from the main thread; but why can I update a StatusStrip Label within my DoWork event? but when I try to update another control, the program throws a cross thread exception (as expected).
And since this is possible, is it a good idea/practice update this label from within event?
Here's my code:
  public Form1()
    {
        InitializeComponent();

        bw = new BackgroundWorker();
        bw.WorkerReportsProgress = true;
        bw.DoWork += bw_DoWork;
        bw.ProgressChanged += bw_ProgressChanged;
        bw.RunWorkerCompleted += bw_WorkCompleted;
    }

   private void bw_DoWork(object sender, DoWorkEventArgs e) {
        toolStripStatusLabel1.Text = "foo";
    }


text:
Q: Suddenly unable to obain IP address but eth0 port blinking rapidly After a server restart, the server is unable to obtain an IP address through a wired ethernet interface, neither automatically nor manually.
However the green light on the back of the machine where the ethernet cable is attached, indicating activity, continues to blink at a very fast and steady rate (eg. as if some large file transfer was being made).
Obtaining an IP address has never been an issue before, and I find this very strange. Whereas normally network manager would obtain an IP automatically, this time it did not, and dhclient -v eth0 fails to get a DHCP offer.
I would like to determine at a low level what kind of traffic is going through the ethernet port, since I'm now concerned about malicious code having been inserted into the server.
How can I determine what kind of traffic is going through the device, at a low level?
I have tried nethogs, but this evidently is not the appropriate tool.
Could tcpdump or wireshark show all the traffic going through the interface? Since the server is offline, haven't been able to test this since I would have to download the appropriate dependencies via another system.
Since I did disable some seemingly non-essential services (and I suspect this is most likely the culprit), are there any services necessary for obtaining an IP address from a wired ethernet?
I've produced a pastebin of a session at the machine in question, including the outputs of ifconfig, the running services, and the failed attempt to obtain an IP through dhclient.
Edit:
To rule out a possible router issue, I tried to verify that I could get an IP using the same ethernet cable into another machine, connected wirelessly to the same router, but in fact, the same problem occurs. So this seems to be an issue with the router's ethernet ports and not in the server configuration, and thus the question is possibly out of the scope of this forum.
I will try restarting the router through the wireless interface, but since I'm clueless about how to debug a router problem, are there any tools or expected behaviour I can use to break down this problem?

A: It's possible you have a faulty network port, I've seen the exact same thing happen on a server due to a power surge (same symptoms of steady link light, and no connectivity). I'd suggest confirming this by setting a static address on the interface, and then seeing if you can pass traffic once it's connected.
Something like (for example):

auto eth0
iface eth0 inet static
    address 10.0.0.20
    netmask 255.255.255.0
    gateway 10.0.0.1

And then: ifdown eth0 && ifup eth0 (as root)
Then try and ping the gateway or another machine on the network. Although this is not necessarily a definite way of determining whether it is a fauly port/card, it should help you narrow it down.


text:
Q: Extend PHP regex to cover "srcset" and "style" attributes I've created a WordPress plugin that turn all links into protocol-relative URLs (removing http: and https:) based off the tags and attributes that I list in the $tag and $attribute variables. This is part of the function. To save space, the rest of the code can be found here.
$content_type = NULL;
# Check for 'Content-Type' headers only
foreach ( headers_list() as $header ) {
    if ( strpos( strtolower( $header ), 'content-type:' ) === 0 ) {
        $pieces = explode( ':', strtolower( $header ) );
        $content_type = trim( $pieces[1] );
        break;
    }
}
# If the content-type is 'NULL' or 'text/html', apply rewrite
if ( is_null( $content_type ) || substr( $content_type, 0, 9 ) === 'text/html' ) {
    $tag = 'a|base|div|form|iframe|img|link|meta|script|svg';
    $attribute = 'action|content|data-project-file|href|src|srcset|style';
    # If 'Protocol Relative URL' option is checked, only apply change to internal links
    if ( $this->option == 1 ) {
        # Remove protocol from home URL
        $website = preg_replace( '/https?:\/\//', '', home_url() );
        # Remove protocol from internal links
        $links = preg_replace( '/(<(' . $tag . ')([^>]*)(' . $attribute . ')=["\'])https?:\/\/' . $website . '/i', '$1//' . $website, $links );
    }
    # Else, remove protocols from all links
    else {
        $links = preg_replace( '/(<(' . $tag . ')([^>]*)(' . $attribute . ')=["\'])https?:\/\//i', '$1//', $links );
    }
}
# Return protocol relative links
return $links;

This works as intended, but it doesn't work on these examples:

However, the code partially works for these examples.

I've played around with adding additional values to the $tag and $attribute variables, but that didn't help. I'd assume I need to update the rest of my regex to cover these two additional tags? Or is there is a different way to approach it, such as DOMDocument?

A: I was able to simplify the code by doing the following:
$content_type = NULL;
# Check for 'Content-Type' headers only
foreach ( headers_list() as $header ) {
    if ( strpos( strtolower( $header ), 'content-type:' ) === 0 ) {
        $pieces = explode( ':', strtolower( $header ) );
        $content_type = trim( $pieces[1] );
        break;
    }
}
# If the content-type is 'NULL' or 'text/html', apply rewrite
if ( is_null( $content_type ) || substr( $content_type, 0, 9 ) === 'text/html' ) {
    # Remove protocol from home URL
    $website = $_SERVER['HTTP_HOST'];
    $links = str_replace( 'https?://' . $website, '//' . $website, $links );
    $links = preg_replace( '|https?://(.*?)|', '//$1', $links );
}
# Return protocol relative links
return $links;


text:
Q: I need help to understand a lisp program that finds the depth of a list I need help to understand my code theoretically. Here is my lisp program:
(defun depth (lst)

  (if (or (null lst) (atom lst)) 0

    (+ 1 (apply 'max (mapcar #'depth lst)))

  ))

I know it works with this example:
(write (depth '((a (b c) d r ((t))))) -> 3

I just can't understand the else statement of the IF statement that I tried.
If you can help me, it will be very much appreciated. Thank you in advance.

A: Here is your code, slightly reformatted:
(defun depth (value)
  (if (or (null value) (atom value))
      0
      (+ 1 (apply 'max (mapcar #'depth value)))))

I renamed lst (you could have written it list, by the way) to value, because the name is confusing as it suggest that the variable is always a list, which is not true. The function depth can be called on any value:
(depth "hello")
=> 0

(depth 100)
=> 0

The then branch of the if is evaluated when value is NIL or any atom. Since NIL is also an atom, the test expression could be simplified as (atom value). When value is an atom, the depth is zero.
The else branch of the if is evaluated when value is not an atom, which by definition of atom means value here is a cons. The function also assumes that it is a proper list, and not some circular list.
Since value is a list in that branch, we can call mapcar on it: (mapcar #'depth value); this is where the function assumes the list is proper.
This computes (depth v) for each v in value. More precisely if value is a list of length n, then that call to mapcar evaluates as a list of numbers (D1 ... Dn) where Di is (depth Vi) for all i between 1 and n.
So we know that (apply 'max (mapcar ...)) is (apply 'max depths) for some list depths of numbers. In general:
(apply fn v1 ... vn list)

... is a way to call the function object denoted by the fn expression with at least n elements (v1 to vn), as well as an arbitrary number of additional elements stored in list. When you quote the function, as 'max, or when you write #'max, you refer to a function by its name in the function namespace.
Contrast this to the usual way of calling a function:
(f x y z)

The function name and the number of arguments being passed is fixed: as soon the form is read we knows there is a call to f with 3 arguments.
The apply function is a built-in that allows you to pass additional arguments in a list, in the last call argument. The above call could be written:
(apply #'f x y z ()) ;; note the empty list as a last argument

This could also be written:
(apply #'f (list x y z)) ;; all arguments in the last list

The only difference is probably a matter of runtime efficiency (and with good compilers, maybe there is no difference).
In your example, you do:
(apply max depths)

Which would be the same as writing (pseudo-code):
(max d1 d2 d3 ... dn)

... where depths is the list (list d1 d2 ... dn).
But we can't literally write them all directly, since the content of the list is only known at runtime.
Thus, the call to apply computes the max depths among all the depths computed recursively. Note that the above is a somewhat improper use of apply, since apply should not be called with lists of arbitrary size: there is a limit in the standard named CALL-ARGUMENTS-LIMIT that is allowed to be as low as 50 in theory, the maximum size of such a list  (we will see an alternative below).
Finally, depth evaluates (+ 1 ...) on this result. In other words, the whole expression can be summarized as: the depth of a list is 1 added to the maximum depth of all its elements.
Using reduce
Instead of apply, you can use REDUCE to compute max successively on a list. This is preferable to apply because:

*

*there is no limitation for the number of elements, like apply
(reduce 'max depths) ;; works the same, but more reliably

*there is no need need to build an intermediate list of depths, you iterate over the list of values, call depth and directly use the result to compute the max. The skeleton is:
(reduce (lambda (max-so-far item) ...)
        value
        :initial-value 0)

Declarative approach
Instead of reduce, the loop macro can be used as a more readable alternative to express the same computation. I also use typecase which in my opinion makes the intent clearer:
(defun depth (value)
  (typecase value
    (atom 0)
    (cons (1+ (loop for v in value maximize (depth v))))))


text:
Q: Extending Zend_Service for Amazon BrowseNodes, Ancestors are not processed The Zend Service for Amazon does not provide BrowseNodes, so I decided to extend it. The Zend code can be found at http://framework.zend.com/manual/de/zend.service.amazon.html.
My code below works almost but Just Ancestors are not processed. I wonder if there is an error in the wsdl or the xpath. I am trying to debug, but or just processing Ancestors. BrowseNodeId, Name, IsCategoryRoot, Children are processed but Ancestors array is always empty. The xpath query is able to find Children, but not Ancestors.
Please find the Code below. And a part of the xml
Here is the anatomy of the wsdl for the XML extract of a ItemLookup
http://docs.amazonwebservices.com/AWSECommerceService/latest/DG/AnatomyofaWSDL.html
The partial of xml response
<BrowseNodes>
    <BrowseNode>
        <BrowseNodeId>10605</BrowseNodeId>
        <Name>Education</Name>
        <Children>...</Children>
        <Ancestors>
            <BrowseNode>
                <BrowseNodeId>21</BrowseNodeId>
                <Name>Education & Reference</Name>
                <Ancestors>
                    <BrowseNode>
                        <BrowseNodeId>1000</BrowseNodeId>
                        <Name>Subjects</Name>
                        <IsCategoryRoot>1</IsCategoryRoot>
                        <Ancestors>
                            <BrowseNode>
                                <BrowseNodeId>283155</BrowseNodeId>
                                <Name>Books</Name>
                            </BrowseNode>
                        </Ancestors>
                    </BrowseNode>
                </Ancestors>
            </BrowseNode>
        </Ancestors>
    </BrowseNode>
</BrowseNodes>

How I am extending Zend_Service_Amazon_Item for BrowseNodes
class Zend_Service_Amazon_Item
{

    /**
     * @var array
     */
    public $BrowseNodes = array();

    public function __construct($dom) {

        // .... the code for the other items

        // .... for browsenode
        $result = $xpath->query('./az:BrowseNodes/*', $dom);
        if ($result->length > 1) {
            /**
             * @see Zend_Service_Amazon_BrowseNode
             */
            require_once 'Zend/Service/Amazon/BrowseNode.php';
            foreach ($result as $r) {
                $this->BrowseNodes[] = new Zend_Service_Amazon_BrowseNode($r);
            }
        }
    }
}

I have created a new Class for the BrowseNodes
class Zend_Service_Amazon_BrowseNode
{
    /**
     * @var integer
     */
    public $BrowseNodeId;

    /**
     * @var string
     */
    public $Name;

    /**
     * @var boolean
     */
    public $IsCategoryRoot;

    /**
     * @var array BrwoserNodes
     */
    public $Ancestors = array();

    /**
     * @var string
     */
    public $Children = array();

    /**
     * Assigns values to properties relevant to BrowseNode
     *
     * @param  DOMElement $dom
     * @return void
     */
    public function __construct(DOMElement $dom)
    {

        $xpath = new DOMXPath($dom->ownerDocument);
        $xpath->registerNamespace('az', 'http://webservices.amazon.com/AWSECommerceService/2011-08-01');
        foreach (array('BrowseNodeId', 'Name') as $el) {
            $result = $xpath->query("./az:$el/text()", $dom);
            if ($result->length == 1) {
                $this->$el = (string) $result->item(0)->data;
            }
        }

        $result = $xpath->query('./az:IsCategoryRoot/text()', $dom);
        if ($result->length == 1) {
            $this->IsCategoryRoot = (bool) $result->item(0)->data ;
        }

        foreach (array('Children','Ancestors') as $el) {
            $result = $xpath->query("./$el/*", $dom);
            if ($result->length > 1) {
                foreach ($result as $r) {
                    array_push($this->$el, new Zend_Service_Amazon_BrowseNode($r));
                }
            }
        }
    }
}

A: I've found the answer, hope it helps other's too.
There are two errors:

*

*I don't know what az: stands for but it is needed. Instead of
    $result = $xpath->query("./$el/*", $dom);

With "az:"
    $result = $xpath->query("./az:$el/*", $dom);

*I've been testing with only one Ancestor, so the argument in if is true, if I have a least two nodes in the result. According to the WSDL I could have Results with BrowseNodes, which have more than one Ancestor, but they must be rare or I was only looking for Items, which has only one Ancestor.
    if ($result->length > 1) {

should be:
    if ($result->length > 0) {

Once again the corrected code in last part of Zend_Service_Amazon_BrowseNode
    foreach (array('Children','Ancestors') as $el) {
        $result = $xpath->query("./az:$el/*", $dom);
        if ($result->length > 0) {
            foreach ($result as $r) {
                array_push($this->$el, new Zend_Service_Amazon_BrowseNode($r));
            }
        }
    }


text:
Q: TensorFlow shuffle() does not shuffle dataset I'm using TensorFlow 2.3.1, and the following code is not shuffling the data.
I have time series data that I want to build features and target for prediction.
Code:
data_len = len(calls['Calls'])

# Load data as TensorFlow dataset
dataset = tf.data.Dataset.from_tensor_slices(calls['Calls'])

# Create data windows and shifting values. Drop incomplete arrays
dataset = dataset.window(5, shift=1, drop_remainder=True)

# Convert into tensors for each window
dataset = dataset.flat_map(lambda window: window.batch(5))

# Split into features and target
dataset = dataset.map(lambda window: (window[:-1], window[-1:]))

# Shuffle data
dataset.shuffle(buffer_size=data_len)

dataset.batch(2).prefetch(1)

# Print output
for x, y in dataset:
    print('x = {}'.format(x.numpy()))
    print('y = {}'.format(y.numpy()))

Result:
x = [1659 4928 3961 3663]
y = [2452]
x = [4928 3961 3663 2452]
y = [2195]
x = [3961 3663 2452 2195]
y = [3796]
x = [3663 2452 2195 3796]
y = [2997]
x = [2452 2195 3796 2997]
y = [2598]
x = [2195 3796 2997 2598]
y = [2605]
x = [3796 2997 2598 2605]
y = [2603]
x = [2997 2598 2605 2603]
y = [2332]
x = [2598 2605 2603 2332]
y = [2025]
x = [2605 2603 2332 2025]

A: Found out the issue.
I wasn't assigning the batching and shuffling back to the dataset.
Thanks anyway.


text:
Q: Header: no number for references page How can I make sure that the references page has no number in the header (i. e., I still want a header, but without a number).

MWE with the problem:
\documentclass[]{article}
\usepackage{fancyhdr}
\fancyhf{} % clear the headers
\fancyhead[LE,RO]{%
   % We want italics
   \itshape
   % The chapter number only if it's greater than 0
   \ifnum\value{section}>0  \thesection. \fi
   % The chapter title
   \leftmark}

\fancyfoot[C]{\thepage}

\fancypagestyle{plain}{
  \renewcommand{\headrulewidth}{0pt}
  \fancyhf{}
  \fancyfoot[C]{\thepage}
}

\setlength{\headheight}{14.5pt}
\pagestyle{fancy}
\begin{document}

\section{Example}

\clearpage

\renewcommand{\thepage}{}

\begin{thebibliography}{99}

\end{thebibliography}

\end{document}

A: Define a new page style, say, bib like
\fancypagestyle{bib}{
  \fancyhf{}
  \fancyhead[LE,RO]{%
   % We want italics
   \itshape
   % The chapter title
   \leftmark}
   \fancyfoot[C]{\thepage}
}

without the section number and then just before \begin{thebibliography}{99} issue \pagestyle{bib}
Code:
\documentclass[]{article}
\usepackage{fancyhdr}
\fancyhf{} % clear the headers
\fancyhead[LE,RO]{%
   % We want italics
   \itshape
   % The chapter number only if it's greater than 0
   \ifnum\value{section}>0  \thesection. \fi
   % The chapter title
   \leftmark}

\fancyfoot[C]{\thepage}

%%% this is not needed as this does nothing. plain page style is exactly this one.
%\fancypagestyle{plain}{
%  \renewcommand{\headrulewidth}{0pt}
%  \fancyhf{}
%  \fancyfoot[C]{\thepage}
%}

\fancypagestyle{bib}{
  \fancyhf{}
  \fancyhead[LE,RO]{%
   % We want italics
   \itshape
   % The chapter title
   \leftmark}
   \fancyfoot[C]{\thepage}
}

\setlength{\headheight}{14.5pt}
\pagestyle{fancy}
\begin{document}

\section{Example}

\clearpage

%\renewcommand{\thepage}{}
\pagestyle{bib}

\begin{thebibliography}{99}

\end{thebibliography}

\end{document}


text:
Q: java fileUpload multiparts return null I can not get file name on my code. Basically it writes upload is successful in result page but it doesnt show file name and doesnt upload to ftp server. And it saves null in database. Could anyone help me on it pls? Here is all the codes:
UserDao.java :
import java.io.File;
import java.util.List;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet(name = "UserDao", urlPatterns = {"/UserDao"})
@MultipartConfig()

public class UserDao extends HttpServlet {

private final String UPLOAD_DIRECTORY = "/upload";

/**
 * Processes requests for both HTTP GET and POST
 * methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        HttpSession session = request.getSession(true);
String x = "";
            if (ServletFileUpload.isMultipartContent(request)) {
                try {
//                x += request;
                    List<FileItem> multiparts = new ServletFileUpload(
                            new DiskFileItemFactory()).parseRequest(request);
                    //File uploaded successfully

                    for (FileItem item : multiparts) {
                        String fileName = item.getName();
                        File file = new File(UPLOAD_DIRECTORY + File.separator + fileName);
                        item.write(file);
                        x += fileName + " @@ ";
                    }
                    request.setAttribute("message", "File Uploaded Successfully: " + UPLOAD_DIRECTORY + File.separator + x);
                } catch (Exception ex) {
                    request.setAttribute("message", "File Upload Failed due to " + ex);
                }
            } else {
                request.setAttribute("message",
                        "Sorry this Servlet only handles file upload request");
            }
        UsersPojo users = new UsersPojo();
            users.setId(Integer.parseInt(request.getParameter("idx")));
            users.setEmail(request.getParameter("email"));
            users.setFirstname(request.getParameter("first_name"));
            users.setLastname(request.getParameter("last_name"));
            users.setPhone("");
            users.setCity(request.getParameter("city"));
            users.setCountry(request.getParameter("country"));
            users.setJob_title(request.getParameter("job_title"));
            users.setCompany(request.getParameter("company"));
            users.setFollow(request.getParameter("follow"));
            users.setPicture(request.getParameter("picture"));
            users.setLogo(request.getParameter("logo"));
            UserDB.updateUser(users);
   request.getRequestDispatcher("/results.jsp").forward(request, response);

welcome.jsp:
<form method="post" action="UserDao" enctype="multipart/form-data">

                                            <input type="hidden" id="idx" name="idx" value="<%=id%>">
                                            <input type="hidden" id="email" name="email" value="<%=up.getEmail()%>">
                                            <input type="hidden" id="follow" name="follow" value="<%=up.getFollow()%>">

                                                    First name*
                                                    <input type="text" name="first_name" id="first_name" value="<%=up.getFirstname()%>" class="form-control" required>

                                                    Last name*
                                                    <input type="text" name="last_name" id="last_name" value="<%=up.getLastname()%>" class="form-control" required>

*You wish to hide your last name:  write only the first letter

                                                    City*
                                                    <input type="text" name="city" id="city" value="<%=up.getCity()%>" class="form-control" required>

                                                    Country*
                                                    <input type="text" name="country" id="country" value="<%=up.getCountry()%>" class="form-control" required>

                                                    Your job title*
                                                    <input type="text" name="job_title" id="job_title" value="<%=up.getJob_title()%>" class="form-control" required>

                                                    Your company*
                                                    <input type="text" name="company" id="company" value="<%=up.getCompany()%>" class="form-control" required>

* Required

Upload your photo

                                                    <input type="file" name="picture" id="picture">

                                            <button type="submit" name="btnEditComp" id="btnEditComp" class="btn1 btn btn-lg btn-primary" style="font-size: 23px;padding-right: 35px;padding-left: 35px;" >
                                                Save
                                            </button>

                                    </form>

results.jsp :

${requestScope["message"]}

A: You need to add the null check at least:
if (fileName != null) {
    File file = new File(UPLOAD_DIRECTORY + File.separator + fileName);
    item.write(file);
    x += fileName + " @@ ";
}

The variable multiparts includes DiskFileItem instances of other fields, for example, idx, email, first_name, ... and they don't have a file name.

A: The following line returns all the items of your multipart form :
List<FileItem> multiparts = new ServletFileUpload(
                            new DiskFileItemFactory()).parseRequest(request);

Therefore, when you are processing the uploaded file you need to exclude the rest of the form items :
                for (FileItem item : multiparts) {
                    if (!item.isFormField()) {
                       String fileName = item.getName();
                       File file = new File(UPLOAD_DIRECTORY + File.separator + fileName);
                       item.write(file);
                       x += fileName + " @@ ";
                    }
                 }


text:
Q: Coordinates all wrong on iPhone 3G? It could be your compiler Note: This is question to which I have already found an answer. It seems that posting a question after finding an interesting answer is encouraged, so I am posting this. Someone else is likely to have the same problem and find this useful.

I have an iOS app that produces charts. Shortly after publishing an update, a user sent me this panicky email:

"the latest update has modified the curves ... not seen more growth
  curves and inserted data are represented as a line descending ...
  before you could see perfectly well
Help me"

I get him to send a screenshot and give more detail. He has an iPhone 3G and this is how girl's chart looks. Most points are drawn at the wrong coordinates: they appear to be drawn at (x,x) instead of (x,y).

Compare with how this is supposed to look (ignore the difference in colours -- pink is for girls, blue for boys):

After much experimentation, I send him a rebuilt version of the previous version (which worked OK for him) and it still doesn't work. So in the end it appears that the code changes in the update have nothing to do with it. What could be the explanation?

A: iPhone original and iPhone 3G use the armv6 architecture, later models armv7. An answer to this Stack Overflow question, and an Apple developer forum thread point to a problem in the armv6 Thumb code produced by XCode 4.2's compiler which cause arithmetic operations on certain data structures, in particular CGPoint, to return completely wrong results. Such as the x value being written into the y value.
The solution is to add the -mno-thumb compiler option to the XCode project. This tells the compiler not to emit Thumb mode code, thereby bypassing the bug. Another solution is to switch back to an earlier XCode (pre-iOS5 SDK), which doesn't have this bug.
So the bug is in the compiler!  How cool is that? :)  In two decades of developing, I was yet to come across such a thing.
Here's a screenshot showing where to add this compiler option if it helps anyone:


text:
Q: Getting exception while printing Resultset with j-text utils' TextTable Class instead of table with ResultSet values Trying the below code to print the table from ResultSet in java but getting error:
Exception in thread "main" java.lang.NoClassDefFoundError:
org/apache/commons/lang/StringUtils
at dnl.utils.text.table.TextTableRenderer.render(TextTableRenderer.java:42)
at dnl.utils.text.table.TextTable.printTable(TextTable.java:76)
at dnl.utils.text.table.TextTable.printTable(TextTable.java:71)
at autopack.JDBC_Connection.main(JDBC_Connection.java:146)
Caused by: java.lang.ClassNotFoundException:
org.apache.commons.lang.StringUtils
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
... 4 more

Code:
for ( int i = 0,j=1; j <= columnsNumber; i++,j++ )
{
    ColumnNames[i]=rsmd.getColumnLabel(j);
}
rs.last();
int RowCount=rs.getRow();
rs.beforeFirst();

Object[][] data = new Object[RowCount][columnsNumber];
int i=0;

while(rs.next())
{
for (int j=0; j+1<=columnsNumber; j++)
{
data[i][j] = rs.getString(j+1);
}
i++;
}

TextTable tt = new TextTable(ColumnNames, data);
tt.setAddRowNumbering(true);
tt.printTable();

Note: Added SOP to print Pass to check where the code is failing or not reaching.
Got the above code example from: Write j-text utils table to file


text:
Q: extjs actioncolumn renderer prevents handler I have a actioncolumn on my grid with this code:
    this.columns =
    [
        {
            xtype: 'actioncolumn',
            items: [{
                icon: '../Content/Images/Approve.png',
                handler: function (grid, rowIndex, colIndex, node, e, record, rowNode) {
                    alert('test approve')
                }
            }
          ...rest of the columns

when I click the icon, I get the "test approve" message, so it works as expected!
If I add the render method bellow to disable the action column for rows that are already approved:
            renderer: function (value, metadata, record) {
                if (record.get('Approved') = 1) {
                    this.items[0].disabled = true
                } else {
                    this.items[0].disabled = false;
                }
            }

the handler stops working on the enabled itens. It seems like the renderer function is preventing the handler to be called. I even tried to add the handler code inside the renderer, but also no success.
Any idea why this would happen?

A: your condition statement in the if statement, i assume you meant to compare not assign. thats probably where your code is breaking


text:
Q: How to simulate data for those distributions which are not defined in MATLAB Suppose there is any distribution whose parameter values are known. So how to simulate data in this case?

A: While your question is rather vague, a classic text on univariate random number generation is Luc Devroye's Non-Uniform Random Variate Generation.


text:
Q: Join three table to get some problem help me? I Want to fetch data three tables "category, subcategory, products" but i have to get some error

Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in
  D:\xammp\htdocs\tam\admin\edit-products.php on line 157

PHP SQL
<?php
    $query=mysqli_query($conn,"select * from  products.*,

                       category.categoryName as catname,

                       subcategory.subcategory as categoryName

                       from products join category on

                       category.cid=products.cid

                       join subcategory on subcategory.sid=products.sid

                       where products.id='$id'");

       while($row=mysqli_fetch_array($query))// line 157
        { ?>

           }?>

A: you did wrong selection it should be like below
select products.*,
       category.categoryName as catname,
       subcategory.subcategory as categoryName
  from products
  join category
    on category.cid=products.cid
  join subcategory
    on subcategory.sid=products.sid
 where products.id=?


text:
Q: how can we get two element per iteration in jstl in for each I want to get two- two element per iteration in jstl. Is it posible that i do so.
Here is my code. dataListTweets is my list which i have set in previous page. i want to iterate two two element per iteration from List.

            <c:forEach items="${dataListTweets}" var="Tweets">

                ${Tweets}
                ${Tweets}

        </c:forEach>
        <c:remove var="dataListDetails" scope="request"/>

A: You can specif a step value in the forEach to iterate every two items of the collections.
Then use varStatus to get the index of the loop to define which tweet to display.

    <c:forEach  step="2" items="${dataListTweets}" varStatus="vs">

            ${dataListTweets[vs.index]}
            ${dataListTweets[vs.index+1]}

    </c:forEach>