text:
Q: Datetime may not intersect other datetime for that user's activity Might be a somewhat specific situation. And I kinda know how to do it in PHP/MySQL. But I was wondering if there was a faster way to do the following scenario:
A user has activities with a start- and end_date. (The activity starts at 12-10-2013 12:00:00 and ends at 12-10-2013 12:15:00  for example.)
Whenever the user creates a new activity. I want to check all the activities the user is part of(user has_many: activities) and see if none of the dates intersect with the date given for the new activity.
Since I'm pretty new to Rails I really don't know where to start searching for date comparisons and all...
Thanks in advance

A: An overlap is defined as another activity for which the end date is greater than or equal to the new activity's start date, and for which the start date is less than or equal to the new activity's end date.
Since you only want to detect whether such a record already exists, an appropriate test would be:
if Activity.where("starts_at <= ?" , new_activity_end_date  ).
            where("ends_at   >= ?" , new_activity_start_date).
            exists?

A: You can use regular comparators for date/times in Ruby (ie: >, < and ==).
Something like the following should do what you are looking for:
if current_user.activities.where("(starts_at <= ? AND ends_at >= ?) OR (starts_at >= ? AND starts_at <= ?)", start_datetime, start_datetime, start_datetime, end_datetime).count
  # There exist activities that fall between start_datetime and end_datetime
else
  # There exist no such activities
end

(starts_at <= start_datetime AND ends_at >= start_datetime) checks whether an event starts before and ends after start_datetime.
(starts_at >= start_datetime AND starts_at <= end_datetime) checks whether an event starts between start_datetime and end_datetime.

A: We must check that all this three kinds of intersection do not happen:

*

*our activity must not happen within another activity

*our activity must not start before another ends

*our activity must not ends after another starts

We can do that using something like this:
class Activity < ActiveRecord::Base

  validate :must_not_be_intersected

  def intersected?
    params = {
      :start => start_date,
      :end => end_date
    }

    Activity::where('start_date <= :start AND end_date >= :end', params)
      .where('(start_date >= :start AND start_date <= :end) OR (end_date >= :start AND end_date <= :end)', params)
      .exists?
  end

private

  def must_not_be_intersected
    errors.add :base, 'Other task running on the same period' if intersected?
  end

end


text:
Q: Node.js & MongoDB: why the db object is undefined? I'm using Node.js, Hapi and MongoDB Native Driver (node-mongodb-native)
I want to access the db object returned by the get() method from db.js in my handler in server.js.
db.js
'use strict'

const MongoClient = require('mongodb').MongoClient

let _db

function connect (url) {
  return MongoClient.connect(url, { server: { poolSize: 5 } })
  .then((db) => {
    _db = db
    console.log('Connected to MongoDB:', db.s.databaseName)
  })
  .catch((e) => {
    throw e
  })
}

function get () {
  return _db
}

function close () {
  if (_db) {
    console.log('Closing MongoDB connection.')
    _db.close()
  }
}

module.exports = {
  connect,
  close,
  get
}

server.js
'use strict'

const Hapi = require('hapi')

const Db = require('./db')
const _db = Db.get()

const server = new Hapi.Server()

server.connection({
  host: 'localhost',
  port: 8080
})

server.route({
  method: 'GET',
  path: '/',
  handler: (req, rep) => {
    console.log(_db) // _db is undefined
  }
})

Db.connect('mongodb://localhost:27017/test')
.then(() => {
  server.start((err) => {
    if (err) {
      throw err
    }
    console.log(`Server running at: ${server.info.uri}`)
  })
})
.catch((e) => {
  console.error(`${e.name}: ${e.message}`)
  return
})

The problem is that Db.get() return undefined.
Now consider this code instead:
const Db = require('./db')

const server = new Hapi.Server()

...

server.route({
  method: 'GET',
  path: '/',
  handler: (req, rep) => {
    const _db = Db.get()
    console.log(_db) // the _db object exists
  }
})

I don't understand why the first code return undefined as the get() method is called and should store the instance into _db thus accessible in the handler function.

A: The value of _db is assigned in a function passed to then of a Promise, the execution of this part is deferred to a point in time until the Promise has been resolved. The server.route is synchronous. It means it will be very likely executed before the Promise has been resolved.
To make it work, wait until the Promise has been resolved:
'use strict'

const MongoClient = require('mongodb').MongoClient

let _db

async function connect (url) {
  try {
    return await MongoClient.connect(url, { server: { poolSize: 5 } })
  } catch (error) {
    throw new Error('Could not connect to Mongo instance');
  }
}

async function get () {
  return _db ? _db : await connect();
}

async function close () {
  if (_db) {
    console.log('Closing MongoDB connection.')
    _db.close()
  }
}

module.exports = {
  connect,
  close,
  get
}

and then
'use strict'

const Hapi = require('hapi')

const Db = require('./db')
const _db = await Db.get()

const server = new Hapi.Server()

server.connection({
  host: 'localhost',
  port: 8080
})

server.route({
  method: 'GET',
  path: '/',
  handler: async (req, rep) => {
    const _db = await Db.get();
    console.log(_db) // _db will be guaranteed to be a valid object, otherwise an error will be thrown
  }
})

Db.connect('mongodb://localhost:27017/test')
.then(() => {
  server.start((err) => {
    if (err) {
      throw err
    }
    console.log(`Server running at: ${server.info.uri}`)
  })
})
.catch((e) => {
  console.error(`${e.name}: ${e.message}`)
  return
})

Read more about async/await there and there.

redpajama_set_name: RedPajamaStackExchange


text:
Q: kubespray dashboard warning forbidden popups I am trying to set up a new kubernetes cluster on one machine with kubespray (commit 7e84de2ae116f624b570eadc28022e924bd273bc).
After running the playbook (on a fresh ubuntu 16.04), I open the dashboard and see those warning popups:
- configmaps is forbidden: User "system:serviceaccount:default:default" cannot list configmaps in the namespace "default"
- persistentvolumeclaims is forbidden: User "system:serviceaccount:default:default" cannot list persistentvolumeclaims in the namespace "default"
- secrets is forbidden: User "system:serviceaccount:default:default" cannot list secrets in the namespace "default"
- services is forbidden: User "system:serviceaccount:default:default" cannot list services in the namespace "default"
- ingresses.extensions is forbidden: User "system:serviceaccount:default:default" cannot list ingresses.extensions in the namespace "default"
- daemonsets.apps is forbidden: User "system:serviceaccount:default:default" cannot list daemonsets.apps in the namespace "default"
- pods is forbidden: User "system:serviceaccount:default:default" cannot list pods in the namespace "default"
- events is forbidden: User "system:serviceaccount:default:default" cannot list events in the namespace "default"
- deployments.apps is forbidden: User "system:serviceaccount:default:default" cannot list deployments.apps in the namespace "default"
- replicasets.apps is forbidden: User "system:serviceaccount:default:default" cannot list replicasets.apps in the namespace "default"
- jobs.batch is forbidden: User "system:serviceaccount:default:default" cannot list jobs.batch in the namespace "default"
- cronjobs.batch is forbidden: User "system:serviceaccount:default:default" cannot list cronjobs.batch in the namespace "default"
- replicationcontrollers is forbidden: User "system:serviceaccount:default:default" cannot list replicationcontrollers in the namespace "default"
- statefulsets.apps is forbidden: User "system:serviceaccount:default:default" cannot list statefulsets.apps in the namespace "default"

The kubectl commands seem fine (proxy works, listing pods etc. return no error, /api is reachable), however, the dashboard seem unable to fetch any useful information. How should I go about debugging that?

A: kubectl create clusterrolebinding default-admin --clusterrole cluster-admin --serviceaccount=default:default

seems to do the trick - I'd welcome an explanation though.
(Is it an oversight in kubespray? I need to set up a variable there? Is it related to RBAC?)

A: The dashboard pod is running with default service account , and that account by default dont have permissions, you can see the token of the default service account inside th dashboard pod:
kubectl exec -it <dashboard-pod> bash
ls -al /var/run/secrets/kubernetes.io/serviceaccount

The command you run in your answer , sets the required permisions for the default service account used by dashboard pod.


text:
Q: mosfet switch power (N or P channel) I think this a simple question but I can't find the answer ! I try but ... that don't came out !
I have an USB connector. In one case, I want to powering myself with my batterie (if I use it with a device and I'm the host). In the other case, I will have Vbus powering by an external host (so I want to cut the power by the battery) -> So the schematic case
I don't want to use a power switch CI.
I found a solution with a simple diode but I lose some voltage power ... I wanted to use a Mosfet for switching power. I can command this mosfet with an MCU. So when I detect vbus power 5V, I cut the battery power ...
How i can do this with a mosfet ? (P or N ...) ?

simulate this circuit – Schematic created using CircuitLab
Thanks you very much

A: You can eliminate the diode voltage drop using a P-channel MOSFET, but there are some subtleties that could catch you out:-

*

*The MOSFET has an internal 'body' diode connected between the Source and Drain. This can perform the same function as your diode, but to get the diode pointing in the right direction the Drain/Source polarity must be reversed.

*If the MCU only outputs 3.3V then the MOSFET's Gate voltage must be raised up to meet the Source voltage. This level shifting can be done with another FET or bipolar transistor, which can also conveniently invert the signal so the FET turns on when the MCU's digital output is high.
The circuit looks like this:-

simulate this circuit – Schematic created using CircuitLab
So far so good. However this scheme has a problem - if external USB power is applied while the FET is turned on then current will flow from the USB port into the battery until the MCU switches the FET off. Also the difference between internal and external USB power is then quite small (~4.5V vs 5V) so the MCU might have trouble determining when external USB power is present.
If you add a booster to get 5V from the battery then the voltage difference could be so small that it is impossible to tell whether external power is present. One solution might be to feed both battery and USB power through the booster, with diodes in series with each source to isolate them from each other. You can then measure USB input voltage without interference from the battery, while the booster produces a full +5V from both power sources.

simulate this circuit
In this scheme you would have one USB port to get power from as a device, and another to put power onto as a host. If you want to do both jobs with a single USB port then you are creating something similar to USB On-The-Go, so it might be easier to use a dedicated OTG controller chip.


text:
Q: Update MySQL column based on multiple values How can I modify this statement to set the region value where there are multiple values in the location_town column?
UPDATE `wp_em_locations` SET `location_region` = 'The-Valley'
WHERE `location_town` = 'Bond'

IE: Bond is not the only town, I have many town names but all should be used to set location_region = The-Valley.
How do I accomplish this using one statement? Or do i need to run the same statement for each town name?

A: You can use either an OR or IN statement
WHERE `location_town` IN ('Bond', 'OtherTown')

or (no pun intended)
WHERE `location_town` = 'Bond' OR `location_town` = 'OtherTown'

A: Is the statement more complex than this? if you're trying to set every row to have location_region set to 'The-Valley' why use the where clause, which only serves to limit the scope of the update query?
Would this do what you're looking for, are am I misunderstanding?
UPDATE `wp_em_locations` SET `location_region` = 'The-Valley' WHERE 1;


text:
Q: how to set correct margin for nexus5 and nexus 5x I am developing the app and now I have very big problem.
As we know nexus 5 and nexus 5x using the same resource directory (xxhdpi) my view getting broken because of some margins.
i.e I have to put 40dp for nexus 5 and 65dp for nexus5x.
So what should do here to make it works in 2 devices?
Is there a way to set layout dimensions correct for both devices.

A: You have to use Android Percent Support Lib which divide your layout View into Percentage....
It is easy to set Views using Percentage which is useful for all device and UI is same in all device .....
Use below link ....
Android Percent Support Lib
I think it solve you problem ....
enjoy coding ....


text:
Q: In Steam, why are some DLC shown as separate entries and some are not? Why is there a difference on how DLC content is shown on Steam? While some DLC is only shown under a "DLC" tab after clicking on "properties" (1), other DLC are shown separately as new game entries (2)?
(1) Example of first case:

(2) Example of second case:

A: Missing Link is weird for DLC, and it kind of rides the line between "standalone expansion" and DLC.  It isn't accessed from Deus Ex: Human Revolution (like the other items you mention), you have to load it separately.  There's no way to start Missing Link from within Human Revolution, and vice versa.
Usually this means that you don't have to own the base game to play ("standalone expansion") but in this case, you do.
In practical terms, you can install Human Revolution without Missing Link (and I believe vice versa).  Most DLC on Steam is not like this - once you own the DLC, you get no choice as to whether or not it is installed with the base game.


text:
Q: Android: Setter in Fragment & get String in RecyclerViewAdapter I'm getting a String from a my MySQL database which works fine. After I got the data I was trying to set the data in a Setter and fill a get the data in my RecyclerAdapter to output it as a list but it wont work.
The only thing that works is getting data from my db and set the setter after that it wont work dont know why.
public ArrayList<NewsData> parseJSON(String result) {
    ArrayList<NewsData> newsData = new ArrayList<NewsData>();
    try {
        JSONArray jArray = new JSONArray(result);
        for (int i = 0; i < jArray.length(); i++) {
            JSONObject json_data = jArray.getJSONObject(i);
            NewsData nd = new NewsData();
            nd.setTitle(json_data.getString("title"));

            Toast.makeText(getActivity(), nd.getTitle(), Toast.LENGTH_SHORT).show();
            newsData.add(nd);
        }
    } catch (JSONException e) {
        Log.e("log_tag", "Error parsing data " + e.toString());
    }

    return newsData;
}

Here I am getting the Data of my database and test if it works by making the data as a Toast and that works fine.
public class HomeRecyclerAdapter extends RecyclerView.Adapter<HomeRecyclerAdapter.ViewHolder> {

    private Context context;

    class ViewHolder extends RecyclerView.ViewHolder {

        public TextView itemTitle;
        public TextView holeText;

        public ViewHolder(final View itemView) {
            super(itemView);
            itemTitle = (TextView) itemView.findViewById(R.id.title_cView);
            holeText = (TextView) itemView.findViewById(R.id.text);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    context = itemView.getContext();
                }
            });
        }
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View v = LayoutInflater.from(viewGroup.getContext())
                .inflate(R.layout.layout_cardviewhome, viewGroup, false);
        ViewHolder viewHolder = new ViewHolder(v);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
    }

    @Override
    public int getItemCount() {
        return 2;
    }
}

This is my adapter I already tried some things but they won't work maybe one of you guys could help me here. So I wanna add the data of the MySQL to the RecyclerView. (The data which i got in "parseJSON")
My Adapter is nearly Empty as the moment as I delete everything that was wrong and dont work
I hope you can understand my english it's not very good. But all in all thanks for trying to help :-)

A: I guess you should pass the newsData as a parameter to the adapter constructor. Inside onBindViewHolder, you could set the TextViews information by getting from the item. Example:
    public class HomeRecyclerAdapter extends RecyclerView.Adapter<HomeRecyclerAdapter.ViewHolder> {

    private Context context;
    private ArrayList<NewsData> newsData;

    public HomeRecyclerAdapter (ArrayList<NewsData> newsData, Context context) {
       this.newsData = newsData;
       this.context = context;
    }

    class ViewHolder extends RecyclerView.ViewHolder {

        public TextView itemTitle;
        public TextView holeText;

        public ViewHolder(final View itemView) {
            super(itemView);
            itemTitle = (TextView) itemView.findViewById(R.id.title_cView);
            holeText = (TextView) itemView.findViewById(R.id.text);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    context = itemView.getContext();
                }
            });
        }
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View v = LayoutInflater.from(viewGroup.getContext())
                .inflate(R.layout.layout_cardviewhome, viewGroup, false);
        ViewHolder viewHolder = new ViewHolder(v);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        NewsData thisNewsData = newsData.get(position);

        holder.itemTitle.setText(thisNewsData.getItemTitle());
        holder.holeText.setText(thisNewsData.getHoleText());
    }

    @Override
    public int getItemCount() {
        return newsDataArray.size();
    }
}

If something is off, please adjust accordingly and let me know if this helps.

A: Pass the initial list to the adapter:
private ArrayList<NewsData> newsData;

public HomeRecyclerAdapter (ArrayList<NewsData> newsData) {
   this.newsData = newsData;
}

Fetch new data from your database in an AsyncTask in doInBackground(). There you can parse the data and create your objects. In onPostExceute() you can modify the data of your adapter. For example you add this to your adapter and call it in onPostExceute():
public void add(NewsData data) {
  this.newsData.add(data);
  notifyDataSetChanged();
}


text:
Q: Jersey Rest Asynchronous response I am trying to get the response back immediately from the method below and proceed with rest of the process. But I don't see my return value "TestAync" anytime. Can you please suggest on how to retrieve (client code) response from the below call.
Here is the client call I am making, appreciate your help.
Future response = ClientBuilder.newClient().target("http://localhost:8080/testasync/test/async/test5").request().async().get();
@GET
@Path("async/{echo}")
public String asyncEcho(@PathParam("echo") final String echo, @Suspended final AsyncResponse ar) {
    TASK_EXECUTOR.submit(new Runnable() {

        @Override
        public void run() {
            try {
                Thread.sleep(SLEEP_TIME_IN_MILLIS);
            } catch (InterruptedException ex) {
                ar.cancel();
            }
            ar.resume(echo);
        }
    });
    return "TestAysnc";
}

A: In the async case the return value (TestAsync) is ignored because JAX-RS runtime (e.g. Jersey) expects that the entity that is sent back to the client would be provided via AsyncResponse#resume(Object) call.
In your particular case test5 would be returned to the client since you're resuming asynchronous response with this string object.
For more info take a look at Asynchronous Server API in Jersey User Guide or read the JAX-RS 2.0 Specification.


text:
Q: How can I add custom view to my custom keyboard in android? How can I add custom view as in image, in my android keyboard?
I need row to have different background color, label and buttons.

A: In your InputMethodService, you define a function called onCreateInputView. Have it return whatever view you want.

A: Just add your view as a footer view. So whenever android keyboard visible your view will looks on top of keyboard.


text:
Q: Irrationality proof by rational approximations Assume we have a sequence of rational numbers $\left(\frac{p_n}{q_n}\right),$ where $\gcd(p_n,q_n)=1, \ \forall n \in \mathbb N$.
We know that $$\lim_{n\to\infty} \left(\frac{p_n}{q_n}\right)= x$$ and $$\lim_{n\to\infty} p_n = \lim_{n\to\infty} q_n = \infty.$$
Assume $x = \frac{M}{N},$ where $\gcd(M,N)=1$. Now, there exists such $k \in \mathbb N$ that $p_n>M$ and $q_n > N, \ \forall n\ge k$.
Does this prove that x is irrational?

A: If $x = M/N$ with positive integers $M,N,m,n$, either $|x - m/n| = 0$ or
$|x - m/n| \ge \dfrac{1}{Nn}$.  On the other hand, if $x$ is irrational there are
infinitely many pairs $(m,n)$ with $0 < |x - m/n| < \dfrac{1}{n^2}$.  In this sense,
irrational numbers can be very well approximated by rationals, but rational
numbers can't be very well approximated by other rationals.

A: Given $x = M/N$ as you say, good approximations parametrized by $n \in \mathbb N$ include $$ \frac{nM + 1}{nN + 1}  $$
A (real) number is irrational if and only if the simple continued fraction for it is infinite. If the number is a "quadratic irrational" $(A + \sqrt B)/ C$ For integers $A,B,C,$ with $C \neq 0$ and $B$ positive but not a square, then the s.c.f. is eventually periodic and infinite.
http://en.wikipedia.org/wiki/Continued_fraction


text:
Q: How to select all list elements based on their total number in CSS without JS or flexbox? Say I have a list with n items and I want to make the width of the first list item "rowspan=2". The width will change depending on the number of n, but in the example below:

SPAN 2

Row 2-3

Row 2-4

Row 2-5

Row 2-6

This would change this:
|-----------------------------------|
|  1  |  2  |  3  |  4  |  5  |  6  |
|-----------------------------------|

to this:
|-----------------------------------|
|  1  |   SPAN2   |  4  |  5  |  6  |
|-----------------------------------|

my original six items are now reduced to five (four regular items, one item spanning two). So I'm writing my selector like this:
ul > li:nth-child(-n+5).ui-grid-span-2 {
  width: 33.33%;
}

but it does not work. Instead this rule applies:
ul > li:nth-child(-n+2).ui-grid-span-2 {
    width: 66.66%;
}

and I don't understand why.
Question:
How do I address "all childs of five childs, the one with class: ui-grid-span-2" directly. This means, instead of all cells being 1/6 width = 16.66%, the one with the class assigned should be 2/6 = 33.33%.
EDIT...:
This is not a dupe of this questions. The solution of Vera allows to set the width based on total number of cells either by siblings (does not apply here, because if the 3rd cell was a rowspan=2, I could only set the width of the following cells, not the previous ones). The original solution requires a line of code for every cell (if have n=10 max) and then doing this for every *-span class = a giant pile of CSS.
ANSWER:
Found out why. Selectors are "greedy" = "take first seven" will include/override "take first six". Solution below.

A: Flexbox seems to be a solution here although the actual question seems unclear.

ul {
  margin: 0;
  list-style: none;
  padding: 0;
  display: flex
}
li {
  border: 1px solid grey;
  flex-grow: 1;
}
.ui-grid-span-2 {
  flex-grow: 2;
}

SPAN 2

Row 2-3

Row 2-4

Row 2-5

Row 2-6

A:

* {
    margin: 0;
    padding: 0;
}
ul {
    list-style: none;
}
li {
    text-align: center;
    display: inline-block;
    width: 16.6%;
    background-color: red;
}
li:last-child, li:first-child, li:nth-child(3) {
    background-color: brown;
}
.ui-grid-span-2 {
    width: 32.2%;
}

SPAN 2

    Row 2-3

    Row 2-4

    Row 2-5

    Row 2-6

I think you CAN'T do what you want for a dinamic number of
's without JS or flex

A: Ok, after some more meddling my original idea works. This means if you have the following HTML:

SPAN 2

Row 1-3

Row 1-4

Row 1-5

Row 1-6

the width of the list elements can be set as I intended:
ul > li:nth-child(-n+4).ui-grid-span-2 {
  width: 33.33%;
}
ul > li:nth-child(-n+3).ui-grid-span-3 {
  width: 50%;
}
ul > li:nth-child(-n+2).ui-grid-span-4 {
  width: 66.66%;
}
ul > li:nth-child(-n+1).ui-grid-span-5 {
  width: 83.33%;
}

Note that by spanning multiple cells, the total number of cells change, too, so the pseudo-selector must be adjusted depending on cells spanned. To make it work with multiple ranges of cells (not always 6 cells as above) it is also required to add a class on the list element to note the number of cells in a row. Otherwise larger selector (take first 8 items) will overwrite/encapsulate smaller ones (take first 7 items).
Still not happy with it and only supporting a single rowspan per row, but... it works and it's not using any of the above proposed solutions (~ siblings, x*y cells * n rowspans rules, flexbox or tables). Keep in mind, the regular cell width declarations need to be amended, too, as a row using rowspan will have less number of cells but require the original intended number of cells' width.
Final CSS for up to 8 cell grids (I have not combined declarations for sake of comprehensability).
Note:
- section ROWSPAN is the relevant section
 - before I ensure cell width is set based on intended not actual number of cells
- selectors are cutoff for relevance.
/* base width */
ul > li {
  width: auto;
}

/* "cell width" */
ul > li:first-child:nth-last-child(1) {
  width: 100%;
}
ul > li:first-child:nth-last-child(2),
ul > li:first-child:nth-last-child(2) ~ li {
  width: 50%;
}
ul.ui-grid-column-3 > li:first-child:nth-last-child(n),
ul.ui-grid-column-3 > li:first-child:nth-last-child(n) ~ li  {
  width: 33.3333%;
}
ul.ui-grid-column-4 > li:first-child:nth-last-child(n),
ul.ui-grid-column-4 > li:first-child:nth-last-child(n) ~ li {
  width: 25%;
}
ul.ui-grid-column-5 > li:first-child:nth-last-child(n),
ul.ui-grid-column-5 > li:first-child:nth-last-child(n) ~ li {
  width: 20%;
}
ul.ui-grid-column-6 > li:first-child:nth-last-child(n),
ul.ui-grid-column-6 > li:first-child:nth-last-child(n) ~ li {
  width: 16.667%;
}
ul.ui-grid-column-7 > li:first-child:nth-last-child(n),
ul.ui-grid-column-7 > li:first-child:nth-last-child(n) ~ li {
  width: 14.285714286%;
}
ul.ui-grid-column-8 > li:first-child:nth-last-child(n),
ul.ui-grid-column-8 > li:first-child:nth-last-child(n) ~ li {
  width: 12.5%;
}

/* ROWSPAN */
/* 3 cells */
ul.ui-grid-column-3 > li:nth-child(-n+2).ui-grid-span-2 {
  width: 66.666%;
}
/* 4 cells */
ul.ui-grid-column-4 > li:nth-child(-n+3).ui-grid-span-2 {
  width: 50%;
}
ul.ui-grid-column-4 > li:nth-child(-n+2).ui-grid-span-3 {
  width: 75%;
}
/* 5 cells */
ul.ui-grid-column-5 > li:nth-child(-n+4).ui-grid-span-2 {
  width: 40%;
}
ul.ui-grid-column-5 > li:nth-child(-n+3).ui-grid-span-3 {
  width: 60%;
}
ul.ui-grid-column-5 > li:nth-child(-n+2).ui-grid-span-4 {
  width: 80%;
}
/* 6 cells */
ul.ui-grid-column-6 > li:nth-child(-n+5).ui-grid-span-2 {
  width: 33.33%;
}
ul.ui-grid-column-6 > li:nth-child(-n+4).ui-grid-span-3 {
  width: 50%;
}
ul.ui-grid-column-6 > li:nth-child(-n+4).ui-grid-span-4 {
  width: 66.66%;
}
ul.ui-grid-column-6 > li:nth-child(-n+4).ui-grid-span-5 {
  width: 83.33%;
}
/* 7 cells */
ul.ui-grid-column-7 > li:nth-child(-n+6).ui-grid-span-2 {
  width: 28.571428571%;
}
ul.ui-grid-column-7 > li:nth-child(-n+5).ui-grid-span-3 {
  width: 42.857142857%;
}
ul.ui-grid-column-7 > li:nth-child(-n+4).ui-grid-span-4 {
  width: 57.142857142%;
}
ul.ui-grid-column-7 > li:nth-child(-n+3).ui-grid-span-5 {
  width: 71.428571428%;
}
ul.ui-grid-column-7 > li:nth-child(-n+2).ui-grid-span-6 {
  width: 85.714285714%;
}

/* 8 cells */
ul.ui-grid-column-8 > li:nth-child(-n+7).ui-grid-span-2 {
  width: 25%;
}
ul.ui-grid-column-8 > li:nth-child(-n+6).ui-grid-span-3 {
  width: 37.5%;
}
ul.ui-grid-column-8 > li:nth-child(-n+5).ui-grid-span-4 {
  width: 50%;
}
ul.ui-grid-column-8 > li:nth-child(-n+4).ui-grid-span-5 {
  width: 62.5%;
}
ul.ui-grid-column-8 > li:nth-child(-n+3).ui-grid-span-6 {
  width: 75%;
}
ul.ui-grid-column-8 > li:nth-child(-n+2).ui-grid-span-7 {
  width: 87.5%;
}

/* responsive */
@media (max-width: 32em) {
ul > li,
ul[class*="ui-grid-column"] > li {
    width: 100%;
  }
}


text:
Q: VAR with different distributions: Does this model exists? I would like to know if models like the one below exist/make sense and, if so, how they are called.
\begin{equation}
X_t \sim \mathcal{Pois} ( \lambda_t )  \\
\lambda_t = \mu_1 + \alpha_1 X_{t-1} + \beta_1 \lambda_{t-1} + \gamma_1 Y_{t} + \delta_1\ Y_{t-1}\\
Y_t = \mu_2 + \alpha_2 Y_{t-1} + \beta_2 \epsilon_{t-1} + \gamma_2 X_t + \delta_2 X_{t-1} + \epsilon_{t} \\
\epsilon_t \sim \mathcal{N}(0,1)
\end{equation}
The one above is similar to a dynamic Poisson model and the one below is similar to an ARMA(1,1).
I think the structure resembles a VAR but I would like to know if it is feasible/acceptable having two different distribution (Poisson and Normal).
A possibly very naive usage would be for example the modelling of volatility ($Y$) and the number of transactions ($X$) together (to check if a high number of transactions helps in forecasting volatilities and vice versa, just to give an idea).


text:
Q: Pause execution till Chrome is done loading I'm currently in the process of developing a file which is used to fill in a form based on the data from the sheet. The issue I'm facing is that the page gets refreshed for each entered field for one section of the code. The refresh time varies based on the computer.
My current solution is to induce a wait of approximately 5-6 seconds which can be inefficient based on the terminal used. Is there a way that the execution can be paused simply till the page is done loading? Also, there are two versions of Excel that are in use, essentially 2013 and 2003. Not sure if that's relevant but I've had to sort out numerous compatibility issues.


text:
Q: Symfony Process npm install. Works in CLI doesn't work with HTTP I have stumbled upon a very weird issue and I sincerely hope that you can explain to me why.
Disclaimer: I know this is a bad idea, this isn't a real-life scenario but just a quirk I stumbled upon and I am curious to find out why this happens.
Consider this piece of code:
$process = new \Symfony\Component\Process\Process('node -v');
$process->mustRun();
echo $process->getOutput();

$process = new \Symfony\Component\Process\Process('npm install');
$process->mustRun();
echo $process->getOutput();

If I run this piece of code as: php filename.php it works as expected.
If I run this piece of code as part of a HTTP request (served by nginx), the first command returns the node version as expected while the second one raise an exception:
(1/1) ProcessFailedException
The command "npm install" failed.

Exit Code: 127(Command not found)

Working directory: /Users/mrx/Documents/www/myCoolProject/

Output:
================

Error Output:
================
env: node: No such file or directory

Same exact thing happens with yarn.
It seems like NODE sets up some settings for NPM if the CLI is detected but I cannot seem to find any literature on this.
I know it's a bit far-fetched and not exactly a PHP related issue but I am really curious for an explanation.
FAQs:

*

*NPM/YARN are correctly installed and works as expected

*Above code works as expected in the CLI of php

A: Exit 127 looks like an out-of-memory issue, npm installs costs a lot of RAM and maybe that exceeds your Nginx or Apache PHP processes limits.


text:
Q: mysql JOIN when one table has no entry I have two tables:
player with player_id and name
team with player_id and team_id
Not all players have an entry in team.
I'm trying to create a query that, given a player_id, will return the name and null if the player_id is not found in the team table.
I've tried the various JOINs but I either get null, null or the name with the first team_id found in the table.
Thanks for any help

A: Do this
SELECT p.PlayerID, t.PlayerID
FROM Player p
LEFT JOIN Team t
ON p.PlayerID = t.PlayerID

If you want null to be returned pick the t.PlayerID as p.PlayerID will not be null if it exists in Player
Your result will look like this
PlayerID   Player Name    TeamID    PlayerID
-------------------------------------------------
0001       John           NULL      NULL

As you can see it is the second PlayerID that is NULL not the first. Pick the second e.g. WHERE t.PlayerID IS NULL


text:
Q: Hadoop 2.7.2 - Error: Could not find or load main class org.apache.hadoop.hdfs.server.namenode.NameNode I am newbie and I am trying to find out a solution to this problem.
I have followed this turorial in order to setup Hadoop 2.7.2 on Ubuntu 15.10
http://idroot.net/tutorials/how-to-install-apache-hadoop-on-ubuntu-14-04/
When I launch "hdfs namenode format" I continue to receive this error
Error: Could not find or load main class org.apache.hadoop.hdfs.server.namenode.NameNode
this is the bashrc content
export JAVA_HOME=/usr/lib/jvm/java-8-oracle

export HADOOP_INSTALL=/usr/local/hadoop

export PATH=$PATH:$HADOOP_INSTALL/bin

export PATH=$PATH:$HADOOP_INSTALL/sbin

export HADOOP_MAPRED_HOME=$HADOOP_INSTALL

export HADOOP_COMMON_HOME=$HADOOP_INSTALL

export HADOOP_HDFS_HOME=$HADOOP_INSTALL

export YARN_HOME=$HADOOP_INSTALL

export HADOOP_COMMON_LIB_NATIVE_DIR=$HADOOP_INSTALL/lib/native

export HADOOP_OPTS="-Djava.library.path=$HADOOP_INSTALL/lib"

Can anyone help me to solve this (stupid I think) question?
Many thanks
Kama

A: First make sure that the directories namenode and datanode already exist in the location specified within the hdfs-site.xml file. You can use the command mkdir to create those.
Then try to format the namenode using
hdfs namenode -format

or
/usr/local/hadoop/bin/hdfs namenode -format

Please note the hyphen.

My bashrc configuration for hadoop:
#HADOOP VARIABLES START
export HADOOP_HOME=/usr/local/hadoop
export PATH=$PATH:$HADOOP_HOME/bin
export PATH=$PATH:$HADOOP_HOME/sbin
export HADOOP_MAPRED_HOME=$HADOOP_HOME
export HADOOP_COMMON_HOME=$HADOOP_HOME
export HADOOP_HDFS_HOME=$HADOOP_HOME
export YARN_HOME=$HADOOP_HOME
export HADOOP_COMMON_LIB_NATIVE_DIR=$HADOOP_HOME/lib/native
export HADOOP_OPTS="-Djava.library.path=$HADOOP_HOME/lib"
export HADOOP_CLASSPATH=${JAVA_HOME}/lib/tools.jar
#HADOOP VARIABLES END

A: Problem solved using the Ashes Script. Main difference is the usage of open jdk instead of oracle jre.
Thanks for the help!

A: I have this error too. For me, it's just because some files in /share/hadoop/yarn/ folder is missing, which was caused by an incomplete download of hadoop.tar.gz that can still be abstracted by command line. May help you, cheers.

A: One cause behind this problem might be a user-defined HDFS_DIR environment variable. This is picked up by scripts such as the following lines in libexec/hadoop-functions.sh:
HDFS_DIR=${HDFS_DIR:-"share/hadoop/hdfs"}
...
if [[ -z "${HADOOP_HDFS_HOME}" ]] &&
   [[ -d "${HADOOP_HOME}/${HDFS_DIR}" ]]; then
  export HADOOP_HDFS_HOME="${HADOOP_HOME}"
fi

The solution is to avoid defining an environment variable HDFS_DIR.
In my case, using sudo helped but for the wrong reasons: there was no problem with the permissions but with the environment variables.


text:
Q: PrimeFaces dataTable not updating after Ajax request I'm currently working with a PrimeFaces dataTable and am trying endlessly to append a new to the dataTable immediately after the user adds it. Server-side, everything is working -- data is saved to both the database and hard disk. I'd like to see a partial-page update following the successful request, and I just can't seem to get it to work. Here is my XHTML code:

                <h:form id="navForm">

                </h:form>

                <h:form id="dataTable" prependId="false">

                            <h:panelGrid columns="2">
                                <h:outputLabel value="Name:" for="txt_name"></h:outputLabel>

                                    <f:facet name="start">
                                        <h:outputText value="Saving..." />
                                    </f:facet>
                                    <f:facet name="">
                                        <h:outputText value="Complete." />
                                    </f:facet>

                            </h:panelGrid>

                            <f:facet name="header">
                                File Name
                            </f:facet>
                            <h:outputText value="#{dir.name}" />

                            <f:facet name="header">
                                File Size
                            </f:facet>

                </h:form>

And finally, here is my backing bean.
public String createNew(){
    newDir.setDateCreated(new Date());
    newDir.setDateModified(new Date());
    newDir.setId(BigDecimal.ZERO);
    newDir.setLocation(ROOT_DIRECTORY + currentUser.getUsername() + "/");
    newDir.setFilesCollection(f);
    newDir.setDescription("");
    newDir.setOwner(currentUser);
    current = newDir;
    create();
    persistDirectoryFromObject(newDir);
    newDir = new Directory();
    RequestContext.getCurrentInstance().addPartialUpdateTarget("dGrid");

    return null;
}

A: If you are using 3.0.M4 you could do:
...

   ...

                        <f:facet name="header">
                            File Name
                        </f:facet>
                        <h:outputText value="#{dir.name}" />

                        <f:facet name="header">
                            File Size
                        </f:facet>

or you could simply:


text:
Q: Blank columns while exporting csv I have a VisualForce page to Export as Csv. In this I have some columns which renders based on a Boolean value. I have added a similar code below,
<apex:outPutlabel value="Prioritisation ANF"  rendered="TRUE"/>  	 <apex:outPutlabel value="Classification CF"  rendered="FALSE"/>  	 <apex:outPutlabel value="Prioritisation CF"  rendered="FALSE"/>  	 <td <apex:outPutlabel value="Classification HBV"  rendered="TRUE"/>

When it exports, it shows Blank columns as in below screenshot. For each (Render=false) it creates a blank space. it looks fine in VisualForce page though.

Any idea to overcome this.?

A: It does not work fine in Visualforce. It happens to render okay only because of the default styles, but the columns are still there. They would probably render differently in the Lightning Design System. Regardless, to fix this situation, you need to put the  td elements inside the conditional render:
<apex:outputPanel rendered="false">text...	</apex:outputText>


text:
Q: What is the word or mental state to describe someone that takes any disagreement with them as negative and unacceptable? What is the word or mental state to describe someone that takes any disagreement with them as negative and unacceptable?
Is there a word or mental condition to describe someone that takes any and all disagreement to them as negativity and being mean?  Can be something as simple as, "I don't think so..." And then respond by getting angry and say that person refuting them is negative?

A: I would say that they are defensive:

*Psychology Constantly protecting oneself from criticism, exposure of one's shortcomings, or other real or perceived threats to the ego.

Example of how to use it in a sentence:

When someone feels insecure about something, any disagreement can feel like harsh criticism and cause them to become angry and defensive.

A: This is shaky ground for anyone who is not a professional psychologist (I am not) but common perceptions are that in some cases such a person may be suffering from paranoia, personality disorder or persecution complex

Cambridge
paranoia:
an extreme and unreasonable feeling that other people do not like you or are going to harm or criticize you

Mind: Effects of Paranoia
If you think someone is threatening you or wants to harm you in some way, you may behave suspiciously or aggressively towards them. You might push them away or decide that you are better off without them.

or you might find that they have a persecution complex:

Merriam Webster
persecution complex:
the feeling of being persecuted especially without basis in reality

Both these conditions may result in over-sensitivity to criticism of even the mildest or most reasoned sort, and result in anger against and rejection of the critic.
And lastly, PPD is Paranoid Personality Disorder:

Helpguide
A person with PPD may feel deeply wary of others, always on guard for signs that someone is trying to threaten, mistreat, or deceive them. No matter how unfounded their beliefs, they may repeatedly question the faithfulness, honesty, or trustworthiness of others. When they perceive they're being persecuted, rejected, or slighted, they're likely to respond with angry outbursts, controlling behavior, or by deflecting the blame onto others.

A:
A person who takes any disagreement with them as negative and
unacceptable is oversensitive / hypersensitive.

Oversensitivity can contribute to various anxiety disorders including obsessive-compulsive disorder.
oversensitive (adj.)

Too easily bothered, upset, offended, etc.
an oversensitive person
oversensitive about his looks
She's oversensitive to criticism.
It is not enough to say "I was only joking", and you ought not to suggest that the recipient is being oversensitive or thin-skinned.
m-w

Excessively or unduly sensitive Collins

hypersensitive (adj.)

If you say that someone is hypersensitive, you mean that they get
annoyed or offended very easily.
Student teachers were hypersensitive to any criticism of their performance. Collins

Sensitive to an abnormal or excessive degree; over-sensitive. (OED)

Being particularly hypersensitive means being somewhat paranoid,
and that means that when people challenge me in any way, I think that
they are in fact insulting me. Martin Kantor; Obsessive-Compulsive
Personality Disorder (2016)

What appears to be inherited is a general emotional
oversensitivity which can predispose one to the development of some form of anxiety disorder. P. De Silva and S. Rachman;
Obsessive-Compulsive Disorder (2004)


text:
Q: When you add a new mongodb replica, how do you know when it has caught up to the master? If you add a new replica to mongodb, how do you know if it has caught up to the master node or at least the other replicas?
Do you add this new replica to your mongodb clients to query from or this will cause issues?

A:
If you add a new replica to mongodb, how do you know if it has caught
  up to the master node or at least the other replicas?

From the documentation Add Members to a Replica Set:

Ensure that the new member has reached SECONDARY state. To check the
  state of the replica set members, run rs.status().

Also see various replica set status.

Do you add this new replica to your mongodb clients to query from or
  this will cause issues?

Clients connect to a replica set. By default all read and write operations go to the primary member. Your replica set can be configured such that the read operations can be directed to secondaries - by setting the Read Preference.
You don't need to do any specific configuration to tell the cilent programs to access the new member of the replica set.


text:
Q: Scope ignored by FB oauth2 login flow I seem to be having troubles setting the correct permissions at login for facebook. It looks like my scope list is completely ignored (not in user permissions, not even asked for in the dialog window). What am I doing wrong here?
The auth url I am using is: https://www.facebook.com/dialog/oauth?client_id=CLIENTID&redirect_uri=REDIRECTURI&response_type=code&scope=email,user_birthday,user_education_history,user_interests,user_relationships,user_relationship_details,user_work_history,user_likes,user_location,user_photos,read_stream,offline_access,publish_stream&state=STATE
CLIENTID, REDIRECTURI and STATE are placeholders obviously...


text:
Q: How can I expand width of UIView from left to right - Swift I have a UIView and I've added a UIView inside it as a subview. I'm hoping to expand the subview to fill a portion of the view, as a percentage, for example:
subview.bounds.width = view.bound.width(num1/max)
where num1 changes every second until it reaches max.

A: A UIView's frame can't be partially changed - to get the result you're looking for, you need to create a new frame, manipulate it, then attach it to your subview, like so:
let newFrame = subview.frame
newFrame.size.width = view.frame.width * num1 / max
subview.frame = newFrame


text:
Q: For loop for read.table? I know this is an absolute mess and I apologise. In R I want to add a column to a set of large txt files and then make new txt files with the new columns. I don't get an error message but it takes a long time to run and eventually it gets killed. Is there a better way to run the below or maybe there is a bug still? I'm new to R so still don't know how it normally behaves.
files <- dir(".../rsid", pattern= glob2rx("final_rsid_chrom*.txt"))

rsid.db <- list()

for (i in files){
rsid.db[[i]]  <- lapply(i, read.table, header = T, sep=" ", stringsAsFactors = F)
rsid.db[[i]]$linkage.new <- apply(rsid_db[[i]], 1, create.alleles.col, "REF", "ALT")
write.table(rsid.db[[i]], "rsid_linkage_new[[i]].txt", quote = FALSE,row.names=FALSE)
}

Roland - I also ran the following separately and it has the same issue (i.e. taking a really long time).
 files <- dir("/home/sjk98/rds/rds-jmmh2-projects/iron/novel/novel_iron/cleaned/3_columns_std/rsid", pattern= glob2rx("final_rsid_chrom*.txt"))

 rsid.db <- list()

 rsid.db  <- lapply(files, read.table, header = T, sep=" ", stringsAsFactors = F)

 quit()

A: There were some bugs which I think are fixed in the below code. However, if create.alleles.col is the time consuming part, we can't help without knowing more about that function.
# someone correct me if I'm wrong, but I don't believe ".../" is a legit path;
# "../risd" looks for risd in the parent dir of the current working directory.
# I think you want a dot before the * in your regext as the original m* matches
# zero or more m characters
files <- dir("../rsid", pattern = "final_rsid_chrom.*\\.txt", full.names = TRUE)

for (i in files){
  # no need to call lapply on a single item; using a temporary variable
  # instead of a list will release the memory from each file instead of
  # building up in RAM if saved to a list
  rsid.tmp  <- read.table(i, header = TRUE, sep=" ", stringsAsFactors = FALSE)

  # if create.alleles.col is the time consuming part, we can't help without
  # knowing more about it
  rsid.tmp$linkage.new <- apply(rsid.tmp, 1, create.alleles.col, "REF", "ALT")

  # create a new file name with _update appended to the end, i.e., oldname_update.txt
  new_file <- sub("(\\.txt)$", "_updated\\1", i)
  write.table(rsid.tmp, new_file, quote = FALSE, row.names = FALSE)
}


text:
Q: How to initialise value for LPVARIABLE.matrix in PULP? I am trying to set initial values for the below created decision variable, but when I try to do am getting an error?

dec_var = LpVariable.matrix("dec_var",(range(10),range(10)),0,1,cat = 'Binary')

for i in range(10):
    for j in range(10):
        dec_var[i][j].setInitialValue(temp_matrix[i][j])

A: Issue found to be using the older version of pulp, after upgrading the library to latest version. I didn't face any issue with this.


text:
Q: Android sliders programmatically > i want to implement slider bar in my application  without using xml. i try to search using google but not able to get any sample code.how to create slider bar in android, pls guide me,

A: This should work, it uses the built in SeekBar. The onProgressChanged is passed the location of the progress and an integer between the value 0-100 when it is changed.
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.SeekBar;

public class SeekBarExample extends Activity {
    LinearLayout ll;
    SeekBar sBar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ll = new LinearLayout(this);
        sBar = new SeekBar(this);
        SeekBar.OnSeekBarChangeListener abc = new SeekBar.OnSeekBarChangeListener() {

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                //Executed when progress is changed
                System.out.println(progress);
            }
        };
        sBar.setOnSeekBarChangeListener(abc);
        LayoutParams sBarLayParams=new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
        ll.addView(sBar,sBarLayParams);
        setContentView(ll);
        }
}


text:
Q: Separately validate two forms of the same page in asp.net using HTML5 validation I have two forms for login and registration.I am trying to use HTML5 validation. When i click the form to submit login, controls of registration is validated and vice versa.How do I prevent that? I know there is something called validation group but I guess that works only for the validationcontrols provided by .NET.
Here's my code:

 Registration

       <asp:TextBox ID="tb_uname" class="login_mem" runat="server"  placeholder="Name" required></asp:TextBox>

       <asp:TextBox ID="tb_address" class="login_mem" runat="server" placeholder="Address" ></asp:TextBox>

       <asp:TextBox ID="tb_email" class="login_mem"  runat="server"  placeholder="Email" ></asp:TextBox>

       <asp:TextBox ID="tb_pass"  class="login_mem" TextMode="Password"  runat="server" placeholder="Password" ></asp:TextBox>

       <asp:Button ID="btn_reg" runat="server" Text="Registration" CausesValidation="false"
             onclick="btn_reg_Click"/>

Login

       <asp:TextBox ID="tb_name" class="login_mem" runat="server" placeholder="username" required></asp:TextBox>

       <asp:TextBox ID="tb_password" class="login_mem" runat="server" placeholder="password"></asp:TextBox>

        <asp:Button ID="btn_log" runat="server" Text="Login" onclick="btn_log_Click"/>
        <asp:Label ID="error" runat="server"></asp:Label>

A: You can add the novalidate tag to your forms to prevent them from validating when submitting them.
<form action="demo_form.asp" novalidate>

Or you could add it to one or multiple forms using javascrit/query:
$(document).ready(function() {
    $("form").attr('novalidate', 'novalidate');
});


text:
Q: Array field always stores the last value of the field into database Help me working with array inputs on my project.
This is the form field:
<form action="" method="">
    <input type="text" class="form-control" name="scores[]">
    <input type="hidden" name="lesson_id[]" value="">
    <input type="hidden" name="year_id" value="">
    <input type="hidden" name="grade_id" value="">
    <input type="hidden" name="clas_id" value="">
    <input type="hidden" name="student_id" value="">
</form>

My Controller:
public function store(Request $request)
    {

        foreach ($request->scores as $score)
        {
            $scr = new Assestment;
            $scr->year_id = $request->year_id;
            $scr->grade_id = $request->grade_id;
            $scr->clas_id = $request->clas_id;
            $scr->student_id = $request->student_id;
            foreach($request->lesson_id as $lesson)
            {
                $scr->lesson_id = $lesson;
            }
            $scr->score = $score;
            $scr->save();
        }

    }

My Model:
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Assestment extends Model
{
    protected $table = 'assestments';

    protected $fillable = [
        'year_id', 'grade_id', 'clas_id', 'student_id', 'lesson_id', 'score',
    ];

    public function students()
    {
        return $this->belongsToMany('App\Models\Student');
    }

}

I would like to make the value of field "scores[]" and "lesson_id[]" as array so that they store multiple data to database.
But when I submit the form, the "lesson_id[]" always store the last value of the form. For example, the field "lesson_id[]" contains multiple values like "1, 2, 3 , 4", but the value stored into database is always "4 (the last value of the field)".
What should I do?

A: Only the last value is stored because you stored the data after foreach loop.
If you want to store the socres[] and lesson_id[] as an array in the same table, you can use serialize()
 $scr = new Assestment;
 $scr->year_id = $request->year_id;
 $scr->grade_id = $request->grade_id;
 $scr->clas_id = $request->clas_id;
 $scr->student_id = $request->student_id;
 $scr->lesson_id = serialize($request->lesson_id);
 $scr->score = serialize($request->$score);
 $scr->save();

To retreive each value, use unserialize()


text:
Q: VBA copy paste all files in a folder My macro is running well since 2 months but now I need some help for another issue.
We are running an controller on our server which is sending mails to our customer with attached pdf. Now this controller and my macro are running sometimes at the same time and when my macro is creating pdfs the controller wants to send it but is not able to do so because its already in creation.
Now I thought the macro could save pdf into another folder and after that it will copy paste all files into the right folder for sending.
My code is this:
Function Copy()

   Dim MyFile2 As Sting
   Dim myPath2 As String, myPath3 As String

   myPath2 = "L:\Host_Export\Pdf-Kundenmail\Test\"
   myPath3 = "L:\Host_Export\Pdf-Kundenmail\"
   MyFile2 = Dir(myPath2 & "*.*")
   Do
        If MyFile2 = "" Then Exit Do
        FileCopy myPath2 & MyFile2, myPath3 & MyFile2
        End If
        myFile2 = Dir
    Loop

End Function

But if I run it there is an error: error on compilation  userdefined typ could not be defined. like this: https://i0.wp.com/www.port135.com/wp-content/uploads/2012/08/error1-1.png.
I alredy googled but don't get it how to set up or import something to fix this issue.

A: Your code won't work because as @user3598756 said, you spelled string incorrectly.  To improve your form though, use a do while loop to combine the if and do statements like so:
Function Copy()
   Dim MyFile2 As String
   Dim myPath2 As String, myPath3 As String

   myPath2 = "L:\Host_Export\Pdf-Kundenmail\Test\"
   myPath3 = "L:\Host_Export\Pdf-Kundenmail\"
   MyFile2 = Dir(myPath2 & "*.*")
   Do while MyFile2 <> ""
        FileCopy myPath2 & MyFile2, myPath3 & MyFile2
        myFile2 = Dir
   Loop
End Function

A: Following sub will copy all files from source folder to destination folder.
    Sub AllFiles()
    Dim FSO As Object
    Dim FromPath As String
    Dim ToPath As String

        FromPath = "C:\Users\Alam\Music\Awlad Hossain"  'Souece Folder
        ToPath = "C:\MyExcelFiles"    'Destination folder

            If Right(FromPath, 1) = "\" Then
                FromPath = Left(FromPath, Len(FromPath) - 1)
            End If

            If Right(ToPath, 1) = "\" Then
                ToPath = Left(ToPath, Len(ToPath) - 1)
            End If

        Set FSO = CreateObject("scripting.filesystemobject")

            If FSO.FolderExists(FromPath) = False Then
                MsgBox FromPath & " doesn't exist"
                Exit Sub
            End If

        FSO.CopyFolder Source:=FromPath, Destination:=ToPath
        MsgBox "You can find the files and subfolders from " & FromPath & " in " & ToPath

    End Sub

More details here:


text:
Q: ASP.NET combine\overlay multiple projects upon build\deploy I have several ASP.NET MVC web projects that all need access to the same set of configuration files.  Since I have multiple configuration files that need to be shared, it is not ideal to have multiple copies of them.
With Maven3, I can overlay individual J2EE webapp's on top of others upon build so I could make one project that contains only config files and have it combined into each of the individual web application projects.
Is there any way to achieve this with MSBuild or any other .NET build tool?
My only solution is to use a build event to copy the files from one project into the others, but when creating a deployment package via MSBuild, it only packages files that are a part of the project, and ignores any additional files that are in the folder.
My ultimate goal is to include these config files in the deployment projects that are generated with msbuild /t:Package (which are eventually deployed to IIS7 with, hopefully, everything they need).

A: I found a solution to my problem.

*

*I place my configuration files in a folder in some shared project.

*Right click on the configuration files and select Properties.

*Ensure Build Action is Content and Copy to Output Directory is Copy Always

*Reference "Shared Project" from "Main Project 1" and "Main Project 2"

Now, when "Main Project 1" and "Main Project 2" are built, their reference project ("Shared Project") will also be built and it will have the configuration files published to the /bin directory.
To access these configuration files:
string configPath = HttpRuntime.BinDirectory + string.Format(@"ConfigDirectory\{0}.config", someConfigFileName );

Then you can read this config file (assuming it is in the standard .NET config format) using:
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap
            {
                ExeConfigFilename = configPath
            };
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);

var settings = ((AppSettingsSection)config.GetSection("appSettings")).Settings;


text:
Q: jQuery Overlay: Closing current overlay and opening another? Please have a look at beta.gulfdine.com. You will see a "Sign in" link. Clicking on it launches a jQuery overlay.
Now click on "Why Join?". This launches another overlay, within which there is a 'Sign up now' link. Clicking on it opens the previous overlay.
Now here's the problem. You'll note that both overlays have the 'expose' option, which shows them with the rest of the screen darkened. This works fine when both are opened independently. However, when I launch the sign up overlay from within "Why Join?", the expose effect is not shown. Also clicking outside the overlay doesn't work.
Here is the code:
/*Overlays*/
var whyJoinOverlay = $("a.whyJoin[rel]").overlay({ expose: '#000', top: 'center', api: true });
var loginLinks = $("a.loginLinks[rel]").overlay({ expose: '#000', top: 'center', api: true });

$("a.callToAction").click(function (e) {
    e.preventDefault();
    whyJoinOverlay.close();
    loginLinks.load();
});

Is this because of something I'm doing wrong, or is this a bug in jQuery overlay?

A: The issue is that that fadeOut animation isn't being allowed to finish before the new modal is loaded. I poked around the documentation a bit and couldn't find a way to pass a callback to the close() function, but you'll need to find some way to do that. When that happens, your code will look something like this:
$("a.callToAction").click(function (e) {
    e.preventDefault();
    whyJoinOverlay.close(function()
    {
        loginLinks.load();
    });
});

This ensures that the close function is done completing before the load function begins, in other words, ensures that the actions are synchronous. Like I said though, you may need to be creative in how that callback gets passed to the close function: it may require a JSON name specifier or it may need to be defined ahead of time. If you can't find a way to do that, it's a limitation of the library that you can either add in or figure out a way to replace.

A: Jimmy seems to have been on the right track about the cause of the error.
It turns out that there is an inbuilt value that needs to be modified in order to make this work, as I found out in the jQuery Tools forums: http://flowplayer.org/tools/forum/40/41903
The modified code now looks like this:
var whyJoinOverlay = $("a.whyJoin[rel]").overlay({
    top: 'center',
    api: true,
    mask: {
        color: "#000",
        loadSpeed: 0,
        closeSpeed:0,//this is REQUIRED for the next overlay to work
        opacity: 0.9
        }
});

var loginLinks = $("a.loginLinks[rel]").overlay({ expose: '#000', top: 'center', api: true });
/* No longer any need for the $("a.callToAction").click() function */


text:
Q: Built-in factorial function in Haskell I know this sounds like a stupid question, but here it is: Is there a built-in factorial in Haskell?
Google gives me tutorials about Haskell explaining how I can implement it myself, and I could not find anything on Hoogle. I don't want to rewrite it each time I need it.
I can use product [1..n] as a replacement, but is there a true Int -> Int factorial built-in function?

A: The best implementation of factorial I know of in Hackage is Math.Combinatorics.Exact.Factorial.factorial in the exact-combinatorics package.  It uses an asymptotically faster algorithm than product [1..n].
http://hackage.haskell.org/package/exact-combinatorics

A: Even though it is commonly used for examples, the factorial function isn't all that useful in practice. The numbers grow very quickly, and most problems that include the factorial function can (and should) be computed in more efficient ways.
A trivial example is computing binomial coefficients. While it is possible to define them as
choose n k = factorial n `div` (factorial k * factorial (n-k))

it is much more efficient not to use factorials:
choose n 0 = 1
choose 0 k = 0
choose n k = choose (n-1) (k-1) * n `div` k

So, no, it's not included in the standard prelude. Neither is the Fibonacci sequence, the Ackermann function, or many other functions that while theoretically interesting are not used commonly enough in practice to warrant a spot in the standard libraries.
That being said, there are many math libraries available on Hackage.

A: No, but you can easily write one. If you are concerned about having to rewrite the function each time you need it, you could always write it as part of a module or a library (depending on how far you want to take this, any how many other similar functions you have). That way you only need to write it once, and can quickly pull it in to any other projects when you need it.

A: Try Hayoo! to search (link on the top of hackage); it came up with this, for example
http://hackage.haskell.org/packages/archive/statistics/latest/doc/html/Statistics-Math.html#v:factorial

A: fac = product . flip take [1..]

A: You have the product function which is in the standard prelude. Combined with ranges you can get a factorial function with minimal effort.
factorial n = product [n, n-1 .. 1]
nCr n r = n' `div` r'
    where
    -- unroll just what you need and nothing more
    n' = product [n, n-1 .. n-r+1]
    r' = factorial r

A: fact n = if n == 0 then 1 else n * fact(n-1)
fact n = foldl(*) 1 [1..n]
fact n = product [1..n]

You can choose either

A: If you're looking for a lambda expression, then you can always use the classic fix (\f x -> if x == 0 then 1 else x * (f (x - 1))).


text:
Q: FastAi GrandparentSplitter File Path I am trying to train a segmentation algorithm with FastAi. I have training and validation data in separate folders, so was planning on using GrandparentSplitter() but for some reason the validation set is empty.
My files are organised as below:
Path ---> train ---> images
                ---> masks
     ---> valid ---> images
                ---> masks

And this is how I set up my datablock and dataloader:
codes = np.array(['background', 'prostate'])

def label_func(x): return path/'train/masks'/f'{x.stem}_mask.png'

db = DataBlock(blocks=(ImageBlock(), MaskBlock(codes)),
              splitter=GrandparentSplitter(train_name='train', valid_name='valid'),
              get_items=get_image_files,
              get_y=label_func)

dls = db.dataloaders(path/'train/images', bs=1)
dls.show_batch()

I am assuming there is something wrong with how I organised the files.

A: i could not make it work with the grandparent
just implement my own get_files


text:
Q: How to select and print a specific JSON value using Python GET Request I am attempting to select an save a specific 'identifier' value(392861) from a JSON url file after retrieving the JSON using a GET request:
getBooking = s.get("https://www.goodlifefitness.com/content/goodlife/en/book-workout/jcr:content/root/responsivegrid/workoutbooking.GetWorkoutSlots.7.2020-12-15.json")

I would like to store this specific 'identifier' value so I can send this value as part of a separate POST request.

A: Can you be more specific? Which "identifier" are you trying to access?
Let's assume you want to access the dayOfWeek tag for each workout, then you can do something like this:
workouts_list = getBooking.json()["map"]["response"][0]["workouts"]
for workout in workouts_list:
    print(workout["dayOfWeek"])

You can do the same thing for other parameters as well by just replacing dayOfWeek to any of the tags available on the JSON response.

A: The following code retreived the information I was looking for.
workouts_list = getBooking.json()["map"]["response"][0]["workouts"]
iden = workouts_list[0]["identifier"]
print(iden)


text:
Q: Write large files to disk in Objective C I have a large file that I receive through a web service that I am trying to write to disk. I can write most files to disk, but this and other files of this size (or greater) seem to be causing issues. The app will crash when I try to convert the string of bits to NSData after receiving memory warnings. Here's the code I am using:
NSString *bits = /*string of file stream*/;
NSData *fileData = [[NSData alloc] initWithBase64EncodedString:bits options:0];

The app will crash when trying to create the fileData variable. Is there a standard to doing this process that I may not be following or is there a trick to working with large files?
Thank you in advance! This issue has been really bothering me.
A Little More Information
It seems accessing the bits string too often will cause the crash due to the large amount of data in the file stream string. I'm not too sure how to deal with this.


text:
Q: Render a control (for an RSS feed) I am trying to find a way of rendering a control (part of a web page) so I can add it to an RSS feed (basically xmlns:content before anyone gasps).
var rendering = item.Visualization.GetRenderings(Context.Device, false)
                .FirstOrDefault(it => it.RenderingID.ToString() == "{968B82C4-46D9-43F3-AD52-82AA2629156B}");

if (rendering!= null)
{
    var sb = new System.Text.StringBuilder(); // needed?
    var sw = new StringWriter(sb);
    using (var wr = new HtmlTextWriter(sw))
        rendering.GetControl().RenderControl(wr);
}

What I am finding is that sw is empty and I was expecting it to contain html (the control displays fine on the website). Any thoughts?

A: I don't think there is an easy way to achieve this. Sitecore runs different pipelines depending on whether this is XSL, WebForms or MVC component...
There was already a question on Stack asking same thing: How to get content of rendering programmatically? But as you can see, author abandoned the idea cause there was no way of getting this easily.


text:
Q: groupadd on Ubuntu 16.04 with PBIS Open stuck with 100% CPU I have Ubuntu 16.04 servers and workstations which are members of an Active Directory domain, using PowerBroker PBIS Open versions 8.5.0.153 and 8.6.0.427. When I try to add a local group using groupadd someNewGroup I see it stuck at 100% CPU. If I specify a group number explicitly with -g then it works fine.
On two other virtual hosts which are actually Proxmox 4.4 containers - a CentOS 7 with PBIS 8.5.0 and Ubuntu 16.04 with PBIS 8.5.2.265 I can add and delete local groups freely with no issues.
With strace I see the that it's stuck after performing a seek on /etc/group:
open("/etc/group", O_RDONLY|O_CLOEXEC)  = 8
open("/etc/default/nss", O_RDONLY|O_CLOEXEC) = 9
fstat(9, {st_mode=S_IFREG|0644, st_size=1756, ...}) = 0
read(9, "# /etc/default/nss\n# This file c"..., 4096) = 1756
read(9, "", 4096)                       = 0
close(9)                                = 0
futex(0x7f2aaefa9a50, FUTEX_WAKE_PRIVATE, 2147483647) = 0
lseek(8, 0, SEEK_CUR)                   = 0
fstat(8, {st_mode=S_IFREG|0644, st_size=882, ...}) = 0
mmap(NULL, 882, PROT_READ, MAP_SHARED, 8, 0) = 0x7f2ab0764000
lseek(8, 882, SEEK_SET)                 = 882

What's wrong here? How can I get groupadd to work properly?


text:
Q: Push into session issue in Laravel Each item contains a list of addons as checkboxes. Every time I check an addon I want to push addon_id into the addons array. It's pushing an addon_id to session but it's not pushing it properly.
This code adds item to cart (Notice: I am creating an empty addons array):
$cart = session()->get('cart', []);

if(isset($cart[$request->item_id])) {

  $cart[$request->item_id]['qty']++;

} else {

   $cart[$request->item_id] = [

      'id' => $request->item_id,
      'category_id' => $request->category_id,
      'price' => $request->item_price,
      'item_name' => $request->item_name,
      'qty' => 1,
      'addons' => [],

   ];

}

session()->put('cart', $cart);

And this code pushes addons to items:
if(isset($request->item_id)) {

   session()->push('cart.addons', $request->addon_id);

}

$cart = session()->get('cart', []);

return response()->json([

   'message' => 'Addon added',
   'cart' => $cart,

]);

This is how addons are being pushed now:
Array
(
    [59] => Array
        (
            [id] => 59
            [category_id] => 27
            [price] => 3.78
            [item_name] => Simple Sandwich
            [qty] => 1
            [addons] => Array
                (
                )
        )

    [57] => Array
        (
            [id] => 57
            [category_id] => 27
            [price] => 5.99
            [item_name] => Cheese Burger
            [qty] => 1
            [addons] => Array
                (
                )
        )

    [addons] => Array
        (
            [0] => 31
        )

    [addons] => Array
        (
            [0] => 61,
            [1] => 60,
            [2] => 31
        )
)

I need them to be pushed like this:
Array
(
    [59] => Array
        (
            [id] => 59
            [category_id] => 27
            [price] => 3.78
            [item_name] => Simple Sandwich
            [qty] => 1
            [addons] => Array
                (
                  [0] => 31
                )
        )

    [57] => Array
        (
            [id] => 57
            [category_id] => 27
            [price] => 5.99
            [item_name] => Cheese Burger
            [qty] => 1
            [addons] => Array
                (
                  [0] => 61,
                  [1] => 60,
                  [2] => 31
                )
        )
)

I tried to find a solution but nothing seems to be working the way I need it.
Help is very much appreciated.

A: Initially you are making an associative array where item_id is the key, but when you are appending in addons you are not specifying against which item_id the addons array should be updated, so you will have to change
if(isset($request->item_id)) {

   session()->push('cart.addons', $request->addon_id);

}

to something like this:
if(isset($request->item_id)) {
   $cart = session()->get('cart');
   if(isset($cart[$request->item_id]) {
   array_push($cart[$request->item_id]['addons'],$request->addon_id);
   session()->put('cart',$cart);
 }
}


text:
Q: Importing PySpark packages I have downloaded the graphframes package (from here) and saved it on my local disk. Now, I would like to use it. So, I use the following command:
IPYTHON_OPTS="notebook --no-browser" pyspark --num-executors=4  --name gorelikboris_notebook_1  --py-files ~/temp/graphframes-0.1.0-spark1.5.jar --jars ~/temp/graphframes-0.1.0-spark1.5.jar --packages graphframes:graphframes:0.1.0-spark1.5

All the pyspark functionality works as expected, except for the new graphframes package: whenever I try to import graphframes, I get an ImportError. When I examine sys.path, I can see the following two paths:
/tmp/spark-1eXXX/userFiles-9XXX/graphframes_graphframes-0.1.0-spark1.5.jar and /tmp/spark-1eXXX/userFiles-9XXX/graphframes-0.1.0-spark1.5.jar, however these files don't exist. Moreover, the /tmp/spark-1eXXX/userFiles-9XXX/ directory is empty.
What am I missing?

A: in my case:
1、cd /home/zh/.ivy2/jars
2、jar xf graphframes_graphframes-0.3.0-spark2.0-s_2.11.jar
3、add /home/zh/.ivy2/jar to PYTHONPATH in spark-env.sh like code above:
export PYTHONPATH=$PYTHONPATH:/home/zh/.ivy2/jars:.

A: This might be an issue in Spark packages with Python in general. Someone else was asking about it too earlier on the Spark user discussion alias.
My workaround is to unpackage the jar to find the python code embedded, and then move the python code into a subdirectory called graphframes.
For instance, I run pyspark from my home directory
~$ ls -lart
drwxr-xr-x 2 user user   4096 Feb 24 19:55 graphframes

~$ ls graphframes/
__init__.pyc  examples.pyc  graphframe.pyc  tests.pyc

You would not need the py-files or jars parameters, though, something like
IPYTHON_OPTS="notebook --no-browser" pyspark --num-executors=4 --name gorelikboris_notebook_1 --packages graphframes:graphframes:0.1.0-spark1.5

and having the python code in the graphframes directory should work.

A: Add these lines to your $SPARK_HOME/conf/spark-defaults.conf :
spark.executor.extraClassPath      file_path/jar1:file_path/jar2
spark.driver.extraClassPath      file_path/jar1:file_path/jar2

A: In the more general case of importing 'orphan' python file (outside of current folder, not part of properly installed package) - use addPyFile, e.g.:
sc.addPyFile('somefolder/graphframe.zip')

addPyFile(path): Add a .py or .zip dependency for all tasks to be executed on this SparkContext in the future. The path passed can be either a local file, a file in HDFS (or other Hadoop-supported filesystems), or an HTTP, HTTPS or FTP URI.


text:
Q: Is there a way to remove ads from Windows spotlight? I like the Windows spotlight feature that rotates different background images in the lock screen. However, it has recently started showing random annoying text ads.

Is there a way to get rid of these ads without disabling Windows spotlight?
I'm using Windows 10 Pro.

A: There are two ways:

*

*by enabling Secure Sign-in. You get to keep your Spotlight rotation wallpapers but all the text ads get replaced with a single "Press Ctrl+Alt+Del to unlock" just above the clock. This worked for me today.

*by installing Dynamic Theme from the MS Store and configure it to Spotlight Wallpaper. This worked at least up to a month ago.

Other solutions you may come across are outdated and patched and will not work now, or they require you to not use Spotlight. Namely,

*

*Turning off 'Get fun facts, tips and more from Windows and Cortana on your lockscreen'. This option has been patched to only show up if you select Picture mode or Slideshow mode, neither of which allows you to keep Spotlight mode.

*Turning off the above option in Picture/Slideshow mode and then switching back to Spotlight. This doesn't work because the option simply isn't relevant to Spotlight anymore, the setting will not persist when you switch back to Spotlight.

*Editing your Local Group Policy under Computer Configuration > Administrative Templates > Windows Components > Cloud Content > Do not show Windows Tips. This has been patched to not apply to the text ads on Spotlight.

A: Run regedit and navigate to
HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager

(you can paste that)
Then change value SubscribedContent-338387Enabled to 0.
Works with Windows 10 2004

A: Just to add to this - Go to
Settings > Personalisation > Lock screen >
Under 'Background' select: 'Picture'.
Turn off: 'Get fun facts, tips and more from Windows and Cortana on your lockscreen'.
The only way to see that setting above is to have 'Picture' selected.
You can then change the Background back to Slideshow or Windows Spotlight if you choose.

A: settings, personalization, lock screen, turn off "get fun facts...from cortana on your lock screen"


text:
Q: Checkbox modified() and other controls enabled in Dynamics AX I override method modified() of checkbox.
I would like to get other control (field) enabled in form if this checkbox is clicked.
    public boolean modified()
    {
    boolean ret;

    if(ManualAssetId.value()== NoYes::Yes)
    {
        Identification_AssetId.enabled(true);
        ret = super();
    }
    else
    {
        Identification_AssetId.enabled(false);
        ret = super();
    }

    return ret;
}

But this field Identification_AssetId is not getting enabled in the form. Why?


text:
Q: Service Worker Causing a Blank Page After Refresh in React Application I have a Node application deployed to Azure, with a test branch leading to a staging instance, and a master branch pointed at the prod deployment. My application works fine on all instances of the application locally, but production and staging are having an issue in which they will not load if they are already cached, and will appear blank after a refresh, and lastly will work properly with a cache reset.
Whenever I refresh the page in production, it is just blank. The service worker is running (I can see it in the chrome serviceworkers-internal tool), but the page just never loads. The file references generated are correct. You can see an example of what is happening here: Live Site and then you can also see the testing site which is also failing with the exact same code deployed: Test Site.
The entirety of the ServiceWorker implementation is out of the box from create-react-app. I've spent several hours trying to track this bug down across a variety of GitHub issues under the react-boilerplate and create-react-app repos and none of them really get anywhere beyond restricting page caching, which I tried to do with no avail with:
Index.html
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate"/>
<meta http-equiv="Pragma" content="no-cache"/>
<meta http-equiv="Expires" content="0"/>

You can find any of the code you have questions about any code at the repo that hosts all of this code.
I'm just kind of getting my feet wet with React/Node, so I'm at a wall and don't really see how to get around this without completely ripping out the ServiceWorker registration.
EDIT: I completely removed the ServiceWorker code from the index.js file and the sight reloads without any issues now. Is there a step I need to complete to get the ServiceWorker to properly reload the page from cache or something?

A: In case someone else finds this question like me, the answer was to disable browser cache on the service worker file (service-worker.js for me) and index.html, and cache forever the rest.
It appears when a change is made the old version of the app continues to run, and on startup it then detects there is a new version. If like me you don't cache the static resources then when it tries to fetch the old version it gets a 404 resulting in a blank page. If you refresh a second time it gets the new version of the app.
I added some code into mine to automatically reload after 5 seconds by modifying registerServiceWorker.js
function registerValidSW(swUrl) {
console.debug('Registering serviceWorker URL [' + swUrl + ']');
navigator.serviceWorker
    .register(swUrl)
    .then(registration => {
        registration.onupdatefound = () => {
            const installingWorker = registration.installing;
            installingWorker.onstatechange = () => {
                if (installingWorker.state === 'installed') {
                    if (navigator.serviceWorker.controller) {
                        // At this point, the old content will have been purged and
                        // the fresh content will have been added to the cache.
                        // It's the perfect time to display a "New content is
                        // available; please refresh." message in your web app.
                        reportInfo('App has been updated. This page will refresh in 5 seconds.');
                        setInterval(()=>window.location.reload(), 5000);
                    } else {
                        // At this point, everything has been precached.
                        // It's the perfect time to display a
                        // "Content is cached for offline use." message.
                        reportInfo('App is cached for offline use.');
                    }
                }
            };
        };
    })
    .catch(error => {
        reportError('Error during service worker registration:', error);
    });

}

A: For anyone having the same issue as me using react and react-router-dom for a single page application, I had only a blank page on my installed application after calling window.location.reload() (on an android One Plus) because I was not redirecting from my route '/user' to the home '/' or '/index.html' on my server
If you have a single page application, please see this awnser for different ways to fix it: https://stackoverflow.com/a/36623117/17434198


text:
Q: How to: (jQuery) Modal login dialog w/ ASP.NET MVC 2? Whats the best way to override the built in login mechanism in ASP.NET MVC 2 so that a modal dialog pops up if the user needs to login (or [Authorize] tag decorates the Controller Action)?
Ive been searching for awhile and nothing really does this
Any help or guidance would be appreciated
jQuery is not a prerequisite but i am familiar with it

A: It's quite possible and not too hard.
http://weblogs.asp.net/mikebosch/archive/2008/02/15/asp-net-mvc-submitting-ajax-form-with-jquery.aspx
This is from another post that I can't seem to find any more:
Yes, it's possible. Just submit the login-form using the method described here by mike bosch and return a json datastructure with the returnUrl if any.
I have created a lightweight LoginResultDTO class that i return as json:
public class LoginResultDTO
{
  public bool Success {get;set;}
  public string Message {get;set;}
  public string ReturnUrl {get;set;}
}

Here's a script block from my LogOn view:
<script type="text/javascript">
        $(document).ready(function() {
            var form = $($("form")[0]);
            form.submit(function() {
                var data = form.serialize();
                $.post(form.attr("action"), data, function(result, status) {
                    if (result.Success && result.ReturnUrl) {
                            location.href = result.ReturnUrl;
                    } else {
                        alert(result.Message);
                    }
                }, "json");
                return false;
            });
        });
</script>

This will ajax wrap the logon form. Note that this is the simplest implementation of the javascript code possible but it's a place to start.
Then I have modified my LogOn action in the AccountController and in the relevant places put something like this:
if(Request.IsAjaxRequest())
{
  return Json(new LoginResultDTO{Success=true,Message="Successfully logged in"});
}else
{
  return View();
}

So this is an ultralight but rather complete version of how jquery authentication could be done in asp.net mvc.

A: You can expose a web service in your project that will validate if the user is logged in.  On $(document).ready() do an $.ajax() call to the web service.  Based on the result you can display the modal popup using the $.dialog() function in the UI library for JQuery.


text:
Q: Problema 'System.OutOfMemoryException' al cargar archivo plano Estoy tratando de cargar un archivo plano grande (250 Mb) en un datatable pero despues de cargar una considerable cantidad de registros (4 M), me arroja el error  'System.OutOfMemoryException'
                DataTable listaTX = new DataTable("listaTX");
                listaTX.Columns.Add("CodDep", typeof(int));
                listaTX.Columns.Add("CodMun", typeof(int));
                listaTX.Columns.Add("CodZon", typeof(int));
                listaTX.Columns.Add("CodPue", typeof(String));
                listaTX.Columns.Add("Mesa", typeof(int));
                listaTX.Columns.Add("CodJal", typeof(int));
                listaTX.Columns.Add("Comunicado", typeof(int));
                listaTX.Columns.Add("CodCirc", typeof(int));
                listaTX.Columns.Add("CodPar", typeof(int));
                listaTX.Columns.Add("CodCan", typeof(int));
                listaTX.Columns.Add("Votos", typeof(int));
                listaTX.Columns.Add("CodTX", typeof(int));

                using (FileStream fs = File.Open(ruta, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                using (BufferedStream bs = new BufferedStream(fs))
                using (StreamReader sr = new StreamReader(bs))
                {
                    try
                    {
                        while ((linea = sr.ReadLine()) != null)
                        {

                            DataRow fila = listaTX.NewRow();
                            fila[0] = linea.Substring(0, 2);
                            fila[1] = linea.Substring(2, 3);
                            fila[2] = linea.Substring(5, 2);
                            fila[3] = linea.Substring(7, 2);
                            fila[4] = linea.Substring(9, 6);
                            fila[5] = linea.Substring(15, 2);
                            fila[6] = linea.Substring(17, 4);
                            fila[7] = linea.Substring(21, 1);
                            fila[8] = linea.Substring(22, 3);
                            fila[9] = linea.Substring(25, 3);
                            fila[10] = linea.Substring(28, 8);
                            fila[11] = linea.Substring(36, 7);
                            listaTX.Rows.Add(fila);
                   }
               }
          }

Si en la casilla de propiedades del proyecto deshabilito la opción "Prefer 32 - bit" me funciona pero hice luego la prueba en una maquina de 32 bits y sale el mencionado error.
¿Existe alguna forma de optimizar el codigo u otro metodo que me permita cargar este archivo grande en un datatable?

A: Para poder montar una estructura más ligera podrías crearte una clase que internamente almacene únicamente el string y devuelva a través de propiedades los diferentes valores:
class Registro
{
    readonly string _value;

    private Registro(string value)
    {
        _value = value;
    }

    #region Conversión implícita con string

    public static implicit operator string(Registro d)
    {
        return d.ToString();
    }

    public static implicit operator Registro(string d)
    {
        return new Registro(d);
    }

    #endregion

    #region Propiedades que devuelven los campos

    public int CodDep => int.Parse(_value.Substring(0, 2));
    public int CodMun => int.Parse(_value.Substring(2, 3));
    public int CodZon => int.Parse(_value.Substring(5, 2));
    public string CodPue => _value.Substring(7, 2);
    public int Mesa => int.Parse(_value.Substring(9, 6));
    public int CodJal => int.Parse(_value.Substring(15, 2));
    public int Comunicado => int.Parse(_value.Substring(17, 4));
    public int CodCirc => int.Parse(_value.Substring(21, 1));
    public int CodPar => int.Parse(_value.Substring(22, 3));
    public int CodCan => int.Parse(_value.Substring(25, 3));
    public int Votos => int.Parse(_value.Substring(28, 8));
    public int CodTX => int.Parse(_value.Substring(36, 7));

    #endregion
}

Así el método de lectura del fichero podría devolver una lista de elementos Registro mucho más ligero que un DataTable:
private static IEnumerable<Registro> GetRecords(string ruta)
{
    var listaTx = new List<Registro>();

    using (StreamReader sr = new StreamReader(ruta))
    {
        while (sr.Peek() >= 0)
        {
            Registro linea = sr.ReadLine();
            if (!string.IsNullOrEmpty(linea)) listaTx.Add(linea);
        }
    }
    return listaTx;
}

Para recuperar todos los registros del fichero simplemente:
var data = GetRecords(rutaFichero);

Aunque si el objetivo es filtrar esos datos para generar un nuevo fichero sería mejor realizar el filtrado al leer el fichero, de esta forma no necesitarías almacenar en memoria el conjunto completo de datos, si no sólo los que vas a utilizar.
Para ello podrías crear una sobrecarga del método de lectura que acepte una condición de filtrado:
private static IEnumerable<Registro> GetRecords(string ruta, Func<Registro, bool> condicion)
{
    var listaTx = new List<Registro>();

    using (StreamReader sr = new StreamReader(ruta))
    {
        while (sr.Peek()>=0)
        {
            Registro linea = sr.ReadLine();
            if (linea != null && condicion(linea)) { listaTx.Add(linea); }
        }
    }
    return listaTx;
}

De esta forma, para por ejemplo obtener todos los registros con CodMun=83 bastaría con hacer:
var data = GetRecords(rutaFichero, r => r.CodMun == 83);

Mucho más rápido y con mucho menos consumo de memoria.

A: Podrías utilizar el iterador yield para ir leyendo linea a linea y evitar la carga completa del fichero en memoria
EDITADO
Voy a ser mas especifico que antes estaba en el curro y no he podido poner mucho ejemplo.
He creado un ejemplo con una lectura de un fichero de texto normal con 1.000.000 de lineas (250MB) y lo leo e inserto en un textBox.
El código que carga el fichero en memoria completamente es el siguiente:
using (StreamReader sr = new StreamReader(cPruebaTxt))
        {
            foreach (string line in GetDataLines(sr))
            {
                richTextBox1.Text += line + Environment.NewLine;
            }
        }

Este código usa varios GB de memoria.
Por otra parte usando la sentencia yield el codigo quedaria así:
private void LoadFile_Click(object sender, EventArgs e)
    {

        using (StreamReader sr = new StreamReader(cPruebaTxt))
        {
            foreach (string line in GetDataLines(sr))
            {
                richTextBox1.Text += line + Environment.NewLine;
            }
        }

    }

     private IEnumerable<string> GetDataLines(StreamReader sr)
    {
        string line = "";

        while ((line = sr.ReadLine()) != null)
        {
                yield return line;
        }

    }

Este código no ha subido de 50MB de uso de memoria, eso si, tarda mas en ejecutarse si solo vamos a leer.
Sin embargo si lo que hacemos es procesar las lineas leidas el tiempo se igualaría bastante, y en caso de ficheros muy grande la primera opción daría un Out of memory mientra que la segunda conseguirá cumplir su objetivo.
Te dejo un pequeño ejemplo:
https://jamesmccaffrey.wordpress.com/2011/02/04/processing-a-text-file-with-the-c-yield-return-pattern/


text:
Q: Using AND and OR in WHERE clause of SQLite in Android I need to delete a record from table in SQLite Android by using AND and OR.
My primitive statement looks like this.
public void deleteUser(user usr)
{
    SQLiteDatabase db = this.getWritableDatabase();
    db.delete(TABLE_USER_DETAILS, KEY_FNAME + " = ?", new String[] { String.valueOf(usr.getLName()) });
    db.close();
}

A: Assuming your naming conventions are consistent, you probably want something like this:
db.delete(TABLE_USER_DETAILS, KEY_FNAME + " = ? AND " + KEY_LNAME + " = ?",
    new String[] { String.valueOf(usr.getFName()), String.valueOf(usr.getLName()) });

If the usr.getFName() and usr.getLName() methods return Strings, you can get rid of the String.valueOf() around each.


text:
Q: Liquid Exception: Unknown tag 'include_relative' In Jekyll, I am trying to use the "include_relative" tag in the layout.html file.
layout.html

{% include_relative /hello.md %}

{% include_relative /bye.md %}

When I run the program it says:
Error:
Liquid Exception: Unknown tag 'include_relative' in layout

I know this tag exists as it is described on the Jekyll documentation web page. I have also used other tags in the layout.html file that work properly, so its specifically the "include_relative" tag that I am struggling with.
How can I get this tag to properly be recognized?


text:
Q: what is this i have big problem in flutter it is my plugins  sdk and i dont know what is cmake it is important
enter image description here
There is an error in vs code android studio. I get an error in every emulator. The error I get in vs code is Exception: Build process failed.
do you have any idea and vs code gave an error solution and a page called cmake came out, what does it do?
enter image description here

A: Please try to reinstall the flutter SDK in your laptop