text:
Q: Redmine can't see git repo from local gitlab server I'm setting up a VM with centos 7, gitlab-ce and redmine. Everything is installed and running, but I'm unable to setup integration: When I try to access http://redmine/projects/myproject/repository, it shows me the (in)famous message:

404 The entry or revision was not found in the repository.

Apache's error log (/var/log/htttpd/error_log) says:

App 3122 stderr: fatal: Not a git repository: '/var/opt/gitlab/git-data/repositories/mygroup/myproject.git'

This is the right path to the project. Following the tip posted by user @sk1p in https://serverfault.com/questions/565030/redmine-not-finding-my-git-repo-on-debian-7-3,  I get "permission denied" messages.
So there's my problem: I'm affraid to change these directories permissions and make everything unsafe. My apache user can only open /var/opt/gitlab:
bash-4.2$ cd /var/opt/gitlab
bash-4.2$ ls -la
total 16
drwxr-xr-x. 11 root         root       4096 Jul 17 16:12 .
drwxr-xr-x.  3 root         root         19 Jul 17 10:17 ..
drwx------.  2 git          root         41 Jul 23 14:57 backups
-rw-------.  1 root         root         38 Jul 17 10:18 bootstrapped
-rw-r--r--.  1 git          git         264 Jul 17 16:12 .gitconfig
drwx------.  4 git          root         49 Jul 17 10:17 git-data
drwxr-xr-x.  7 git          root         82 Jul 27 10:04 gitlab-rails
drwx------.  2 git          root         49 Jul 17 10:17 gitlab-shell
drwx------.  3 root         root         45 Jul 17 10:18 logrotate
drwxr-x---.  8 root         gitlab-www 4096 Jul 28 09:09 nginx
drwxr-xr-x.  3 gitlab-psql  root         77 Jul 28 09:09 postgresql
drwxr-x---.  2 gitlab-redis git          57 Jul 28 09:19 redis
drwx------.  2 git          git          55 Jul 17 16:06 .ssh
bash-4.2$ cd git-data/
bash: cd: git-data/: Permission denied
bash-4.2$ cd git-data/repositories/mygroup/myproject.git
bash: cd: git-data/repositories/mygroup/myproject.git: Permission denied

Browsing the directories as root, these are the permissions for the project dir:
[root@srv mygroup]# ls -l
total XX
(...)
drwxrwxrwx. 6 git git 4096 Jul 28 07:48 myproject.git

As you can see, I tried 777ing the whole thing. No success. I will revert it later, promisse. I also tried adding apache user to groups:
[root@srv mygroup]# groups apache
apache : apache root git

So how can I make it right? I did try searching for a solution at the webs (actually doing it since yesterday), the thing I didn't tried yet is chowning the repo to apache.apache, because I'm affraid it breaks something for gitlab.
Sorry for my broken english. =]

A: I've found a different solution. I don't think it's optimal and I'm still looking for a better way, but here's what I did:
There's a guide at http://www.redmine.org/projects/redmine/wiki/HowTo_Easily_integrate_a_%28SSH_secured%29_GIT_repository_into_redmine explaining how to integrate a git repo to redmine using ssh. This guide creates just a "mirror" of each repo, so I hope it doesn't consume much space (I'll find out soon). I got some trouble to create my apache user's ssh key and authenticate, but this other troubleshoot (Gitlab prompts for password while push for git user, @VonC tips) helped me a lot.


text:
Q: How do I use multiple createPage routes in gatsby-node.js Im currently having an issue when using multiple createPage routes in gatsby-node.js. I am trying to use Gatsby js with Shopify commerce storefront & and another CMS for blog articles so I need a way of creating routes when viewing products and when viewing blog articles respectively.
Currently, I am experiencing an error that only appears when trying to view a product detail page that reads:
(EnsureResources, ) TypeError: Cannot read property 'page' of undefined
My gatsby-node.js currently looks like this
const path = require(`path`)

// Create product page urls
exports.createPages = ({ graphql, actions }) => {
  const { createPage } = actions
  return graphql(`
    {
      allShopifyProduct {
        edges {
          node {
            handle
          }
        }
      }
    }
  `).then(result => {
    result.data.allShopifyProduct.edges.forEach(({ node }) => {
        const id = node.handle
      createPage({
        path: `/product/${id}/`,
        component: path.resolve(`./src/templates/product-page.js`),
        context: {
            id,
        },
      })
    })
  })
}

// Create blog post slug urls
exports.createPages = async ({graphql, actions}) => {
  const {createPage} = actions
  const blogTemplate = path.resolve('./src/templates/blog.js')
  const res = await graphql (`
    query {
      allContentfulBlogPost {
        edges {
          node {
            slug
          }
        }
      }
    }
  `)

  res.data.allContentfulBlogPost.edges.forEach((edge) => {
    createPage ({
      component: blogTemplate,
      path: `/blog/${edge.node.slug}`,
      context: {
        slug: edge.node.slug
      }
    })
  })
}

A: You can't define the same API (createPages) twice. Do it in one function, especially since you can all put it into one query.
This code is obviously untested, but should work:
exports.createPages = async ({ graphql, actions }) => {
  const { createPage } = actions

  const result = await graphql(`
    {
      shopify: allShopifyProduct {
        nodes {
          handle
        }
      }
      contentful: allContentfulBlogPost {
        nodes {
          slug
        }
      }
    }
  `)

  const shopifyTemplate = require.resolve(`./src/templates/product-page.js`)
  const contentfulTemplate = require.resolve('./src/templates/blog.js')

  if (result.errors) {
    return
  }

  result.data.shopify.nodes.forEach(product => {
    const id = product.handle

    createPage({
      path: `/product/${id}/`,
        component: shopifyTemplate,
        context: {
            id,
        },
    })
  })

  result.data.contentful.nodes.forEach(post => {
    createPage ({
      component: contentfulTemplate,
      path: `/blog/${post.slug}`,
      context: {
        slug: post.slug
      }
    })
  })
}

The nodes is a shortcut for edges.node and valid syntax. The shopify: is an alias before the name of the query. You don't need to use path, you can also use require.resolve. The async/await syntax is better to read IMO.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Interface, delegate, other? (C#, Unity) What I have:
public void New_Click()
{
    MenuManager.GoToMenu(MenuName.NewDescr);
    StartCoroutine(WaitForClose());
}

IEnumerator WaitForClose()
{
   yield return new WaitWhile(MenuManager.MenuOpen);
   listMonitor.AddToGrid(Descriptor.List.Last());
   yield return null;
}

What I want:
public void New_Click()
{
    MenuManager.GoToMenu(MenuName.NewDescr);
    WaitForClose(listMonitor.AddToGrid(Descriptor.List.Last()));
}

Basically, I'd like to implement a wrapper around a method call, but not have to specify StartCoroutine() nor write out the WaitForClose() method every time the method is used. I have little experience with delegates and Interfaces - are those the answer? If so, how?

A: You could generalize the WaitForClose() method you've shown by allowing an Action delegate to be passed. E.g.:
public void New_Click()
{
    MenuManager.GoToMenu(MenuName.NewDescr);
    StartCoroutine(WaitForClose(() => listMonitor.AddToGrid(Descriptor.List.Last())));
}

IEnumerator WaitForClose(Action action)
{
   yield return new WaitWhile(MenuManager.MenuOpen);
   action();
   yield return null;
}

Extending the above, you can then simplify the invocation a bit so it's closer to your "what I want" example:
public void New_Click()
{
    MenuManager.GoToMenu(MenuName.NewDescr);
    WaitForClose(() => listMonitor.AddToGrid(Descriptor.List.Last()));
}

void WaitForClose(Action action)
{
    StartCoroutine(WaitForCloseCoroutine(action));
}

IEnumerator WaitForCloseCoroutine(Action action)
{
   yield return new WaitWhile(MenuManager.MenuOpen);
   action();
   yield return null;
}

A: Peter had EXACTLY where I was going to go.  But since you are completely new to the concept and will probably read more about it, I will start you with this.
The keyword "Action", instead of things like int, string, someClass, etc, you are telling this method that you want a procedure/method to be called when the specific point-in-time comes as Peter demonstrates by calling the lower-case "action()".
The other cool thing you can do is even allow actions that require some sort of additional parameters.  Maybe you want to conditionally have some time delay to allow, values to compute, or whatever else.  You can specify what data type parameters you want to pass in as well.  The only difference is the signature such as
public void SomeFunction( Action<int> doSomething )
{
    // suppose some randomized value that you want the function to handle
    var someRand = SomeIntValueFromSomeRandomFunction();
    // notice the Action signature is saying it should be a function that
    // will expect and integer data type to be passed to it when actually called.
    // above I get some random number, then call that Action method with it.
    doSomething( someRand );
}

Similarly you can do things with FUNCTIONS that RETURN values.  The only difference is the last parameter is the expected data type being returned AFTER the function is called.
Using ACTIONS
Using FUNCTIONS as well


text:
Q: Using Command Design Pattern for just Undo Okay so this is my first time using really any Design Pattern so forgive me but I'm really struggling with the concept. From what I've read there needs to be the Command interface, usually this would hold public void execute(); In my case I think I want to only have public void undo(); My question is on all the other classes that are required. My program is essentially done and I'm trying to merge this design pattern in at the end to put in a Undo function. It's a LinkedList that i defined with my own methods. Here's some of the code:
public class LinkedList<E> implements Serializable{

/** number of Nodes on the list */
private int count;

/** the first Node in the list */
private Node head;

/** the last Node in the list */
private Node tail;

/**Stack holding commands*/
private Stack<Command> undo = new Stack<Command>();

/** Inserts a given student's data into the database
 * @param student given student data to be inserted into database
 * @return none*/
public void insert(Student student){
    //case where input is null
    if(student.getName() == null || student.getGNumber() == null)
        throw new IllegalArgumentException();
    Node temp = head;
    //case where there is no list
    if(head == null){
        head = new Node(student, null);
        tail = head;
        count = 1;
    }

    //case where top has existing Nodes
    else{
        //brings reference to end of list
        while(temp.getNext() != null)
            temp = temp.getNext();

        temp.setNext(new Node(student, null));
        tail = temp;
        count ++;

    }
}

Now would that be the receiver class? And do I still need a separate class for each command? Really all I want is an Undo Stack of commands, and each time I call a method I push it's undo onto that stack. For all the Command Design Pattern examples I could find they've all been the same example of that Light Switch which really doesn't do a good job showing a generic need.
Okay sorry for being really long winded, I guess here is the TL;DR question:
Can I add a Stack in my LinkedList, and then add a undo method also in the LinkedList that pops the stack? and add a push statement in each of my methods? or do I still need to go through all the steps and classes of the Command Design Pattern?
EDIT:
After some thought I realized to push a command into my Stack I need command objects for each of my methods, is there a way to implement this into my LinkedList class?


text:
Q: django update_or_create method creates record but with empty values I am trying use update_or_create method, it's working but the issue which I see is, it's creating an empty record even though the fields are null=False & blank=False.
Any idea about this folks?

A: If your field is null=False and blank=False that doesn't mean that the constraints are present in the database. Please check if the column in DB cannot be null and/or run migrations to add it to the DB.
Additionally you need to specify non-default values using the defaults argument of get_or_create():
    obj, created = Person.objects.get_or_create(first_name='John', last_name='Lennon',
              defaults={'birthday': date(1940, 10, 9)})


text:
Q: Check a key's state without keyPressed/Released events I need the check the state of a key (whether it's being pressed down or not) without using an event based method.  Storing key states does not work; I need to check the real time state of the key.  Anybody know how?  Platform is JCreator v5.0 LE

A: I don't see exactly the point, seeing how keyPressed(), keyReleased(), and keyTyped() are called whenever any key is pressed, without fail.
You also said that storing states is not working. Have you tried something like this?
boolean[] keys = new boolean[222]; // 222 is the highest keyCode value i know

public void keyPressed(KeyEvent e) { keys[e.getKeyCode()] = true; }
public void keyReleased(KeyEvent e) { keys[e.getKeyCode()] = false; }

// True is pressed, False is released
public boolean getState(int keyCode) {
  return keys[keyCode];
}

This is really the most reasonable way of checking the "real-time" state of a key. You can't just ask the computer for the state of a key without using a Listener. Perhaps some more information on what you need the "real-time" state for will get you a better answer.


text:
Q: An Upper bound for the number of independent events Assume Ω is a finite probability space (|Ω|=n),
So There are at most $\log_2 n$ non-trivial  different independent events.
I need to prove this but I actually don't understand why it is true.


text:
Q: RREF of matrix credibility I've been given an assignment and there is always the emphasise to prove everything, not just find the answer.
Now in this case, we're given a matrix, A, defined in R^3,  of which we need to find the basis of the col(A), then give the dim col(A) [should be written as dim(A)]. Then we are asked for the row(A), then give the dim row(A) [should be written rank(A)]. Finally, the null(A) and then following is find the nullity dim null(A) [again should be written simply as the nullity(A)].
Super simple to work out... But what am I missing here??
Is it not suffice to just find RREF(A) and simply extract the pivot columns, pivot rows and by definition find the dim(A) and rank(A)??
I can use some theorem to show that nullity(A) = n - rank(A), where n represents the number of columns I have in A.
Which in this case alone shows nullity(A) = 1, and we're working in R^3, so I can just find the cross product of my basis vectors for the col(A).
Like relatively speaking this seems suspiciously easy compared to my last assignment. Would anyone know what I'm missing with my approach?


text:
Q: Uses for the Java Void Reference Type? There is a Java Void -- uppercase V-- reference type. The only situation I have ever seen it used is to parameterize Callables
final Callable<Void> callable = new Callable<Void>() {
            public Void call() {
                foobar();
                return null;
            }
        };

Are there any other uses for the Java Void reference type? Can it ever be assigned anything other than null? If yes, do you have examples?

A: Before generics, it was created for the reflection API, to hold TYPE returned by Method.getReturnType() for a void method, corresponding to the other primitive type classes.
EDIT: From the JavaDoc of Void: "The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the Java keyword void".  Prior to Generics, I am aware of no use other than reflection.

A: You can create instance of Void using reflections, but they are not useful for anything.  Void is a way to indicate a generic method returns nothing.
Constructor<Void> constructor = Void.class.getDeclaredConstructor();
constructor.setAccessible(true);
Void v = constructor.newInstance();
System.out.println("I have a " + v);

prints something like
I have a java.lang.Void@75636731

A: As you can't instantiate Void, you can use Apache commons Null object, so
Null aNullObject = ObjectUtils.Null;
Null noObjectHere = null;

in the first line, you have an object, so aNullObject != null holds, while in the second line there is no reference, so noObjectHere == null holds
To answer the poster's original question, the usage for this is to differentiate between "the nothing" and "nothing", which are completely different things.
PS: Say no to Null object pattern

A: Future<Void> works like charm. :)

A: Given that there are no public constructors, I would say it can't be assigned anything other than null. I've only used it as a placeholder for "I don't need to use this generic parameter," as your example shows.
It could also be used in reflection, from what its Javadoc says:

The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the Java keyword void.

A: All the primitive wrapper classes (Integer, Byte, Boolean, Double, etc.) contain a reference to the corresponding primitive class in a static TYPE field, for example:
Integer.TYPE == int.class
Byte.TYPE == byte.class
Boolean.TYPE == boolean.class
Double.TYPE == double.class

Void was initially created as somewhere to put a reference to the void type:
Void.TYPE == void.class

However, you don't really gain anything by using Void.TYPE. When you use void.class it's much clearer that you're doing something with the void type.
As an aside, the last time I tried it, BeanShell didn't recognise void.class, so you have to use Void.TYPE there.

A: Void was created to wrap its primitive void type. Every primitive type has its corresponding Reference type. Void is used to instantiate a generic class or use of a generic method, a generic argument which you are not interested in. Here is an example...
public void onNewRegistration() {
    newRegistrationService.createNewUser(view.getUsername(), view.getPassword(),
            view.getInitialAmount(), view.getCurrency(), new AsyncCallback<Void>() {
      @Override
      public void onFailure(Throwable caught) {

      }

      @Override
      public void onSuccess(Void result) {
        eventBus.fireEvent(new NewRegistrationSuccessEvent());
      }
    });
  }

Here, as you can see, I don't want anything from the server that I am asking to create a new registration ,but public interface AsyncCallback<T> { .... } is a generic interface, so i provide Void since generics don't accept primitive types

A: Void has become convention for a generic argument that you are not interested in. There is no reason why you should use any other non-instantiable type, such as System.
It is also often used in for example Map values (although Collections.newSetFromMap uses Boolean as maps don't have to accept null values) and java.security.PrivilegedAction.

A: When you use the visitor pattern it can be cleaner to use Void instead of Object when you want to be sure that the return value will be null
Example
public interface LeavesVisitor<OUT>
{
   OUT visit(Leaf1 leaf);

   OUT visit(Leaf2 leaf);
}

When you will implement your visitor you can explicitly set OUT to be Void so that you know your visitor will always return null, instead of using Object
public class MyVoidVisitor implements LeavesVisitor<Void>
{
    Void visit(Leaf1 leaf){
        //...do what you want on your leaf
        return null;
    }

    Void visit(Leaf2 leaf){
        //...do what you want on your leaf
        return null;
    }
}

A: It is also commonly used on Async-IO completion callbacks when you dont have the need for an Attachment object. In that case you specify null to the IO operation and implement CompletionHandler<Integer,Void>.

A: It may be rare case but once, I used Void in aspect classes.
This was an aspect which runs after methods that has an @Log annotation, and logs the method returned and some info if the method return type is not void.
 @AfterReturning(value = "@annotation(log)",
       returning = "returnValue",
       argNames = "joinPoint, log, returnValue"
      )
    public void afterReturning(final JoinPoint joinPoint, final Log log,
            final Object returnValue) {

            Class<?> returnType = ((MethodSignature) joinPoint.getSignature())
            .getReturnType();
           if (Void.class.isAssignableFrom (returnType)) ) {
            //Do some log
         }
}


text:
Q: R mapping filled.contour georeferencing interpolation I'm trying to make a map kind of like this, but with higher resolution, and less of a tile like appearance:

Which used this code:

samps <- read.csv("Petra_phytoplankton+POM_xydata_minusNAs_noduplicates.csv")   #my data for sampling sites, contains a column of "lat" and a column of "lon" with GPS points in decimal degrees

samps_test<-samps

x<-samps_test$longitude
y<-samps_test$latitude
z<-samps_test$d13C

## interpolation using akima
x0<-seq(min(x), max(x), length = 100)
y0<-seq(min(y), max(y), length = 100)
z.hat <- interp(x,y,z)

#plot
par(mar=c(4.1,4.1,1,1))
image.plot(z.hat)
map(add=TRUE, fill=TRUE)
points(samps_test$longitude,samps_test$latitude,pch=4)

But I wanted to interpolate with higher resolution so I used filled.contour() to create this map:

As you can see, the map and raw data points are not plotting correctly....how do I fixed this? I have a feeling it is because the filled.contour() plot is not georeferenced (so not in the same coordinate system as the map and data points)...but how do I change this?
Code for the second map:

df <-read.table("Petra_phytoplankton+POM_xydata_minusNAs_noduplicates.txt",header=T)
attach(df)
names(df)
fld <- with(df, interp(x = longitude, y = latitude, z = d13C))

filled.contour.ungeoreferenced<-(filled.contour(x = fld$x,
                           y = fld$y,
                           z = fld$z,
                           color.palette =
                             colorRampPalette(c("blue", "green","yellow","orange","red")),
                           xlab = "Longitude",
                           ylab = "Latitude",
                           key.title = title(main = "d13C", cex.main = 1)))

map(add=TRUE, fill=TRUE)

points(samps_test$longitude,samps_test$latitude, pch=4) #not plotting in the same space

I also tried making this graph in ggplot with geom_tile but it didn't work?
Also, I realise this is probably another question, but at the moment I don't know how to change axes titles and the like as it doesn't seem to be plotting with the base plot package, so normal commands don't work.
FYI here is a subset of my dataset:

latitude    longitude   d13C
-65 -70 -27.7
-61 150 -32.2
-61 150 -28.3
-60 116 -26.8
-60 116 -24.7
-47 38  -24.8
-38 150 -20.5
19  -65.7   -19.9
19  -65.5   -18.5
18  -60.7   -20
18  -58.5   -18.2
18  -57.8   -19
17  -55.4   -18.6
17  -50.8   -18
17  -47.1   -18.3
17  -45.5   -19.4
16  -43.3   -17.9
15  -40.7   -18.5
14  -39.3   -19.9
12  -36.7   -19.9
12  -36.2   -19.9
11  -34.4   -19.2
10  -32 -18.5
9   -30.3   -19.3
8   -29.2   -19.4
7   -26.6   -18.2
7   -25.5   -19.3
6   23.9    -20
3   -21.3   -20.4

I checked out these help forums but they don't tell me how to convert my datapoints OR map into the same scaling as filled.contour does. Plotting a box within filled.contour plots in R?
Adding points to filled.contour function in R


text:
Q: In selection sort, if we have two duplicate elements, what is the behavior of the algorithm? If we delete the part starting with if (indexMax != i) from the code below (the last part) the Algoritm shatters, why?
public static void selectionSort(int[] array) {
    for (int i = 0; i < array.length; i++) {
        int indexMax = i;

        for (int j = i + 1; j < array.length; j++) {
            if (array[indexMax] < array[j]) {
                indexMax = j;
            }
        }

        if (indexMax != i) {
            int temp = array[i];
            array[i] = array[indexMax];
            array[indexMax] = temp;
        }
    }
}

A: From the code you posted with my comments:
    int indexMax = i;  // initial value of indexMax

    for (int j = i + 1; j < array.length; j++) {
        // please note that j starts with (i+1)
        if (array[indexMax] < array[j]) {
            indexMax = j;  // index of Max candidate
        }
    }

    if (indexMax != i) {   // means that the above loop reassigned indexMax
        int temp = array[i];  // so we are swapping
        array[i] = array[indexMax];
        array[indexMax] = temp;
    }

So if (indexMax != i) means "Did we find a better Max?"

A: Your code would do the following:
arr[] = 1, 5, 2, 4, 3

// find the max from arr[0..4]
// substitute it with the index 0, if it is not of that index already
arr[] = 5, 1, 2, 4, 3

// find the max from arr[1..4]
// substitute it with the index 1, if it is not of that index already
arr[] = 5, 4, 2, 1, 3

// find the max from arr[2..4]
// substitute it with the index 2, if it is not of that index already
arr[] = 5, 4, 3, 1, 2

// find the max from arr[3..4]
// substitute it with the index 3, if it is not of that index already
arr[] = 5, 4, 3, 2, 1

The substitute it with the index i, if it is not of that index already is that if statement

For a longer array, with duplicates, check this Kotlin Playground Code I created for you. You can change the array as you wish, and you can trace the switching of the values.

A: In the picture you can see how duplicate items move their relative position.This introduce instability.
For three duplicate items:

For two duplicate items:


text:
Q: CSS3 rotate3d Inaccuracies Does anyone know of a solution to the inaccuracies produced by the css3 transform attribute: rotate3d (or rotateX, rotateY, rotateZ)?
The function computes an elements position by applying the rotation angle to the matrix [cos(angle) sin(angle) -sin(angle) cos(angle) someOtherTrigForZ(angle) someOtherTrigForZ(angle)]..
I am creating a cube using these css3 attributes, and if you inspect the id=cube element in this jsfiddle (after rotating the cube a few times using arrow keys)(look in computed styles), you can see that the rotate3d matrix does not apply any kind of number fixing (some sort of rounding method) to computed styles.
-webkit-transform: matrix3d(0.7, 0, 0, 0, 0, 0.04943792709533707, -0.6982520256787774, 0, 0, 0.6982520256787774, 0.04943792709533707, 0, 0, 0, 0, 1);

The result I am getting is poorly drawn elements that do not line up; this is visible to the naked eye if you look at the borders on the cube's faces.
Does anyone know of a way to smooth out/round the trigonometry calculations so that my borders aren't choppy?

A: In the jsfiddle you linked to, the css class for the cube faces has the border set as border:1px solid black; This is actually adding and extra pixel on each edge of a face. That's an extra 2px added to both the width and height. I think this is causing the misalignment. If you add the css property -webkit-box-sizing: border-box; to the face class, the misalignment should be corrected.


text:
Q: Getting not-null errors despite having a default value set. I have the following database column:
 `last_modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP

With the following mapping in hibernate:
@Temporal(TemporalType.TIMESTAMP)
@Column(name="last_modified", nullable=false, length=19)
public Date getLastModified() {
    return this.lastModified;
}

This has been working fine for months now but all of a sudden out of nowhere I am getting the following error:

javax.persistence.PersistenceException: org.hibernate.PropertyValueException: not-null property references a null or transient value: com.fs.model.BrowserHistory.lastModified

So I am wondering, why is this happening all of a sudden? Is it OK if I set the lastModified field to be nullable?

A: Looks like you would like to record the modification timestamp. To avoid setting it manually (or not setting it and getting errors) you can use lifecycle callbacks:
@PrePersist
public void updateTimestamps() {
    lastModified = new Date();
}

A: I found out that database generated columns need some specific annotations:
@Column(name="last_modified", nullable=false, length=19, insertable=false, updatable=false)
@Generated(GenerationTime.ALWAYS)

We are trying this out now but I think it will fix the issue.


text:
Q: PHP failed to open stream ao tentar incluir pasta superior Estou com um problema no meu PHP que não sei o que está acontecendo.
Atualmente, sempre que eu vou voltar uma pasta em algum diretório eu uso ./
por exemplo: "./javascript/jquery.js"
Não sei porque esta acontecendo isso, porque a maneira correta de voltar pastas seria ../javascript/jquery.js e isso está atrapalhando em alguns processos. Quando vou usar include também uso include_once("./model/Produto.php") e quando vou chamar esse include em outro lugar ele da o erro  failed to open stream: No such file or directory porque está ./ e não ../
Existe alguma forma de corrigir isso? Lembrando que sempre que meu index.php usa o .htaccess no meio da página que usa um $_GET que pega o que foi digitado na url e dá um include_once("caminho/arquivo.php"), isso pode influenciar em algo?
Edit1: se eu usar ../ para voltar invés de ./ dá o erro failed to open stream: No such file or directory em qualquer diretório

A: Suponha a seguinte hierarquia de pastas:
raiz
  pasta1
    arquivo1.php
  pasta2
    arquivo2.php
  index.php

Se você estiver dentro do arquivo arquivo1.php e quiser fazer um require para o arquivo index.php voce deve fazer require_once '../index.php'.
Se você quiser fazer um require_once de dentro do arquivo index.php para o arquivo1.php você deve fazer require_once './pasta1/arquivo1.php'.
Essa organização vai falhar se houver inclusões multiplas, como por exemplo, arquivo1.php incluindo index.php e index.php incluindo arquivo2.php.

A: Uma possibilidade é você utilizar a constante mágica __DIR__, segundo o manual ela contém:

O diretório do arquivo. Se usado dentro de um include, o diretório do
  arquivo incluído é retornado. É equivalente a dirname(FILE). O
  nome do diretório não possui barra no final, a não ser que seja o
  diretório raiz.

Dessa maneira fica mais fácil você se localizar já que a referencia passa a ser sempre o caminho relativo ao arquivo que você está editando.
No caso de uma estrutura:
/index.php
   /model/model1.php
   /controller/controller1.php

Dentro de controller1.php se você quiser incluir o arquivo model1.php ficaria:
include(__DIR__ . "/../model/model1.php");


text:
Q: Do I need to use "to" in sentences such as these?
What I want is (to) go to the cinema.
What you should do is (to) shut up and dance.

I know that "to" is frequently omitted in such cases, but if you were to write a formal paper, would you include it or not?

A: Your examples are wh-clefts. In the words of the 'Longman Student Grammar of Spoken and Written English' wh-clefts consist of:

a clause introduced by a wh-word, usually what; this clause has
  its own point of focus, usually at the end of the wh-clause
a form of the verb be
the specially focused nominal element

The specially focused element in the first example is to go to the cinema. This takes the
form of a to-infinitive, because as a non-cleft it would occur as I want to go to the cinema, and not as I want go to the cinema.
The specially focused element in the second example is shut up and dance. This takes the form of a bare infinitive, because as a non-cleft it would occur as You should shut up and dance, and not as You should to shut up and dance. That in turn is because the bare infinitive is required after  modal verbs such as should.

A:
What I want is to go to the cinema. (grammatical)
*What I want is go to the cinema.  (asterisk means ungrammatical)

As Barrie has pointed out, both of the example sentences are Wh-Cleft constructions.
That means they have been done things to. This sentence is from the prototype

*

*I want (for me) to go to the cinema.  (Equi: same subject for want and go) ==>

*I want to go to the cinema. (Wh-Cleft) ==>

*What I want is to go the cinema.
The infinitive complementizer to in this sentence is still needed
to mark the infinitive clause to go the cinema
on the right side of the fulcrum of cleavage is
(the fulcrum be is inserted by the Wh-cleft rule);
this balances the embedded What-clause what I want
on the left side of the fulcrum.
It's that construction balanced on a fulcrum that marks a cleft sentence.
In the second case, however,

What you should do is shut up and dance.

the original has no infinitive complementizer to; on the contrary,
the infinitive forms do, shut (up), and dance
are governed by the modal auxiliary should, which is deleted in the downstairs clauses
by conjunction reduction (and not by Equi).
So there is no infinitive complementizer to.

*

*You should shut up and (you should) dance. (Conjunction Reduction) ==>

*You should shut up and dance. (Wh-Cleft: adds active pro-verb do) ==>

*What you should do is shut up and dance.

A: Yes you absolutely need to in the first example. You cannot say:
What I want is go cinema.

This is not a case where to is functioning as a preposition that may be omitted. To go is the infinitive form of the verb, which is the form required by that sentence.
The second one should not have the word to at all. This sentence is an imperative (a command or a directive). You can distill that sentence down to:
Shut up and dance!

As for use in a formal paper, I wouldn't use either of them. I would say:
I want to go to the cinema.
Just shut up and dance.

I don't know what type of formal paper you're writing, but this sounds like dialogue to me.

A: Why not "What I want is going to cinema"?


text:
Q: mysql join to list item from two tables I am having two tables table_purchase1 and table_purchase2. From these tables i want to list purchase history with order by date.
My tables
table_purchase1

purchase_id   user_id    item    date
  1               1       AA1    2011-06-10
  2               1       AA2    2011-06-12

table_purchase2

purchase_id   user_id    item      date
  1               1       BB1    2011-06-11
  2               1       BB2    2011-06-13

Expecting result
item
BB2,AA2,BB1,AA1

How can i do this
Thanks

A: You can use UNION:
(SELECT item, `date` FROM table_purchase1)
UNION
(SELECT item, `date` FROM table_purchase2)
ORDER BY `date`

If you need single row following might work:
SELECT GROUP_CONCAT(
(  (SELECT item, `date` FROM table_purchase1)
 UNION
  (SELECT item, `date` FROM table_purchase2)
 ORDER BY `date`
))

A: (SELECT
item
FROM
table_purchase1)
UNION
(SELECT
item
FROM
table_purchase2)
ORDER BY `date`

A: $sql = (SELECT item, date FROM table_purchase1) UNION (SELECT item, date FROM table_purchase2) ORDER BY date


text:
Q: does chronic have any options of date format it parses? (ruby) I need to tell chronic that the format of date is day-month-year is that possible? The data I pass to chronic could also be words today/yesterday/2 days ago.
Currently chronic gives me 2 Dec 2010 instead of 12 Feb 2010 from 12-02-2010
The only solution I can think of is to swap day and month before passing the string to chronic.
require 'chronic'

puts "12-02-2010 = #{Chronic.parse('12-02-2010')}"  #should be 12 Feb 2010

puts "yesteday = #{Chronic.parse('yesterday')}" #working ok
puts "Today = #{Chronic.parse('today')}"        #working ok

A: The output of chronic can be easily formatted. chronic.parse returns a time object.  You can use strftime for formatting as described here.
puts Chronic.parse('today').strftime('%d %b %Y') #=> 23 Feb 2010

As far as the input is concerned, I cannot find anything in chronic that will do it automatically.  Manipulating the input string is probably the way to go.
Edit:  Chronic has an internal pre_normalize that you could over-ride..
require 'chronic'
puts Chronic.parse('12-02-2010').strftime('%d %b %Y') #=> 02 Dec 2010

module Chronic
  class << self
    alias chronic__pre_normalize pre_normalize

    def pre_normalize(text)
      text = text.split(/[^\d]/).reverse.join("-") if text =~ /^\d{1,2}[^\d]\d{1,2}[^\d]\d{4}$/
      text = chronic__pre_normalize(text)
      return text
    end
  end
end
puts Chronic.parse('12-02-2010').strftime('%d %b %Y') #=> 12 Feb 2010

A: I've found this question today, 20 months after it has been asked. It seems that there is a way to indicate to swap months and days. Just use the :endian_precedence option:

:endian_precedence (Array) — default: [:middle, :little] — By default,
  Chronic will parse "03/04/2011" as the fourth day of the third month.
  Alternatively you can tell Chronic to parse this as the third day of
  the fourth month by altering the :endian_precedence to [:little,
  :middle]

Example here:
Chronic.parse('12-02-2010').strftime('%d %b %Y')   #=> 02 Dec 2010
Chronic.parse('12-02-2010', :endian_precedence => [:little, :median]).strftime('%d %b %Y') #=> 12 Feb 2010

Hope this helps!
Dorian


text:
Q: JS; Can someone correct my Quick Sort function? I still have difficulties using recursive calls.
My function exceeds the max call stack. Any help please?
function quickSort(arr) {
    let n = arr[arr.length-1];
    const inf = [];
    const sup = [];
    for(let i = 0; i<arr.length; i++){
        if(arr[i]<= n){inf.push(arr[i])}
        else(sup.push(arr[i]));
    }
    if(inf.length === 1 && sup.length === 1){
        return inf.concat(sup)
    }else if(inf.length === 1 && sup.length > 1){
        quickSort(sup);
        return inf.concat(sup)
    }else if(inf.length > 1 && sup.length === 1){
        quickSort(inf);
        return inf.concat(sup)
    }else{
        quickSort(inf);
        quickSort(sup);
        return inf.concat(sup)
    }
  }

Thank you.

A: Let us take an example array arr = [3,2,7,5,4,6].
In the first recursive call
inf = [3,2,7,5,4,6]
sup = [7]

Now, since sup.length === 1 and inf.length > 1, the execution would go into the third if-else condition. In this recursive call, we have
inf = [3,2,5,4,6] // Same as the original array sent into parameter
sup = []

This basically falls in an infinite recursive call loop.
In order to recover from infinite loops like this, you need to add a condition to check when inf.length === 0 or sup.length === 0.
Possible solution: In the for loop, during the last iteration, you can check if either of the arrays are empty, and since the last iteration would always result in the equal case, i.e in the above code arr[i] = n, you can push it to the empty array and move ahead with the further if else conditions.
Considering the test case I took earlier, in the second iterative call, I would push 6 not to inf[] but to sup[] making the inf[] and sup[] arrays as follows:
inf = [3,2,5,4]
sup = [6]

This will resolve the infinite loop issue.


text:
Q: Git revert merge to specific parent I have a git repo and am having trouble reverting a merge. The current hash is 0ce2ca0b35f59af267241cf4d40d16a3e13ba6f3. and it has two parents:
df1acf5f54426d30f12c6b4558c3dd922297aae3
e19b912404ffd3c153ccac3072dbf22396896d2a

doing the following will revert to df1acf5f54426d30f12c6b4558c3dd922297aae3
git revert -m 1 0ce2ca0b35f59af267241cf4d40d16a3e13ba6f3

how do I revert to e19b912404ffd3c153ccac3072dbf22396896d2a?

A: git revert -m 2 0ce2ca0b35f59af267241cf4d40d16a3e13ba6f3

Parents are numbered starting with 1; you want the second one.


text:
Q: django custom authentication backend with custom middleware (both username,password and token absed auth) I am in a situation where I need to make a custom authentication and custom middleware to authenticate and authorize the user. I have to chek the username password params in the POST request or if the cookie is set or not for token based authentication. Now, as I know that function overloading is not allowed in python, how could I achieve it. I am putting the code below for custom auth and custom middleware.
Custom Middleware:
from django.contrib.auth import authenticate

class AuthMiddleWare(object):
    def process_request(self, request):

        if request.path != '/favicon.ico':
            print "inside process_request " + request.path

            if request.method == 'POST' and request.POST.has_key('username' ) and request.POST.has_key('password'):
                authenticate(username = request.POST.get('username'),password = request.POST.get('password'))

            if 'SPRING_SECURITY_REMEMBER_ME_COOKIE' in request.COOKIES:
                authenticate(token = request.COOKIES.get('SPRING_SECURITY_REMEMBER_ME_COOKIE'))

        return None

And the custom auth backend :
from core.api import NcpAPI

class CustomNCPAuthBackend(object):
    """
    This is custom authentication backend.
    Authenticate against the webservices call.

    The method below would override authenticate() of django.contrib.auth
    """
    def authenticate(self, username = None, password = None):
        print "inside authenticate of username and password with username being : "+username
        return None

    def authenticate(self,token=None):
        print "inside authenticate of token with token being : "+token
        return None

The problem is even when I am checking for username and password in post request it calls the token one as token is there, but how could I force it somehow?
I tried deleting the cookie and trying again but still it doesn't fire up the authentication function with username and password as params.
What could be solution for this please?

A: You are correct, Python doesn't support function overloading, because it simply doesn't need it. What happens in your case is that the second declaration of authenticate overwrites the first one, so you are left with only one version of authenticate, the one that takes token as a parameter.
What you should do instead is (just an example, there are many possible solutions):
class CustomNCPAuthBackend(object):
    """
    This is custom authentication backend.
    Authenticate against the webservices call.

    The method below would override authenticate() of django.contrib.auth
    """
    def authenticate_password(self, username=None, password=None):
        print "inside authenticate of username and password with username being : "+username
        return None

    def authenticate_token(self,token=None):
        print "inside authenticate of token with token being : "+token
        return None

    def authenticate(self, token=None, username=None, password=None):
        if token is not None:
             return self.authenticate_token(token)
        else:
             return self.authenticate_password(username, password)

This way it will work with the AuthMiddleWare you wrote.


text:
Q: Understanding an issue with the namedtuple typename and pickle in Python Earlier today I was having trouble trying to pickle a namedtuple instance. As a sanity check, I tried running some code that was posted in another answer. Here it is, simplified a little more:
from collections import namedtuple
import pickle

P = namedtuple("P", "one two three four")

def pickle_test():
    abe = P("abraham", "lincoln", "vampire", "hunter")
    f = open('abe.pickle', 'w')
    pickle.dump(abe, f)
    f.close()

pickle_test()

I then changed two lines of this to use my named tuple:
from collections import namedtuple
import pickle

P = namedtuple("my_typename", "A B C")

def pickle_test():
    abe = P("ONE", "TWO", "THREE")
    f = open('abe.pickle', 'w')
    pickle.dump(abe, f)
    f.close()

pickle_test()

However this gave me the error
  File "/path/to/anaconda/lib/python2.7/pickle.py", line 748, in save_global
    (obj, module, name))
pickle.PicklingError: Can't pickle <class '__main__.my_typename'>: it's not found as __main__.my_typename

i.e. the Pickle module is looking for my_typename. I changed the line P = namedtuple("my_typename", "A B C") to P = namedtuple("P", "A B C") and it worked.
I looked at the source of namedtuple.py and at the end we have something that looks relevant, but I don't fully understand what is happening:
# For pickling to work, the __module__ variable needs to be set to the frame
# where the named tuple is created.  Bypass this step in enviroments where
# sys._getframe is not defined (Jython for example) or sys._getframe is not
# defined for arguments greater than 0 (IronPython).
try:
    result.__module__ = _sys._getframe(1).f_globals.get('__name__', '__main__')
except (AttributeError, ValueError):
    pass

return result

So my question is what exactly is going on? Why does the typename argument need to match the name of the factory for this to work?

A: In the section titled What can be pickled and unpickled? of the Python documentation it indicates that only "classes that are defined at the top level of a module" can be pickled. However namedtuple() is a factory function which is effectively defining a class (my_typename(tuple) in your second example), however it's not assigning the manufactured type to a variable named my_typename at the top level of the module.
This is because pickle saves only the "fully qualified" name of such things, not their code, and they must be importable from the module they're in using this name in order to be able to unpickled later (hence the requirement that the module must contain the named object at the top level).
This can be illustrated by seeing one workaround for the problem—which would be to change one line of the code so that the type named my_typename is defined at the top level:
P = my_typename = namedtuple("my_typename", "A B C")

Alternatively, you could just give the namedtuple the name "P" instead of "my_typename":
P = namedtuple("P", "A B C")

As for what that namedtuple.py source code you were looking at does: It's trying to determine the name of module the caller (the creator of the namedtuple) is in because the author knows that pickle might try to use it to import the definition to do unpickling and that folks commonly assign the result to variable with the same name that they passed to the factory function (but you didn't in the second example).


text:
Q: Django-Haystack elasticsearch queries Haystack generates elasticsearch queries to get results from elasticsearch. The queries get prepended with a filter containing the following query:
"query": {
    "query_string": {
        "query": "django_ct:(customers.customer)"
     }
}

What is the meaning of the django_ct(..) query? Is this a function that haystack installs in elasticsearch? Is it some caching magic? Can I get rid of this part altogether?
The reason why I'm asking is that I have to build a custom query to use an elasticsearch multi_field. In order to change the queries I want to understand first how haystack generates its own queries.

A: Haystack uses Django's content types to determine which model attributes to search against in Elasticsearch. This is not really best practice, but it's how it's done in HS.
Basically, the code in HS looks something like this:
app_name, model_name = django_ct.split('.')
ct = ContentType.objects.get_by_natural_key(app_name, model_name)
model = ct.model_class()
# do stuff with model

So, you really don't want to ignore it when using haystack, if you are indexing more than one model in your index.
I have a couple other answers based on elasticsearch here: index analyzer vs query analyzer in haystack - elasticsearch? and here: Django Haystack Distinct Value for Field
EDIT regarding multi-fields:
I've used Haystack and multifields in the past, so I'm not sure you need to write you own backend. The key is understanding how haystack creates searches. As I said in one of the other posts, everything goes into query_string and from there it creates a lucene based search string. Again, not really best practice.
So let's say you have a multi-field that looks like this:
            "some_field": {
                "type": "multi_field",
                "fields": {
                    "some_field_edgengram": {
                        "type": "string",
                        "index": "analyzed",
                        "index_analyzer": "autocomplete_index",
                        "search_analyzer": "autocomplete_search"
                    },
                    "some_field": {
                        "type": "string",
                        "index": "not_analyzed"
                    }
                }
            },

In haystack, you can just search against some_field and some_field_edgengram directly.
For example SearchQuerySet().filter(some_field="cat") and SearchQuerySet().filter(some_field_edgengram="cat") will both work, but the first will only match tokens that have cat exactly and the second will match cat, cats, catlin, catch, etc, at least using my edgengram analyzers.
However, just because you use haystack for indexing and search doesn't mean you have to use it for 100% of your search solutions. In the past, I've used PYES in some areas of the app and haystack in others, because haystack lacked the support for more advanced features and the query_string parsing was losing some of the finer grained accuracy we were looking for.
In your case, you could get results from the search engine via elasticutils or python-elasticseach directly for some more advanced searches and use haystack for the other more routine searches.


text:
Q: How can I make an object immutable in the Google V8 Javascript engine? Is it possible to make an object immutable in the V8 Javascript Engine? V8 is embedded in a C++ application.
In my case I've created and populated an Array (code is simplified)
auto arr = v8::Array::New(isolate, 10);
for (auto i = 0; i < 10; ++i)
{
    arr->Set(context, i, v8::Integer::New(isolate, i));
}

I'd like to make the resulting object "read-only" (as you might get by calling Object.freeze) before passing it to a script. One of my script authors got themselves in a confusing situation by trying to re-use this object is a convoluted way, and I'd like to make it harder for this to happen by making the object immutable.
I understand that I can do this in Javascript (Object.freeze), but I would like to be able to do it in C++ if possible.

A: This approach works, although it's a little inelegant. Essentially, I'm calling "Object.freeze" directly in Javascript, as I couldn't find a way to invoke this functionality from C++. I'm less than fluent in V8, so my code may be unnecessarily verbose.
/**
 * Make an object immutable by calling "Object.freeze".
 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze
 **/
void ezv8::utility::MakeImmutable(v8::Isolate * isolate, v8::Local<v8::Object> object)
{
    ezv8::Ezv8 ezv8(isolate);
    auto globalTmpl = v8::ObjectTemplate::New(isolate);
    auto context = v8::Context::New(isolate, nullptr, globalTmpl);

    v8::Isolate::Scope scope(isolate);
    v8::Locker locker(isolate);
    v8::HandleScope scope(ezv8.getIsolate());
    v8::Context::Scope context_scope(context);

    // Define function "deepFreeze" as listed on the "Object.freeze" documentation page cited above.
    std::string code(
        "function deepFreeze(obj) {\n"
        "    var propNames = Object.getOwnPropertyNames(obj);\n"
        "    propNames.forEach(function(name) {\n"
        "        var prop = obj[name];\n"
        "        if (typeof prop == 'object' && prop !== null)\n"
        "            deepFreeze(prop);\n"
        "    });\n"
        "    return Object.freeze(obj);\n"
        "};");

    v8::Local<v8::String> source = v8::String::NewFromUtf8(isolate, code.c_str());

    v8::Local<v8::Script> compiled_script(v8::Script::Compile(source));

    // Run the script!
    v8::Local<v8::Value> result = compiled_script->Run();

    v8::Handle<v8::Value> argv[]{ object };

    v8::Handle<v8::String> process_name = v8::String::NewFromUtf8(isolate, "deepFreeze");
    v8::Handle<v8::Value> process_val = context->Global()->Get(process_name);

    v8::Handle<v8::Function> process_fun = v8::Handle<v8::Function>::Cast(process_val);
    v8::Local<v8::Function> process = v8::Local<v8::Function>::New(isolate, process_fun);

    // Call the script.
    v8::Local<v8::Value> rv = process->Call(context->Global(), 1, argv);
}


text:
Q: Installing Laravel I am on a windows 8 machine and I'm trying to learn laravel. I copy and pasted my PHP folder from C:\xampp to C:\php, installed composer, ran composer install  then composer create-project laravel/laravel learning-laravel. So far everything was created so I went into the directory and tried to use 'php artisan serve' and got the following error.
C:\Users\denni_000\learning-laravel>php artisan serve
Warning: require(C:\Users\denni_000\learning-laravel\bootstrap/../vendor/autoloa
d.php): failed to open stream: No such file or directory in C:\Users\denni_000\l
earning-laravel\bootstrap\autoload.php on line 17

A: Why you copied php folder

*

*download composer install it.

*download laravel latest version and store it on your xampp/htdocs/laravel

*and run cmd with composer install command

For more follow install laravel on windows xampp
or Laravel 4.1 installation with composer in xampp

A: Follow the installation guide from Laravel

*

*Install Composer:
Like Laravel.com says: "Make sure to place the ~/.composer/vendor/bin directory in your PATH so the laravel executable can be located by your system."

*Type the following statement in the command line:
composer global require "laravel/installer=~1.1"

*Create a fresh Laravel project in a specified directory with the "laravel new" command:
laravel new blog

You can also create a Laravel project using composer, like such:
composer create-project laravel/laravel --prefer-dist

A: For windows Simply download Laragon which includes latest php 5.6.7, Apache, Mysql, Redis, Memcached an alternative to Xampp or Mamp with small size. Easy to install laravel and create project with auto create virtual host by it. Thank you.

A: U need to go to the directory where laravel is installed and run the following command.
composer update

A: Install Laravel 4.2 with composer:
sudo composer.phar create-project laravel/laravel project-directory-name 4.2 --prefer-dist

A: Here is a different way to setup laravel, may be you guys will like it
Step 1:
Clone https://github.com/laravel/laravel or you may download zip also.
Step 2:
Navigate to downloaded folder in command prompt and run composer install
Step 3:
open the folder and rename .env.example to .env and update the credentials mentioned in file.
Step 4:
After these steps if you navigate to the directory from web-server it will cause an error No supported encrypter found. The cipher and / or key length are invalid. to fix this just run php artisan key:generate
Done!
Hope you guys like this way :)

A: You need to install all the laravel required dependency.
To do that, you need to tell composer to install everything needed.
Below is the command to use to install that's required in laravel composer.json.
composer install

A: If you want to learn laravel I seriously recommend you use laravel homestead with vagrant.
For this you need to:

*

*Install virtualbox.

*Install vagrant.

*Install git.

*Install ssh.exe (Download msysgit and copy the content of bin folder to git bin folder).

*Install Homestead on Vagrant (Follow the steps on laravel/homestead documentation page).

*Install Laravel on Homestead (Follow the steps on laravel/installation documentation page).

This method apply to Windows, Linux or Mac, only change the step 4 on linux or mac.


text:
Q: Missing 1 pin in my Ethernet Port - Can I get 1gbit again? One of the pins inside my Ethernet port on my laptop was bent, so I tried to correct it but it broke off.
It's the leftmost one (it connects to the white/orange cable).
My internet is working but I'm getting a 100mbit connection.
So my question is, can I change/reroute some cables inside the network cable to get it back at 1gbit, or do I need to buy an USB network adapter?

A: Gigabit ethernet requires all 8 pins to connect.  See the diagram below:

You can buy a gigabit to USB adapter.
Alternatively, the ethernet port can probably be replaced in the laptop by someone good at soldering.  Check computer repair shops in your area and ask them if they can remove and replace it.  Not all shops do soldering work.


text:
Q: MVC 4 RenderSection() don't visualize defined section I have a project based on MVC 4. I am trying to use the @RenderSection("Footer", false) functon to visualize my footer, but it is not displayed. I will post two links to my Layout file and to my View file.

*

*Layout link: http://pastebin.com/78cQE5vD

*View link: http://pastebin.com/r5qewYi2


text:
Q: awk partly string match (if column/word partly matches) My dummy file looks like this:
C1    C2    C3
1     a     snow
2     b     snowman
snow     c     sowman

I want to get line if there is string snow in $3. I can do this like this:
awk '($3=="snow" || $3=="snowman") {print}' dummy_file

But there should be more simpler way.

A: Print lines where the third field is either snow or snowman only:
awk '$3~/^snow(man)?$/' file

A: Also possible by looking for substring with index() function:
awk '(index($3, "snow") != 0) {print}' dummy_file

Shorter version:
awk 'index($3, "snow")' dummy_file

A: awk '$3 ~ /snow/ { print }' dummy_file

A: Maybe this will help
http://www.math.utah.edu/docs/info/gawk_5.html
awk '$3 ~ /snow|snowman/' dummy_file

A: GNU sed
sed '/\s*\(\S\+\s\+\)\{2\}\bsnow\(man\)\?\b/!d' file

Input:

C1    C2    C3
1     a     snow
2     b     snowman
snow     c     sowman
      snow     snow     snowmanx

..output:

1     a     snow
2     b     snowman


text:
Q: Java Event Listeners I'm trying to separate components of my Java desktop app into different classes.  For example, I have a MenuBar class, called from the MainClass, that creates the JMenuBar.
Normally, I would implement ActionListener in the MenuBar class and override actionPerformed() to keep everything organized.  But if I do that, how can I let the MainClass know what was clicked?
I tried implementing my own ActionListener, but I couldn't come up with a solution that was capable of dispatching events to other classes.
MainClass.java
public class MainClass extends JFrame {

     private static void createAndShowGUI() {

        JFrame.setDefaultLookAndFeelDecorated(false);
        JFrame frame = new JFrame("Main Window");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        MenuBar menuBar = new MenuBar();
        JMenuBar mb = menuBar.createMenu();
        frame.setJMenuBar(mb);

        frame.setSize(400,400);
        frame.setVisible(true);

     }

     public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
        public void run() {
           createAndShowGUI();
        }
      });
    }

}

MenuBar.java
public class MenuBar implements ActionListener {

     public JMenuBar createMenu() {

         JMenu menu;
         JMenuItem item;

         JMenuBar menuBar = new JMenuBar();

         menu = new JMenu("Main");
         menuBar.add(menu);

         item = new JMenuItem("New");
         menu.add(item);

         return menuBar;

   }

   @Override
   public void actionPerformed(ActionEvent e) {
         JMenuItem source = (JMenuItem)(e.getSource());
         System.out.println("Action triggered on: "+source.getText());
         // *** Let MainClass know what was clicked ??
   }

}

EDIT
I realized I can just create an ActionListener in the MainClass and pass that to the MenuBar class, like this:
Amended MainClass.java
ActionListener l = new ActionListener() {
   public void actionPerformed(ActionEvent ae) {
     System.out.println(ae.getActionCommand());
   }
};

MenuBar menuBar = new MenuBar();
frame.setJMenuBar(menuBar.createMenu(l));

And then, in MenuBar, I just apply the ActionListener to each of the menu items.
Amended MenuBar.java
public JMenuBar createMenu(ActionListener l) {

    item = new JMenuItem("Hide When Minimized");
    item.addActionListener(l);
    menu.add(item);

}

A: One possible solution is MainClass implements ActionListener and pass its instance to MenuBar.createMenu():
public class MenuBar {

   public JMenuBar createMenu( ActionListener l ) {
      ...
      menuItem.addActionListener( l );
   }
   ...
}

MainClass side:
public class MainClass extends JFrame {

   @Override
   public void actionPerformed(ActionEvent e) {
      Object source = e.getSource();
      System.out.println( "Action triggered by: " + source );
   }

   private static void createAndShowGUI() {
      ...
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      MenuBar menuBar = new MenuBar();
      JMenuBar mb = menuBar.createMenu( frame );
      frame.setJMenuBar( mb );
      ...
   }
}

Another way is to use java.beans.PropertyChangeListener and java.beans.PropertyChangeSupport


text:
Q: Find the biggest Value in one row and print a different row I am learning Python and I'm trying to print out the city with the biggest population.
I have the function where I can get the biggest population
but I don't know how can I return the city with the biggest population.
The code I already have:
import csv

csvfile = open('worldcities.csv', "r", encoding="utf8")
csv_reader = csv.reader(csvfile, delimiter=';')
next(csv_reader, None)  # skip the headers

maxVal = []

for row in csv_reader:
    try:
        maxVal.append(float(row[9]))
    except ValueError:
        a = 1

print ("\nDie Stadt mit der höchsten Einwohnerzahl:", max(maxVal))

My CSV data:

A: import pandas as pd
df = pd.read_csv('worldcities.csv', sep=';', encoding='utf-8')
print(df.iloc[df['population'].idxmax(), :])


text:
Q: How to statistically prove that my diagnostic method works Let's say I have N samples and two diagnostic methods (one is one which I develop and the other one is default). There are four groups to which these N samples fall:

A: My method +, referential +
B: My method -, referential -
C: My method +, referential -
D: My method -, referential + (actually, zero samples here)

Is there a way to statistically prove, knowning number of samples for groups A, B, C, that my method is "better" than the default?
More specific schema of what I do:
There is known diagnosis method of samples. I develop a way to process samples in order to increase sensitivity of that method. I take sample, diagnose it, then I process it, and diagnose it again.
Sometimes after the processing sample which was "negative" becomes "positive", from which I conclude that my method worked — it allowed to diagnose "hidden" form of agent, which couldn't be noticed initially. I know this from the theoritical background of my work.
— Is there a way to prove statistically that positive result after my processing, when there was negative before, is not merely an "error" or "random"?
— Is there some other way/schema of an experiment which I could use to statistically prove that my method really uncovers hidden factor, not just giving random results?


text:
Q: What is the best way to inject HTML into the DOM with jQuery? I'm working on a calendar page that allows a user to click on a day, and enter an entry for that day with a form that pops up.
I'm no stranger to DOM manipulation with jQuery, but this is something I've done before and I'm beginning to wonder if there's a more efficient way to do this?
Would building the HTML manually within JavaScript be the most efficient way performancewise (I assume this is true, over using functions like appendTo() etc) or would creating a hidden construct within the DOM and then cloning it be better?
Ideally I want to know the optimal method of doing this to provide a balance between code neatness and performance.
Thanks,
Will

A: Here you can find the explanation.

A: Working with huge chunks of HTML strings in JavaScript can become very ugly very quickly. For this reason it might be worth considering a JavaScript "template engine". They needn't be complicated - Check out this one by Resig.
If you're not up for that then it's probably fine to just continue as you are. Just remember that DOM manipulation is generally quite slow when compared to string manipulation.
An example of this performance gap:
// DOM manipulation... slow
var items = ['list item 1', 'list item 2', 'list item 3'];
var UL = $('
');
$.each(items, function(){
    UL.append('
' + this + '
');
});

// String manipulation...fast
var items = ['list item 1', 'list item 2', 'list item 3'];
var UL = $('
').append( '
' + items.join('

') + '
' );

A: Maybe not the most popular approach.
Have the html code generated in the backend. The dialog will be in a css hidden div. When you want it to "pop", just apply different css styles and change a hidden input value(i guess the dialog interacts with that certain date).


text:
Q: SQLite3 imported information not working in a while loop vrnaam = input("Vul de voornaam van de student in: ")
atnaam = input("Vul de achternaam van de student in: ")
while vrnaam or atnaam not in str(stdpaden):
    print("Foute invoer")
    vrnaam = input("Vul de voornaam van de student in: ")
    atnaam = input("Vul de achternaam van de student in: ")

The while loop is for if someone puts in the name and surname of someone incorrectly. "stdpaden" is extracted from a table inside an SQLite 3 database. Using a print statement it looks like this:
[('4', 'Joswa', 'Schrevel', '1', 'Intelligent Systems', 'nee')]

Yet when I call vrnaam = Joswa and atnaam = Schrevel, it doesn't work and it just stays inside the loop. Is there anything I am overseeing?

A: First, stdpaden is a list of tuples, so you need to flatten that to a list of strings. You can do that in a list comprehension ([i for x in stdpaden for i in x]). Then, your or statement doesn't make sense as is: I guess you're trying to see if both vrnaam or atnaam, so you need to give each their own not in statement. I think this works (it breaks out of the loop if you insert Joswa and Schrevel):
while vrnaam not in [i for x in stdpaden for i in x] or atnaam not in [i for x in stdpaden for i in x]:
    print("Foute invoer")
    vrnaam = input("Vul de voornaam van de student in: ")
    atnaam = input("Vul de achternaam van de student in: ")

For clarity of code, I would personally unpack your list of tuples first:
stdpaden = [i for x in stdpaden for i in x]

while vrnaam not in stdpaden or atnaam not in stdpaden:
    print("Foute invoer")
    vrnaam = input("Vul de voornaam van de student in: ")
    atnaam = input("Vul de achternaam van de student in: ")

Alternative to the list comprehension
Instead of [i for x in stdpaden for i in x], you could use itertools to flatten your stdpaden list of tuples:
stdpaden = list(itertools.chain(*stdpaden))

while vrnaam not in stdpaden or atnaam not in stdpaden:
    print("Foute invoer")
    vrnaam = input("Vul de voornaam van de student in: ")
    atnaam = input("Vul de achternaam van de student in: ")


text:
Q: What's the best practice of typing hint after python 3.9? After python3.9, there are at least three ways to use typing hint. Take the build-in collection set for instance:
# way 1
def f(s: set[str]) -> str:
    pass

# way 2
def f(s: typing.Set[str]) -> str:
    pass

# way 3
def f(s: collections.abc.Set[str]) -> str:
    pass

# way 3': or arguable collections.abc.MutableSet vs collections.abc.Set
def f(s: collections.abc.MutableSet[str]) -> str:
    pass

Furthermore, for some abstract type there are two version in typing and collections.abc, take Mapping for instance:
def f(m: typing.Mapping[str, int]) -> int:
    pass

def f(m: collections.abc.Mapping[str, int]) -> int:
    pass

According to The Zen of Python:

There should be one-- and preferably only one --obvious way to do it.

I am confused which one is best?

A: You should be using the set[str] style of typing. Looking at PEP 585:

Importing those from typing is deprecated. Due to PEP 563 and the intention to minimize the runtime impact of typing, this deprecation will not generate DeprecationWarnings. Instead, type checkers may warn about such deprecated usage when the target version of the checked program is signaled to be Python 3.9 or newer.

So importing those from python's typing package is now deprecated and you ideally should not be using those anymore; however, if you need to be backwards compatible with older versions of python, you can get by using them for now. Just be aware that in 5 years you may need to go in and update your code base since you will nedd python 3.9:

Tooling, including type checkers and linters, will have to be adapted to recognize standard collections as generics.
On the source level, the newly described functionality requires Python 3.9


text:
Q: Uniform norm for all functions Uniform norm on the space of continuous functions from [0,T] on $\Bbb R$ is
$\|f\|=\max_{t\in[0,T]} |f(x)|$
I am wondering why can't we extend this norm to all functions including functions that are not continuous? What properties of a norm do not for a discontinuous function?

A: Non continuous functions are not necessarily bounded, and so the maximum need not exist. You can however replace max by supremum and extend to the space of all bounded functions.


text:
Q: Deadlock on tidtcpserver.active = false (Delphi2007/indy10) I am having a problem with some code that was written by a developer that has now left our company, the code implements a tcpserver that responds to an XML based protocol. This appears to be working absolutely fine in our test environment but one or two customers are having problems with application shutdown.
I have traced this to what appears to be a deadlock when tidtcpserver.active = false is called. I am already aware that a deadlock can be caused by one of the connection treads making a synchronised call to the main thread, whilst the main thread is waiting for the connection threads to terminate.
I am already using a tidthreadsafestringlist to pass the data to the main thread for processing, and where I need to call a procedure from the main thread I have created a tidnotify descendant to do this. can anyone think of anything else to look for.

I had already been checking the exception handling,
this is what i have in the onexecute event
try
  // code to handle connection including tidnotify etc....
except
  on E:Exception do
  begin
    if (e.InheritsFrom(EIdSilentException) = False) then
      TXMLTraceNotify.XMLTrace('TCPServerExecute: ' + E.Message,ttProblem, FTraceProc);
    raise; //we must raise all exceptions for indy to handle them.
  end;

end;

Here is how i'm using the TS-stringlist
Declaration.
public
  TransactionStrings: TIdThreadSafeStringList;

its created in the constructor and destroyed in the destructor.
this is how i'm adding to it in the context of the tcpserver.
  TransactionStrings.Add(newTrans.AsString);

And this is how i'm reading from it in the context of the main application thread
slXMLTrans := TStringList.Create;
try
  slTemp := FCustomXMLServer.TransactionStrings.Lock;
  try
    slXMLTrans.Assign(slTemp);
    slTemp.Clear;
  finally
    FCustomXMLServer.TransactionStrings.Unlock;
  end;

  if slXMLTrans.Count > 0 then
  begin
    for i := 0 to Pred(slXMLTrans.Count) do
      TAbstractTerminal.ProcessXMLTrans(slXMLTrans[i]);
    slXMLTrans.Clear;
  end;
finally
  slXMLTrans.Free;
end;

I think this is the correct way to use it but I await your comments.

A: Deadlocks when setting the Active property to False are a classic, and often discussed, issue when using TIdTCPServer incorrectly.  The only way the server deadlocks is when the connection threads do not terminate correctly.  That MAY be caused by synchronizing operaton to the main thread while the main thread is busy deactivating the server, in which case the use of TIdNotify would does eliminate any such deadlock conditions.
However, that is not the only way to prevent a connection thread from terminating.  Another possibility is if your server event handlers have exception handling in them that is blocking Indy's internal notifications from being processed.  That can cause runaway threads that keep running but never know that they need to stop.  If you are catching exceptions in your code, make sure you re-throw any EIdException-derived exceptions and let the server handle them internally.


text:
Q: restoring view's counter I have an additional page called "precious feet" and when I first set it up I could view the amount of visits it got, however now it won't show this information, it also gives me the option to "like" which it never did before and I assume that is because it is my page and of course I will like it. Can anybody help me restore the functions. I have tried logging out and back in again but to no avail.

A: It sounds like you aren't the page admin anymore or you have a group not a page. Try clicking on the down arrow on the top right and under "Use Facebook as:" select your page. If it isn't there then it's likely you are no longer a page admin.


text:
Q: How to avoid retaining string values in C in function calls Edit: solution was to use strdup()
I have re-asked my question.
How to create to a new string to use as a key everytime I call a function?
I want to a fresh variable char[] newer everytime my function is called. The reason is because I set my key as newer in a global hashmap. I don't want keys being modified everytime I call the function and modify newer.
#include <stdio.h>
#include <string.h>
void new(){
    char  newer[45];
    printf("%s\n", newer);
    strncat(newer,"hi",1235);
}
int main()
{
    int i = 0;
    for (i = 0; i < 6; i++){
        new();
    }
}

My current output is
hi
hihi
hihihi
hihihihi
hihihihihi

but I want it to be
hi
hi
hi
hi
hi

Edit: I forgot to mention the purpose of my code.
I'm not able to post the code completely since it's a school project. Basically let's say I have a global hashmap that takes (key,value) pairs. Everytime I call the new() it should add a new entry to the hashmap. For example I have a function add which is supposed to add (key = newer, value = "something") to the global hashmap. I want hashmap = { key1="hi":value1="stuff",key2="hihi":value2=stuff2"} after 2 calls to the function.
For some reason my hashmap ends up being {key1="hi:value1="stuff"} after 1 call and then {key1="hihi":value1="stuff",key2="hihi":value2="stuff2"} after 2 calls. The reason is because the key1 = newer and key2 = newer so thus key1=key2. This means that everytime I modify variable newer in a function call, it literally changes my previous key's values
For example in python I could do the following since everytime I call newer, it is a fresh variable that has no relationship with previous calls using newer.
def new(i,diction):
    newer = "hi" * i
    diction[newer] = "stuff" + str(i)

diction = {}
for i in range(10):
    new(i,diction)

print(diction)

Essentially result is
{'': 'stuff0', 'hihi': 'stuff2', 'hihihihihihi': 'stuff6', 'hi': 'stuff1', 'hihihi': 'stuff3', 'hihihihi': 'stuff4', 'hihihihihihihi': 'stuff7
', 'hihihihihihihihihi': 'stuff9', 'hihihihihihihihi': 'stuff8', 'hihihihihi': 'stuff5'}
I want to ask how to do the same thing in C

A:
I want to reset the value of the char[] newer everytime my new function is called.

All you need is to initialise it properly:
char newer[45] = "";

As a general rule, you should always initialise local variable before using it. Failing to do so will usually lead to unexpected behaviour as you've seen in your code.

A: Made a small modification to your program as below.And now it's showing expected output:
1)initilized the char array.
2)appended hi to array and size modified to 2
3)print it.
#include <stdio.h>
#include <string.h>

void new()
{
    char  newer[45]="";
    strncat(newer,"hi",2);
    printf("%s\n", newer);
}
int main()
{
    int i = 0;
    for (i = 0; i < 6; i++){
        new();
    }
}


text:
Q: Convert array into json i have data which is an array like:
arr=["[[name,address,contact],[name1,address1,contact1],[name2,address2,contact2]]"]

How to change this array in json and get those value in a table in react.

A: Use json.parse

arr=["[[name,address,contact],[name1,address1,contact1],[name2,address2,contact2]]"]
let datax = JSON.parse(arr[0].replace(/(\w+)/g, '"$1"'));
console.log(datax)


text:
Q: N-Ch FET with open-drain output I stumbled across this line in this datasheet (page 10):

Serial Data Output Pin. Internal N-Ch FET with open-drain output that
  requires external pull-up resistor. It shifts out the previous eight
  SDI bits that allow daisy-chain operation of multiple packages.

Could somebody briefly explain what this means? Specifically, if I'm not planning on using the daisy-chain functionality, can I leave this pin unconnected or do I need to connect it to an external pull-up resistor regardless?

A: The data that you shift in on SDI will be shifted out on SDO. You can optionally connect multiple of these devices in series:

simulate this circuit – Schematic created using CircuitLab
This means you only need a single data pin and a clock pin on your microcontroller to access all these device, all you need to do is apply enough clock pulses to get the data to/from all the devices.
The open drain means that the output can only pull low, pull to ground. It cannot by itself make a high signal, it needs help for that from an external resistor. The transistor pulls the output low and when the transistor is 'released' the resistor will pull the output up to Vcc.

simulate this circuit
The advantage of open drain (or open collector when using a BJT) is that you can tie multiple outputs together without problems.

A: If you are not using the serial daisy chain then you can leave the SDO pin open and not have to install a pullup resistor on this pin.
The AD5290 part is designed to allow its use in analog circuits that have power supplies up to and including +/- 15V. This allows the "digital pot" terminals to connect into OpAmp circuits (and other similar types) that operate on voltage rails of this magnitude.
The main reason that the SDO pin on this part is open drain is that it allows the device to be built into a package of 10 pins and eliminates a need for a digital logic level supply pin. If the SDO pin (the only digital output on the part) was designed with a push-pull output then the extra digital supply pin would be required.
As others have stated the open drain nature of the pin is such that the pin could be be tied together with multiple other open drain outputs but that has very little utility in the use of this particular part. Instead it can have a role in the daisy chain operation when the digital supply levels are other than a 5V supply. A close look at the VIH and VIL specifications for the part will show that the inputs to this device can be driven equally well from a digital realm of 5V or from 3.3V.The open drain SDO can be externally wired up to a 5V or a 3.3V pullup with equal utility depending on which digital rail is used in the system.

A: See page 16. SDO is only used if devices are daisy-chained.

A: SDO is an open-drain output-only pin.  It needs a pullup resistor in order to drive a logic 1 out, otherwise the SDO pin will remain at ground.  The internal NFET drives a "0".  Open drain pins allow multiple devices to be tied together w/o fighting, since there's no active pullup.


text:
Q: How to rename, in an XML file, specific tags that are embedded in some other specific tags What is the xmlstarlet command to replace a tag value by another one, only for specified tags embedded in other specified tags?
Example: searching every occurance of the tag b, that needs to be replaced by d only if it is within the  ...  tag (inside other tags):

*

*Input example:
<c>This is an example. This is a test;</c>

*Desired output:
<c>This is an example. This is <d>a test;</d></c>

This post is related to How to replace, in an XML file, specific strings of characters in some specified tags with other strings of characters embedded in tags in the solution I am trying to find to format xml files.

A: $ cat file
<c>This is an example. This is a test;</c>

$ xmlstarlet ed --rename '//a/b' -v 'd' file
<?xml version="1.0"?>
<c>This is an example. This is <d>a test;</d></c>

This renames all b nodes that occur directly under an a node.  The new name for these nodes will be d.  Since I'm using // in front of a/b in the XPath expression, it does not matter where the a node is located within the document structure.


text:
Q: how to create postgresql server on rhel7 linux vm in gcp I am actually planning to have a PostgreSQL instance on rhel7 linux vm running on google cloud platform,
Can you let me know the process for the same.
One more query is it ok to install postgresql on vm rather than going for a cloud sql instance on gcp?
Thanks,
Moin.

A: Just go to the PostgresSQL official downloads page for redhat and install the software.
You can get the RPMs there if you need to do an air-gapped installation.
You'll need to configure postgres later. See Posgres docs Chapter 18. Server Setup and Operation.


text:
Q: Meaning of class file on the file system I'm studying on lambda expressions, the book illustrates an example that uses toString() method of lambda expressions.
Supplier<ArrayList<String>> s1 = ArrayList<String>::new;
ArrayList<String> a1 = s1.get();
System.out.println(s1);
//Output: functionalinterface.BuiltIns$$Lambda$1/791452441@1fb3ebeb

It explains meaning of the output as,

This actually does mean something. Our test class is named BuiltIns ,
  and it is in a package that we created named functionalinterface .
  Then comes $$ , which means that the class doesn't exist in a class
  file on the file system. It exists only in memory.

I don't understand the meaning of the last sentences. Could you express it?
Source: OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide, Jeanne Boyarsky, Scott Selikoff

A: Well the book is slightly misleading. The statement it indeed correct, but with a minor correction. It assumes that if you have $ in a class name it is automatically created (not by you); which might not be a fact.
For example suppose this example:
public class TestSO {

   public static void main(String[] args) {
      Test t = new Test() {
      };
   }

   static class Test {}
}

You have created an anonymous inner class which is actually a plain class created by the compiler. If you compile TestSO you will see a class called TestSO\$1.class that was a created for you. If you inspect how it looks with javap -c -p TestSO\$1.class you will see something like this:
final class TestSO$1 extends TestSO$Test { ...

But at the same time it is perfectly legal for you to declare a class/method that contains the $ symbol:
static class $$Test2$$ {}

So the presence of $$ is not a strong indication that the class is generated by compiler/runtime. Also that's an implementation detail that could change some day...
Now at the same time the book is correct in the fact that the class doesn't exist in a class file on the file system. It exists only in memory.
Supplier is an interface and you have not provided a class that implements it, have you? Well what happens next is interesting.
I am not going to go in a lot of details, but here is a simplified explanation.
If you de-compile your example (javap -p -c -v TestSO.class) you will see a line like this:
invokedynamic #2,  0  // InvokeDynamic #0:get:()Ljava/util/function/Supplier;

What invokedynamic does is letting the runtime decide how to provide an actual instance of that Supplier.  And at runtime there is an actual class created that implements that Supplier that is used.
You can see how that class looks like with a command used when running it:
-Djdk.internal.lambda.dumpProxyClasses=/Your/Path/Here

As a result in that path you will see a class called:
TestSO$$Lambda$1.class

And again if you decompile it with javap -c -p  TestSO\$\$Lambda\$1.class:
 final class TestSO$$Lambda$1
         implements java.util.function.Supplier {....

What the author is trying to say is that there will be a class generated for you at runtime that implements the Supplier interface, but its not you who have created it.

A: This cite is an attempt to explain something in easier or more colloquial terms, avoiding to be too formal, however, the result can be called disastrous.
The name actually means nothing. The class of the instance provided for a lambda expression or method reference is intentionally unspecified and so is its name. It is even unspecified whether the toString() method which is implicitly invoked when executing System.out.println(s1); will produce the "classname@hashcode" output.
Whether file systems are involved or not, is irrelevant. The correct and the actual point is that the class of that instance is not among the classes created by the Java compiler when your application is compiled. Instead, it is provided by the JRE at runtime in an implementation specific way. OpenJDK does provide a generated class that happen to have a name that contains the class containing the lambda expression and a $$, but, as said, that's an implementation detail. And, as explained by Eugene, the dollar sign is a legal part of Java identifiers, so the presence of two dollar signs doesn't prove a particular property.

A:
When you create a class, you type out a .java file and compile it to a
  .class file. Both are actual files that exist somewhere on your
  filesystem. The $$ shows it is different. There is no .java class on
  the filesystem. Instead Java creates the class for us. That way you
  don't have to type out a class and can just supply the lambda
  expression.

Answered by its author, Ms.Boyarsky


text:
Q: Interplay between the cosmological constant and "microscopic" properties of string vacua As far as I understand, string phenomenology is usually concerned with compactifications of string theory, M-theory or F-theory in which the uncompactified dimensions form a 4-dimensional Minkowski spacetime. However, we know our actual universe has a positive cosmological constant hence its asymptotics are that of a De Sitter spacetime. On the intuitive level it makes sense to me, since the microscopic physics should have little to do with spacetime asymptotics. However, from another point of view I see a problem.
It seems to me that a cosmological constant in the effective 4-dimensional field theory requires a non-vanishing Ricci tensor in the compactified dimensions. For example, the classical case study for anti-De Sitter string theory is AdS_4 x S_6. The compactified dimensions form the sphere, a manifold with positive curvature, compensating the negative curvature of AdS.
This non-vanishing Ricci tensor seems to require different topology from a vanishing Ricci tensor.  Hence all standard compactifications like Calabi-Yau manifolds, G2 manifolds etc. don't seem to be compatible with a non-vanishing cosmological constant.
What am I missing here?

A: First of all, in the most recent decade, string phenomenology isn't talking about strictly Minkowski vacua. E.g. in the KKLT paper, you will see $AdS_4$ vacua uplifted to $dS_4$ by antibranes and no Minkowski space at any place in between.
The fact that a nonzero C.C. is generated for the large 3+1 dimensions doesn't mean that one can't find any shape of the hidden dimensions that exactly obey the equations of motion. Just like there exists a "tiny C.C." deformation of the flat Minkowski space, namely the $dS_4$ space with a small C.C. around us, there also exist solutions for the compact 6/7 dimensions that have a tiny (but nonzero) Ricci tensor proportional to the Ricci scalar. In the Calabi-Yau case, these deformed solutions will strictly no longer be $SU(3)$ holonomy manifolds; they will be $U(3)$ holonomy (Kähler) manifolds if we acknowledge that the Ricci curvature, while tiny, is nonzero.
In braneworld compactifications and compactifications on singular compactified manifolds, the energy density is typically concentrated at the loci of the branes or the singularities.


text:
Q: stupid `NetTrain[]` question Consider this sequence:
net = NetInitialize[
  NetChain[{LinearLayer[100], LogisticSigmoid, LinearLayer[100],
    LogisticSigmoid, LinearLayer[100], LogisticSigmoid,
    LinearLayer[100], LogisticSigmoid, LinearLayer[1] },
   "Input" -> {2, 11}]]

net = NetTrain[net, foo]

Tells me that the first element to NetTrain[] should be a fully specified net. But what is it about the net that is underspecified?

A: As swish hinted, the problem may due to an incorrect previous return. For example:
net = NetInitialize[
  NetChain[{LinearLayer[100], LogisticSigmoid, LinearLayer[100],
    LogisticSigmoid, LinearLayer[100], LogisticSigmoid,
    LinearLayer[100], LogisticSigmoid, LinearLayer[1]},
   "Input" -> {2, 11}]]

If we provide the incorrect training data, NetTrain fails with an error message
net = NetTrain[net, {RandomReal[{0, 1}, {2, 11}] -> 1}]
(* $Failed *)

NetTrain::invindim: Data provided to port "Output" should be a list of
  length-1 vectors.

Now if you run the training again with the correct data, you get the same error message in your question
net = NetTrain[net, {RandomReal[{0, 1}, {2, 11}] -> {1}}]
(* $Failed *)

NetTrain::invnet: First argument to NetTrain should be a fully
  specified net.

This is because, in the second run, the net has a value of $Failed, which is not a neural network.


text:
Q: Как вставить getText() в командную строку? Делаю так
Process pr=Runtime.getRuntime().exec(new String[]{"cmd.exe","/c","netsh wlan set hostednetwork mode=allow ssid=\"name.getText();\"

Но вместо введенного значения в TextField получаю "\"name.getText();"
Как правильно получить значение из TextField?

A: Всем спасибо за помощь!
Решил данную проблему так:
" + name.getText() +"

A: Зависит от того, что вы хотите получить. Если значение должно быть в кавычках, т.е. что-то такое: netsh wlan set hostednetwork mode=allow ssid="name", то надо сделать так:
"netsh wlan set hostednetwork mode=allow ssid=\"" + name.getText() + "\""

Если же без кавычек, то так:
"netsh wlan set hostednetwork mode=allow ssid=" + name.getText()

В Java, как и во многих других языках, при работе со строками, надо понимать, что \ означает экранирование символа, т.е. он будет добавлен к строке как есть(либо че как спец. символ, например \n перенос строки), а не восприниматься компилятором, как служебный символ.


text:
Q: How to push a new object into a JSON file using PHP I would like to push new object inside a JSON file with PHP but I don't find any solution on internet due to the format.
Here is my Json file.
{
"html": {
    "snippet1": {
        "id":"snippet1",
        "title":"A title"
    },
    "snippet2": {
        "id":"snippet2",
        "title":"Another title"
    }
}
}

And here is the php file
$json = file_get_contents('./content.json');
$data = json_decode($json);

$id = "snippet3";
$title= "My title";

I expect to push those new data inside the JSON.
The result should be:
 {
"html": {
    "snippet1": {
        "id":"snippet1",
        "title":"A title"
    },
    "snippet2": {
        "id":"snippet2",
        "title":"Another title"
    },
    "snippet3": {
        "id":"snippet3",
        "title":"My title"
    }
}
}

Thank you

A: $json = file_get_contents('./content.json');
$data = json_decode($json, true); //added true to make it an array

$id = "snippet3";
$title = "My title";

$data['html'][$id]['id'] = $id; //add the id to the array
$data['html'][$id]['title'] = $title; //add the title to the array
$newData = json_encode($data, true); //turn the array back into json

$writeJson = file_put_contents("content.json", $newData); //write the json array to json file


text:
Q: Mysql with docker: Can't connect to local MySQL server through socket I cannot use MySQL anymore in my Docker container:
root@mysql-container:/# mysql -uroot -proot
mysql: [Warning] Using a password on the command line interface can be insecure.
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (111)

mysqld is running:
root@mysql-spirit-ssl:/etc/mysql/conf.d# /etc/init.d/mysql start
[info] A MySQL Server is already started.

Trying to stop mysqld timed out:
root@mysql-container:/# /etc/init.d/mysql stop
............................................................[info] Attempt to shutdown MySQL Community Server 5.7.17 timed out.

So I tried to start using the mysqladmin way:
root@mysql-container:/# /usr/bin/mysqladmin --port=8889 -u root shutdown
mysqladmin: connect to server at 'localhost' failed
error: 'Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (111)'

So I checked that MySQL daemon is running:
root@mysql-container:/# ps -eax
  PID TTY      STAT   TIME COMMAND
    1 ?        Ssl    0:01 mysqld

And that socket exists:
root@mysql-container:/# ls -l /var/run/mysqld/mysqld.sock
-rwxrwxrwx. 1 mysql mysql 0 Jan  4 10:12 /var/run/mysqld/mysqld.sock

I already tried to:

*

*restart my Docker container

*comment bind address in my.cnf and restart my Docker container

*kill mysqld process => does not work, process is still listed by ps -eax

*recreate my Docker container

*restart Docker

*restart the server

*delete pid and sock files, and /etc/init.d/mysql start
Result of cat /var/log/mysql/error.log:
2018-02-27T15:27:35.966028Z 0 [ERROR] InnoDB: Unable to lock ./ibdata1 error: 11
2018-02-27T15:27:35.966061Z 0 [Note] InnoDB: Check that you do not already have another mysqld process using the same InnoDB data or log files.

However I cannot kill that mysqld process, either with pkill mysqld, kill -9 1 or initctl --system stop mysql.
Could this be related to Docker?

A: Remark: The MySQL daemon could not be killed because it was owned by Docker user systemd+ and it was the entry point of the container. Indeed mysqld was process with PID 1. This means that MySQL daemon could be restarted by simply restarting the Docker container, and that MySQL configuration could be modified in between.
I noticed in MySQL logs tail -f /var/log/mysql/error.log that a data recovery was triggered on daemon start due to an anomaly detected during internal log scan: the database was not closed properly. However the recovery could not repair the data and an intentional crash was performed. As a consequence, the container was restarted and so on. This infinite loop prevented mysqld to start and the socket to be used by the client mysql.
1) This configuration of /etc/mysql/conf.d/my.cnf enabled to skip the recovery:
[mysqld]
innodb_force_recovery=4

and to use mysql client with socket to dump important schemas and/or delete corrupted schemas.
Do not forget to remove this line from my.cnf after you're done!
2) Perfoming a mysql upgrade and repair could also have been beneficial:
docker exec -it mysql-container mysql_upgrade -u root -p --force
mysqlcheck -u root -p --auto-repair --check --all-databases

Restarting the Docker container is necessary after this step.
3) Also, deleting MySQL internal logs (that were scanned and triggered the recovery) was necessary:
cd /var/lib/mysql/mysql/
rm ibdata1 ib_logfile0 ib_logfile1

Now I can use MySQL again, from inside and outside the container.


text:
Q: Why 4 dimensional array size 800 x 100 x 100 x 100 work only with allocatable array? I tried to work with 4 dimensional array size 800 x 100 x 100 x 100 but get stuck in this error:
/var/folders/cd/jlh3y5md6t70w3h9w747_87c0000gn/T//ccZySij1.s:282:zerofill size (3200000000.) <0! Ignored.
/var/folders/cd/jlh3y5md6t70w3h9w747_87c0000gn/T//ccZySij1.s:282:Rest of line ignored. 1st junk character valued 44 (,).
/var/folders/cd/jlh3y5md6t70w3h9w747_87c0000gn/T//ccZySij1.s:283:zerofill size (3200000000.) <0! Ignored.
/var/folders/cd/jlh3y5md6t70w3h9w747_87c0000gn/T//ccZySij1.s:283:Rest of line ignored. 1st junk character valued 44 (,).
make: *** [run.out] Error 1

But if I use allocatable array instead of normal array I can pass this error.
The question is why?
Note: Usual array size 800 x 80 x 80 x 80 still can work.
Edit from request: Code which use allocatable array
  9     integer :: x_size = 100
 10     integer :: y_size = 100
 11     integer :: z_size = 100
 12     integer :: t_size = 800
 13
 14     real, dimension(:,:,:,:), allocatable :: l1, l2
 15     allocate(l1(t_size, z_size, y_size, x_size), &
 16              l2(t_size, z_size, y_size, x_size))

Edit from request: Code which use normal array
  9     integer :: x_size = 100
 10     integer :: y_size = 100
 11     integer :: z_size = 100
 12     integer :: t_size = 800
 13
 14     real, dimension(t_size, z_size, y_size, x_size) :: l1, l2


text:
Q: C#/Why does Get html returns random junk characters? I have this for ex:
Link
This code:
const String nick = "Alex";
const String log = "http://demonscity.combats.com/zayavka.pl?logs=";
foreach (DateTime cd in dateRange)
{
string str = log + String.Format("{0:MM_dd_yy}", cd.Date) + "&filter=" + nick;
String htmlCode = wc.DownloadString(str);
}

returns something...."‹\b\0\0\0\0\0\0я•XYsЫЦ~зЇёѕ™d)bг.тBҐ$ЪRЖ'<2УN&сh@р '"\f\0J–—_Фџђ§¤нt¦г6ќѕУЄђ0'IQtТґcµо№X(jі-Щ/Ђі|g?`yҐ¶ц"
Other links works fine.
I think the problem is with codepage, how can i fix it? Or it's server problem?

A: The issue is that the response is GZip-compressed (response has a Content-Encoding: gzip header). You need to first decompress it, then you'll be able to read it:
public class StackOverflow_6660689
{
    public static void Test()
    {
        WebClient wc = new WebClient();
        Encoding encoding = Encoding.GetEncoding("windows-1251");
        byte[] data = wc.DownloadData("http://demonscity.combats.com/zayavka.pl?logs=08_07_11&filter=Alex");
        GZipStream gzip = new GZipStream(new MemoryStream(data), CompressionMode.Decompress);
        MemoryStream decompressed = new MemoryStream();
        gzip.CopyTo(decompressed);
        string str = encoding.GetString(decompressed.GetBuffer(), 0, (int)decompressed.Length);
        Console.WriteLine(str);
    }
}

A: I think it is returning result in gzip format which it should not unless client explicitly accepts the format.


text:
Q: Continuum random variable distribution: integral and trapezium-rule methods give different result
Suppose p.d.f. is $\frac{1}{63}x^{2}$. Find the $P(4<x<5)$.

I've tried with integration method and trapezium-rule, but they give me different result.
With integration,

$$\int_{4}^{5}\frac{1}{63}x^{2}\:dx=\left.\frac{1}{63}\:\right[_4^5\:\frac{1}{3}x^{3}=\frac{1}{63}\:(\frac{125}{3}-\frac{64}{3})=\frac{61}{189}$$

But with trapezium-rule,

$$(5-4)\cdot\frac{f(5)+f(4)}{2}=1\cdot\frac{(\frac{25}{63}+\frac{16}{63})}{2}=\frac{41}{126}$$

What I missed?

A: The trapezoidal rule is an approximation.  It only gives you the same answer when you partition the interval up into $n$ pieces and take $n\to\infty$ (the limit).  Your first solution looks correct.