text:
Q: Cocos2d - Top down camera view with rotation I'm trying to create a top down car game where the camera follows both the player and the player's rotation. I can get CCFollow to work easily, but I have had no success with CCCamera. I assume that I need the camera in order to make rotation follow the player (i.e. have the player facing up at all times) but I have had no luck on google.
Can anyone either provide a code snippet or a tutorial on how to create a rotation-following top down camera?
Cheers!

A: My suggestion: don't use the CCCamera.
Your game design requires the car to move over a track. In programming terms this is often much easier accomplished by keeping the car static, and instead moving the background underneath.
Assume your car is at the center of the screen. It's supposed to move from left to right. Instead of moving the car or the camera, move the background layer - just in reverse: move the background layer from right to left to make it seem like the car is moving from left to right.
The same is true for rotation. If you want the car to turn left, rotate the background in clockwise direction.
This is a lot easier and can be accomplished simply by changing the position and direction properties of the background layer. Note that you do not need to do this for each object in the background layer, it's sufficient to add all objects to the background layer in the appropriate positions and then just change the background layer properties. The layer's children will follow accordingly.


text:
Q: Database with low memory requirements and Ruby interface I need a database with low memory requirements for a small virtual server with few memory. At the moment I'm stuck with SQLite and Kyoto Cabinet or Tokyo Cabinet. The database should have a Ruby interface.
Ideally I want to avoid key-value-stores, because I have "complex" queries (more complex than looking up a single key) and tuples as keys. On the other hand I don't want to have a fixed schema and avoid the planning and migration efforts of a SQL database. A database server is also not necessary because only a single application will use the database.
Do you have any recommendations and numbers for me?

A: *

*There is schema-less Postgresql (Postgresql 9.2 + json). Not as hard/confusing to set up as I thought. You get lots of flexibility with queries while still getting the benefits of schema-less storage.  PG 9.2 includes plv8js, a new language handler that allows you to create functions in JavaScript. Here is one example of how you can index and query JSON docs in PG 9.2: http://people.planetpostgresql.org/andrew/index.php?/archives/249-Using-PLV8-to-index-JSON.html

*CouchDB (Use BigCouch. Based on CouchDB, but fewer bugs/problems.):

*

*very low memory requirements.

*schema-less.

*HTTP-based interface. Ruby has plenty of HTTP clients. HTTP caching (like Varnish) can also speed reads.

*creative/complex queries. You can create indexes and queries on any key in the document (record). You can get very creative with queries since the indexes are very programmable.

Downsides:

*

*Learning curve of setting up your queries/indexes.

*You have to schedule a type of cleanup operation called "compaction".

*Data will take up more space compared to other databases.

*More: http://www.paperplanes.de/2010/7/26/10_annoying_things_about_couchdb.html
If disk is cheap and memory expensive, it would make a good candidate for your needs.
"...another strength of CouchDB, which has proven to serve thousands of concurrent requests only needed about 10MB of RAM - how awesome is that?!?!" (From: http://www.larsgeorge.com/2009/03/hbase-vs-couchdb-in-berlin.html )

A: SQLite3 is a great fit for what you are trying to do. It's used by a lot of companies as their embedded app database because it's flexible, fast, well tested, and has a small footprint. It's easy to create and blow away tables so it plays well with testing or single-application-use data stores.
The SQL language it uses is rich enough to do normal things but I'd recommend  using Sequel with it. It's a great ORM and easily lets you treat it as a full-blown ORM, or drop all the way down to talking raw SQL to the DBM.

A: You are looking for a solution that only has a database file and no running server, probably. In that case, Sqlite should be a good choice - If you don't need it, just close the connection and that's it. Sqlite has everything that you need from and RDMS (expect for enforcing FK's directly, but that can be done with triggers), with a very little memory footprint, so in that case you are probably worried more about the memory your ORM (if any) uses.
Personally, I use sqlite for that use case as well, as it is portable and easy to access and install (which shouldn't be the problem on a server anyway, but in a desktop application it is).

A: BerkeleyDB with SQLite API is what you need.
http://www.oracle.com/technetwork/database/berkeleydb/overview/sql-160887.html

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can you have global methods in PHP? In languages like Ruby/Javascript, you can apply object operators to anything. I.e.,
var string = "Pancakes";
alert(string.length);
// 8

What is this called when everything is in object? Is there anything that can make PHP behave this way instead of having to hack something together yourself? Is this something that is currently requested in the PHP community?
The ability to do echo (new String("Hello"))->length() would be nice, or even "Hello"->length();  I would even settle for:
$var = "Hello";
echo $var->length;

A: It's called Object-oriented programming. PHP supports OOP, but a lot of the language is implemented as flat functions which accept arguments.
You would need to define your own objects if you wanted to operate on them, otherwise you're stuck with having to use functions like strlen() on the built in types such as String.

A: Java programmers use the term autoboxing for the ability of calling methods on primitive values. JavaScript has this feature too, and it works by creating temporary wrapper objects. I don't know about Ruby.
In PHP that's not possible. new String("Hello")->length() is also not possible, mainly because there is no String class with methods like length. You could create your own, but is it worth it? Also, you might be interested in this hack.

A: They call this object oriented programming.  The newer versions of PHP are OO.  You can create classes with methods to accomplish what you are referring to.

A: Object orientation (OO) is something that was tacked on to PHP "after the fact". Before OO was implemented everything was done using functions (like many other C-like programming languages).
When it comes to PHP, strings, integers, booleans, etc. are just data. They are primitive types and cannot do anything; they are just named values stored in memory. This is why you need to use functions, like strlen($str). The function operates on the value.
In languages like Ruby and Javascript most data types, such as strings, are, practically speaking, actually objects (or in some cases kinda-sorta objects). They contain various properties like .length, and methods like .indexOf(). Another word for such data types is a composite type (they are composed of more than one thing).
So, in PHP you can say that it is normal to write strlen($str) to figure out how long a string is; likewise, in Javascript or Ruby it is normal to write str.length.
It is possible to write a String class in PHP, but it is kind of beside the point. It is like learning to count to ten, but insisting that it be done in base-7. It is not very practical, and people will think you are crazy.


text:
Q: Double acute accent (long Hungarian umlaut) in Wordpress (or in math mode) Is it possible to display ő and ű characters in Wordpress' Latex?
As far as I know, the Latex of Wordpress works in math mode, but it seems to me that the double accute (long Hungarian umlaut) is missing from the accents of math mode.
Is there any workaround for this?
Edit: I need these characters inside a {cases} block, so WP editor doesn't solve this.

A: Mico's advice solved my problem.
This works in Wordpress:
$latex \text{Erd\H{o}s}$

and all Hungarian accents are available so:
$latex a=\begin{cases}
1, & \text{\'{a}rv\'{i}zt}\text{\H{u}r\H{o} t\"{u}k\"{o}rf\'{u}r\'{o}g\'{e}p} \\
0, & \text{\'{A}RV\'{I}ZT}\text{\H{U}R\H{O} T\"{U}K\"{O}RF\'{U}R\'{O}G\'{E}P}
\end{cases}$


text:
Q: How do you determine the complexity class of a problem like solving an integral? The P and NP classes relate to decision problems, but what about calculus problems, specifically computing an integral? How does one figure out if a certain class of integrals is in P or NP? Can something like this be rephrased in terms of a decision problem? Or is there another, indirect method?

A: I'm not sure if this is the answer you're looking for, but there is a general algorithm to solve indefinite integrals called the Risch algorithm.  Basically, given a set of elementary functions (polynomials, exponentials, logarithms, sin, cos, etc.) one can write the integral of a function composed of elementary functions in a normal form.  I'm a little unclear as to when and where decidability comes in (maybe a good starting point is the Wikipedia section on it) but it looks like as a step in the Risch algorithm is deciding the constant problem which is unknown to have an algorithm for it.  From the Wikipedia page, it is known that adding the absolute value function makes the problem undecidable (Richardson's Theorem).
If one restricts to definite integrals, then just deciding whether an integral is 0 or not can be NP-Complete as the following integral representation of the Number Partition Problem shows:

Given $n$ numbers, $(a_0, a_1, \cdots, a_{n-1})$, in the range of $1$ to $M$, find whether the following integral is zero or not:
  $$ \frac{1}{2 \pi} \int_{-\pi}^{\pi}\ \  \prod_{k=0}^{n-1}(e^{i a_k \theta } + e^{ - i a_k \theta }) d\theta $$

Notice that each term in the expanded product will be a combination of all the $a_k$'s.  Should one of the combinations in the exponent sum to 0, that term will evaluate to a positive number.  Since the $a_k$'s are integers, should the term in the exponent not sum to 0, the integral will evaluate to 0.  All terms with a non-zero exponent vanish while all terms with a 0 exponent count for 1 thus providing a "counting" function of all possible solutions.
If one wants to find the actual value of that integral, then this problem becomes $\#P$.

A: You have to use a higher type model to faithfully talk about complexity and computability of operators in analysis like integration. You may want to check Akitoshi Kawamura's thesis "Computational Complexity in Analysis and Geometry". He proves that integration is $\mathsf{\#P\text{-}complete}$ operator.


text: Q: Is there any potential downsides to using random UUID as temporary file/directory name? Is it reasonable to just use a random UUID (UUID version 4) based on /dev/urandom or CryptGenRandom to name temporary files/directories? The name collision is highly unlikely, but is there any potential problems? Why isn't such scheme used more frequently?


text:
Q: How to prevent to update changed data I use SQL Azure and have application, which sync data with external resource. Data is huge, approx 10K records, so, I get it from DB one time, update something if necessary during some minutes and save changes. It works, but problem with simultaneously access to data. IF during these some minutes other service add changes, these changes will be rewritten.
But in the most cases it concerns fields, which my application does not touch!
So, for example, my Table Device:
public partial class Device : BaseEntity
{
    public string Name { get; set; }

    public string IMEI { get; set; }

    public string SN { get; set; }

    public string ICCID { get; set; }

    public string MacAddress { get; set; }

    public DeviceStatus Status { get; set; }

first service (application with long-term process) can modify SN, ICCID, MacAddress, but not Status, second service, vice versa, can modify only Status.
Code to update in the first service:
        _allLocalDevicesWithIMEI = _context.GetAllDevicesWithImei().ToList();

(it gets entities, not DTO, because really there are many fields can be changed)
and then:
        _context.Devices.Update(localDevice);

for every device, which should be changed
and, eventually:
        await _context.SaveChangesAsync();

How to mark, that field Status should be excluded from tracing?

A: One simple method to avoid update the status field when calling the first service is create a update entity not include the status field, and create another update entity for the second service which includes the status field.
Another way to resolve this problem is override the SaveChangesAsync method and control the update logic by yourself, but it's complex I think and the behavior is implicit, it will not easy for others to understand your code.

A: To avoid rewrite, you can specify RowVersion on entities. This is so called optimistic concurrency, it will throw error if rewrite happens and you can retry operation if someone already changed something. Or you can just level up your Transaction level, to something like RepeatableRead/Serialized to lock these rows for entire operation (which of course will pose huge performance impact and timeouts). Second option is simple, and good enough for background jobs and distributed transactions, first one is more flexible and usually faster. but hard to implement across multiple endpoints/entities.


text:
Q: Spring Data REST rename resource The following the JSON representation of a GClass as generated by default with Spring Data REST.
{
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/api/classes/1"
    },
    "gClass" : {
      "href" : "http://localhost:8080/api/classes/1"
    }
  }
}

It's a class's reference to itself (that's fine) and then that same information again but with the property type included this time. The issue I have is that I can't figure out how to change "gClass" to "class".
From the Spring Data REST reference doc:

For every association of the domain type, we expose links named after the association property. You can customize this behavior by using @RestResource on the property.

This works for me on properties in entity classes, but not on references to itself. I can't, for example, annotate my class (GClass) with:
@Entity
@Table(name="CLASSES")
@RestResource(rel="class")
public class GClass {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long classId;

    public GClass() {}

    public long getClassId() {
        return classId;
    }

    public void setClassId(int classId) {
        this.classId = classId;
    }
}

The repository is a simple JpaRespository. I can change both it's relation name and path name without issue.
@RepositoryRestResource(collectionResourceRel = "classes", path = "classes")
public interface GClassRepository extends JpaRepository<GClass, Long>{}

I can create a RepresentationModelProcessor bean that removes the link from every EntityModel and re-creates the link with a new rel name. That solution seems as though that's a very involved process for a pretty standard piece of customization. What am I missing?


text:
Q: Proof writing advice. I am new to writing informal proofs. I am fine with formal proofs, but the transition is jarring. I do understand the necessity of informal proofs. My questions are:

*

*How do I figure out which steps to include?

*How should I format the proofs? Most informal proofs are presented in a paragraph form. Consider instead the proof format below. Is this acceptable? Professors, what would you say to a student who wrote a proof like this? I find this easier to write than paragraphs, since no effort is spent on choice of words.

Prove: $\bigcap \{ \mathcal{P}(X) : X \in A \} = \mathcal{P}(\bigcap A)$.

*

*First we prove that $\bigcap \{ \mathcal{P}(X) : X \in A \} \subseteq \mathcal{P}(\bigcap A)$.

*

*Assume $y  \in \bigcap \{ \mathcal{P}(X) : X \in A \}$.

*Then, for all $X \in A$, $y \in \mathcal{P}( X)$.

*Then, for all $X \in A$, $y \subseteq X$.

*Assume $z \in y$.

*Then, for all $X \in A$, $z \in X$.

*Then, $z \in \bigcap A$.

*Then, for all $z \in y$, $z \in \bigcap A$.

*Then, $y \subseteq \bigcap A$.

*Then $y \in \mathcal{P}( \bigcap A )$.

*Now we prove that $\mathcal{P}(\bigcap A) \subseteq \bigcap \{ \mathcal{P}(X) : X \in A \}$.

*

*Assume $y \in \mathcal{P}(\bigcap A)$.

*Then, $y \subseteq \bigcap A$.

*Assume $z \in y$.

*Then, $z \in \bigcap A$.

*Then, for all $X \in A$, $z \in X$.

*Then, for all $X \in A$ and for all $z \in y$, $z \in X$.

*Then, for all $X \in A$, $y \subseteq X$.

*Then, for all $X \in A$, $y \in \mathcal{P}( X )$.

*Then, $y  \in \bigcap \{ \mathcal{P}(X) : X \in A \}$.

*Thus, $\bigcap \{ \mathcal{P}(X) : X \in A \} = \mathcal{P}(\bigcap A)$.

A: I wouldn't be so structured. Being formal is fine, until it makes communicating a proof hard. So, you want to show that
$$\bigcap_{X\in A} P(X) = P(\cap A)$$
The left hand side consists of those sets $z$ that are subsets of every set in $A$. Because $\cap A$ is the intersection of all sets in $A$, and because $z$ is a subset of all of the sets in $A$, $z$ is a subset of $\cap A$.
Conversely, assume that $z$ is a subset of $\cap A$. This means that $z$ is contained in every set in $A$. That is, $z$ is a subset of every $X\in A$, which means $z$ is in $ \bigcap_{X\in A} P(X) $.

A: See whether this link helps you: http://mypages.valdosta.edu/plmoch/MATH4161/Spring%202004/informal_proofs.htm. This is also very useful : https://www.google.co.in/url?sa=t&source=web&rct=j&url=https://people.cs.pitt.edu/~milos/courses/cs441/lectures/Class6.pdf&ved=0ahUKEwiAqP_W17nQAhVLNY8KHfCmCHEQFggbMAA&usg=AFQjCNGZJxYFtzDjN6b3CCNXP3smeFQwOw&sig2=zUfeNvUxhGHr6zstsaKVIw.


text:
Q: MySQL export into Outfile issue I created a Stored procedure with a cursor in order to get the info from a few tables into a temp table and then export the result into multiple files, one for each Client ID, the cursor and the loop get all the info right but I'm having syntax issues when creating each file
BEGIN
    DECLARE id_cli INT;
  DECLARE cur_id_cli CURSOR FOR SELECT id FROM cliente ORDER BY id;

  OPEN cur_id_cli;

  read_loop: LOOP
    FETCH cur_id_cli INTO id_cli;

DROP TEMPORARY TABLE IF EXISTS tmp_reporte_enviadas_sucursal_mensual;
  CREATE TEMPORARY TABLE tmp_reporte_enviadas_sucursal_mensual

  SELECT  *  FROM
  ((SELECT 'Promo_id', 'Mensaje', 'Sucursal_id', 'Direccion') UNION ALL (SELECT
      p.id,
          p.mensaje,
          s.id,
          s.direccion
  FROM
      Usuario_Promo AS up, Promo_Sucursal AS ps, Cliente_Sucursal AS cs, Cliente AS c, Promo AS p, Sucursal AS s
  WHERE
      p.id = ps.Promo_id
          AND up.promo_id = ps.id
          AND up.recibido = 1
          AND ps.Cliente_Sucursal_id = cs.id
          AND cs.cliente_id = id_cli
          AND DATE(up.fecha_recibido) BETWEEN (NOW() - INTERVAL 30 DAY) AND NOW()
          AND s.id = cs.sucursal_id
  ORDER BY p.id)) AS tmp_reporte_enviadas_sucursal_mensual;

SET @idCli = CAST(id_cli AS CHAR);
SET @fullOutputPath = CONCAT('D:/Octagon/Apps/Flyermob/Clientes/Reportes_Sql/reporte_enviadas_sucursal_mensual_',@idCli,'.csv');

SELECT * FROM
INTO OUTFILE @fullOutputPath
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '\"'
FROM tmp_reporte_enviadas_sucursal_mensual;

SELECT * FROM tmp_reporte_enviadas_sucursal_mensual;

  END LOOP;

  CLOSE cur_id_cli;
END

here's where I'm having the issue:
SELECT * FROM
    INTO OUTFILE @fullOutputPath
    FIELDS TERMINATED BY ','
    OPTIONALLY ENCLOSED BY '\"'
    FROM tmp_reporte_enviadas_sucursal_mensual;

Whenever I try to save, it says that there's a syntax problem near @fullOutputPath if I remove this section, the procedure run perfectly and I get all the results for each Client Id.
Just to get it out of the way id_cli is a primary key, so there's no chance of  repeating and I have full permissions on @fullOutputPath.

A: Try this:
SELECT * FROM tmp_reporte_enviadas_sucursal_mensual
    INTO OUTFILE @fullOutputPath
    FIELDS TERMINATED BY ','
    OPTIONALLY ENCLOSED BY '\"';

A: I managed to make it work with
SET @idCli = CAST(id_cli AS CHAR);
SET @fullOutputPath = CONCAT('flyermob/cliente/reporte_enviadas_sucursal_mensual_cliente_',@idCli,'.csv');

set @q1 := concat("SELECT * INTO OUTFILE '",@fullOutputPath,
"' FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '\"'
FROM tmp_reporte_enviadas_sucursal_mensual");

prepare s1 from @q1;
execute s1;
deallocate prepare s1;

It creates the file in the MySql default folder


text:
Q: Best practises storing credentials/secrets across devices/teams TL;DR
An issue I've rarely seen addressed is storing of secrets/credentials across devices/teams.

Context:
There are countless questions and solutions storing credentials, API keys, secrets, etc for devices or backend servers using secure storage mechanisms or as environment variables.
Below are a few solutions specifically designed for deployed systems/apps, store on a device or credentials for a server.

*

*Process env.

*Device Secure Storage

*Hashicorp (paid solution)

*AWS Secret manager for AWS projects

*Firebase Secret manager, pay per read
All of these are specific towards an active implementation or to a deployed device/server but non provide access to developer(s) e.g. running local emulator with e.g. Stripe webhook integration.
2 scenarios to illustrate my point and emphasize the problem:

*

*Scenario 1:
An on-the-move freelance developer working on a backend / mobile app project. Primary workstation is a Windows PC, but frequently uses Macbook for travel and work.
Here, an issue with credentials would be: do one store this in VCS, e.g. Github? Surely, that would be easiest but it is not recommended to do this for several security reasons. Alternative is to copy, electronically or physically to 'new' device.

*Scenario 2
A team of 3 are working on a project. Each works on their own use-cases. 2 require credentials for an online service. Credentials are shared physically or electronically. During development, credentials are changed (for whatever reason) and needs to be distributed to team members to finish.
Same issue, does one commit these credentials to VCS or share them electronically/physically.

Question
What are common/best practises sharing api keys/credentials/auth tokens across teams/devices?
The only possible solution I found addressing these needs is using git-secret


text:
Q: Does the access speed depend on the number of files on a network share? In our office we use a RAID5 of SSDs as a network share. This share is accessed as a network drive from Windows-PCs and Mac.
Sometimes this network share becomes awfully slow in terms of access times and transfer speed.
I am not the admin and therefore do not have full insight into the system.
One of the admins now proposed that this may have to do with the number of files that are stored on the network share. Some folders contain millions of few kB files.
Does the access speed depend on the number of files on a network share?


text:
Q: I need to query MYSQL records based on the first characters of values I have 1 MYSQL table with 8000 records. I would like to query First name, Middle name, and Last name by the first characters of their full name. For instance, i have 40 rows of records (First name, Middle name, and Last name) which their first character of their name is SSS. My question is, how do i query "SSS" to only return 6 results and when i query "SSS" again i need another 6 results and so on until all the 40 records query ends.
I used the following query but only return the first 6 results and when i query "SSS" the next time, it returns the same results over and over. Please i need your help.
SELECT *
FROM Table
WHERE  (UPPER(FName) LIKE UPPER('S%')
       AND UPPER(MName) LIKE UPPER('S%')
       AND UPPER(LName) LIKE UPPER('S%')
ORDER BY ID
LIMIT 6 OFFSET 0

Thanks in advance.

A: You're ordering by ID - good. Remember max ID of the last returned data set and when you query next time add condition ID > your_last_max_id

A: Second time, change offset:
LIMIT 6 OFFSET 6

and then
LIMIT 6 OFFSET 12

etc.


text:
Q: Download localizable 'strings' files from server I would like to be able to add/edit languages in my iOS applications. Therefore, I followed the approach in this question, could not get it to work however.
This is what I did:
I created a folder myFolder and dragged the localization folders (en.lproj, ...) from my XCode project into that folder. Then I renamed it to myFolder.bundle.
Then I tried to load that whole bundle from a URL like so:
NSURL *url = [NSURL URLWithString:@"http://192.168.0.12/language_plists/Localizable.bundle"];
NSBundle *bundle = [[NSBundle alloc] initWithURL:url];

which throws the following error:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSBundle initWithURL:]: non-file URL argument'

A: Explicitly it will not work using a non-file URL, because NSBundle only deals with File URLs.  At best if you were to download, you would have to download into either Cache or Document locations, and you would have to do so explicitly.
Further, You will need to re-submit the App in order to get many of the benefits of localization, because your App Store entry will only contain languages that can be tested before download.

A: You have option with this github
Download your json file in your document directory and access its path.
i.e.
//Download the app from server and save it to Document directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [[paths lastObject] stringByAppendingPathComponent:@"strings.json"];


text:
Q: How to test object from factory with mocha with sinon Background
I have a factory function that creates dogs that bark:
const dogFactory = () => {
    const bark = name => console.log(`${name} just barked!`);

    return{
        bark
    };
};

One would use it like:
const dog = dogFactory();
dog.bark("boby"); //"boby just barked!"

I also have an hotel of dogs. Business is not going good, so to keep appearances I am creating my own dogs ! This hotel thus takes a dogFactory as an argument and looks like the following:
const dogHotel = deps => {
    const {
        dogFactory
    } = deps;

    let dogsHosted = [];

    const feed = () => {
        dogsHosted.push(dogFactory());
        dogsHosted.forEach( (dog, i) => dog.bark(i));
    }

    return{
        feed
    };
};

You would use it like:
const hotelAwsome = dogHotel({dogFactory: dogFactory});
hotelAwsome.feed();

This hotel feeds dogs. Because there is no business it creates a dog and then feeds everyone. Every time a dog is fed, it barks of happiness!
Problem
One would think that creating infinite dogs in a broken hotel would be the problem, but that is not the case!
The problem here is that I want to make sure the dogs are happy barking. That is, that for each dog in the hotel bark is being called.
Code
This is currently my test. I am using mocha as a test suite, I am using sinon to spy on my fake factory objects:
const sinon = require( "sinon" );
const chai = require( "chai" );
const expect = chai.expect;

describe("dog hotel", () => {

    const fakeFacory = () => {
        const bark = () => sinon.spy()
        return {bark};
    };

    it("should make the dogs bark with happiness when feeding them!", () => {
        const hotelAweomse = dogHotel({dogFactory: fakeFacory});
        hotelAwesome.feed();
        //expect something here
    });
});

The issue here is that I am passing a fake dog factory, but I can't check with sinon if the dog are barking or not!
Question
How do I test if the dogs that are created in the hotel, are barking?

A: You should move the spy creation out of the fake factory. Now you can just use the spy properties (callOnce, calls) in the expect.
Kudos for the entertaining question :)
describe("dog hotel", () => {
    const spy = sinon.spy(); // create the spy outside

    const fakeFacory = () => {
        return {
          bark: spy // assign it to bark
        };
    };

    it("should make the dogs bark with happiness when feeding them!", () => {
        const hotelAweomse = dogHotel({dogFactory: fakeFacory});
        hotelAwesome.feed();

        // expect only one bark
        expect(spy.calledOnce).to.be.true;

        // expect a number of barks
        expect(spy.calls).to.equal(1);
    });
});


text:
Q: Reductive quotient of parahoric subgroups of a simply connected simple group. Let $G$ be a simply-connected simlpe group over a local field $K$ and $P_x$ a maximal parahoric subgroup of it. Let $P_x^+$ be the pro-unipotent radical of $P_x$. Then $P_x/P_x^+$ is a connected reductive group over the residue field $\kappa$ with root system $\Phi_x$.
Question: Is it true that $P_x/P_x^+$ is a simply connected semisimple group with root system $\Phi_x$? If not, is it ture that $P_x/P_x^+$ has a simply connected derived group?
Any reference?


text:
Q: python 3.5 robobrowser, fill input with one value at a time I am trying to scrap a webpage after entering input value using python 3.5 and robobrowser. The problem I am facing is: While trying to input each value at a time in the input.
<select name="ctl00$ContentPlaceHolder1$DDLDistrict" onchange="javascript:setTimeout('__doPostBack(\'ctl00$ContentPlaceHolder1$DDLDistrict\',\'\')', 0)" id="ctl00_ContentPlaceHolder1_DDLDistrict">
    <option value="Select District">Select District</option>
    <option selected="selected" value="8">Agra</option>
    <option value="9">A</option>
    <option value="29">B</option>
    <option value="70">C Nagar</option>
    <option value="72">D</option>
    <option value="58">Y</option>
    <option value="40">Z</option>
</select>

Part of my Python code is:
import re
from robobrowser import RoboBrowser

# Browse to Genius
browser = RoboBrowser(history=True)
browser.open('http://164.100.180.82/ceouptemp/RollPDF.aspx')
from bs4 import BeautifulSoup
form = browser.get_form(name='ctl00$ContentPlaceHolder1$DDLDistrict')

A: Just to double-check, make sure you've actually found the form, but printing the form. The code that follows assumes you have an interactive Python session going with the code you posted above.
>>> print(form)

If you get some a value that begin with, <RoboForm __, then you're in business. If you get None, then you haven't actually selected the form and you should try the following to figure where the form is,
>>> browser.get_forms()

Once you have found the form that includes the select list assigned it the variable name form, you can change the value of the form to some values (such as '29' as follows):
>>> form['ctl00$ContentPlaceHolder1$DDLDistrict'].value = '29'

If you want a list of all the options, you can do:
>>> form['ctl00$ContentPlaceHolder1$DDLDistrict'].options

Happy scrapping!
Check out the RoboBrowser docs for more information (note the example on checkboxes works just like selects): https://github.com/jmcarp/robobrowser


text:
Q: Compact list conversion using LINQ This is my code:
 List<bool> results1 = new List<bool>();
 List<int> items1 = ...;
 foreach (var item in items1)
     results1.Add((item >= 1600 && item <= 5000));

I'm sure this can be compacted into one line, but how?

A: results1 = items1.Select(i => i >= 1600 && i <= 5000).ToList();

A: ConvertAll doesn't change the original list. In order to make this one-liner, you probably should substitute items1 with the code ... where you get your items, if you are not using it somewhere else.
 List<bool> results1 = items1.ConvertAll(i => i >= 1600 && i <= 5000);


text:
Q: monte carlo simulation - confidence intervals construction I am starting with Monte Carlo Simulation. I have run simulation to estimate the mean and the variance of the exponential distribution.
Simulation:
I have generated random sample from uniform distribution (sample size n) and then using the inverse function method generated the exponential distribution.
I have run this simulation  N1, N2, and N3 times where N1 < N2 <  N3.
Results:
All worked well, when I plot the results I can see that the distribution of means and variances tends to the normal distribution as the number of simulation increases.
Questions:
1) Would you please help and clarify how the empirical and theoretical confidence intervals should be derived?
2) what is the manifestation of the Law of Large Numbers in this exercise?
3) and what is manifestation of Central Limit Theorem in this exercise?

A: *

*I don't know what you mean by a theoretical confidence interval, perhaps a confidence interval where you use the value of $\sigma$ which is known in advance? As for the empirical confidence interval, that would be

$$\left (\overline{X}-\frac{t_{N,\alpha} S}{\sqrt{N}},\overline{X}+\frac{t_{N,\alpha} S}{\sqrt{N}} \right )$$
where $\overline{X}$ is the sample mean, $S$ is the sample standard deviation, $N$ is the sample size, and $t_{N,\alpha}$ comes from Student's $t$ distribution. Specifically, if you want your interval to have confidence $0<\alpha<1$, then $t_{N,\alpha}$ is the number $b$ such that the probability for Student's $t$ distribution with $N-1$ degrees of freedom to be between $-b$ and $b$ is $\alpha$. For large $N$ this is well-approximated by the corresponding value from the standard normal distribution.

*You should see that your sample means are all close to the true mean if $N$ is large. (In this form I am using the strong law of large numbers; you need a whole bunch of sample means to make sense of the weak law of large numbers).

*If you take a bunch of sample means for a large but fixed $N$, $\mu$ is the true mean and $\sigma$ is the true standard deviation, then you have a bunch of instances of $\overline{X}$. If you make a histogram of the quantity $\sqrt{N}\frac{\overline{X}-\mu}{\sigma}$ using these values of $\overline{X}$, the distribution you get should look approximately like a standard normal.


text:
Q: WPF Binding not being updated Properly I am having the most frustrating issue I have had in a while, I have setup as below, and recently it has stopped working on the clients computers for no reason(or no reason that I can tell note I haven't changed any code in this section for months and this has only started happening in the last week) what is happening is the the Text is not becoming visible when the user hits edit, the weird thing is is that it works 100% in debug, release (using VS2010) and having the program installed on my computer, and I am stumped I can seem to replicate at all on my own computer. My question is simply (albiet a little vague) can anyone point or tell me where to look it debug this?
View Model Section (just a typical binding):
    private bool _editingSpecifications = false;
    public bool EditingSpecifications
    {
        get { return _editingSpecifications; }
        set
        {
            System.Windows.MessageBox.Show("In EditingSpecifications property PRE: "+value);
            if (_editingTraceSpecifications == value)
                return;
            _editingSpecifications = value;
            base.OnPropertyChanged("EditingSpecifications");
            System.Windows.MessageBox.Show("In EditingSpecifications property POST");
        }
    }

View:
  <TextBox Visibility="{Binding Path=EditingSpecifications, Converter={StaticResource BoolToVis2}}" Text="{Binding Path=Specifications, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Left" Width="262">...</TextBox>

And Converter:
 public class BoolToVisibiltyConverter2 : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (targetType != typeof(Visibility))
            throw new InvalidOperationException("The target must be a Visibility");
        System.Windows.MessageBox.Show((bool)value + " :BoolToVisibiltyConverter2");
        if ((bool)value)
            return Visibility.Visible;
        return Visibility.Collapsed;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if ((Visibility)value == Visibility.Visible)
            return true;
        return false;
    }
}

Its a MVVM setup where the ViewModel binds to the view on demand(ie when the user wishes to edit etc), the code above is all I feel is relevant (if you need more just ask :)), as you can see I have some messagebox pop up and from that I get this scenario:
The user loads the first View hits edit messagebox pops up
1) "In EditingSpecifications property PRE: "+value
2) (bool)value + " :BoolToVisibiltyConverter2"
3) "In EditingSpecifications property POST"
Everything works as expected, however on loading a second view (note this could even be the same view just closed and reopened)
1) "In EditingSpecifications property PRE: "+value
2) (bool)value + " :BoolToVisibiltyConverter2" - but not this, so in otherwords the converter is not called on the second and any subsequent attempts to edit the specifications.
3) "In EditingSpecifications property POST"
If you hit edit again on the same box you only get:
1) "In EditingSpecifications property PRE: "+value - which is kinda expected.
EDIT- Bit More Detail
The problem being that only on first edit attempt will the Textbox become visible, and will not become visible on any subsequent requests after closing and opening the view :/ And I feel it has something to do with the binding not being updated from the ViewModel on update request but I can't replicate it.
And the only way to reset this is to close and open the program, and as I stated before I can only replicate this behaviour on the clients computer and never on my own. So could anyone please tell me or point me in any direction of where to look please.

A: There was a similar problem introduced in WPF 4.0 when navigating backwards to a page: the page would be displayed correctly, but the bindings wouldn't work. The workaround was to wrap the contents of the View into a DataTemplate, so that the View would be instantiated anew every time it was displayed.
Another thing you could try is setting the DataContext to null and then back to the ViewModel, in order to force a reset of the bindings.
By the way: why are you writing your own BooleanToVisibilityConverter? There is one in System.Windows.Controls ...


text:
Q: Can Sql Server BULK INSERT read from a named pipe/fifo? Is it possible for BULK INSERT/bcp to read from a named pipe, fifo-style?
That is, rather than reading from a real text file, can BULK INSERT/bcp be made to read from a named pipe which is on the write end of another process?
For example:

*

*create named pipe

*unzip file to named pipe

*read from named pipe with bcp or BULK INSERT

or:

*

*create 4 named pipes

*split 1 file into 4 streams, writing each stream to a separate named pipe

*read from 4 named pipes into 4 tables w/ bcp or BULK INSERT

The closest I've found was this fellow (site now unreachable), who managed to write to a named pipe w/ bcp, with a his own utility and usage like so:
start /MIN ZipPipe authors_pipe authors.txt.gz 9
bcp  pubs..authors out  \\.\pipe\authors_pipe -T -n

But he couldn't get the reverse to work.
So before I head off on a fool's errand, I'm wondering whether it's fundamentally possible to read from a named pipe w/ BULK INSERT or bcp. And if it is possible, how would one set it up? Would NamedPipeServerStream or something else in the .NET System.IO.Pipes namespace be adequate?
eg, an example using Powershell:
[reflection.Assembly]::LoadWithPartialName("system.core")
$pipe = New-Object system.IO.Pipes.NamedPipeServerStream("Bob")

And then....what?

A: Unfortunately, both SSIS flat file adaptors, BULK INSERT and BCP take an exclusive write lock on the file (even though it does not actually write to it). This is why this doesn't work.
I am not sure pipes can be set up to allow two exclusive locks on the same pipe without some serious hacking. You could detour it I suppose or hack into fltmgr.sys :)
As the other posters suggested, using the .NET API to do bulk or the OLEDB or ODBC interface instead is likely simpler, even though it means you have to write your own file parser.

A: I have succeeded in getting BULK INSERT (but not BCP) to work correctly with named pipes on Windows 7 ans SQL Server 2008R2. There are some tricks.
First, I had to create two named pipe instances on two different threads, both with the same pipe name. SQL Server would open the first instance, read a few bytes from it, and close it, causing WriteFile to raise a PipeException in the first thread.  SQL Server would then immediately reopen the named pipe, and stream in all of the data from it. If I didn't have a second thread sitting in the background ready to serve the data, SQL server would return an error before my first thread had time to recover from the PipeException.
Second, I had to write all of the data in a single call to WriteFile. I started with a loop where I wrote multiple batches to the pipe, but BULK INSERT only used the first batch that I wrote. It seems to do a non-blocking read, and treat any read that returns zero bytes as an end-of-file.
Third, an XML format file, if used, must be written to a regular file. I have not succeeded in getting SQL Server to read the format file from a pipe. I don't know if it can read a non-XML format file from a pipe.

A: I'd comment on @DanMenes (thanks for the inspiration), but for reference purposes, I'm adding it as a separate answer.
I've worked out a solution in .NET which opens up a pipe (actually 2, first one gets destroyed like @DanMenes said), prepares streaming the data to it and then starts the BULK INSERT with an auto-generated format file.
The premise is that I can do stuff like
  var inMemoryData = new[] {
    new[] { "val1", "val2" },
    new[] { "val3", "val4" },
  };

  using (var importer = new Importer(SqlConnection, "MyTable", "Col1", "Col2"))
  {
    importer.Import(inMemoryData);
  }

I'll summarize the implementation of Importer:
1. Create the pipe
var stream = new NamedPipeServerStream(name, PipeDirection.Out, 2, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
stream.BeginWaitForConnection(OnConnection, this);

2. Accept connections
public void OnConnection(IAsyncResult asyncResult)
{
  Stream.EndWaitForConnection(asyncResult);

  var buffer = Encoding.UTF8.GetBytes(data);
  Stream.Write(buffer, 0, buffer.Length);
  Stream.Close();
}

3. Start BULK INSERT
var insertCommand = DbConnection.CreateCommand();
insertCommand.CommandText = "BULK INSERT [MyTable] FROM '\\.\pipe\mypipe' WITH (FORMATFILE='c:\path\to\formatfile')";
insertCommand.ExecuteNonQuery();

See the GitHub project for more details.
Note: I have yet to add performance tests to the project, but preliminary tests did show performance gains between 2x and 5x with respect to transactional INSERTs.

A: Does BCP accept STDIN?  If so, you might want to try just piping it straight through without creating a named pipe...for instance:
gunzip authors.txt.gz | bcp schema.tablename


text:
Q: Strange Behavior of ScheduledTask I have a background task that handles some simulations. It has worked fine for quite some time but all of a sudden it did not work at all. I traced it down to some strange behavior of ScheduledTask
In[1]:= Attributes[ScheduledTask]
Out[1]= {}

In[2]:= obj=SessionSubmit[ScheduledTask[Print[DateString[]],{3,5}]]
During evaluation of In[2]:= Thu 10 Sep 2020 12:56:37
During evaluation of In[2]:= Thu 10 Sep 2020 12:56:37
During evaluation of In[2]:= Thu 10 Sep 2020 12:56:37
Out[2]= TaskObject[Task UUID: ab3631dd-10dd-4b52-88df-c12dda751f4f
Task environment: Session
Task type: Scheduled
**Evaluation expression: Null**
]

SetAttributes[ScheduledTask, HoldFirst]

In[4]:= obj = SessionSubmit[ScheduledTask[Print[DateString[]], {3, 5}]]

Out[4]= TaskObject[<|
  TaskUUID -> adaf1093 - 6 ccc - 4 ccb - 927 f - b34e0832fac3,
  TaskEnvironment -> Session, TaskType -> Scheduled, << 3 >>,
  HandlerFunctionsKeys -> {Task, TaskUUID, TaskType, TaskStatus,
    TaskEnvironment, HandlerFunctions, HandlerFunctionsKeys,
    EventName, EvaluationExpression, << 4 >>, Rema << 11 >> nt,
    NextScheduledTime, TotalRunCount, MessageOutput, PrintOutput},
  AutoRemove -> True|>]

Very strange that ScheduledTask does not have any attributes, not even Protected.
I have to manually set HoldFirst in order to get the expected behavior.
Any Idea what is going on?
I have rebooted the computer with no difference. The only change I can think of is that I updated windows 10.


text:
Q: how can I add thumbs up and thumbs down at the end of every conversation in bot framework? I'm trying to get feedback from the user on every answer given by the chatbot. Is there a way I can show a thumbs-up and a thumbs-down icon at the end of every conversation (as of now they are all FAQs) so that I can capture if the user is satisfied with the answer or not?

A: I've used the suggested actions feature:
var msg = new builder.Message(session)
      .text(response)
      .suggestedActions(builder.SuggestedActions.create(session, [
                        builder.CardAction.postBack(session, "thumbs-up", ""),
                        builder.CardAction.postBack(session, "thumbs-down", ""),
                       ]));
      session.send(msg);


text:
Q: Wordpress need to add parent Category (custom taxonomy) to items I am working on a Wordpress website using a custom post type and custom taxonomy(tour-category).
I am making changes to the search filters the below bit of code pulls in the taxonomies(tour-category) and displays them so you can filter them on and off to update the search.
I have managed to add the category slug to the div class but really I need them to display the parent taxonomy(tour-category). on the div class for each of the filter items.
So I can target any taxonomy(tour-category) under a specific parent using CSS as I want to be able to hide none relevant ones, without having to hide them one by one I will just target all that are under a parent.
Hope someone can help :-)
Thanks
Lee
<?php if(is_array($tour_types) && count($tour_types) && $show_tour_types) : ?>
   <?php foreach($tour_types as $type) : ?>
        <?php
        $checked = in_array($type->slug, $checked_types);
        $checked_attr = $checked ? 'checked' : '';
        ?>

    <div class="mkdf-tours-type-filter-item <?php echo esc_attr($type->slug); ?>">
        <input <?php echo esc_attr($checked_attr); ?> type="checkbox" id="mkdf-tour-type-filter-<?php echo esc_attr($type->slug); ?>" name="type[]" value="<?php echo esc_attr($type->slug); ?>">
        <label for="mkdf-tour-type-filter-<?php echo esc_attr($type->slug); ?>">

                <?php echo esc_html($type->name); ?>

<?php endforeach; ?>


text:
Q: Calender: Show dates upto next 1 week from current week Hello friends I have a calendar with next previous button when user clicks on next button next week schedule will come if again user clicks nothing will happen I want to show dates upto next 1 week

My JavaScript for Next Button
function Next()
    {

    /*sunday*/
    var next_sunday = new Date(current_week.setDate(current_week.getDate() - current_week.getDay()+7));
    var sunday = [next_sunday.getDate()];
    var smonth = [next_sunday.getMonth() + 1] ;
    var syear = [next_sunday.getFullYear()];
    var sunday_date= syear + '-' + smonth + '-' + sunday;
    alert(sunday_date);
    document.getElementById("sunday").innerHTML =sunday;
    /*monday*/
    var next_monday = new Date(current_week.setDate(current_week.getDate() - current_week.getDay()+1));
    var monday = [next_monday.getDate()];
    var mmonth = [next_monday.getMonth() + 1] ;
    var myear = [next_monday.getFullYear()];
    var monday_date= myear + '-' + mmonth + '-' + monday;
    alert(monday_date);
    document.getElementById("monday").innerHTML =monday;

    /*Tuesday*/
    var next_tuesday = new Date(current_week.setDate(current_week.getDate() - current_week.getDay()+2));
    var tuesday = [next_tuesday.getDate()];
    var tmonth = [next_tuesday.getMonth() + 1] ;
    var tyear = [next_tuesday.getFullYear()];
    var tuesday_date= tyear + '-' + tmonth + '-' + tuesday;
    alert(tuesday_date);
    document.getElementById("tuesday").innerHTML =tuesday;
    /*Wednesday*/
    var next_wedday = new Date(current_week.setDate(current_week.getDate() - current_week.getDay()+3));
    var wednesday = [next_wedday.getDate()];
    var wmonth = [next_wedday.getMonth() + 1] ;
    var wyear = [next_wedday.getFullYear()];
    var wednesday_date= wyear + '-' + wmonth + '-' + wednesday;
    alert(wednesday_date);
    document.getElementById("wednesday").innerHTML =wednesday;
    /*Thursday*/
    var next_thuday = new Date(current_week.setDate(current_week.getDate() - current_week.getDay()+4));
    var thursday = [next_thuday.getDate()];
    var thmonth = [next_thuday.getMonth() + 1] ;
    var thyear = [next_thuday.getFullYear()];
    var thursday_date= thyear + '-' + thmonth + '-' + thursday;
    alert(thursday_date);
    document.getElementById("thursday").innerHTML =thursday;
    /*friday*/
    var next_friday = new Date(current_week.setDate(current_week.getDate() - current_week.getDay()+5));
    var friday = [next_friday.getDate()];
    var fmonth = [next_friday.getMonth() + 1] ;
    var fyear = [next_friday.getFullYear()];
    var friday_date= fyear + '-' + fmonth + '-' + friday;
    alert(friday_date);
    document.getElementById("friday").innerHTML =friday;
    /*saturday*/
    var next_satday = new Date(current_week.setDate(current_week.getDate() - current_week.getDay()+6));
    var saturday = [next_satday.getDate()];
    var samonth = [next_satday.getMonth() + 1] ;
    var sayear = [next_satday.getFullYear()];
    var saturday_date= sayear + '-' + samonth + '-' + saturday;
    document.getElementById("saturday").innerHTML =saturday;
    alert(saturday_date);
    $("#date").datepicker("setDate", new Date(next_monday));

    var months = ['January','February','March','April','May','June','July','August','September','October','November','December'];
    var week_month = months[next_satday.getMonth()] ;
    var week_year = [next_satday.getFullYear()];
    document.getElementById("endDate").innerHTML =week_month +' '+ saturday + ',' + ' ' + week_year;

    }

please suggest somthing

A: I got the answer I used if else loop first I have captured current week last date mean Saturday date and then compared with next saturday
Javascript
 function Next()
{
    // get current week saturday
    var textbox_value=document.getElementById("date").value;
    var current_week = new Date(textbox_value);
    var next_satday = new Date(current_week.setDate(current_week.getDate() - current_week.getDay()+6));
    var current_satday = [next_satday.getDate()];
    //alert(current_satday);

     // last week saturday as per my requirement
     // you can modify as per your requirement
    var curr = new Date;
    var firstday = new Date(curr.setDate(curr.getDate() - curr.getDay()));
    var lastday = new Date(curr.setDate(curr.getDate() - curr.getDay()+6));
    var last_satday = [lastday.getDate()];
    //alert(last_satday);

    if(current_satday <= last_satday){
    //alert('success');

    /*sunday*/
    var next_sunday = new Date(current_week.setDate(current_week.getDate() - current_week.getDay()+7));
    var sunday = [next_sunday.getDate()];
    var smonth = [next_sunday.getMonth() + 1] ;
    var syear = [next_sunday.getFullYear()];
    var sunday_date= syear + '-' + smonth + '-' + sunday;
    //alert(sunday_date);
    document.getElementById("sunday").innerHTML =sunday;
    /*monday*/
    var next_monday = new Date(current_week.setDate(current_week.getDate() - current_week.getDay()+1));
    var monday = [next_monday.getDate()];
    var mmonth = [next_monday.getMonth() + 1] ;
    var myear = [next_monday.getFullYear()];
    var monday_date= myear + '-' + mmonth + '-' + monday;
    //alert(monday_date);
    document.getElementById("monday").innerHTML =monday;

    /*Tuesday*/
    var next_tuesday = new Date(current_week.setDate(current_week.getDate() - current_week.getDay()+2));
    var tuesday = [next_tuesday.getDate()];
    var tmonth = [next_tuesday.getMonth() + 1] ;
    var tyear = [next_tuesday.getFullYear()];
    var tuesday_date= tyear + '-' + tmonth + '-' + tuesday;
    //alert(tuesday_date);
    document.getElementById("tuesday").innerHTML =tuesday;
    /*Wednesday*/
    var next_wedday = new Date(current_week.setDate(current_week.getDate() - current_week.getDay()+3));
    var wednesday = [next_wedday.getDate()];
    var wmonth = [next_wedday.getMonth() + 1] ;
    var wyear = [next_wedday.getFullYear()];
    var wednesday_date= wyear + '-' + wmonth + '-' + wednesday;
    //alert(wednesday_date);
    document.getElementById("wednesday").innerHTML =wednesday;
    /*Thursday*/
    var next_thuday = new Date(current_week.setDate(current_week.getDate() - current_week.getDay()+4));
    var thursday = [next_thuday.getDate()];
    var thmonth = [next_thuday.getMonth() + 1] ;
    var thyear = [next_thuday.getFullYear()];
    var thursday_date= thyear + '-' + thmonth + '-' + thursday;
    //alert(thursday_date);
    document.getElementById("thursday").innerHTML =thursday;
    /*friday*/
    var next_friday = new Date(current_week.setDate(current_week.getDate() - current_week.getDay()+5));
    var friday = [next_friday.getDate()];
    var fmonth = [next_friday.getMonth() + 1] ;
    var fyear = [next_friday.getFullYear()];
    var friday_date= fyear + '-' + fmonth + '-' + friday;
    //alert(friday_date);
    document.getElementById("friday").innerHTML =friday;
    /*saturday*/
    var next_satday = new Date(current_week.setDate(current_week.getDate() - current_week.getDay()+6));
    var saturday = [next_satday.getDate()];
    var samonth = [next_satday.getMonth() + 1] ;
    var sayear = [next_satday.getFullYear()];
    var saturday_date= sayear + '-' + samonth + '-' + saturday;
    document.getElementById("saturday").innerHTML =saturday;
    //alert(saturday_date);
    $("#date").datepicker("setDate", new Date(next_monday));

    var months = ['January','February','March','April','May','June','July','August','September','October','November','December'];
    var week_month = months[next_satday.getMonth()] ;
    var week_year = [next_satday.getFullYear()];
    document.getElementById("endDate").innerHTML =week_month +' '+ saturday + ',' + ' ' + week_year;
    }


text:
Q: How does VPC relate to EC2 in AWS? How to explain to a complete beginner about the relationship between EC2 and VPC? I've recently encountered this problem when viewing a online Udemy course. It has an episode instructing the viewers to set up a VPC. It doesn't explain when to use such a VPC when you can simply launch a EC2 and use the instance directly.
Is VPC a virtual box that you can put stuff like EC2 inside it?

A: EC2-Classic is the original release of Amazon EC2. In EC2-Classic, instances run in a single, flat network that is shared with other customers. With EC2-VPC, instances run in a virtual private cloud that is logically isolated to only one AWS account.
Source: Link

A: VPC helps you to have your custom network and allows you to have grouped networks for your resources. For example, you can maintain webservers and databases in one network and if you also have any other application servers and api servers and their respective environments can be maintained in a different network. Basically network isolation helps you to manage your resources effectively.

A: I suggest you need to do training that starts at the beginning, explaining VPC, EC2, etc properly. Alternately you can read the AWS documentation.
A quick overview: VPC is virtual private cloud. It can be thought of as a virtual data center or a virtual network. You deploy AWS resources including EC2 servers, RDS databases, or any of there 160+ other services into a VPC. There are a few services that do not use VPCs - for example the Transit Gateway is an account level service that lets you connect VPCs across many accounts.
VPCs are isolated from each other and the internet by default. You can peer VPCs, and you can add an internet gateway.
Each VPC has a CIDR network address range, most people use /16 networks with /24 subnets. You cannot peer VPCs that have overlapping CIDR ranges.
VPCs are not a physical resources, they're a virtual resource based on the AWS hyperplane (there's a good session on the hyperplane on youtube from Re:Invent). They're highly available with no single point of failure.


text:
Q: Power fucntion langage C code blockss compiler void sommeascf(n)
    for(i=1; i<=n; i++){
        result= result+ 1/i^n
    }
}

the problem I'm facing is :

result = result + 1/i^n

How can I put the power function into this arithmetic operation ?

A: ^ this is bitwise XOR operator in C . You can write that expression using pow function like this -
result= result+ 1/(pow(i,n));

Note - You need to include header <math.h>


text:
Q: How to push into an existing session array , key and value in laravel With php I used
if (!isset($_SESSION['cart']) || !isset($_SESSION['cart'][$product])) {
    $_SESSION['cart'][$product] = 0;
    $_SESSION['cart'][$product] = $_SESSION['cart'][$product] + $product_quantity;

}else{
    $_SESSION['cart'][$product] = $_SESSION['cart'][$product] + $product_quantity;
}

I tried with put() but it's not working, cause every time I try to insert a new value it replace the first one
session()->put('cart',[request('variant_id') => request('quantity')]);

With push() I put inside the array cart another array with key and value
session()->push('cart',[request('variant_id') => request('quantity')]);

Is there a way to insert into session array with key and value cause right now I can't figure it out how to do it


text:
Q: Xcode Provisioning Profiles Location Where are the Provisioning Profiles located in Xcode 8.3.3 within the project and/or file directory?

A: Where they have been for older versions of Xcode: ~/Library/MobileDevice/Provisioning\ Profiles
Provisioning profiles are not stored with the project.  Xcode has a common area and the profile is pulled when you build and bundled with the ipa.

A: *

*Go to the Finder

*From the "Go" menu navigate down to "Go to Folder"
or

*Hit Command+Shift+G from the Mac OS X desktop or a Finder window

*Search below Path

~/Library/MobileDevice/Provisioning Profiles

A: FWIW if you're building into a physical device, then if you dig through your derived data, you can find:
/Users/my_username/Library/Developer/Xcode/DerivedData/MyCompanyName-ebd35ntnhtdhykyasixtkvjjqlcsu/Build/Products/Debug-iphoneos/CoolAppName.app/embedded.mobileprovision

In the Build/Products/Debug-iphoneos directory you'll find your app name just like:
CoolAppName  // it won't have any `.app` extension or anything.

You just have to right click on it and hit 'show package contents' or just change directory to that...
then find a file with .mobileprovision extension.
Remember you won't find this if you're building with simulator, because simulators, don't need provisioning profiles.
How to see what's inside?
Either just use Preview or see detailed instructions from Dev Forums - Quinn on how to dump it. e.g.
$ security cms -D -i ~/Library/MobileDevice/Provisioning\ Profiles/8d04addd-d7f5-4872-bd48-f6885bb67433.mobileprovision


text:
Q: Code-first approach - connection string to generate the database in SQL Server Express [Windows Authentication] I'm trying to define a connection string for EF code-first approach to generate the database in SQL Server Express.
I'm logging into my pc using /user account, once I put following connection string in web.config file in my WebAPI project
<connectionStrings>
    <add name="libraryappconnectionstring"
         connectionString="Data Source=minchiepad\SQLEXPRESS;Initial Catalog=LibraryAppDB;Integrated Security=SSPI;"
         providerName="System.Data.SqlClient"/>
</connectionStrings>

I can see its listing under server explorer tab

When I try to connect I'm getting following error

Once I googled, all the related answer for this errors are for existing DBs

Where should I configure to fix that error connection string or SQL Server? And how?

A: One of the possibility is user don't have access to the DB you attempting to access.
Check these settings.

Try changing the Default Database to LibraryAppDB in General Properties
I can see Space in the username at first, does local user has same name. Check is that causing any issue by any means.
Check "user mapping" to know the DB access allowed to this user.


text:
Q: How to handle large number of requests in scrapy? I'm crawling around 20 million urls. But before the request is actually made the process gets killed due to excessive memory usage (4 GB RAM). How can I handle this in scrapy so that the process doesn't gets killed ?
class MySpider(Spider):
name = "mydomain"
allowed_domains = ["mydomain.com"]
urls = []
for d in range(0,20000000):
    link = "http://example.com/"+str(d)
    urls.append(link)
start_urls = urls

def parse(self, response):
    yield response

A: I think I found the workaround.
Add this method to your spider.
def start_requests(self):
    for d in range(1,26999999):
        yield scrapy.Request("http://example.com/"+str(d), self.parse)

you dont have to specify the start_urls in the starting.
It will start generating URLs and start sending asynchronous requests and the callback will be called when the scrapy gets the response.In the start the memory usage will be more but later on it will take constant memory.
Along with this you can use
scrapy crawl somespider -s JOBDIR=crawls/somespider-1

By using this you can pause the spider and resume it any time by using the same command
and in order to save CPU (and log storage requirements)
use
LOG_LEVEL = 'INFO'

in settings.py of the scrapy project.

A: I believe creating a big list of urls to use as start_urls may be causing the problem.
How about doing this instead?
class MySpider(Spider):
name = "mydomain"
allowed_domains = ["mydomain.com"]

start_urls = ["http://example.com/0"]

def parse(self, response):
    for d in xrange(1,20000000):
        link = "http://example.com/"+str(d)
        yield Request(url=link, callback=self.parse_link)

def parse_link(self, response):
    yield response


text:
Q: Internal Server Error returned when uploading to OneDrive I am attempting to upload a file to OneDrive using the MS Graph API, but today I have started to receive an error back when trying to upload.
The error is being thrown on this line:
var uploadSession = await graphClient.Users[userId].Drive.Items[itemId].ItemWithPath(fileName).CreateUploadSession().Request().PostAsync();

The error message I am getting back is simply 'InternalServerError' with the message 'Object reference not set to an instance of an object'.  The code I have has been working happily in production for a year, but today has suddenly started throwing this exception.
I have tried debugging local, but do not get any more information and I have updated the nuget packages to the latest version, but still get the same error.

A: Issue was caused by a Microsoft update, which has now been resolved.  Github issue 646


text:
Q: Sharing static data between multiple processes I have a WCF service (instantiated within a Console application on NetTCP), this service has static data (large volume) which gets instantiated on the load.
I have multiple instances of this Console application running at once, and all of them are doing the same static data initialization , is there a way that I can have a single data source and share the data among processes so that each process does not have to consume large amount of memory?

A: You can use memory mapped files; but each process must have its own memory due to how Windows protects applications.
From http://msdn.microsoft.com/en-us/library/dd997372.aspx:

Non-persisted files are memory-mapped files that are not associated with a file on a disk. When the last process has finished working with the file, the data is lost and the file is reclaimed by garbage collection. These files are suitable for creating shared memory for inter-process communications (IPC).

With any sort of "shared" data, you'll have the additional task of synchronizing access.

A: The quick solution would be to write another dedicated service which you run first. It would load the data once and makes it available to other service instances as needed.
The more robust solution is to store the data in a database or caching layer that all the services connect to. The caching layer is a nice choice because your service can lazy load it if its not in the cache (keeping more of your current design) and it can be fast (in memory). Some cache options include:

*

*Windows AppFabric

*Memcached

*NCache


text:
Q: Hide default style class of p:selectOneRadio I have used p:selectOneRadio in my xhtml page but I am not being able to remove their default style class .ui-helper-hidden-accessible, hence the radio button icons are not being visible.
My code is as follows:
<p:selectOneRadio
     id="whetherRegisteredThroughEdistrictApp"
     layout="grid" value="#{loginMBean.whetherCitizenUser}"
     required="true" requiredMessage="#{i18n['errmsg-req-fields']}"
>
    <f:selectItem itemLabel="Yes" itemValue="#{true}" />
    <f:selectItem itemLabel="No" itemValue="#{false}" />
    <p:ajax event="change" update="notcitizenUserDiv, citizenUserDiv" />
</p:selectOneRadio>

A: I think Javascript is the best way to do:
$( '#yourDivName input[type="radio"]' ).removeAttr( "disabled" );

or you can find with id end disable the disable attribute.
var radio = $('[id$=radio] input');
radio.attr('disabled','disabled');


text:
Q: Multidimensional associative array into html table I'm currently learning php and I'm trying to print a multidimensional associative array in html table format and I'm having some trouble looping through each of the elements, here's the code
$test =array(
'One'=>array('fname' => 'John', 'lnom' => 'Dupond', 'age' => 25, 'city' => 'Paris'),
'Two' => array('fname' => 'Deal', 'lnom' => 'Martin', 'age' => 20, 'city' => 'Epizts'),
'Three' => array('fname' => 'Martin', 'lnom' => 'Tonge', 'age' => 18, 'city' => 'Epinay'),
'Four'=> array('fname' => 'Austin', 'lnom' => 'Dupond', 'age' => 33, 'city' => 'Paris'),
'Five'=> array('fname' => 'Johnny', 'lnom'=>'Ailta', 'age' => 46, 'city'=> 'Villetaneuse'),
'Six'=> array('fname' => 'Scott', 'lnom' => 'Askier', 'age'=>7, 'city'=>'Villetaneuse')
);

what I'm trying to do :
foreach($test['One'] as $key=> $value)
{

    echo $value;
}

I'm not too sure about the rest if I should use a nested foreach loop or something else to print all the keys + values ..

A: If you want to loop through this array completely and turn it to an html table you need two loops - one for the main and second for inner array for example:
<?php

$test =array(
'One'=>array('fname' => 'John', 'lnom' => 'Dupond', 'age' => 25, 'city' => 'Paris'),
'Two' => array('fname' => 'Deal', 'lnom' => 'Martin', 'age' => 20, 'city' => 'Epizts'),
'Three' => array('fname' => 'Martin', 'lnom' => 'Tonge', 'age' => 18, 'city' => 'Epinay'),
'Four'=> array('fname' => 'Austin', 'lnom' => 'Dupond', 'age' => 33, 'city' => 'Paris'),
'Five'=> array('fname' => 'Johnny', 'lnom'=>'Ailta', 'age' => 46, 'city'=> 'Villetaneuse'),
'Six'=> array('fname' => 'Scott', 'lnom' => 'Askier', 'age'=>7, 'city'=>'Villetaneuse')
);

?>

        #
        fname
        lnom
        age
        city

<?php

foreach($test as $key => $val){
    ?>

        <?php echo $key;?>	<?php

        foreach($val as $k => $v){
            ?><?php echo $v;?>	<?php
        }
    ?>
<?php
}

?>

Will return:
#     fname  lnom   age city
One   John   Dupond 25  Paris
Two   Deal   Martin 20  Epizts
Three Martin Tonge  18  Epinay
Four  Austin Dupond 33  Paris
Five  Johnny Ailta  46  Villetaneuse
Six   Scott  Askier 7   Villetaneuse

A: Just loop the outer array:

<?php foreach ($test as $person) { ?>

        <?= $person['fname'] ?>
        <?= $person['lnom'] ?>
        <?= $person['age'] ?>
        <?= $person['city'] ?>

<?php } ?>

The variable $person will contain the sub array, from which you just fetch the elements you want.
If you want to output every column dynamically (not needing to write $person['fname'] etc), then you can create a nested loop:
<?php foreach ($test as $person) { ?>

    <?php foreach ($person as $value) { ?>

        <?= $value ?>

    <?php } ?>

<?php } ?>


text:
Q: matlab: difference between KeyPressFcn and WindowKeyPressFcn The Matlab documentation definition for KeyPressFcn is a "callback function invoked by a key press that occurs while the figure window has focus."
Similarly, the definition for WindowKeyPressFcn is a "callback function invoked by a key press that occurs while either the figure window or any of its children has focus."
As far as I understand, the children of figures are entities like axes, plot objects, and annotation objects. If one of these children has focus, then its parent figure presumably also has focus (at least its handle would be returned by gcf). Therefore, I don't see any practical distinction between KeyPressFcn and WindowKeyPressFcn other than that the former, by implication of its name lacking the term Window, might also take effect when no figures are active, such as when operating in the command window (though this conjecture is in disagreement with the callbacks definition, which explicitly invokes the presence of a figure window).
Could someone pleas explain the difference between these two callback functions and when use of one over the other might be preferred?

A: As you suggest in your question the difference is in focus.

*

*KeyPressFcn is evaluated only when the figure has focus (but not its children).

*WindowKeyPressFcn, on the other hand, is evaluated whenever the figure or any of its children has focus.

This can be illustrated with following code:
function test_keypress_vs_windowkeypress

h.hf = figure();
h.edit = uicontrol('Style', 'edit', 'Units', 'Normalized',...
    'Position', [0.2, 0.2, 0.6, 0.6]);

% set callbacks
set(h.hf, 'KeyPressFcn', @wintest);
set(h.edit, 'KeyPressFcn', @edittest);

function wintest(h, e)
    disp('window button press');

function edittest(h, e)
    disp('editbox button press');

The function creates a figure (that has a KeyPressFcn) with an ugly edit box (has a KeyPressFcn too).
Now if you:

*

*press any key when the edit box has focus only the edittest callback is evaluated.

*press any key when the figure has focus only the wintest callback is evaluated.

*change the window callback to be WindowKeyPressFcn and press a key while the edit box has focus - both callbacks will be evaluated (first the figure callback then the edit box callback).


text:
Q: Play video in swing (VLCJ without VLC) How can I play a video in swing with the library vlcj without having vlc installed?
What I have done:
1: Downloaded the vlcj library, vlcj 2.4.1 (zip) and add all to build path:
(docs1)
2: Downloaded the libvlc.dll and libvlccore.dll and put them in project folder:
(docs2)
(docs3)
3: Downloaded a sample video from http:(here video) and put it in project folder:
sample_mpeg4.mp43: (docs4)
I then created the following class to show the video in swing:
public class MediaPlayer extends JPanel {

// Declares our media player component
private EmbeddedMediaPlayerComponent mediaplayer;
// This string holds the media URL path
private static String mediapath;
private JPanel panel;

public MediaPlayer() {
    String projectPath = System.getProperty("user.dir");
    String vlcpath = projectPath;
    mediapath = projectPath + "\\sample_mpeg42.mp4";

    // Check if the .dll is correct
    File f = new File(vlcpath + "/libvlc.dll");
    System.out.println("VLC PATH CORRECT: " + f.exists());

    NativeLibrary.addSearchPath(RuntimeUtil.getLibVlcLibraryName(), vlcpath);
    mediaplayer = new EmbeddedMediaPlayerComponent();

    panel = new JPanel();
    panel.setLayout(new BorderLayout());
    panel.add(mediaplayer, BorderLayout.CENTER);
    setLayout(new BorderLayout());
    add(mediaplayer, BorderLayout.CENTER);
}

public void play() {
    mediaplayer.getMediaPlayer().playMedia(mediapath);
}

public static void main(String[] args) {
    MediaPlayer mediaplayer = new MediaPlayer();
    JFrame ourframe = new JFrame();
    ourframe.setContentPane(mediaplayer);
    ourframe.setSize(720, 560);
    ourframe.setVisible(true);
    mediaplayer.play();
    ourframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

}
But getting the error:

Exception in thread "main" java.lang.RuntimeException: Failed to load
  the native library. The error was "Unable to load library 'vlc':...

Do I need to have something else/more then the libvlc.dll and libvlccore.dll?

A: A typical VLC installation on Windows goes in "Program Files\VideoLAN\VLC".
In that directory you will find libvlc.dll and libvlccore.dll.
You will also find a "plugins" directory with a lot of sub-directories containing shared libraries for video/audio decoding and playback, as well as other things like LUA support, media meta-data support, service discovery, the vlc GUI, and so on.
You need those shared libraries too.
In principle you do not need all of those shared libraries, you just need the ones required to play your media (you may not be interested in LUA for example, nor the vlc GUI so you could remove those).
In practice, the difficulty is in working out precisely which sub-set of the shared libraries you need (there's no definitive list describing which plugin is needed for which purposes) so I expect most people just redistribute all of them.
You do need to be careful what you redistribute, because while most of the VLC plugins are now licensed under LGPL, not all of them are.

A: Minor addition to the answer by caprica. I moved VLC folder contents to {project.dir}/lib folder, removed everthing except dll files and plugins folder. I still faced the exception with an output "Vlc plugin error, No plugins found". I found as issue here, which mentions that new jna version included in vlcj versions 3.10.0+ messes with VLC plugin loading.
Solution: either include vlcj version 3.9.0 as a dependency, or as I did, pull the vlcj source from github, and in vlcj pom.xml change the jna.version from 4.1.0 to 3.5.2, run 'mvn clean install' and use this local vlcj artifact in your project with this version(to avoid confusion in the future between local repo and maven repo, change vlcj version to 3.xx.xx-custom or similar, so local artifact will be used always).
In the code, add custom path like this:
NativeLibrary.addSearchPath(RuntimeUtil.getLibVlcLibraryName(), "./lib");


text:
Q: Can Maven run non-build tasks? I moved from Ant to Maven and I miss one thing: the ability to execute an arbitrary task. I wanted to get rid of Ant's build.xml but I still need it just for this.
Occasionally I need to run some stats for XML processing and PDF processing. They are not part of the build but I need to automate them anyway. In Ant I used to just compile and run a java class in the code to using the java Ant task, e.g.:
<target name="gen-stats">
  <java classname="com.utl.StatsGen" classpath="build" />
</target>

<target name="compute-complexity">
  <java classname="com.utl.PDFComplexity" classpath="lib/pdf-cpx.jar" />
</target>

Trying to wrap my brain around it. Maybe Maven wasn't designed to do help with any automation, but only addresses "build oriented" tasks. Is it?

A: Basically, Maven define Phases, Goals, Plugins and Lifecycles.
Phase: A stage during a defined build Lifecycle.
Each Phase is a sequence of goals.
Goal: A Goal is responsible for a specific task.
Plugin: A Plugin is a group of Goals (Goals aren't necessarily all bound to the same phase).
Lifecycle: A Lifecycle is a sequence of Phases.
Having said that, there is a default set of Maven's Lifecycles.

*

*default (main lifecycle responsible for handle project deployment -build and deploy your project-)

*clean (lifecycle responsible for handle project cleaning)

*site (lifecycle reponsible for create project's site documentation)

Default Lifecycle phases
<phases>
  <phase>validate</phase>
  <phase>initialize</phase>
  <phase>generate-sources</phase>
  <phase>process-sources</phase>
  <phase>generate-resources</phase>
  <phase>process-resources</phase>
  <phase>compile</phase>
  <phase>process-classes</phase>
  <phase>generate-test-sources</phase>
  <phase>process-test-sources</phase>
  <phase>generate-test-resources</phase>
  <phase>process-test-resources</phase>
  <phase>test-compile</phase>
  <phase>process-test-classes</phase>
  <phase>test</phase>
  <phase>prepare-package</phase>
  <phase>package</phase>
  <phase>pre-integration-test</phase>
  <phase>integration-test</phase>
  <phase>post-integration-test</phase>
  <phase>verify</phase>
  <phase>install</phase>
  <phase>deploy</phase>
</phases>

Clean Lifecycle phases
<phases>
  <phase>pre-clean</phase>
  <phase>clean</phase>
  <phase>post-clean</phase>
</phases>
<default-phases>
  <clean>
    org.apache.maven.plugins:maven-clean-plugin:2.5:clean
  </clean>
</default-phases>

Site Lifecycle phases
<phases>
  <phase>pre-site</phase>
  <phase>site</phase>
  <phase>post-site</phase>
  <phase>site-deploy</phase>
</phases>
<default-phases>
  <site>
    org.apache.maven.plugins:maven-site-plugin:3.3:site
  </site>
  <site-deploy>
    org.apache.maven.plugins:maven-site-plugin:3.3:deploy
  </site-deploy>
</default-phases>

See you that in default lifecycle there is not default-phases defined. It's because default phases to be executed in this lifecycle are specific defined for each packaging (ear, jar, war, rar, pom, etc). See default lifecycle bindings.
So, if you run 'mvn PHASE' eg. 'mvn install' you will execute default lifecycle INSTALL phase and all the preceding phases as well (this will execute all phases except those after the one defined 'install','deploy' will not be executed).
When you run 'mvn PLUGIN:GOAL' executes the defined plugin goal eg. 'mvn compiler:compile'. It will run all phases up to the defined phase (and all goals in those phases) including your defined goal.

There are a set of plugins that you can use to execute a OS command or a java process. Also there is a plugin to run Ant tasks that can be useful.
Mojo Exec plugin
mojo exec plugin reference
Eg. Execution using command line:
mvn exec:java -Dexec.mainClass="com.example.Main" [-Dexec.args="argument1"] ...

Eg. Execution using a POM configuration:
<project>
  ...
  <build>
    <plugins>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>exec-maven-plugin</artifactId>
        <version>1.6.0</version>
        <executions>
          <execution>
            ...
            <goals>
              <goal>java</goal>
            </goals>
          </execution>
        </executions>
        <configuration>
          <mainClass>com.example.Main</mainClass>
          <arguments>
            <argument>argument1</argument>
            ...
          </arguments>
          <systemProperties>
            <systemProperty>
              <key>myproperty</key>
              <value>myvalue</value>
            </systemProperty>
            ...
          </systemProperties>
        </configuration>
      </plugin>
    </plugins>
  </build>
   ...
</project>

Maven Antrun plugin
antrun plugin reference
Eg. POM configuration:
<project>
  ...
  <build>
    <!-- To define the plugin version in your parent POM -->
    <pluginManagement>
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-antrun-plugin</artifactId>
          <version>1.8</version>
        </plugin>
        ...
      </plugins>
    </pluginManagement>
    <!-- To use the plugin goals in your POM or parent POM -->
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-antrun-plugin</artifactId>
        <version>1.8</version>
      </plugin>
      ...
    </plugins>
  </build>
  ...
</project>

The maven-antrun-plugin has only one goal, run.
Eg. command line execution:
mvn antrun:run

More about usage and how to define your Ant targets in pom.xml:
usage
Antrun usage example
1 - Add plugin definition like this:
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-antrun-plugin</artifactId>
    <version>1.8</version>
    <executions>
         <execution>
            <id>my-gen-stats-task</id>
            <phase>pre-site</phase>
            <goals>
                <goal>run</goal>
            </goals>
            <configuration>
                <target>
                    <ant antfile="${basedir}/build.xml">
                        <target name="gen-stats"/>
                    </ant>
                </target>
            </configuration>
        </execution>
    </executions>
    <dependencies>
        <dependency>
            <groupId>commons-net</groupId>
            <artifactId>commons-net</artifactId>
            <version>1.4.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.ant</groupId>
            <artifactId>ant-commons-net</artifactId>
            <version>1.8.1</version>
        </dependency>
    </dependencies>
</plugin>

2 - Execute your defined maven phase:
mvn pre-site

You can play with SITE lifecycle... Try this example and see how if you run 'mvn pre-site' only your ant tasks defined in 'pre-site' phase are executed. Try running 'mvn site' and see how 'pre-site' and 'site' tasks are executed:
Eg.
<build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-antrun-plugin</artifactId>
                <version>1.8</version>
                <executions>
                    <execution>
                        <id>my-pre-site</id>
                        <phase>pre-site</phase>
                        <goals>
                            <goal>run</goal>
                        </goals>
                        <configuration>
                            <tasks>
                                <echo>PRE-SITE PHASE!!!</echo>
                            </tasks>
                        </configuration>
                    </execution>
                    <execution>
                        <id>my-site</id>
                        <phase>site</phase>
                        <goals>
                            <goal>run</goal>
                        </goals>
                        <configuration>
                            <tasks>
                                <echo>SITE PHASE!!!</echo>
                            </tasks>
                        </configuration>
                    </execution>
                    <execution>
                        <id>my-post-site</id>
                        <phase>post-site</phase>
                        <goals>
                            <goal>run</goal>
                        </goals>
                        <configuration>
                            <tasks>
                                <echo>POST-SITE PHASE!!!</echo>
                            </tasks>
                        </configuration>
                    </execution>
                    <execution>
                        <id>my-site-deploy</id>
                        <phase>site-deploy</phase>
                        <goals>
                            <goal>run</goal>
                        </goals>
                        <configuration>
                            <tasks>
                                <echo>SITE DEPLOY PHASE!!!</echo>
                            </tasks>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
</build>


text:
Q: How to expire a session when the system sits idle in asp.net mvc3 How can i expire a session when the system sits idle for some time. After completing that time  it should be redirected to login page. I need to do this controller side. I am using asp.net mvc3 application.

A: The session will expire on the server when it times out.
If you want the browser to redirect at the same time you'd have to have a counter on the client, in JavaScript, which on 0 would do a redirect to your login page.
The controller cannot force the redirect of a browser without some action from the client.  You could also look at having some kind of persistant connection like SignalR but that might be more than you need.
Another solution would be to have a refresh header like in this answer
ASP.NET Push Redirect on Session Timeout


text:
Q: Open source+free+webbased pdf viewer I am looking for a PDF viewer which must have the following features

*

*Open source

*Free

*Web Based

*PHP/MySQL web-application supportive.

*caching facility

I have already seen flexpaper, do-pdf, sumatra pdf and many others but those doesn't fulfill my above criteria

A: So I guess you want to show your PDF's stored on your file system without using the user's default PDF viewer? Just open it with a php viewer class (e.g. http://www.phpclasses.org/package/6464-PHP-Alter-a-PDF-document-to-make-it-print-when-opened.html). It complies with 1,2,3 and 4. No.5 is up to your programming.


text:
Q: Replace primary key created by devise with my own created attribute I am new to rails. I am creating an application using devise gem. I made user model using gem and views and controller everything.
But i faced an issue. I create an extra field in user model name User_ID and i want to make it primary key. But devise already created one in postgres database so i am enable to create it.
Please, can someone help me in this how to make my extra field primary key instead of the one devise created.
Please help me in this.

A: You may want to try this In your migration file
class AddUserIdToUsers < ActiveRecordMigration[5.0]
def change add_column users,
user_id, integer
end
end

And then in your model
class User < ActiveRecordBase
self.primary_key = "user_id"
end


text:
Q: How do prevent page reload/refresh from submitting ajax called form and get the texts and uploaded file/image? I want to call forms and upload image with some texts. But i dont want submitting refresh the page. How can i do that? Thank you very much...

When i click to Bring Form button a form comes and when i clicked to submit button page refreshing and form disapears. Like this...

Form disapears. I dont want this. How to do that? Here codes...
index.html
<!DOCTYPE html>

<title>TEXT & FILE UPS</title>

    <button onclick="bring_form();" >Bring Form</button>

custom.js
$(document).ready(function () {

$("#form_1_0").on('submit',(function(e){
    e.preventDefault();

    var formData = new FormData(this);

    var action = "test";

    formData.append('action', action);

    $.ajax({
        url: "actions.php",
        type: 'POST',
        data: formData,
        async: false,
        success: function (data) {
            console.log(data);
            alert(data);
        },
        cache: false,
        contentType: false,
        processData: false
    });

    return false;
}));

});

function bring_form(){
var action = "bring_form";
$.ajax({
    type: "POST",
    url: "actions.php",
    beforeSend: function () {
    },
    data: {action: action},
    success: function(msg)
    {
        var msg = msg.trim();

        $("#form_field").html(msg);

    }
});
}

actions.php
<?php

if(!empty($_POST)){

    $action = $_POST["action"];

    if($action == "bring_form"){

        echo '<form id="form_1_0" method="post" enctype="multipart/form-data">
                <input type="text" name="txt_1" value="Bob" />
                <input type="text" name="txt_2" value="James" />
                <input type="text" name="txt_3" value="Smith" />
                <input name="image" type="file" />
                <button >Submit</button>
            </form>';

    }elseif($action == "test"){

        print_r($_POST);
        print_r($_FILES);

    }

}

?>

A: You need to delegate the submit handler to an element that actually exists at the time you call it since the form doesn't exist
Try changing:
$("#form_1_0").on('submit',(function(e){

To
$(document).on('submit',"#form_1_0",function(e){


text:
Q: Import CSV file/Transform data with compound values in a cell Is there a way to import a csv file or transform a table with delimited compound values?
Example:
CSV file has:
| years | model |
| -------- | -------------- |
| 2019,2020,2021    | ABC            |
Database should end up like:
| year | model |
| -------- | -------------- |
| 2019    | ABC            |
| 2020   | ABC            |
| 2021   | ABC            |
I am using HeidiSQL as my database GUI, so if it works with that, great! Otherwise I can run it through the command line if necessary.

A: I found this answer that uses a query to transform the data as @cboden and @P.Salmon mentioned: https://stackoverflow.com/a/5493616/12197178
With some modifications I got it to work.
WITH tmp(id, make, DataItem, years) AS
(
SELECT
    id,
    make,
    LEFT(years, CHARINDEX(';', years + ';') - 1),
    STUFF(years, 1, CHARINDEX(';', years + ';'), '')
FROM Testdata
UNION all

SELECT
    id,
    make,
    LEFT(years, CHARINDEX(';', years + ';') - 1),
    STUFF(years, 1, CHARINDEX(';', years + ';'), '')
FROM tmp
WHERE
    years > ''
)
SELECT
    id,
    DataItem,
    make
FROM tmp
ORDER BY id;
-- OPTION (maxrecursion 0)
-- normally recursion is limited to 100. If you know you have very long
-- strings, uncomment the option


text:
Q: Add JavaScript object to an existing JavaScript object in for loop I am trying to append a JavaScript object to an existing JavaScript object in the loop.
var object1 = { key1: true, header: 'Title A', Size: 100 };
$.each(elements, function (i, item) {
  let headerDisplay = '';
  headerDisplay = this.title;
  var row = { key1: true, header: '' + headerDisplay + '', Size: 100 };
  Object.assign(object1, row);
});

I have tried with Object.assign(), but it is giving only the last object.
Expecting output array similar to
var finalObject = [
  { key1: true, header: 'Title A', Size: 100 },
  { key1: true, header: 'Title1', Size: 100 },
  { key1: true, header: 'Title2', Size: 100 },
  ...
];

Please let me know how can we add objects to an existing one in loop

A: since you are already using jQuery why not try the $.extend() functionality? it should look something like this:

 var object1 = { "key1": true, "header": "Title A", "Size": 100};
$.each(elements, function (i, item) {
    let headerDisplay = '';
    headerDisplay =  this.title;
    var row = { "key1": true, "header": ""+headerDisplay+"", "Size": 100};
    $.extend(object1, row)
  });

keep in mind that this method will modify the first object1.
If that is not the intended behavior you could pass an empty object as the first argument of the function and pass the result to another variable like this:

const newObject = $.extend({}, object1, row)

Not sure what you are trying to do but perhaps there are better alternatives to that. Trying to keep a collection of your objects in an array may be another feasible solution. Good luck!!

A: please try it...:

 var object1 = { "key1": true, "header": "Title A", "Size": 100};
 var res = [object1];
$.each(elements, function (i, item) {
    let headerDisplay = '';
    headerDisplay =  this.title;
    var row = { "key1": true, "header": ""+headerDisplay+"", "Size": 100};
    res.push(row);
  });

now you have res as finalObj.


text:
Q: Android: is it possible to fire/emulate D-Pad KeyEvent? I have a game for Android that uses hardware keys (D-pad). There are lots of lines of code in my onKeyDown and onKeyUp callbacks throughout the program.
Now I'm trying to add support for a bluetooth gamepad, which generates its own events when various keys/sticks/triggers are pressed. And I would like to "mirror" these events from the gamepad as events from the D-pad, to use the existing onKeyDown and onKeyUp callbacks.
In other words I want to generate/emulate pressing of D-pad keys programmatically. Is it possible?

A: Try this.
Use these:
int KEYCODE_DPAD_DOWN   Key code constant: Directional Pad Down key.
int KEYCODE_DPAD_LEFT   Key code constant: Directional Pad Left key.
int KEYCODE_DPAD_RIGHT  Key code constant: Directional Pad Right key.
int KEYCODE_DPAD_UP     Key code constant: Directional Pad Up key.

Check out the official doc


text:
Q: Map database params field values to custom names I am trying to handle an array of errors on the front end side and display them on the page. I am getting the fields that user has entered from the backend and trying to map them out. However, backend params are being returned in camelcase. Please see below:

I want to render:
The input field(s) for email, favorite sport, gpa score are unacceptable
But I am seeing
The input field(s) for email, favoriteSport, gpaScore are unacceptable
Is there any way I can map the name of the params to a custom name?
Here is my code:
Array.isArray(errors) ? `The input fields for ${errors.map(item => item.param)} are unacceptable`

Any way i could map the param names to my own liking?

A: const mapper = (item) => {
  return {
   gpaScore: 'GPA Score',
   favoriteSport: 'Favorite Sport',
  }[item.param] || 'Unknown property'
}

return `The input fields for ${errors.map(item => mapper(item)).join(', ')} are unacceptable`

A: This is where you could use something like react-intl to format messages but in general, you'd need something that turns programmatic keys into user-friendly messages
const t = {
  email: "email",
  favoriteSport: "favourite sport",
  gpaScore: "GPA score"
}

const fields = errors.map(({ param }) => t[param] ?? param)

const message = `The input fields for ${fields.join(", ")} are unacceptable`


text:
Q: How to perform untarring in parallel (pyspark) I have a 13 GB bzipped tar file in pyspark.
I can read the bzipped file into an RDD and Spark will split the bzipped file into partitions because bzip2 is a splittable file format. I can even then see the RDD contains 400 partitions. Each partition contains the uncompressed bzipped data (part of the tar file).
However considering that tar files are not splittable (from my understanding) I cant perform an untar operation on each of these 400 partitions
# The following RDD contains 400 partitions

bzipped_rdd = sc.textFile("s3a://some_bucket/file.tar.bz2")

bzipped_rdd.saveAsTextFile("data_directory")

# I would like to now perform an untar operation on each partition

What is the best way to do this?


text:
Q: How to insert html tag to selected text - summernote I'm setting up textarea with summernote, and want to create custom button that can insert code html tag
I try create simple custom button from summernote documentation
this my code
var CodeButton = function (context) {
        var ui = $.summernote.ui;

        // create button
        var button = ui.button({
            contents: ' Code',
            tooltip: 'Code',
            click: function (value) {
                var range = $('#textarea').summernote('createRange')
                // invoke insertText method with 'hello' on editor module.
                context.invoke('editor.insertHtml', ''+range.toString()+'');
            }
        });

        return button.render(); // return button as jquery object
    }

let say I want to change
test
 to be
test
, but code above doesn't change anything

A: click: function (value) {
var text = context.invoke('editor.getSelectedText');
// You can initialize node with class instead of calling addClass.
var $node = $('
'+text+'
');

// http://summernote.org/deep-dive/#insertnode
context.invoke('editor.insertNode', $node[0]);
}


text:
Q: Regression, Independence & Normality of x and y variables (not residuals) I am trying to predict productivity of inbound process of a warehouse using
y-value = productivity in terms of pcs/hr
x-value = # pcs and ratio pcs/SKU. (where SKU = stock keeping unit)
Basic hypothesis -->
(1) the more work there are (busier people are), the more they rush and the better the productivity.
(2) In addition, since people handle 1 SKU only once, the more pcs/SKU, means the less time you have to spend per piece (ie if it takes 1 min to input information for 1 SKU, you could do 1 pcs in one minute at 1pcs/SKU or 100 pcs in one minute at 100pcs/SKU).
Questions -->
(1) does y variables and both of the x variables have to be normally distributed? I understands the residuals need to be normally distribution, but does the input and output itself also have to be normally distributed?
(2) The number of pcs is contained in both x1 and x2, does this pose a problem. I believe this will create dependency problem?
Thanks a lot for your help.

A: For question (1), it is as you said. The residuals do need to be normally distributed, but the X and Y need not be.
For question (2), it is alright to use the fraction. The dependency problem arises when there is a linear relationship between #PC and #PC/SKU, but here there should not be one. SKU is not constant (if it is this variable is not informative), so a simple linear relationship between the two variables you want to include in your regression probably will not exist unless SKU itself is correlated with #pc.

A: How much of a correlation do there need to be for it to become a problem? cov(piece,piece/sku) > absolute value(0.5) ?
From my understanding the number of SKU $\le$ number of pieces.
So if the number of pieces increases the number of SKU will certainly increase. Although it is not true that you will have higher pcs/SKU simply because the number of pieces is large.


text:
Q: Twitter boostrap 3 margin grid issues I am beginner in twitter bootstrap My question is simple can i use my custom CSS  in bootstrap also, is it a correct way or i have to use only bootstrap classes Like i am facing margin padding issues
For Example
i used the .container-fluid class now i want to use .wrap class of mine
.wrap{
   width:1249px;
   margin:0px auto;
}
then i used the .row and .col in it suppose the first col is col-sm-4 how and in .col-sm-4 i use h1 heading it need margin from left
the actual question is, Is it a correct way of using own classes when we need?
is it make any difference? the responsiveness will remain the same? Thanks in advance

A: Yes you can use your own class also along with bootstrap 3.However it might affect the responsiveness of your page, since you are fixing the width. So, if the page becomes less than 1249px, it will show a horizontal scroll.