Q:

String Pool management

Strings are immutable objects and are stored in the String Pool. Suppose in an application none of the strings are created using new operator. In this case also is it necessary to use equals method instead of == for String objects equality checks ?
I feel the answer of above question is probably yes and it has something to do with String Pool size.
How is the String Pool managed ? Memory is limited so I feel String pool also has a definite size. Does it work like LRU cache, discarding the least used Strings when the pool is full?
Please provide your valuable inputs.
My question is not about size of string pool. My question is if none of the strings are creared using new operator then using == will always be safe. Is this statement correct or can it happen that in this case also two string references haing same string characters may return false. I know design wise I should always use equals method butI just want to know the language specifications.

A:

Strings are immutable objects and are stored in the String Pool. Suppose in an application none of the strings are created using new operator. In this case also is it necessary to use equals method instead of == for String objects equality checks?

If you always use equals() you never need to worry about the answer to this question, but unless you only plan on comparing string literals the situation can never possibly arise.

I feel the answer of above question is probably yes

Correct.

and it has something to do with String Pool size.

No.

How is the String Pool managed? Memory is limited so I feel String pool also has a definite size.

No.

Does it work like LRU cache, discarding the least used Strings when the pool is full?

No, but Strings that have been intern()-ed can be garbage-collected from the pool.


Q:

Are compact subspaces of compact subspaces are compact subsubspaces?

Similar question in Algebra: Subsubgroups are subgroups of subgroups / Multiplicative Property of the Index
There, we had that for $A \subseteq B \subseteq C$ and $C$ is a group:

If $A$ is a subgroup of $B$ and $B$ is a subgroup of $C$, then $A$ is a subgroup of $C$.
If $A$ is a subgroup of $C$ and $B$ is a subgroup of $C$, then $A$ is a subgroup of $B$.

Now, I want to know for $A \subseteq B \subseteq C$ where $A, B$ and $C$ are topological spaces, do we have any of the following?

If $A$ is a compact subspace of $B$ and $B$ is a compact subspace of $C$, then $A$ is a compact subspace of $C$.
If $A$ is a compact subspace of $C$ and $B$ is a compact subspace of $C$, then $A$ is a compact subspace of $B$.
If $A$ is a compact subspace of $B$ and $A$ is a compact subspace of $C$, then $B$ is a compact subspace of $C$.

Analogue for connectedness: Are connected subspaces of connected subspaces are connected subsubspaces?

A:

1 & 2 are true, and 3 is false.
I refer to Topology by James Munkres. Let $A, B$ and $C$ have respective topologies $\mathscr T_A, \mathscr T_B$ and $\mathscr T_C$, where $\mathscr T_A$ is the subspace topology of $A$ in $B$, and $\mathscr T_B$ is the subspace topology of $B$ in $C$. Note that by Exer 16.1 (*), $\mathscr T_A'$, the subspace topology of $A$ in $C$, is equal to $\mathscr T_A$.

Pf: Let $A$ be covered by sets open in C:

$$A \subseteq \bigcup_{D \in \mathscr D} D, \tag{1}$$
for some $\mathscr D \subseteq \mathscr T_C$. By Lemma 26.1 (*), $A$ is a compact subspace of $C$, if we can find find some finite subcollection of $\mathscr D' \subseteq \mathscr D$ that covers $A$ i.e.
$$A \subseteq \bigcup_{D \in \mathscr D'} D.$$
Observe that by taking intersection of both sides of $(1)$ with $B$, we get
$$A = A \cap B \subseteq [\bigcup_{D \in \mathscr D} D] \cap B = \bigcup_{D \in \mathscr D} [D \cap B],$$
where, for every $D \in \mathscr D$, $D \cap B$ is open in $B$, by definition of $\mathscr T_B$. Thus, $A$ is covered by sets open in $B$. Hence, since $A$ is a compact subspace of $B$, we have a finite subcover $\mathscr D'' \subseteq \mathscr D$ of $A$:
$$A \subseteq \bigcup_{D \in \mathscr D''} [D \cap B].$$
Observe that
$$\bigcup_{D \in \mathscr D''} [D \cap B] \subseteq \bigcup_{D \in \mathscr D''} D$$
Therefore, we can choose $\mathscr D' = \mathscr D''$. QED

Pf: Let $A$ be covered by sets open in B:

$$A \subseteq \bigcup_{D \in \mathscr D} D$$
for some $\mathscr D \subseteq \mathscr T_B$. By Lemma 26.1 (*), $A$ is a compact subspace of $B$, if we can find find some finite subcollection of $\mathscr D' \subseteq \mathscr D$ that covers $A$ i.e.
$$A \subseteq \bigcup_{D \in \mathscr D} D.$$
By definition of $\mathscr T_B$, every $D \in \mathscr D$ has a partner $E_D \in \mathscr T_C$ s.t. $D = B \cap E_D$. Thus, we can collect all the $E_D$'s in some $\mathscr E \subseteq \mathscr T_C$, namely $\mathscr E: = \{E_D | D = B \cap E_D \ \text{for some} \ D \in \mathscr D \}$ s.t.
$$\bigcup_{D \in \mathscr D} D = \bigcup_{E_D \in \mathscr E} [B \cap E_D].$$
Observe that $$A \subseteq \bigcup_{D \in \mathscr D} D = \bigcup_{E_D \in \mathscr E} [B \cap E_D] \subseteq \bigcup_{E_D \in \mathscr E} E_D.$$
Thus, $A$ is covered by sets open in $C$. Hence, since $A$ is a compact subspace of $C$, we have a finite subcover $\mathscr E' \subseteq \mathscr E$ of $A$:
$$A \subseteq \bigcup_{E_D \in \mathscr E'} E_D.$$
Observe that by taking intersection of both sides with $B$, we get
$$A = A \cap B \subseteq \bigcup_{E_D \in \mathscr E'} [B \cap E_D] = [\bigcup_{E_D \in \mathscr E'} E_D] \cap B.$$
Therefore, we can choose $\mathscr D'$ to be made up of the $D$'s in $\mathscr D$ that have a partner $E_D \in \mathscr E'$. QED

$$[0,1] \subseteq (-14,77) \subseteq \mathbb R$$

Note: That $B$ is a compact subspace of $C$ is not used. Therefore, we have for $A \subseteq B \subseteq C$:

If $A$ is a compact subspace of $B$, then $A$ is a compact subspace of $C$.
If $A$ is a compact subspace of $C$, then $A$ is a compact subspace of $B$.

(*)
Exer 16.1

Lemma 26.1


Q:

Inject runtime dependency into nix package

Adding a runtime dependency to a package through override buildInputs causes the package to rebuild. Is there a simple way to inject runtime dependencies into a package without recompiling?
So basically adding package/bin to PATH and package/lib to LD_LIBRARY_PATH

A:

If I understand correctly that you want to tweak the environment used when a Nix-installed app is run, not the one used when it is built, then a method I know of is as follows below. By using it, you essentially create a wrapper script, which overrides the "default command". So, something similar like creating e.g. a custom ~/bin/vim script, which adds some options/env overrides to the default vim binary, which is called with a "hardcoded original path" inside the script.
One example of it in nixpkgs is how vimutils.vimWithRC overrides vim command with a custom script. For your own use, you could write more or less something like below:
with import <nixpkgs> {};

writeScriptBin "vim" ''
  #!/usr/bin/env bash
  export PATH=package/bin:$PATH   # whatever you like; I've added what you asked for
  export LD_LIBRARY_PATH=package/lib:$LD_LIBRARY_PATH
  ${vim}/bin/vim --my-options "$@"
'';

If you put it in my-vim.nix, you should be able to install it with:
$ nix-env -e vim   # REMOVE NORMAL VIM. I think this should be done first to avoid conflict
$ nix-env -i -f my-vim.nix

And hopefully it'll work and "override" the default vim for you.
DISCLAIMER: I haven't actually tested it in this exact form, sorry. Don't have a Nix console handy at this moment, unfortunately.


Q:

function that returns a pointer; In C

I imagine this to be a relatively simple answer.  I am just getting used to pointers and I am just about done however I cannot figure out this error:

PtrBasicBCGold.cc:27:13: error: no matching function for call to
  'HelperFunc'    maxPtr = HelperFunc(&i1, &i2, &i3, &i4);
              ^~~~~~~~~~ PtrBasicBCGold.cc:3:6: note: candidate function not viable: no known conversion from 'int **' to  'int *' for 1st
  argument; remove &   int *HelperFunc(int *i1, int *i2, int *i3, int
  *i4)
       ^ 1 error generated.

The prompt is to keep the below setup of an increment function and a helper.  But I cannot figure out how to return the pointer without an error of this sort.
#include <stdio.h>

int *HelperFunc(int *i1, int *i2, int *i3, int *i4)
{

   if(*i1 > *i2 && *i1 > *i3 && *i1 > *i4)
   {
       return i1;
   }
      if(*i2 > *i1 && *i2 > *i3 && *i2 > *i4)
   {
      return i2;
   }
   if(*i3 > *i1 && *i3 > *i2 && *i3 > *i4)
   {
      return i3;
   }
   else return i4;
}

void IncrementMax(int *i1, int *i2, int *i3, int *i4)
{
   int *maxPtr;
   maxPtr = HelperFunc(&i1, &i2, &i3, &i4);
   *maxPtr = *maxPtr + 1;
}

int main() {
   int i1, i2, i3, i4;

   scanf("%d %d %d %d", &i1, &i2, &i3, &i4);

   IncrementMax(&i1, &i2, &i3, &i4);

   printf("%d %d %d %d", i1, i2, i3, i4);

   return 0;
 }

A:

The problem is in this line:
maxPtr = HelperFunc(&i1, &i2, &i3, &i4);
You function call does not match with your prototype. Note that i1, i2, etc. are already pointers, so you do not need & which is the address of. If you do so it would be pointer to pointer to int, which is not what you need.
This change should fix the issue:
maxPtr = HelperFunc(i1, i2, i3, i4);


Q:

How to send push notification to Specific user in Web-push?

I have an existing web site , i just need to push notification to the site, for that i am using
Nodejs web-push package , I can able to receive notifications but i need to change it to User Specific,
For Example i want to send the notifications for the users based on the country
This is my code
client.js
const publicVapidKey = 'xxxxxx';

if ('serviceWorker' in navigator) {
  console.log('Registering service worker');

  run().catch(error => console.error(error));
}
function urlBase64ToUint8Array(base64String) {
  const padding = '='.repeat((4 - base64String.length % 4) % 4);
  const base64 = (base64String + padding)
    .replace(/-/g, '+')
    .replace(/_/g, '/');

  const rawData = window.atob(base64);
  const outputArray = new Uint8Array(rawData.length);

  for (let i = 0; i < rawData.length; ++i) {
    outputArray[i] = rawData.charCodeAt(i);
  }
  return outputArray;
}

async function run() {
  console.log('Registering service worker');
  const registration = await navigator.serviceWorker.
    register('worker.js');
  console.log('Registered service worker');

  console.log('Registering push');
  const subscription = await registration.pushManager.
    subscribe({
      userVisibleOnly: true,
      // The `urlBase64ToUint8Array()` function is the same as in
      // https://www.npmjs.com/package/web-push#using-vapid-key-for-applicationserverkey
      applicationServerKey: urlBase64ToUint8Array(publicVapidKey)
    });
    // subscription.user = $('.header-user-name').find('span').text();
  console.log('Registered push');

  console.log('Sending push');
  await fetch('http://localhost:3000/subscribe?user='+$('.header-user-name').find('span').text(), {
    method: 'POST',
    body: JSON.stringify(subscription),
    headers: {
      'content-type': 'application/json'
    }
  });
  console.log('Sent push');
}

Worker.js
console.log('Loaded service worker!');

self.addEventListener('push', ev => {
  const data = ev.data.json();
  console.log('Got push', data);

  ev.waitUntil(self.registration.showNotification(data.title, {
    body: 'Hello, World!',
    registration_ids: [$('.header-user-name').find('span').text()]
    icon: 'http://mongoosejs.com/docs/images/mongoose5_62x30_transparent.png'
  }));

});

Server Code (localhost:3000/push)
app.get('/push',function(req,res) {

  const payload = JSON.stringify({ title: 'Hello '+ user.name +' ' + req.query.title,  });

  console.log(req.query);
  console.log("yahooooooooooooooooooooooooooooooooo");

  webpush.sendNotification(newSubscription, payload).catch(error => {
    console.error(error.stack);
  });
  res.send({result : 'Success'});
});

A:

After long gap, I got an solution for this problem ,
Steps to be followed ,

Need to create express api to store user subscription in to the database ,
Need to get the user based on countries from database (you can prefer your own backend language i have choosen Nodejs),
then create an api which can send push notifications using given parameter like (Country, Users, Etc)

Happy Coding


Q:

Azure DevOps: How to merge two code coverage reports for different tests (.net core, angular)

We have two different types of tests in pipeline: unit(.net core) and frontend (angular/karma). Each of them can publish code coverage report via to "PublishCodeCoverageResults@1", but only one front or back. It depends on which test runs last. I think the last coverage owerwrites previous. However we need both code coverage publish.
Is there way to merge 2 coverage report and then publish them in one Code Coverage tab or add the second tab?

A:

Is there way to merge 2 coverage report and then publish them in one Code Coverage tab or add the second tab?

AFAIK, ReportGenerator can merge multiple coverage files into one, e.g. merge several Cobertura XML files into just one Cobertura XML file:
Check the document ReportGenerator for some more details.
You can do the following steps in the Azure devops:

Install the ReportGenerator extension:    https://marketplace.visualstudio.com/items?itemName=Palmmedia.reportgenerator
Configure the ReportGenerator task to produce HTML and Cobertura    (this is the default)
Configure the Publish code coverage results task and point it to the    HTML files directory and the merged Cobertura file generated by
  ReportGenerator

Currently the Publish code coverage results task regenerates the HTML
  report. To avoid that, you have to create a new environment variable:
  disable.coverage.autogenerate: 'true'

Check this thread for some more details.
Hope this helps.


Q:

For arbitrary vectors w and u there is a linear operator T such that T(w) = u?

I need to know whether in an arbitrary vector space $V$, given arbitrary non-zero vectors $v,u\in V$, there is a linear operator $T:V\to V$ such that $T(v) = u$.
I know that this statement is true if the dimension of $V$ is finite. But I don't know if the result holds for spaces of infinite dimension. So, being more specific: Let $V$ be a vector space of infinite dimension, given arbitrary non-zero vectors $v,u\in V$, is there a LINEAR map $T:V\to V$ such that $T(v) = u$?
If the latest one is true, I ask a more specific question: Let $V$ be a vector space of infinite dimension, given arbitrary non-zero vectors $v,u\in V$, is there a LINEAR CONTINUOUS map $T:V\to V$ such that $T(v) = u$?

A:

Under the axiom of choice, you may extend the linearly independent set $\{v\}$ to a basis $B$ (see here) for details.  Now, you can map $v$ to $u$, and all other basis elements to $0$.
If you do not accept AC, I have no idea.


Q:

Excel custom data validation use own made function

I'm trying to use my own made function inside custom data validation formula.
But for some reason it does not work.
My function:
Public Function IsNumberXValid(x) As Boolean
   IsNumberXValid = IsNumeric(x) And Math.Cos(x) <> 1
End Function

When I put this function inside formula field it shows following warning:

What am I doing wrong?

A:

With normal worksheet functions, it is easy to apply DV:

It is slightly more complex with a UDF()  This approach uses a "helper" cell.
I begin with a tiny UDF():
Public Function IsPrime(L As Long) As Boolean
    arr = Array(5, 7, 11)
    IsPrime = False
    For Each a In arr
        If L = a Then
            IsPrime = True
            Exit Function
        End If
    Next a
End Function

The UDF() returns True for a couple of inputs.  I want to apply DV to cell D1 using the udf() as a rule.
I am using cell E1 as my "helper".  In cell E1 I put my UDF():
=IsPrime(D1)

Next I Name my "helper" cell:

Finally, I return to cell D1 and apply the DV:


Q:

Is Current CoffeeScript Module Pattern Valid?

I have a Node.js web application that's written in CoffeeScript, which has a set of "services".  These various services are currently exposed as a CoffeeScript class, which does a few things that I like.
For one, I get a method that gets ran once as the instance of the service is started.  On some services this allows me to fetch authentication tokens, create connections, etc. that are requirements for said services.  Using CS classes also allows me to have properties that can be referenced in the specific methods exposed to the class instance (status, helper methods, etc.)
Originally when I took over the application services were exposed similar to this:
class SchedulerService
  constructor: (@msgBus, connStr) ->
    # Some logic setting up service.
  somePublicMethod: (cb) ->
    cb()

module.exports = SchedulerService

More recently, I've taken up the habit of not exposing the class itself, but an instance of the class.
# Some code that grabs msgBus connection, dbConnStr

class SchedulerService
  constructor: (@msgBus, connStr) ->
    # Some logic setting up service.
  somePublicMethod: (cb) ->
    cb()

module.exports = new SchedulerService(msgBus, dbConnStr)

If you look at the docs these modules will be cached, allowing for these services to be required and have initialization be done once per service.
Are there any downsides to this sort of module pattern?  One thing I'd have to worry about is having the module cache invalidated, but it seems like that wouldn't likely happen under normal circumstances.
Another worry is boilerplate code to grab these common values, but I feel like that's solvable by a module whose only job is to supply these sort of arguments.
Any other things that I'm missing here?  Seems like a viable service pattern with CoffeeScript.

A:

I can think of a few reasons to expose the class and not the singleton instance.

Testability of the service
Reusability of the class
Life cycle management of service instances

If you are purposefully hiding the class constructor, how can you ever write unit tests that exercise only its code and none of its dependencies (its constructor arguments). You have just removed the ability to mock out it's depencies and test the class in isolation.
If the class is not meant to be part of a public API, reusability isn't much of an issue as you can always change the code later. However, structuring your code for reusability upfront costs very little and has the potential to save you a lot of work down the road if your singleton pattern doesn't work for some class of problems.
My third point is less common, but should you ever want services instances to be created and managed in the context of something like a database connection it becomes more important. Managing the resource creation/cleanup life cycle becomes a lot easier when you can encapsulate the concept in its own little box.


Q:

How many distributions of $18$ different objects into $3$ different boxes.

How many distributions of $18$ different objects into $3$ different boxes are there with twice as many objects in one box as in the other two combined$?$
Soln:
It appears to me as an arrangement problem with repetition of some sort.  As such I did this:  $$\binom{3}{1} \frac{18!}{(2n)! n! n! }$$
i did $\binom{3}{1}$ to account for the fact any of the $3$ boxes could get the double amount.  $\frac{18!}{(2n)! n! n! }$ was done partially because I have seen a formula relating to this sort of problem,  but personally I am trying to understand the REASON behind why this formula works here, that is if my treatment was correct

A:

Here are two ways to think about this problem:
1) You have 18 objects, you need to choose 12 (see my comment) to put in the first bag. You can do this in ${18 \choose 12}$ ways. You then need to take the remaining 6 objects and put $n$ of them in the second bag. This can be done in ${6 \choose n}$ ways. The total is therefore:
$${18 \choose 12}\times{6 \choose n}=\frac{18!}{12!6!}\times\frac{6!}{n!(6-n)!}=\frac{18!}{12!n!(6-n)!}$$
2) You imagine the balls are numbered from 1 to 18 and each bag has a letter on it: A, B, C. You now want 12 balls corresponding to A, $n$ balls corresponding to B and $6-n$ balls corresponding to C. This is the same as rearranging the 12 copies of an object A, $n$ copies of an object B and $6-n$ copies of an object C. There are $18!$ ways to arrange these objects. However due to the repeats we need to divide by $12!$ to account for interchanging all the object A's. Similarly divide by $n!$ to account for interchanging all the object B's and divide by $6-n$ to account for interchanging all the object C's.
$$$$
Final Note: You only need the value ${3 \choose 1}$ if the bags are somehow distinct or have an order to them. If they are identical leave out that term.


Q:

Unable to boot ARM disk image

I'd wish to reverse engineer the firmware of the Netgear R8300 - Nighthawk X8 AC5000 Smart WiFi Router / R8300 (available to download here).
I was able to extract the contents of the image using binwalk, however I'd wish to test some executable in a "live" situation. In order to do that I tried to use QEMU.
Sadly, no matter what, I'm getting a system crash.
I started with:
$ qemu-system-arm -M vexpress-a9 -hda R8300-V1.0.2.100_1.0.82.chk
Warning: Orphaned drive without device: id=scsi0-hd0,file=R8300-V1.0.2.100_1.0.82.chk,if=scsi,bus=0,unit=0
qemu: fatal: Trying to execute code outside RAM or ROM at 0x04000000

As far as I can understand QEMU has a driver but he doesn't know what do to with that.
So I tried to specify more params manually:
qemu-system-arm -M vexpress-a9 \
   -drive file=R8300-V1.0.2.100_1.0.82.chk,format=raw \
   -device scsi-hd,id=scsi0-hd0

qemu-system-arm: -device scsi-hd,id=scsi0-hd0: No 'SCSI' bus found for device 'scsi-hd'

I tried to play with some different device type, but it seems that I can't find the correct bus.
I even tried to split the image into different pieces (kernel and filesystem), but I still got a crash.
I'm pretty new to reverse engineering, can I have some hints or suggestions on what should I do to boot my firmware image?
EDIT.
Playing a little with the command I was able to get a different error message:
$ qemu-system-arm -M vexpress-a9 -cpu cortex-a9 \
   -redir tcp:8888::80 -m 512 \
   -drive file=R8300V1.0.2.100_1.0.82.chk,format=raw \
   -device scsi id=scsi0-hd0,if=ide-hd

qemu-system-arm: -device scsi: drive with bus=0, unit=0 (index=0) exists

I tried to specify a different bus, unit and index, but the error is still the same

A:

I generally try to avoid booting the whole embedded OS when analyzing a target system. Instead, try to run a single target binary with qemu-system-arm -E PATH="/bin:/usr/bin" -E OTHERENVVARS=foo -g 10000 ./myTargetBinary.
See slides 27+ in my presentation https://files.sans.org/summit/hackfest2015/PDFs/IoT-Devices-Fall-Like-Backward-Capacitors-Or-the-Month-Josh-Was-Forced-to-Wear-Pants-Josh-Wright.pdf. You may need to setup the appropriate chroot for the necessary libraries in myTargetBinary. Often, errors in running a binary requires more analysis to identify missing conf files, necessary environment variables, specific hardware access, etc., requiring some preliminary static disassembly prior to runtime analysis.


Q:

What's the right way to make digital representations of prints?

I'm mostly a film-and-paper photographer: I take pictures, process the film and then make prints in the darkroom.  The end-product of what I do is very definitely a bit of paper.
But I'd like to be able to show representations of these prints digitally (ie on the internet...).  I'd be interested in knowing what the best way to do this is, and also how it's done professionally.  I am specifically interested in digital representations of the print: things that will be displayed on a screen, not on producing physical copies of it on paper.
Obviously such a representation can never be exact – there's no way of representing things like texture of the paper surface on a screen for instance – but I want to be able to produce digital representations of my work ('my work' being 'prints') which will give people the best idea I can of what the physical object looks like.
There are three obvious approaches:

scan the neg (I can do this) and then process the digital copy of it in such a way that it looks like the print I would have made;
take a very careful photograph of the print, controlling white-balance and so on (so I get a good representation of the paper colour), and use that as the image;
scan the print with a flatbed scanner (this is a variation on the previous approach, really).

The first of these is both hard and unappealing: it requires me to do a lot of work I'm not very interested in to reproduce what I already do in the darkroom, and also may or may not do a good job of representing what the print actually looks like.
The second I can do, and it should be reasonably easy.  Keeping the prints flat is the hard bit, but I can mat them if need be.
I can't currently do the third, but I could buy a flatbed scanner if it's clearly the best approach.
I'd be interested in knowing two things.

What other people do who have the same problem but don't have access to the resources that, for instance, museums &c have?
How this is done professionally – if museums or galleries, say, want to produce web pages with good images of physical prints, how do they do this?

I appreciate that a lot of the appearance of things is down to screen calibration: I specifically don't want to address that problem: rather I'm interested in how I could make a digital representation of a print which has the best chance of being displayed well on a properly calibrated screen.

A:

Considering that you put a significant amount of work in at the darkroom printing stage then scanning the print is the best way to go.  However this can be done either by yourself using a your own scanner or by sending the originals to a company that will scan them to professional standard.  The second option I would only use if the images were to be reproduced in a published book.  A lot of this depends on what the digitized images will be used for - reproduction in a published book, your website, social media sharing, archival purposes.  If the digitized images are only ever going to be viewed on a monitor (ie. they won't be reprinted) then you only need low resolution scans of the original print.  A decent flatbed scanner should easily do the job and it shouldn't cost that much.
Personally I would scan the originals myself except for those few images that will be published in print form in which case I would consider using the services of a company to do the scanning for me.


Q:

ufw enable is not working, and it crashes my OS

Where the problems started:
First i tried to install fail2ban from the ISPmanager UI, the fail2ban was installed but i got a error related to the package coremanager-pkg-fail2ban, and the fail2ban was not working so i tried to uninstalled it using the ISPmanager UI and using the command apt-get remove coremanager-pkg-fail2ban but it said that there's no package with this name, and this error still remains:
error
I did apt-get remove fail2ban and apt-get purge auto-remove fail2ban after this i reinstalled fail2ban using the command apt-get install fail2ban and i was getting this error: failed to validate path /var/run/fail2ban too many levels of symbolic links. I searched a bit and i found this answear https://serverfault.com/a/949286/521284, what did solved my problem with the fail2ban, and now fail2ban is running on my server:
root# systemctl status fail2ban
fail2ban.service - Fail2Ban Service
    Loaded: loaded (/lib/systemd/system/fail2ban.service; enabled; vendor preset: enabled)
    Active: active (running) since Mon 2019-04-29 15:44:15 EDT; 18min ago
    Docs: man:fail2ban(1)
    Process: 293 ExecStart=/usr/bin/fail2ban-client -x start (code=exited, status=0/SUCCESS)
    Main PID: 411 (fail2ban-server)
    CGroup: /system.slice/fail2ban.service
           â””â”€411 /usr/bin/python3 /usr/bin/fail2ban-server -s /var/run/fail2ban/fail2ban.sock -p /var/run/fail2ban/fail2ban.pid -x -b

Apr 29 15:44:13 testdomain systemd[1]: Starting Fail2Ban Service...
Apr 29 15:44:14 testdomain fail2ban-client[293]: 2019-04-29 15:44:14,540 fail2ban.server [374]: INFO Starting Fail2ban v0.9.3
Apr 29 15:44:14 testdomain fail2ban-client[293]: 2019-04-29 15:44:14,541 fail2ban.server [374]: INFO Starting in daemon mode
Apr 29 15:44:15 testdomain systemd[1]: Started Fail2Ban Service.

But when i do ufw enable i get this error and my OS crashes and i need to restart the OS:
root# ufw enable
ERROR: problem running ufw-init
modprobe: ERROR: ../libkmod/libkmod.c:514 lookup_builtin_file() could not open builtin file '/lib/modules/2.6.32-042stab127.2/modules.builtin.bin'
modprobe: FATAL: Module nf_conntrack_ftp not found in directory /lib/modules/2.6.32-042stab127.2
modprobe: ERROR: ../libkmod/libkmod.c:514 lookup_builtin_file() could not open builtin file '/lib/modules/2.6.32-042stab127.2/modules.builtin.bin'
modprobe: FATAL: Module nf_nat_ftp not found in directory /lib/modules/2.6.32-042stab127.2
modprobe: ERROR: ../libkmod/libkmod.c:514 lookup_builtin_file() could not open builtin file '/lib/modules/2.6.32-042stab127.2/modules.builtin.bin'
modprobe: FATAL: Module nf_conntrack_netbios_ns not found in directory /lib/modules/2.6.32-042stab127.2
iptables-restore: line 4 failed
iptables-restore: line 77 failed
iptables-restore: line 30 failed
ip6tables-restore: line 4 failed
ip6tables-restore: line 138 failed
ip6tables-restore: line 30 failed
sysctl: permission denied on key 'net.ipv4.tcp_sack'

Problem running '/etc/ufw/before.rules'
Problem running '/etc/ufw/user.rules'
Problem running '/etc/ufw/before6.rules'
Problem running '/etc/ufw/user6.rules'

I'm tring to solve this problem with the ufw, could someone help? My ubuntu version is 16.04. And i'm using Apache2

A:

Your "virtual machine" is not a true virtual machine, but an OpenVZ "container" (and not a modern container, but an ancient pre-LXC container). OpenVZ does not permit containers to load kernel modules, which you have to do in order to use the firewall features you are trying to use. Further, the 2.6.32 based kernel which they supply is too old to use many modern Linux features anyway. It was released in 2009!
To solve the problem, get a new VPS from another provider, which does not use OpenVZ or its commercial variant Virtuozzo.


Q:

Ring Homomorphism from $\mathbb{Z}$ to a Field $F$

I have so far shown that $\phi: \mathbb{Z} \to F$ is a unique ring homomorphism if $\phi(n)=n$ and that $ker(\phi) = (n) = \{nm|m \in \mathbb{Z}\}$ with $n = 0$ or $n=p$ with $p$ a prime number. ($n$ is called the characteristic of $F$).
Now, I have to show the following two points.

If $F$ has characteristic $p \gt 0$, $\phi$ induces an injective homomorphism $\mathbb{F}_{p} \hookrightarrow F$. ($\mathbb{F}_{p}$ is a subfield of $F$).
Let $F$ be a finite field with $q$ elements. Show that $q$ is a positive power of the characteristic $p$ of $F$.

I just really have no clue how to approach these problems and would appreciate a lot if help is given. I am also not even sure what $\hookrightarrow$ means. Can anybody help? Thanks.

A:

Hint: For 1, the first isomorphism theorem for rings describes how, in general, $\phi:R \to S$ induces an injective homomorphism from $R/\ker \phi$.
For 2, note that $\Bbb F_q$ is a vector space over its subfield $\Bbb F_p$.


Q:

Linux and Windows File System?

Okay, I've somehow convinced myself to install Mint Linux (15: Olivia) beside my lovely Windows 8 operating system. Now, the only problem I have is sharing files between the two Operating Systems. What I used to have with my Windows 7 and Windows 8 install was a triple partition with the Win8 and Win7 Operating Systems in separate partitions, then another with all my files and what not. I want to have the same setup, though swapping the Win7 partition with Mint Linux, though I'm told that there are compatibility issues? Any light that can be shed on this would be absolutely wonderful, and thanks in advance!

A:

Just to set the record straight, Linux NEVER had problems reading any Windows partitions. It is Windows that cannot read Linux partitions. The compatibility problems you heard about were about NTFS. A few years ago (about 10 or so) it was slightly complicated to set up your Linux Desktop and have it write to NTFS partitions. It was always possible, it is just that the software that enables that was new and buggy and sometimes had trouble writing. As far as I know reading was never a problem.
Now, Windows, probably through a conscious marketing strategical choice, has never supported reading or writing from anything other than the native Windows file systems such as VFAT and NTFS. It is possible, but you need third party software and it is not transparent. Both Macs and Linux and Unix etc can deal with various file systems, as far as I know it is only Windows that has decided to hobble itself in such a way.
Anyway, NTFS-3G, the *nix software that enables reading and writing on NTFS partitions is now very mature and stable. So much so that it is included in the Linux kernel. What this means in practical terms is that your Linux OS can read and write to an NTFS partition out of the box, you shouldn't need to install or do anything else.
Bottom line, create a shared data partition using the NTFS file system and both Linux and Windows will happily be able to read and write from/to it.


Q:

Adding labeling expression to Custom Overlay Grid in ArcGIS Desktop?

I have a custom overlay grid whose labels are driven by an ugly attribute field which contains unnecessary leading zeroes and other labeling no-nos.
How can I introduce a labeling expression to this grid?
I am using ArcGIS 10 SP1 for Desktop.

A:

Per Esri, it is not possible at this time to incorporate a label expression with a custom overlay grid; Label expressions are not supported with grid labels.


Q:

Matplotlib wrong color scheme when plotting colorbar

I get the wrong color scheme and range when I try to plot colorbar with contourf. It works well with pcolormesh. I'm aiming to only use 1 colorbar for all the subplots
fig = plt.figure(figsize=(9,8))
gs = gridspec.GridSpec(nrows=1, ncols=3)
color = plt.get_cmap('PRGn')

ax0 = plt.subplot(gs[0, 0])
ax0.contourf(x, y, z1, cmap=color)

ax1 = plt.subplot(gs[0, 1])
ax1.contourf(x, y, z2, cmap=color)

ax2 = plt.subplot(gs[0, 2])
ax2.contourf(x, y, z3, cmap=color)

# colorbar
im = plt.gca().get_children()[0]
cax = fig.add_axes([.918, 0.175, 0.025, 0.4])
cb = fig.colorbar(im, cax=cax)

Thank you

A:

The easiest is to store the result of contourf in a variable to pass to plt.colorbar.
Note that for the 3 plots to use the same colorbar, the limits need to be the same for each. Default, vmin and vmax are set to the minimum and maximum of the given z-array. To get them equal for the 3 plots, one could set them to the global minimum and maximum.
Here is an example (using the modern way to define the subplots):
import numpy as np
import matplotlib.pyplot as plt

fig, (ax0, ax1, ax2) = plt.subplots(nrows=1, ncols=3, figsize=(9, 8))

# create some dummy data, where z1, z2 and z3 possibly have different ranges
x, y = np.meshgrid(np.linspace(0, 4, 20), np.linspace(300, 850, 20))
z1 = np.cos(x) + np.sin(y / 100)
z2 = np.cos(x) + np.sin(y / 100) + 0.2
z3 = np.cos(x) + np.sin(y / 100) + 0.5
vmin = min(z1.min(), z2.min(), z3.min())
vmax = max(z1.max(), z2.max(), z3.max())

cmap = plt.get_cmap('PRGn')
contour_z1 = ax0.contourf(x, y, z1, cmap=cmap, vmin=vmin, vmax=vmax)
contour_z2 = ax1.contourf(x, y, z2, cmap=cmap, vmin=vmin, vmax=vmax)
contour_z3 = ax2.contourf(x, y, z3, cmap=cmap, vmin=vmin, vmax=vmax)

# colorbar
cax = fig.add_axes([.918, 0.175, 0.025, 0.4])
cb = fig.colorbar(contour_z1, cax=cax)
plt.show()


Q:

Maven phantom managed dependencies

I just got into a very weird dependency issue, never saw that before.
I have a parent project which declares in dependencyManagement the version for the Netty libary:
<dependency>
    <groupId>io.netty</groupId>
    <artifactId>netty-bom</artifactId>
    <version>4.1.29.Final</version>
    <type>pom</type>
    <scope>import</scope>
</dependency>

I have submodules that declare dependencies on Netty JARs, for example:
<dependency>
    <groupId>io.netty</groupId>
    <artifactId>netty-transport</artifactId>
</dependency>

For some reason, the retained Netty version is 4.1.27.Final AND IT IS NOT MENTIONED ANYWHERE!!
I thought Eclipse may be causing the issue, so I tried with the mvn executable on command line - same thing. I thought that may be some conflict with installed POMs/JARs in my local Maven repository, so I removed the entire directory inside the higher com directory - same thing.
I have no idea what is going here - never saw such behavior from Maven.
Using Eclipse, if I look at the effective POM for my parent project, I see all the Netty dependencies with version 4.1.27.Final inside dependencyManagement. But I have no idea where it gets these dependencies from...

The parent POM (only dependencies and dependencyManagement):
<dependencies>
    <dependency>
        <groupId>commons-logging</groupId>
        <artifactId>commons-logging</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.1.3</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session-bom</artifactId>
            <version>Apple-SR1</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>${spring.boot.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>

        <!-- Apache Commons -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.8</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-csv</artifactId>
            <version>1.5</version>
        </dependency>
        <dependency>
            <groupId>commons-cli</groupId>
            <artifactId>commons-cli</artifactId>
            <version>1.4</version>
        </dependency>

        <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-java-sdk-bom</artifactId>
            <version>1.11.401</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>

        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>${c3p0.version}</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.connector.version}</version>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-bom</artifactId>
            <version>4.1.29.Final</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>

        <dependency>
            <groupId>dnsjava</groupId>
            <artifactId>dnsjava</artifactId>
            <version>2.1.8</version>
        </dependency>

        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>26.0-jre</version>
        </dependency>

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>${aspectjrt.version}</version>
        </dependency>
    </dependencies>
</dependencyManagement>

The child POM:
<dependencies>
    <!-- dependency to other child modules -->

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-logging</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-log4j2</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jetty</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-json</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-websocket</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-messaging</artifactId>
    </dependency>

    <dependency>
        <groupId>org.eclipse.jetty.websocket</groupId>
        <artifactId>websocket-client</artifactId>
    </dependency>

    <dependency>
        <groupId>io.netty</groupId>
        <artifactId>netty-transport</artifactId>
    </dependency>

    <dependency>
        <groupId>commons-cli</groupId>
        <artifactId>commons-cli</artifactId>
    </dependency>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-lang3</artifactId>
    </dependency>

    <dependency>
        <groupId>dnsjava</groupId>
        <artifactId>dnsjava</artifactId>
    </dependency>

    <dependency>
        <groupId>com.github.kenglxn.qrgen</groupId>
        <artifactId>javase</artifactId>
        <version>2.4.0</version>
    </dependency>

    <dependency>
        <groupId>com.google.guava</groupId>
        <artifactId>guava</artifactId>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
    <dependency>
        <groupId>com.mchange</groupId>
        <artifactId>c3p0</artifactId>
    </dependency>

    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
    </dependency>
</dependencies>

A:

It comes from spring-boot-dependencies which declares netty-bom too.
Perhaps changing the order helps. You may also exclude it.


Q:

How free handles null pointer

Possible Duplicates:
checking for NULL before calling free
What happens when you try to free() already freed memory in c?

Hope this isn't a totally dumb question. Anyway...
What happens when a null pointer is passed to free.
Thank you!
P.S. What about a standard compliant allocator? Thanks again!

A:

It immediately returns without doing anything.
Per 7.20.3.2, paragraph 3:

The free function causes the space pointed to by ptr to be deallocated, that is, made
  available for further allocation. If ptr is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by the calloc, malloc, or realloc function, or if the space has been deallocated by a call to free or realloc, the behavior is undeﬁned.

A:

The man page says:

free() frees the memory space pointed
  to by ptr, which must have been
  returned by a previous call to
  malloc(), calloc() or realloc().
  Otherwise, or if free(ptr) has already
  been called before, undefined
  behaviour occurs. If ptr is NULL, no
  operation is performed.


Q:

What are the meanings of metalanguage and metasyntax and EBNF?

I am trying to understand what BNF, metalanguage, and metasyntax are.
From https://proofwiki.org/wiki/Definition:Metalanguage

A metalanguage of a formal language is a formal language used to
  specify the formal language (make statements about the formal
  language).
The object language of a metalanguage is the language described by
  that metalanguage.

From https://proofwiki.org/wiki/Definition:Syntax

The syntax of a formal language is its structure, and is specified by
  a formal grammar of the formal language.

So I wonder if a formal grammar of a formal language is a
metalanguage of the formal language?
From https://proofwiki.org/wiki/Definition:Metalanguage/Metasyntax

The syntax of a metalanguage is called a metasyntax of the object
  language of that metalanguage.

From http://en.wikipedia.org/wiki/Extended_Backus–Naur_Form

Extended Backus–Naur Form (EBNF) is a family of metasyntax notations,
  any of which can be used to express a context-free grammar.

Does it mean that a context-free grammar is a metalanguage of a
context-free language, and EBNF is a syntax for the context-free grammar as a metalanguage, and therefore EBNF is a metasyntax for the context-free language as a object language?
From http://en.wikipedia.org/wiki/Metasyntax

A metasyntax describes the allowable structure and composition of
  phrases and sentences of a metalanguage, which is used to describe
  either a natural language or a computer programming language.
Some of the widely used formal metalanguages for computer languages
  are Backus–Naur Form (BNF), Extended Backus–Naur Form (EBNF), Wirth
  syntax notation (WSN), and Augmented Backus–Naur Form (ABNF).

Does it mean that EBNF is a metalanguage of a formal language, and
this formal language is a context-free grammar?

Thanks and regards!

A:

In general, informally, a metalanguage is a language used to talk
about a language, possibly to specify it or to study its properties.
For example, linguists use English to describe the English
language. As a consequence English is used as its own metalanguage.
To avoid confusion, various quoting system are used to distinguish the
two level. For example, when talking about a small animal that barks,
we use the word "dog". Here, "dog" represent a word of a language
being talked about, not any of the possible meanings of that word in
the language it belongs to. It cannot bite.
When a language A is used as metalanguage to talk about a language B,
B is called the object language. But, though sometimes used in a
formal way, this is very similar to saying that wheather is the object
of many conversations.
In computer science, a well known example is the programming language
ML. The name ML actually stand for metalanguage. ML was initially
conceived by Robin Milner as a metalanguage to develop proofs about a small language
called pplambda in the LCF theorem prover. Hence, both syntactic and
semantic properties of pplambda can be expressed in ML.
Another well known example is Lisp, a language that is its own meta
language, and has been the first programming language to have that property. Lisp programs can be syntactically represented as a Lisp
data structure. The semantics of Lisp is also expressed in Lisp, since
the first Lisp interpreter was written in Lisp.
This works so well that the feat has since be often repeated for many other
programming languages, and it is very customary to write the first
compiler of a language in the
language itself, as part of a language bootstrapping process. Hence
the language is self compiling. This requires defining both the syntax
and the semantics of the language in itself.
So, in effect, most programming languages are, or can be, a
metalanguage for themselves, and for other programming languages.
That is actually the least one can expect from languages that often
claim to have Turing power.
The concept of metalanguage often concerns a conplete object language,
whether natural language or programming language, with syntax and semantics. But it can also
concern languages in the formal language sense, which are only syntax.  A mathematical
formalism used to describe (a family of) formal languages (regular
sets, context-free, recursively enumerable, ...) is a metalanguage for
this formal language.
This is more interesting when the syntax of the metalanguage belongs to the same language
family as the formal languages it describes.  The best known example is the
BNF language (Backus-Naur Form), and its later EBNF variant. It is a
language used to write context-free (CF) grammars, thus to define
purely syntactic languages. Its own syntax is context-free, hence
describable in BNF.  Hence BNF can be syntactically its own metalanguage,
but not semantically.  But then, BNF describes only CF languages and
has no claim for Turing power.
It is to be noted that BNF has a CF syntax, but it also has
semantics. The semantics of a BNF program is precisely a CF grammar and the formal language it defines,
to which the BNF program associates no semantics. A context-free
grammar just defines a formal language, and no semantics is
associated. Hence it is wrong to consider that BNF is a CF
grammar.  BNF has a CF grammar which defines its syntax.
Answering your questions
Regarding the two preliminary quotes. They are expressed in the
context of formal systems, and "formal" means mathematically defined,
which may include both syntax and semantics for the language. It does
not contradict the above discussion, but rather confirms it.

A formal grammar of a formal language is not a metalanguage of
the formal language. The mathematical formalism used to write the
grammar is in this case the metalanguage.
The quote goes into an issue that I did not address here, that of the
structure that a syntax definition can attach to the strings of a
formal language. It is, as far as I see, quite unrelated to the
concept of metalanguage, when we talk of formal languages in the
formal language theory sense. Two different syntactic definitions can
produce the same language, when considering only the string it
defines for the language. But these definitions implicitly associate
diffrerent structures with the string (such as parse-trees in the context-free
case) and that can be important.
When the formal language is actually the syntax of a complete
language that also has semantics, the structure is important as it is
usually organizing the definition of the semantics, which is the
purpose of many metalanguages.
As written above, a context-free grammar cannot be a metalanguage
since it has no semantics. The formalism used to write the CF grammar
is a metalanguage for the purely syntactic formal language defined by
this CF grammar. EBNF is a language with both syntax and semantics.
A program  (or whatever you want to call it: text, description,
grammar, ...) written in EBNF is a text using the syntax of
EBNF. This text has a meaning, defined by the semantics of EBNF,
which is the CF grammar it describes. EBNF is not a metasyntax, but a
meta language for syntax.
This calls for more precision. I consider that the word metasyntax is
just shorthand for the expression "syntax of [a/the] metalanguage". I
do not ses what other meaning it could have.
The first quote is just nonsense to me. The second quote is poorly
phrased and should rather be (if I understand the intent):

Extended Backus-Naur Form (EBNF) is a family of metalanguages for
  defining syntax, any of which can be used to express a context-free
  grammar.

The quote (out of its context) is in agreement with what I said so
far. The expression "formal metalanguage" is not to be understood as
formal language in the formal language theory sense, but as a
language with a formally, i.e., mathematically, defined syntax and
semantics.
This quote alone just say that EBNF is a widely used metalanguage for
computer languages, but without being more precise about it.
Actually, according to me, EBNF is a metalanguage for (more than one)
formal languages in the formal language theory sense, since it can
only talk about the syntax, and pure syntax without semantics may be
seen as such a formal language. But these formal languages are those
described by the grammars expressed in EBNF. A grammar itself is not
a language, but it may be part of a language seen as a global object of study, since it can describe its syntax.

I hope this clarifies things.


Q:

Are ideas real?

If I have the idea of an "apple" or its taste,

is the idea as real as the apple itself?

Specifically

do the objects of the 6th consciousness depend on anything except the 6th consciousness?

In normal philosophical terms

does the idea depend on the mind having the idea, in order to exist?

I think these are all equivalent questions, because causation is the conventional truth - ideas, the ultimate - no causation, and the middle - the buddha nature or mind-body.

A:

The illusion (AtthaPaññatti;UpādāyaPaññatti) and the name (NāmaPaññatti) are not real, never arise. I think they are called "Conceptual (Paññati)" in english, right?
Everything is Paññatti which imagine by mind, not real. except arisable 5 aggregates which depending on various origins each time and Nibbāna which never arise and not depending on anything. The mind uses them to imagine Paññatti.
The real is  each arisable element in 5 aggregates which mind using to create illusion and name. Even if we talking about the 5 aggregates which possible to arise in the future, this 5 aggregates is real as well. Opposite, the 5 aggregates which being not arisable, is NāmaPaññatti instead.
Each arisable element (both Nāmas and Rūpas) are depending on various origin to really arise.
So, the Buddhā said in SN SaṅkhataLakkhaṇaSutta:

Sankhatalakhaṇasuttaṃ –– The signs of a compounded

Bhikkhus, these three are the signs of a compounded. What three? The arising is evident, the fading is evident and the change is evident. Bhikkhus, these three are the signs of a compounded.

Nibbāna is real because it is the opposite of ariseable clinging 5 aggregates. no one can finish 5 aggregates while everyone are knowing Paññatti everyday. Only Nibbāna can finish 5 aggregates after one knows it.
Another, the special illusion is used in the concentration meditation to avoid 5 strings. This is like a stable brighter and brighter light which appear only at mind door only. This is the way to get out of 5 strings in CittaVisuddhi (mind purification).
See AbhidhammatthaSaṅgaha chapter 8 Paññatti.


Q:

Angular2- Is it possible to include an library without a typing file?

I am working on a google-maps app with angular 2 now I made this earlier in vanilla javascript. But there I use libraries as RichMarkers and infoBox, now my question is, is it possible to include these without using a typing file (because there aren't yet) I tried the infoBubble from definetlyTyped, but it is not matching with the angular2-google-maps so it throws me errors.
Does anybody know how to include a library without a typing file is this possible?
This is my component code:
import {Component, Directive} from '@angular/core';
import {GoogleMapsAPIWrapper} from 'angular2-google-maps/core';

declare var fontawesome:any;
declare var RichMarker:any;
declare var RichMarkerPosition:any;
declare var google:any;

@Component({
    selector: 'poly-layer',
    template: '

'
})
export class PolyLayer {
    constructor(private _wrapper: GoogleMapsAPIWrapper) {
        this._wrapper.getMap().then((map) => {

            var myLatLng = new google.maps.LatLng(-25.363882, 131.044922);
            var marker_html = '

'+ 'number' + '

';

            var marker = new RichMarker({
                position: myLatLng,
                map: map,
                flat: true,
                anchor: RichMarkerPosition.MIDDLE,
                content: marker_html
            });

            marker.setMap(map);
        });
    }
}

Where google is not defined in the index of richmarker: RichMarker.prototype = new google.maps.OverlayView();
How do I define this ?
Here a PLUNKER

A:

You can use declare foo; to tell the TS compiler that it safely can assume foo exists and it won't produce an error if your code refers to foo.


Q:

Is an unload event handler guaranteed to finish execution before the loading of the next page wipes it out?

I'm trying to figure out how the unload event works. I'm using a $(window).unload() handler to send a list of several custom values to my analytics service when the user moves to another page. I make a separate API call to the service for each value.
I'm just wondering if I can rely on my handler running every time till it's finished, or if there'll be some occasions when the loading of the next page's JavaScript will interrupt it before it can register all the values in the list.
The jQuery documentation on .unload() says "It is not possible to cancel the unload event with .preventDefault()." To me this implies that after the browser starts executing your unload handler there's no way to hold it back from loading, parsing and executing the JS of the new page.
But the MDN page on the window.onunload event says "The resources removal is processed after the unload event occurs."
So does this mean the browser runs a page's unload function till it's finished, and only then scraps it to load the next page's JS?

A:

MDN seems to have multiple versions in their site. Here's another one about unload which describes the state of the document during unload.

unload
The unload event is fired when the document or a child resource is being unloaded.
It is fired after:

beforeunload (cancellable event)
pagehide

The document is in a particular state:

all the resources still exist (img, iframe etc.)
nothing is visible anymore to the end user
UI interactions are ineffective (window.open, alert, confirm etc.)
an error won't stop the unloading workflow

As far as I know, async requests (ajax) could possibly be fired but not guaranteed that they will arrive on the server or even get off the browser.

In the context with one of your tags (analytics), it seems like you are trying to know when the user leaves the page.

Why not do a heartbeat/regular ping to the server? The last known ping could be used as an estimate of when the user was last seen on that page.

Or store the time the user left the page inside a cookie, like some sort of "pending report". This can be executed inside unload. The next time your script meets the cookie, have it parsed for the pending data and send it to the server.


Q:

Unable to change the value of foreign key to foreign key of an object Django

I am having a model structure like:
class user(models.Model):
    name = models.CharField(max_length=100)
    tasks = models.IntegerField(default=0)

class project(models.Model):
    worker = models.ForeignKey(user, on_delete=models.CASCADE)
    project_name = models.CharField(max_length=100)

class task(models.Model):
    project = models.ForeignKey(project, on_delete=models.CASCADE)
    task_name = models.CharField(max_length=150)
    expected_date = models.DateField(auto_now=False,auto_now_add=False,)
    actual_date = models.DateField(auto_now=False,auto_now_add=False,blank=True,null=True,)

I want to traverse through the task list and if actual date field is not null i.e. task completed then to update the tasks field in user class by 1. I have written the following code:
a = task.objects.filter(actual_date__isnull=False)
for x in a:
    x.project.worker.tasks+=1

However this is not giving the desired result. What should I do?

A:

You are not saving your object after modifying it - simply modifying the value doesn't write it to the database. Try this instead:
a = task.objects.filter(actual_date__isnull=False)
for x in a:
    worker = x.project.worker
    worker.tasks += 1
    worker.save()

On a separate note you should consider following PEP8 conventions and using CamelCase for your class names. As it is currently you can very easily mix up classes with objects.


Q:

Are there specific organizational processes or tools (not necessarily software) that can help in developing and structuring research ideas?

I am doing research in computer Science as a PhD student. I have some research ideas and for months I've been continuously thinking about them, developing them and make them more specific. I mean, these ideas continually change until one day they are finalized. Over time they are more specific and complex.
I use Evernote to write down my ideas, and sometimes maybe also brainstorm mapping tools like Mindmeister. But I found these tools are not good enough, e.g. not easy to structurize my ideas, or modify, elaborate them, in a word, manage my ideas.
Do you have any good methods or tools for the organization/management of your developing research ideas? How do professors and professional scholars and researchers deal with this issue?

A:

May I recommend Org mode? It's free software, and it was created by Carsten Dominik, an academic himself. Its focus is to help you maintain hierarchical notes and to-do lists, but it has a lot of other features that are useful for juggling large amounts of information, such as tags, links, many kinds of summary reports, and capture (a way to quickly add a note in the right place before you forget it), as well as many features useful for scientists in particular, like tables, spreadsheets, mathematical notation, export (as papers, slideshows, or websites), and support for source code and reproducible research. Perhaps best of all, Org documents are text files, so you can munge them with standard Unix tools at whim. I've moved more and more of my workflow to Org since I started using it in 2010, and I regret nothing.
Org has a steep learning curve, which gets steeper if you aren't already a disciple of the Church of Emacs. But as I see it, getting used to Emacs is worth it even without Org mode, especially if you do a lot of programming. I was an Emacs zealot for years before I took up Org.

A:

Anytime I get a chance, I try to use the productivity applications. These may be associated with time management or structuring ideas etc. I found out that there is no best way to do this. Every application has some heuristics behind, and these are mostly decided by the developers. Sometimes an app may seem to solve your problem, but later you may realize that it is not what you want or need. In my opinion, you need to come up with your own way to do it. However, let me list some ways/advices I encounter:

Open a google document. Write down your ideas as a list. If you need
to structure them, nest the list items. Go over the document
periodically.
Take a look at wunderlist. They have done a good
job task/note management. wunderlist 2 has just released with new features.
Trello is another example. It may seem
to be an project management tool, but you can use for managing your
ideas on a whiteboard-style.
Springpad is another way to    save/organize things online.
Your example Evernote, and others    like do.com,
todoist can be listed also. If you really need    to find the
right application you need to search hard. Take a look at here as well.
Mindmup is a online mind mapping tool.
Hiro is another newly released tool. Try it here.

For me, the best way is to keep a small notebook and write down what I have done in terms of research day by day. I also note the ideas for my thesis. After some point, when you go back and check your progress, you would be amazed how much things changed and become more mature. But the most important thing is that I realized what is best for me is to grep a pen and write down it on a paper rather than some website.

A:

Aibase has the option to put formulas, mind-maps, bullet points lists, diagrams, sketches, to-do list in ONE document, basically a hybrid software (Evernote + MindMapping) for creative project managment. Best software I ever bought for knowledge and project management

I explained the software here more in detail


Q:

Am I to use like or unlike here?

He is not fond of sweets, like his brother.
He is not fond of sweets, unlike his brother.

My situation is:
His brother is fond of sweets but he is not.

To make this sense, which one from the pair of sentences at the top do I use? What would the other sentence of the pair mean anyway?
I think leaving out the comma in the first sentence has a different meaning from that with comma.
Edit
Does leaving out the comma in the first sentence mean anything different? If it does, what would be the meanings with and without the comma?

A:

Good Question.
The second sentence is right, in this case.
Like - It means ' similar to '.

He is not fond of sweets, like his brother.

Here, he and his brother are not fond of sweets.
Unlike - when using to contrast somebody or something with another person or thing.

He is not fond of sweets, unlike his brother.

Here, he is not fond of sweets but his brother is fond of sweets.

A:

He is not fond of sweets like his brother.

Without the comma, this sentence could be read as either:
[He is not] [fond of sweets] [like his brother.] (who is fond of sweets)
or
[He is] [not fond of sweets] [like his brother.] (who is also not fond of sweets)
or as User1986 has pointed out
[He is not fond of] [sweets like his brother]. (who is a gingerbread man maybe?)
The third interpretation doesn't make much sense in the limited context we have, but it does demonstrate how ambiguous a sentence without commas can be. The punctuation resolves the ambiguity by making the first part of the sentence one thought:
[He is not fond of sweets,] [(like/unlike) his brother].
In the sentence with the comma, if you use like, his brother has similar taste and is also not fond of sweets. If you use unlike, his brother is different and is fond of sweets. So, for your situation, you would use unlike.


Q:

How can I test an internal method inside a component in React?

I am trying to test spy a method used inside a React component but I am failing. The component is the below :
export class SiderMenu extends PureComponent {

formatter(data, parentPath = '', parentAuthority) {
  return data.map((item) => {
  const result = {
    ...item,
    path: `${parentPath}${item.path}`,
  };
  return result;
});
}
constructor(props) {
  super(props);
  this.menus = this.formatter(props.menuData);
}
render(....)
}

I am using enzyme and I want to test that the formatter method has been called:
describe.only('SiderMenu.formatter', () => {
  it('Expect to have been called', () => {
  // const spy = jest.spyOn(SiderMenu.prototype, 'formatter');
  const wrapper = shallow(<SiderMenu />);
  const instance = wrapper.instance();
  const method = jest.spyOn(instance, 'formatter');
  expect(method).toHaveBeenCalled();
  });
 });

I tried also to spy the method using the prototype of the component but I constantly taking the below error

TypeError: Cannot read property '_isMockFunction' of undefined

This error is created by the 'jest.spyOn(instance, 'formatter');'. Can someone help me out about this ? How can I test that formatter method has been called ?

A:

The following works perfectly fine for me:
describe.only('SiderMenu.formatter', () => {
  it('Expect to have been called', () => {
    const spy = jest.spyOn(SiderMenu.prototype, 'formatter');
    const wrapper = shallow(<SiderMenu menuData={[{ path: 'foo' }]} />);
    const instance = wrapper.instance();

    expect(spy).toHaveBeenCalled();
  });
});

Make sure you are passing some menuData so that the component doesn't blow up when it tries to map over undefined. There are some gotchas with getting this to work (such as using class properties), but you've avoided them here. For more info, see this GitHub issue.


Q:

Dropwdown nav / sorting dd in same aligment as button

I'm playing with dropdown menus in CSS and I run into some troubles.
I wish to make dropdown boxes be in same line as button you click to open dd.
This is CSS code:
/* for all */
* {
    margin: 0;
    border: 0;
    padding: 0;
}

/* style in first box */
#a1 {
    display: block;
    background-color: lightblue;
    height: 300px;
}

h1 {
    text-align: center;
    padding: 25px;
    font-size: 6em;
    font-family: Shrikhand;
    color: white;
    text-shadow: 5px 5px #000000;
}

/* style in second box */
#a2 {
    display: block;
    background-color: lightyellow;
    height: 300px;
}

#mbar {
    width: 100%;
    height: 50px;
    background-color: gray;
}

.li {
    height: 20px;
    float: left;
    padding: 15px;
    text-decoration: none;
    list- style: none;
    background-color: lightgray;
    border-left: 1px solid black;
}

.li2 {
    height: 20px;
    padding: 15px;
    text-decoration: none;
    list-style: none;
    background-color: lightgray;
    display: none;
    width: 130.981px;
}

.dd {
    width: 130.981px;
}

    .dd:hover .li2 {
        display: block;
    }

Here is HTML code:

index

gallery

                dropdown

dropdown1

dropdown2

contact

This is the link to codepen
Anyway if you click on dropdown button you will see that dropdown nav is out of aligment with dropdown button.

A:

you need to play it with positions: demo
short answer is :
.dd {
 position: relative;
}

.dd ul {
 position: absolute;
 left: 0;
 top: 50px;
}


Q:

jQuery get all descendant nodes including text nodes

Is there a way in jQuery to get all descendant nodes of a parent node, including text nodes, recursively? I know the $.contents() method, but as the jQuery documentation states:

the .contents() method allows us to search through the immediate children of these elements in the DOM tree

My problem is, that I have a child node that contains more (non-text) nodes, and I need instead of just the parent.
I am trying some workaround now:
var contents = container.contents();
var foo = $('.foo');
var index = contents.index(foo);
contents.splice(index,1,$('.foo').contents());

...but this inserts the array instead of the individual elements. My final step would be pushing the elements to the contents array one by bone, but I'd like to know if there is a better way to do this.

A:

I don't really understand what you are trying to do but in order to get all descendant nodes of a certain element you may use the following:
var nodes = $('*', container).addBack().contents();

DEMO: http://jsfiddle.net/5vfBg/


Q:

Custom Cell not resizing UILabel's

I'm designing a custom cell on my storyboard and it's not resizing my labels according to its text's size. I'm using this code:
- (void)awakeFromNib {
    titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
    titleLabel.numberOfLines = 0;
    [titleLabel sizeToFit];
    //[titleLabel setBackgroundColor:[UIColor grayColor]]; -- I put this code here just to be sure that awake from nib is working
}

Should I implement something else?
Regards!

A:

You should call sizeToFit in layoutSubviews method.


Q:

Text color in TextViews of ListView setted by selector works only in "normal" state

I create ListView and my own ListAdapter. I use simple_list_item_2. I want to change color of text for each state. There is code of dark.xml below:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_selected="true" android:color="@color/selectedTextListColor"/>
    <item android:state_focused="true" android:color="@color/selectedTextListColor"/>
    <item android:state_pressed="true" android:color="@color/selectedTextListColor"/>
    <item android:color="@color/textListColor"/>
</selector>

Next it is part of code when I try to set that functionality. I think there is a problem.
ArrayAdapter<Element> adapter = new ArrayAdapter<Element>(instance, android.R.layout.simple_list_item_2, songsArray){

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        TwoLineListItem row;

        if (convertView == null) {
             LayoutInflater inflater = (LayoutInflater)getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
             row = (TwoLineListItem)inflater.inflate(android.R.layout.simple_list_item_2, null);

             } else {
             row = (TwoLineListItem)convertView;

                        }

        Element song = songsArray[position];
        String data = song.text();

        int dashIndex = data.indexOf("-");

        TextView text2 = row.getText2();
        text2.setText(data.substring(0, dashIndex-1).trim());
        text2.setTextSize(12.0f);
        text2.setPadding(10, text2.getPaddingTop(), text2.getPaddingRight(), text2.getPaddingBottom());

        TextView text1 = row.getText1();
        text1.setText(data.substring(dashIndex+1).trim());
        text1.setTextSize(18.0f);
        text1.setPadding(10, text1.getPaddingTop(), text1.getPaddingRight(), text1.getPaddingBottom());

        text1.setTextColor(getResources().getColor(R.color.dark));

        return row;
    }

};

It still works in such a way, that text has color red and it didn't change on press. Could you tell correct way? Pay attention on line
text1.setTextColor(getResources().getColor(R.color.dark));

I think there is my mistake.

A:

text1.setTextColor(getResources().getColorStateList(R.color.dark));

That was my problem. Now it works great.


Q:

Scrapy FormRequest parameter not working but showing all result instead

I am scraping this webpage https://researchgrant.gov.sg/eservices/advanced-search/?keyword=&source=sharepoint&type=project&status=open&_pp_projectstatus=&_pp_hiname=&_pp_piname=&_pp_source=sharepoint&_pp_details=#project using Scrapy FormRequest. My code is as below. The parameter _pp_hiname with ab and _pp_piname with pua should only return 1 result in response.text but instead it returns all the result in HTML code. Parameter apparently not working but I couldn't see any wrong with it.
def start_requests(self):
    params = {
        'keyword': '',
        'source': 'sharepoint',
        'type': 'project',
        'status': 'open',
        'page': '1',
        '_pp_projectstatus': '',
        '_pp_hiname': 'ab',
        '_pp_piname': 'pua',
        '_pp_source': '',
        '_pp_details': '',
        'name':'advancesearchawardedprojectsp'
    }
    yield scrapy.FormRequest('https://researchgrant.gov.sg/eservices/mvcgrid',callback=self.parse_item,method='POST',formdata=params,headers = {'X-Requested-With':'XMLHttpRequest'})

def parse_item(self,response):
    print(response.text)

Should be only 1 entry:

But apparently it is showing all entry:

Latest update:
class ToScrapeCSSSpiderSG(scrapy.Spider):
name = "toscrapesg-css"
# start_urls = [
    # 'https://researchgrant.gov.sg/eservices/mvcgrid',
# ]
params = {
    'name':'advancesearchawardedprojectsp'
    }
args = {
        'keyword': '',
        'source': 'sharepoint',
        'type': 'project',
        'status': 'open',
        'page': 1,
        '_pp_projectstatus': '',
        '_pp_hiname': 'ab',
        '_pp_piname': '',
        '_pp_source': '',
        '_pp_details': '',
        'name':'advancesearchawardedprojectsp'
    }
def start_requests(self):
    args = urllib.parse.urlencode(self.args)
    url = 'https://researchgrant.gov.sg/eservices/mvcgrid?' + args
    yield scrapy.FormRequest(url,callback=self.parse_item,method='POST',formdata=self.params,headers = {'X-Requested-With':'XMLHttpRequest'})

def parse_item(self,response):
    args = urllib.parse.urlencode(self.args)
    url = 'https://researchgrant.gov.sg/eservices/mvcgrid?' + args
    for quote in response.xpath('//div[contains(@style,"overflow-x:auto")]'):
        for row in quote.xpath('./table[contains(@class,"table-striped")]/tbody/tr'):
            link=row.xpath('td[1]/a/@href').extract_first()
            yield scrapy.FormRequest(link,callback = self.parse_product,method='GET')

    onclick = response.xpath('//a[@aria-label="Next page"]/@onclick').get()
    if onclick:
        self.args['page'] += 1
        args = urllib.parse.urlencode(self.args)
        url = 'https://researchgrant.gov.sg/eservices/mvcgrid?' + args
        yield scrapy.FormRequest(url, callback=self.parse_item, method='POST', formdata=self.params, headers = {'X-Requested-With': 'XMLHttpRequest'})

def parse_product(self,response):
        text = response.xpath('//span[contains(@id,"ctl00_ctl47_g_b43c0a74_fae0_498f_b75e_c103772db011_ctl00_lblProjectTitle")]/text()').extract()
        # text = info.xpath('./text()').extract()
        print(text)

Console message:

A:

It sends in POST body only Name=advancesearchawardedprojectsp. Other parameters should be in url as query.
So url should be
https://researchgrant.gov.sg/eservices/mvcgrid?keyword=&source=sharepoint&type=project&status=open&page=1&_pp_projectstatus=&_pp_hiname=ab&_pp_piname=pua&_pp_source=&_pp_details
You can use urllib.parse.urlencode(args) for this.
And it gives me one result.
import urllib.parse

def start_requests(self):

    params = {
        'name':'advancesearchawardedprojectsp'
    }

    args = {
        'keyword': '',
        'source': 'sharepoint',
        'type': 'project',
        'status': 'open',
        'page': '1',
        '_pp_projectstatus': '',
        '_pp_hiname': 'ab',
        '_pp_piname': 'pua',
        '_pp_source': '',
        '_pp_details': '',
    }

    args = urllib.parse.urlencode(args)

    url = 'https://researchgrant.gov.sg/eservices/mvcgrid?' + args

    yield scrapy.FormRequest(url, callback=self.parse_item,method='POST',formdata=params,headers = {'X-Requested-With':'XMLHttpRequest'})

EDIT: example which loads next pages and check button Next Page to stop.
EDIT: now it can save in csv file.
import scrapy
import urllib.parse

class MySpider(scrapy.Spider):

    name = 'myspider'
    #allowed_domains = []

    params = {
        'name': 'advancesearchawardedprojectsp'
    }

    args = {
        'keyword': '',
        'source': 'sharepoint',
        'type': 'project',
        'status': 'open',
        'page': 1,
        '_pp_projectstatus': '',

        #'_pp_hiname': 'tan',
        #'_pp_piname': '',
        '_pp_hiname': 'ab',
        '_pp_piname': '', #'pua',

        '_pp_source': '',
        '_pp_details': '',
    }

    def start_requests(self):

        # create request for first page
        args = urllib.parse.urlencode(self.args)

        url = 'https://researchgrant.gov.sg/eservices/mvcgrid?' + args

        yield scrapy.FormRequest(url, callback=self.parse_item, method='POST', formdata=self.params, headers={'X-Requested-With': 'XMLHttpRequest'})

    def parse_item(self,response):
        #print('parse_item] url:', response.url)
        #print('parse_item] text:', response.text)

        #for quote in response.xpath('//div[contains(@style,"overflow-x:auto")]'):
        #    for row in quote.xpath('./table[contains(@class,"table-striped")]/tbody/tr'):
        #        link = row.xpath('td[1]/a/@href').extract_first()
        #        yield scrapy.Request(link, callback=self.parse_product)

        for row in response.xpath('//table[@name="MVCGridTable_advancesearchawardedprojectsp"]/tbody/tr'):
            link = row.xpath('.//a/@href').get()
            #title = row.xpath('.//a/text()').get()
            yield scrapy.Request(link, callback=self.parse_product)

        # create request for next page
        onclick = response.xpath('//a[@aria-label="Next page"]/@onclick').get()

        if onclick:
            # next page
            self.args['page'] += 1
            args = urllib.parse.urlencode(self.args)
            url = 'https://researchgrant.gov.sg/eservices/mvcgrid?' + args
            yield scrapy.FormRequest(url, callback=self.parse_item, method='POST', formdata=self.params, headers={'X-Requested-With': 'XMLHttpRequest'})

    def parse_product(self, response):
        #print('parse_product] url:', response.url)

        # .extract_first() or .get() instead of .extract()
        project_id = response.xpath('//span[@id="ctl00_ctl47_g_b43c0a74_fae0_498f_b75e_c103772db011_ctl00_lblProjIdExt"]/text()').get()
        title = response.xpath('//span[@id="ctl00_ctl47_g_b43c0a74_fae0_498f_b75e_c103772db011_ctl00_lblProjectTitle"]/text()').get()
        pi = response.xpath('//span[@id="ctl00_ctl47_g_b43c0a74_fae0_498f_b75e_c103772db011_ctl00_lblLeadPIName"]/text()').get()
        hi = response.xpath('//span[@id="ctl00_ctl47_g_b43c0a74_fae0_498f_b75e_c103772db011_ctl00_lblHostInstName"]/text()').get()
        date = response.xpath('//span[@id="ctl00_ctl47_g_b43c0a74_fae0_498f_b75e_c103772db011_ctl00_dtPickerStartDate"]/text()').get()
        # etc.

        item = {
            'id': project_id,
            'title': title,
            'pi': pi,
            'hi': hi,
            'date': date,
        }

        yield item

# --- run without project and save in `output.csv` ---

from scrapy.crawler import CrawlerProcess

c = CrawlerProcess({
    'USER_AGENT': 'Mozilla/5.0',
    # save in file CSV, JSON or XML
    'FEED_FORMAT': 'csv',     # csv, json, xml
    'FEED_URI': 'output.csv', #
})
c.crawl(MySpider)
c.start()


Q:

Exclude Element From CSS Class In Div

Is it possible to not apply a css class to a specific element in the class?
For example:

LinkedIn

Please follow my LinkedIn account to get updated on my experiences and skills and join my network!

In this code I would like to exclude the img tag from the container class so the CSS isn't applied to that element. I know I could just make two separate divs of the same class and put the anchor tag in the middle but I want to know if I can do this programmatically.

A:

    div.dummy  :not(a):not(img) {
      background: black;
      color: white;
      font - size: 20 px;
      width:100%;
      height:50px;
      position:relative;
    }

LinkedIn

Please follow my LinkedIn account to get updated on my experiences and skills and join my network!

You can see in the above demo that except img tag, all are getting affected.
Try using :not selector
Read here consulting can i use
else have a particular css for the img overriding any css you want.

A:

The`:not(selector) selector matches every element that is NOT the specified element/selector.
:not(.container>img) {
       background-color: blue;
       //your css here
    }


Q:

Is there a minimum damage rule?

In D&D3e, if you successfully hit a target you always did at least 1 point of damage (before applying Damage Resistance), even if you had a Strength penalty.  I can't find any mention of that rule in the 5e PHB.  Does the rule no longer apply, or did I just overlook it?

A:

It is correct to say the 3.5e rule no longer appears in 5e. Another tweet (god I wish we had that back in the 90s) clarifies that the minimum is indeed 0.

JeremyCrawford
@JeremyECrawford
  There is not a damage minimum of 1, so it is possible to deal 0 damage with an attack.

Jack Abrasion
@jackAbrasion
    @JeremyECrawford Do attacks do a minimum 1 point of damage, or would an unarmed strike from a goblin (STR -1) do 0 damage?

8:56 AM - 11 Jun 2015

A:

There is no such rule in 5e.
An unarmed strike by someone (other than a monk or tavern brawler) with less than 10 strength will never do any damage, (even on a crit), for example.


Q:

Why is it customary to put many closing parentheses on one line in Lisp-based languages?

Usually code looks like this:
(one-thing
    (another-thing arg1 (f arg5 r))
    (another-thing arg1 (f arg5 r)))

Why doesn't it like this?:
(one-thing
    (another-thing arg1 (f arg5 r))
    (another-thing arg1 (f arg5 r))
)

It allows adding and removing "another-thing" lines more easily (without removing and re-adding trailing closing parenthesis). Also you can put a some comment on that lone closing parenthesis (such as "; end of the loop").
How bad is it when I mix by code that uses the second style with existing code that uses the first style?

A:

In Lisp and other languages that use S-expressions for syntax, the parentheses are primarily for the benefit of the compiler, while layout and indentation (which are ignored by the compiler) are for the benefit of programmers.
So there is no need to put closing parentheses on their own lines: well-chosen line breaks and indentation will be sufficient to make the structure clear.
For example,
(defun clone-indirect-buffer-other-window (newname display-flag &optional norecord)
  "Like `clone-indirect-buffer' but display in another window."
  (interactive
   (progn
     (if (get major-mode 'no-clone-indirect)
         (error "Cannot indirectly clone a buffer in %s mode" mode-name))
     (list (if current-prefix-arg
               (read-buffer "Name of indirect buffer: " (current-buffer)))
           t)))
  (let ((pop-up-windows t))
    (clone-indirect-buffer newname display-flag norecord)))

The structure is clear (to a moderately experienced Lisp programmer) from the indentation. Nothing would be added by bringing some of the closing parentheses down onto new lines:
(defun clone-indirect-buffer-other-window (newname display-flag &optional norecord)
  "Like `clone-indirect-buffer' but display in another window."
  (interactive
   (progn
     (if (get major-mode 'no-clone-indirect)
         (error "Cannot indirectly clone a buffer in %s mode" mode-name)
       )
     (list (if current-prefix-arg
               (read-buffer "Name of indirect buffer: " (current-buffer))
             )
           t)
     )
   )
  (let ((pop-up-windows t))
    (clone-indirect-buffer newname display-flag norecord)
    )
  )

I should add that nearly all Lisp programmers use an editor that displays matching parentheses, performs automatic indentation, and provides a user interface for working direcly with balanced expressions.  In Emacs, for example, there's M-( for inserting a new expression, M-) for moving past the end of the current expression, C-M-k for deleting the expression after point, and so on.
So Lisp programmers never have to count parentheses by hand in order to figure out which ones match.

Taylor R. Campbell eloquently expresses this rationale:

The actual bracket characters are simply lexical tokens to which little significance should be assigned.  Lisp programmers do not examine the brackets individually, or, Azathoth forbid, count brackets; instead they view the higher-level structures expressed in the program, especially as presented by the indentation.  Lisp is not about writing a sequence of serial instructions; it is about building complex structures by summing parts.  The composition of complex structures from parts is the focus of Lisp programs, and it should be readily apparent from the Lisp code.  Placing brackets haphazardly about the presentation is jarring to a Lisp programmer, who otherwise would not even have seen them for the most part.

A:

There are two points to be made here:

Conventions are important in themselves. Sticking to wrapped parens means your code is more readable by other lisp programmers, and if you adopt this style you will also develop practice at reading theirs
The advantages of splitting )s onto their own lines are not actually advantages in the eyes of most lispers.  If you are using a half-decent editor it will have commands that understand balanced expressions, for moving across them, cutting, pasting, transposing, etc.  So you don't need
)  ; end of the loop

in lisp any more than you need
# end of the loop

in some whitespace-sensitive language like Python

See e.g. http://www.gnu.org/software/emacs/manual/html_node/emacs/Expressions.html

A:

Short answer: Deviating from recognized standards only serves to alienate potential contributors.  No one style is optimally better than another.
Long answer: http://blog.fogus.me/2010/08/30/community-standards/


Q:

Remove Shutdown, Suspend, Restart, and Hibernate from the user switcher menu

I'm using a desktop as both a router for my local network and as a normal desktop with multiple users. I have Maverick running on it. Occasionally, one of the desktop users will accidentally press Shutdown, Restart, Suspend, or Hibernate, leading to me having to fix the network at random times of day. I know how to restart and shutdown from the command line. I do not need the GUI interface.
How can I remove the Shutdown, Suspend, Restart, and Hibernate options form the user switcher menu? All the I want left is the "Lock Screen", "Guest Session", List of users and "Logout" left.
A system wide solution would be best, but I can do one on each user if necessary.

A:

Option 1:
Install gconf-editor, run gksu gconf-editor and on /apps/indicator-session/ supress the restart and shutdown.
I'm not sure about suspend and hibernate, maybe changing <allow_active> to no on /usr/share/polkit-1/actions/org.freedesktop.upower.policy will do the trick.

Option 2:
Remove the Indicator session package and add desktop shortcuts to logout and locking the screen.
The command to logout is gnome-session-save --logout-dialog and to lock the screen use gnome-screensaver-command --lock.

A:

For Ubuntu 14.04 and 16.04 (Unity)
Use gsettings to disable most of menu items in indicator session menu and use systemctl to disable suspend ability itself at systemd level. This solution is not perfect, though.
How to disable menu items
To begin with, look for relevant keys using gsettings command and filter with grep command. Use "session" and "menu" for keywords to filter twice.
$ gsettings list-recursively | grep session | grep menu
com.canonical.indicator.session suppress-logout-menuitem false
com.canonical.indicator.session force-restart-menuitem false
com.canonical.indicator.session suppress-restart-menuitem false
com.canonical.indicator.session suppress-shutdown-menuitem false
com.canonical.indicator.session user-show-menu true

Then, use gsettings to set relevant keys with value that is opposite to current values i.e. "false" becomes "true", vice versa. Run the following commands, one by one.
$ gsettings set com.canonical.indicator.session suppress-shutdown-menuitem true
$ gsettings set com.canonical.indicator.session suppress-restart-menuitem true
$ gsettings set com.canonical.indicator.session suppress-logout-menuitem true
$ gsettings set com.canonical.indicator.session user-show-menu false

For suppress-logout-menuitem key to take effect, user may need to reload Unity desktop (run unity command in Terminal or HUD command prompt, no need to log out or anything).
And that is all needed to do for hiding most of menu items.

Following above steps, all menu items are now hidden in indicator session menu except for "Suspend" menu item. There is an open bug regarding the inability to hide the Suspend menu item. Confirming and subscribing to it may encourage it's resolution.
Given that the menu item cannot be suppressed directly, the next easiest solution is to disable any suspension at system-wide level.
How to disable suspend in Ubuntu 14.04 (Unity, upstart)
In 14.04 release, there are several ways to disable suspension i.e. edit configuration files for polkit-1 or pm-utils. But there is no clarification of which will actually work properly.
How to disable suspend in Ubuntu 16.04 (Unity, systemd)
In 16.04 release, disable any suspension with systemd as noted on Debian Wiki.
$ sudo systemctl mask sleep.target suspend.target hibernate.target hybrid-sleep.target
Created symlink from /etc/systemd/system/sleep.target to /dev/null.
Created symlink from /etc/systemd/system/suspend.target to /dev/null.
Created symlink from /etc/systemd/system/hibernate.target to /dev/null.
Created symlink from /etc/systemd/system/hybrid-sleep.target to /dev/null.

The systemctl command will take effect immediately. No need to reboot or anything.
As a result, whenever the "Suspend" menu item is clicked, the system does not go to sleep but only cause the screen to turn blank and returned to login screen (similar effect to "Lock Screen").
Workaround for known issue after suspend
Even without actual suspension, the same known issue will arise when resuming current session: Network manager does not wake up after suspend. The workaround is to restart the service.
$ sudo systemctl restart network-manager.service

The network manager will be restarted and networking will be available again.
Tested all above working in Ubuntu 16.04 (Unity), fresh installed in VirtualBox.

A:

For suspend and hibernate, instead of editing a package file that will be replaced when the package is updated, one can use files  in /etc/polkit-1/localauthority. Disable suspend with the file /etc/polkit-1/localauthority/90-mandatory.d/disable-suspend.pkla containing :
[Disable suspend]
Identity=unix-user:*
Action=org.freedesktop.upower.suspend
ResultActive=no

This is inspired by the file /var/lib/polkit-1/localauthority/10-vendor.d/com.ubuntu.desktop.pkla containing, among other things, the configuration to disable hibernation :
[Disable hibernate by default]
Identity=unix-user:*
Action=org.freedesktop.upower.hibernate
ResultActive=no

At least, it's what I use on Ubuntu 12.04.
More on PolicyKit local authority: http://hal.freedesktop.org/docs/polkit/pklocalauthority.8.html


Q:

What are the differences between incoming/outgoing connections?

If I understood correctly, a connection is outgoing if it was initiated by my node, otherwise it is incoming. Therefore, I was under the impression that with a fully synced blockchain, you should have many incoming connections (because many other nodes are currently downloading from you) and very few outgoing connections (because your node doesn't need to initiate a lot of connections, since its blockchain is up-to-date).
However, I've been running a VPS node 24/7 for several months now (hence it is fully synced), and at the time of writing it has 20 incoming connections and ~800 outgoing connections (I didn't put any limits on the number of connections).
How to explain such a high number of outgoing connections? Why does my node need to initiate all these connections, if its version of the blockchain is up-to-date?

A:

Your understanding is correct: outgoing connections are initiated by you, incoming connections are initiated by the peer. You can certainly have a peer syncing from you via an outgoing connection though.
The 800 connections is just a bug in the accounting. They're not all actual connections. You can see that using netstat or similar tool.
When a node is synced, it still needs connections to process new transactions and blocks. The default is to keep 8 outgoing connections, regardless of whether the node is synced.


Q:

Append data to a DB2 blob

In my DB2 database, I have a table with a Blob:
CREATE TABLE FILE_STORAGE (
    FILE_STORAGE_ID integer,
    DATA blob(2147483647),
    CONSTRAINT PK_FILE_STORAGE PRIMARY KEY (FILE_STORAGE_ID));

Using the db2jcc JDBC driver (db2jcc4-9.7.jar), I can read and write data in this table without any problems.
Now I need to be able to append data to existing rows, but DB2 gives the cryptic error
Invalid operation: setBinaryStream is not allowed on a locator or a reference. ERRORCODE=-4474, SQLSTATE=null

I use the following code to append my data:
String selectQuery = "SELECT DATA FROM FILE_STORAGE WHERE FILE_STORAGE_ID = ?";
try (PreparedStatement ps = conn.prepareStatement(selectQuery, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE)) {
    ps.setInt(1, fileStorageID);
    try (ResultSet rs = ps.executeQuery()) {
        if (rs.next()) {
            Blob existing = rs.getBlob(1);
            try {
                // The following line throws the exception:
                try (OutputStream output = existing.setBinaryStream(existing.length() + 1)) {
                    // append the new data to the output:
                    writeData(output);
                } catch (IOException e) {
                    throw new IllegalStateException("Error writing output stream to blob", e);
                }

                rs.updateBlob(1, existing);
                rs.updateRow();
            } finally {
                existing.free();
            }
        } else {
            throw new IllegalStateException("No row found for file storage ID: " + fileStorageID);
        }
    }
}

My code is using the methods as suggested in OutputStream to the BLOB column of a DB2 database table. There also seem to be other people who have the same problem: Update lob columns using lob locator.
As a workaround, I currently read all the existing data into memory, append the new data in memory, and then write the complete data back into the blob. This works, but it's very slow and obviously it will take longer if there's more data in the blob, getting slower with each update.
I do need to use Java to update the data, but apart from switching away from the JVM, I am happy to try any possible alternatives at all, I just need to append the data somehow.
Thanks in advance for any ideas!

A:

If you only need to append data to the end of a BLOB column and don't want to read the entire value into your program, a simple UPDATE statement will be faster and more straightforward.
Your Java program could run something like this via executeUpdate():
UPDATE file_storage SET data = data || BLOB(?) WHERE file_storage_id = ?

The parameter markers for this would be populated by setBlob(1, dataToAppend) and setInt(2, fileStorageID).