text:
Q: Using @IndexingDependency derivedFrom and a property bridge I would like to use hibernate search's @IndexingDependency with a PropertyBridge but I can't seem to make it work.
I get this error :
Hibernate ORM mapping: type 'com.something.Person': path '.currentStatus':
  failures:
    - HSEARCH700020: Unable to find the inverse side of the association on type
    'com.something.Person' at path '.currentStatus<no value extractors>'. Hibernate Search
    needs this information in order to reindex 'com.something.Person' when
    'com.something.Status' is modified. You can solve this error by defining the inverse
    side of this association,  either with annotations specific to your integration
    (@OneToMany(mappedBy = ...) in Hibernate ORM)  or with the  Hibernate Search
    @AssociationInverseSide annotation. Alternatively, if you do not need to reindex
    'com.something.Person' when 'com.something.Status' is modified, you can disable
     automatic reindexing with @IndexingDependency(reindexOnUpdate = ReindexOnUpdate.SHALLOW)

Not sure if I'm doing something wrong or if what I'm trying to do isn't possible. Thank for the help.
Here are the files involved.
Person.class
@Entity
@Table
@Indexed
public class Person {
    @OneToMany(mappedBy = "patient", cascade = CascadeType.ALL)
    private Set<Status> status = new HashSet<>();

    @Transient
    @StatusBinding(fieldName = "currentStatus")
    @IndexingDependency(derivedFrom = @ObjectPath(@PropertyValue(propertyName = "status")))
    public Status getCurrentStatus() {
        return this.status.stream()
            .filter(it -> it.getDate().isAfter(LocalDate.now()))
            .max(Comparator.comparing(Status::getDate))
            .orElse(null);
    }
}

StatusBinding.class
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD})
@PropertyMapping(processor = @PropertyMappingAnnotationProcessorRef(type = StatusBinding.Processor.class))
@Documented
public @interface StatusBinding {

    String fieldName() default "";

    class Processor implements PropertyMappingAnnotationProcessor<StatusBinding> {
        @Override
        public void process(PropertyMappingStep mapping, StatusBindingannotation, PropertyMappingAnnotationProcessorContext context) {
            StatusBinderbinder = new StatusBinder();
            if (!annotation.fieldName().isBlank()) binder.setFieldName(annotation.fieldName());
            mapping.binder(binder);
        }
    }
}

StatusBinder.class
public class StatusBinder implements PropertyBinder {
    @Setter private String fieldName = "mainStatus";

    @Override
    public void bind(PropertyBindingContext context) {
        context.dependencies()
            .use("status")
            .use("date")
            .use("note");

        IndexSchemaObjectField mainStatusField = context.indexSchemaElement().objectField(this.fieldName);

        context.bridge(Status.class, new StatusBridge(
                mainStatusField.toReference(),
                mainStatusField.field("status", context.typeFactory().asString()).toReference(),
                mainStatusField.field("date", context.typeFactory().asLocalDate()).toReference(),
                mainStatusField.field("note", context.typeFactory().asString()).toReference()
        ));
    }

    private static class StatusBrige implements PropertyBridge<Status> {
        private final IndexObjectFieldReference mainStatusField;
        private final IndexFieldReference<String> statusField;
        private final IndexFieldReference<LocalDate> dateField;
        private final IndexFieldReference<String> noteField;

        public StatusBrige(
                IndexObjectFieldReference mainStatusField,
                IndexFieldReference<String> statusField,
                IndexFieldReference<LocalDate> dateField,
                IndexFieldReference<String> noteField
        ) {
            this.mainStatusField = mainStatusField;
            this.statusField = statusField;
            this.dateField = dateField;
            this.noteField = noteField;
        }

        @Override
        public void write(DocumentElement target, Status mainStatus, PropertyBridgeWriteContext context) {
            DocumentElement statutElement = target.addObject(this.mainStatusField);
            statutElement.addValue(this.statusField, mainStatus.getStatus);
            statutElement.addValue(this.dateField, mainStatus.getDate());
            statutElement.addValue(this.noteField, mainStatus.getNote());
        }
    }
}

A: Problem
When a Status entity is modified, Hibernate Search doesn't know how to retrieve the corresponding Person having that Status as its currentStatus.
Solution
Assuming the currentStatus is always contained in status, and since Status.patient is the inverse side of the Person.status association, you  should only need to add this:
    @Transient
    @StatusBinding(fieldName = "currentStatus")
    @IndexingDependency(derivedFrom = @ObjectPath(@PropertyValue(propertyName = "status")))
    // ADD THIS ANNOTATION
    @AssociationInverseSide(
            inversePath = @ObjectPath(@PropertyValue(propertyName = "patient"))
    )
    public Status getCurrentStatus() {
       // ...
    }

Why?
I'll try to explain this, but it's a bit complex, so bear with me.
Derived properties and the inverse side of associations are related concepts: they share the common purpose of allowing Hibernate Search to perform automatic reindexing.
However, they are still separate concepts, and Hibernate Search is not able to infer one from the other.
With @IndexingDependency(derivedFrom), you are defining what the computation of currentStatus depends on:
    @IndexingDependency(derivedFrom = @ObjectPath(@PropertyValue(propertyName = "status")))
    public Status getCurrentStatus() {

This tells Hibernate Search that currentStatus will change whenever the status property changes. With that information, Hibernate Search is able to determine that whenever you call person.getStatus().remove(...) or person.getStatus().add(...) (for example), your Person entity needs reindexing, because currentStatus is indexed, and it probably changed.
In your custom binder, you're also defining dependencies:
        context.dependencies()
            .use("status")
            .use("date")
            .use("note");

This tells Hibernate Search that whenever the status, date, and note properties of a Status entity change, the Person having that Status as its currentStatus will need reindexing.
However... what Hibernate Search doesn't know is how to retrieve the person having that Status as its currentStatus.
It may know how to retrieve all persons having that Status in their status set, but that's a different thing, isn't it? Hibernate Search doesn't know that currentStatus is actually one of the elements contained in the status property. For all it knows, getCurrentStatus() could very well be doing this: status.iterator().next().getParentStatus(). Then the current status wouldn't be included in Person#status, and it's unclear if myStatus.getPatient() could return a Person whose currentStatus is myStatus.
So you need to tell Hibernate Search explicitly: "from a given Status myStatus, if you retrieve the value of myStatus.getPatient(), you get the Person whose currentStatus property may point back to myStatus". That's exactly what @AssociationInverseSide is for.


text:
Q: scikit-learn RandomForestClassifier produces 'unexpected' results I'm trying to use sk-learn's RandomForestClassifier for a binary classification task (positive and negative examples). My training data contains 1.177.245 examples with 40 features, in SVM-light format (sparse vectors) which I load using sklearn.dataset's load_svmlight_file. It produces a sparse matrix of 'feature values' (1.177.245 * 40) and one array of 'target classes' (1s and 0s, 1.177.245 of them). I don't know whether this is worrysome, but the trainingdata has 3552 positives and the rest are all negative.
As the sk-learn's RFC doesn't accept sparse matrices, I convert the sparse matrix to a dense array (if I'm saying that right? Lots of 0s for absent features) using .toarray(). I print the matrix before and after converting to arrays and that seems to be going all right.
When I initiate the classifier and start fitting it to the data, it takes this long:
[Parallel(n_jobs=40)]: Done   1 out of  40 | elapsed: 24.7min remaining: 963.3min
[Parallel(n_jobs=40)]: Done  40 out of  40 | elapsed: 27.2min finished

(is that output right? Those 963 minutes take about 2 and a half...)
I then dump it using joblib.dump.
When I re-load it:
RandomForestClassifier: RandomForestClassifier(bootstrap=True, compute_importances=True,
        criterion=gini, max_depth=None, max_features=auto,
        min_density=0.1, min_samples_leaf=1, min_samples_split=1,
        n_estimators=1500, n_jobs=40, oob_score=False,
        random_state=<mtrand.RandomState object at 0x2b2d076fa300>,
        verbose=1)

And test it on real trainingdata (consisting out of 750.709 examples, exact same format as training data) I get "unexpected" results. To be exact; only one of the examples in the testingdata is classified as true. When I train on half the initial trainingdata and test on the other half, I get no positives at all.
Now I have no reason to believe anything is wrong with what's happening, it's just that I get weird results, and furthermore I think it's all done awfully quick. It's probably impossible to make a comparison, but training a RFClassifier on the same data using rt-rank (also with 1500 iterations, but with half the cores) takes over 12 hours...
Can anyone enlighten me whether I have any reason to believe something is not working the way it's supposed to? Could it be the ratio of positives to negatives in the training data? Cheers.

A: Indeed this dataset is very very imbalanced. I would advise you to subsample the negative examples (e.g. pick n_positive_samples of them at random) or to oversample the positive example (the latter is more expensive and but might yield better models).
Also are you sure that all your features are numerical features (larger values means something in real life)? If some of them are categorical integer markers, those feature should be exploded as one-of-k boolean encodings instead as scikit-learn implementation of random forest s cannot directly deal with categorical data.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why is $\tan((1/2)\pi)$ undefined? Why is the trigonometric function $\tan((1/2)\pi)$ undefined?

A: The identity that relates $\color{blue}{\tan}$ with $\color{red}{\sin}$ and $\color{green}{\cos}$ is: $$\color{blue}{\tan}(\alpha)=\frac{\color{red}{\sin}(\alpha)}{\color{green}{\cos}(\alpha)}\tag{1}$$
and $\color{green}{\cos}\color{black}{(}\pi/2\color{black})=0$, adding to it the fact that division by zero is undefined, it follows that $\color{blue}{\tan}(\pi/2)$ is undefined.

Furthermore, since $\color{green}{\cos}\left(n\pi-\pi/2\right)=0$ for every $n\in\Bbb Z$ , we conclude from $\text{(1)}$ that for every $n\in\Bbb Z$, $\color{blue}{\tan}(n\pi-\pi/2)$ is undefined.

A: Here's an answer that is not really about division by $0$. $\tan(\alpha)$ is the length of the line segment that is tangent to the unit circle in the image below. So what would happen to this length if $\alpha$ were $\pi/2$?

Note this diagram works for all nonvertical angles as long as you interpret the "length" of the tangent segment as negative if it ends up on the lower side, and also as long as you are willing to pull back rays from obtuse angles until they intersect that vertical line there.
It's debatable that $\tan(x)$ is defined as $\frac{\sin(x)}{\cos(x)}$, as some other answers suggest. I think its name suggests that its original definition is more like what we see in this diagram: something about a tangent line. It just happens to be equal to $\frac{\sin(x)}{\cos(x)}$ because of similar triangle ratios. Similarly, $\sec(x)$ is the length of the hypotenuse in this picture, and a secant line is any line that cuts through a curve, like the hypotenuse here cuts through the circle.

A: Because $\tan(x)$ is defined as being equal to $\sin(x)/\cos(x)$, and $\cos(\pi/2)=0$. So $\tan(\pi/2)=1/0$, which is undefined because of the division by zero.

A: Well, you can see that
$$\tan x:= \frac{\sin x}{\cos x}$$
and it's known that $\sin \frac{\pi}{2}=1$ and $\cos \frac{\pi}{2}=0$.

A: A feature not explained in other answers is that you can't define the tan function as simply "infinite" at the point of discontinuity. From one side it is unboundedly positive, and from the other unboundedly negative.


text:
Q: App crashing when trying to add a second table Ok so I'm really confused at the moment.  I'm trying to add a new table to my program, but whenever I do I crashes on my, specifically at the onCreate method.  I cannot for the love of me figure out why.  Any suggestions?
Also this is an error I get, but I can't find categories.db anywhere
Caused by: android.database.sqlite.SQLiteException: no such table: categories.db (code 1): , while compiling: SELECT * FROM categories.db
private final static int DB_VERSION = 2;

public static String TABLE_NAME = "players";
public static String DB_NAME = "playerslist.db";
public static String SCORE = "score";
public static String ID = "_id";
public static String PLAYER_NAME = "name";

public static String CATEGORY_TABLE_NAME = "categories";
public static String CATEGORY_NAME = "category_name";
public static String CATEGORY_VALUE = "category_value";
public static String CATEGORY_ID = "category_id";
public static String CATEGORY_PLAYER_ID = "category_player_id";

public static String CREATE_PLAYER_TABLE = "CREATE TABLE "+TABLE_NAME+" ("+ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+PLAYER_NAME+" TEXT, "+
        SCORE+" TEXT)";
public static String CREATE_CATEGORY_TABLE = "CREATE TABLE "+CATEGORY_TABLE_NAME+"("+CATEGORY_ID+" INTEGER" +
        "PRIMARY KEY AUTOINCREMENT, "+CATEGORY_NAME+" TEXT, "+CATEGORY_VALUE+" INTEGER, "
        +CATEGORY_PLAYER_ID+" INTEGER)";

public SQLHelp(Context context) {
    super(context, DB_NAME, null, 2);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(CREATE_PLAYER_TABLE);
    db.execSQL(CREATE_CATEGORY_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    for(int i = oldVersion; i < newVersion; i++){
        switch(i){
            case 1:
                db.execSQL(CREATE_CATEGORY_TABLE);
            break;
        }
    }
}

A: Change your CREATE TABLE Strings to include IF NOT EXISTS as,
CREATE TABLE IF NOT EXISTS Table_name(Columns)

A: Delete your application from the device or emulator, and INSTALL/RUN again, and it should work.
I had the same problem, and I simple delete the application from device and it worked.

A: Try this..
While creating the second table, you had "INTEGER" + "PRIMARY KEY AUTOINCREMENT"..
I made that in one.
public static String CREATE_CATEGORY_TABLE = "CREATE TABLE "+CATEGORY_TABLE_NAME+"("+CATEGORY_ID+ " INTEGER PRIMARY KEY AUTOINCREMENT, "+CATEGORY_NAME+" TEXT, "+CATEGORY_VALUE+" INTEGER, "
    +CATEGORY_PLAYER_ID+" INTEGER)";

You should call SQLiteOpenHelper
private static class DatabaseHelper extends SQLiteOpenHelper{
    DatabaseHelper(Context context){
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
    public void onCreate(SQLiteDatabase db){
          db.execSQL(CREATE_PLAYER_TABLE);
          db.execSQL(CREATE_CATEGORY_TABLE);
    }
    public void onUpgrade(SQLiteDatabase db, int arg1, int arg2{
          db.execSQL("DROP TABLE IF EXISTS " + CREATE_PLAYER_TABLE);
          db.execSQL("DROP TABLE IF EXISTS " + CREATE_CATEGORY_TABLE);
          onCreate(db);
    }


text:
Q: Split long string into small chunks without breaking HTML tags and words I am breaking long text into smaller chunks using while loop. My string contains html code and I dont want the user to see those open or closed braces.
my template string contains following text.
var text = "I love Stackoverflow. It helps me lot and Bla bla bla bla bla bla ";

var textString = '

 Working from home

'+text+'

';

I am using the following method
var i = true;
      var start = 0;
      var end = 20;
      var increment = 0;
        var incremented = 0;
       var val1 = textString.slice(start,end);
        while (i == true) {
             val1 = data.slice(start,end);
                var check  = val1.endsWith(' ');
            while (check == false) {
            end = end+1;
                incremented = incremented+1;
            val1 = data.slice(start,end);
                if(val1.endsWith(' ')){
                check = false;
                }else{
                check = true;
                }
                 end = end+20+incremented;
                 start = start+20+incremented;
                 if(start>textString.length){
                      i=false;
                 }
         }
}

An Example is here:
    var text1 = 'I love Stackoverflow. It helps me lot and Bla bla bla bla bla
    bla';
    var text2 = 'Some Random Text';
    var text3 = 'Some Random Text';
    var text4 = 'Some Random Text';
    var text5 = 'Some Random Text';
    var text6 = 'Some Random Text';

    var textString = '

     text1

'+text2+'

     text3

'+text4+'

    text5

'+text6+'

';

and output i need should be like
    arr[0] = '

     text1

'+text2+'

';

    arr[1] = '

     text3

'+text4+'

';

    arr[2] = '

     text5

'+text6+'

';

This is my Current output:

A: HTML DOM nodes include their content so you can't split them without breaking them. The following code will convert your string into a DOM tree. Split off all the child nodes and re-combine them without breaking words or HTML based on the length of their text content.
If your data is bad and, for example, has a single paragraph that takes up more than one page, or a long series of letters with no spaces, than it is likely you will need to come up with custom solutions for each type of HTML tag and long series of characters.
Even with this solution you may find that additional effort is need to keep pre tags within your page targets.
This function takes two arguments, your string and the maximum length you would like for the textContent in characters.
var shard = function(str, len) {

    var el = document.createElement('div');
    el.innerHTML = str;
    var child = el.firstChild;

    var parts = [];
        while(child) {
          if (child.nodeType == 3) {
            var texts = child.nodeValue.split('')
              .reduce(function(a,b){
                 if (b.split(/\s/).length > 1) {
                    a[a[a.length-1].length > 0 ? a.length: a.length - 1] = b;
                    a[a.length] = ''
                 } else {
                    a[a.length - 1] = a[a.length - 1] + b;
                 } return a; },['']);
            for(var idx=0; idx<texts.length; idx++) {
                parts.push(document.createTextNode(texts[idx]));
            }
          } else {
            parts.push(child);
          }
          child = child.nextSibling;
        }

    var textParts = parts.map(function(el) { return el.textContent; });

    var partsOut = [''];

    var t = 0;

    for(var idx=0; idx<parts.length; idx++) {

        if ((t + textParts[idx].length) > len) {
          partsOut[partsOut.length] = parts[idx].nodeType == 3 ?
              parts[idx].nodeValue : parts[idx].outerHTML;
          t = textParts[idx].length;
        } else {
          partsOut[partsOut.length - 1] = partsOut[partsOut.length - 1] + (
             parts[idx].nodeType == 3 ?
             parts[idx].nodeValue :
             parts[idx].outerHTML
         );
          t += textParts[idx].length;
        }

    }

    return partsOut;

};

This is probably not what you want to use in a production environment but it does make an attempt, where possible, to break up HTML into unbroken pieces with a target length of the text content.

A: you could split the string using spaces
let wordsArray = text.split(" ")

then reduce is to whatever chunks you want
let chunks = Array()
const wordsInChunkCount = 100
let temp = wordsInChunkCount
let str = ''
wordsArray.forEach(item => {
  if (temp > 0) {
    str += ' ' + item
    temp--
  } else {
    chunks.push(str)
    str = ''
    temp = wordsInChunkCount
  }
})

after that you will have your chunks in the chunks array


text:
Q: All Shortest Paths To A Given Vertex Given a directed graph G=(V,E) and a weight function w : E - > R+  (only positive weights for edges in the graph) , I need to find all the shortest paths from every vertex v in V to a given vertex k.
I've thought about reversing the edges in the graph and then running Dijkstra's algorithm from the vertex k. I wonder whether a shortest path p from k to v1 is actually the shortest path from v1 to k in the original graph ( before reversing edges ).
I'd be grateful if anyone could explain if and why it does / does not happen.
Thanks in advance.

A: (This won't be the most formal proof in the world, but hopefully its good enough to convince yourself).
Lets say for a vertex v, in graph G, the shortest path from v to k is of length m.
The two things you want to know are:
 1. In the reversed graph, G*, there is a path of length m from k to v.
 2. In the reversed graph, G*, there are no paths from k to v that are shorter than m.
Before I start, can we take one thing on faith:
Lemma 1: If you have a directed path from vertex v to vertex w, and you reverse every edge on the path, then you have a path from vertex w to vertex v. This is provable, but I think its fairly common sense. I'll prove it if you want me to.
For point 1: Consider the path in G from v to k consisting of m edges. If you reverse each of these edges, you will have a path from k to v of length m (by Lemma 1).
For point 2: Suppose there exists a path in the reversed graph G*, from k to v of length n < m. If you reverse this path, then there is a path of length n from v to k (Lemma 1). This means that there is a path from v to k in the original graph that is shorter than m, contradicting the statement that the path of length m is the shortest.


text:
Q: Number theory proof mod p For a given prime $p$ and integer $k$,  $k∈<1, p-1>$ $S(k)$ is defined as a sum of remainders of $k, k^2, k^3, ..., k^{p-1}$ when divided by $p$. Prove that $S(k)=\frac{1}{2}p(p-1)$ is true for an odd number of different k.
I managed to prove that $S(p-1)=\frac{1}{2}p(p-1)$ but can't see how to do it further.

A: (Fill in the gaps as needed. If you're stuck, show your work and explain what stumps you.)
Hint: Prove that $S(k) = \frac{1}{2} p (p-1)$ iff there exists an $a$ such that $ k^a \equiv -1 \pmod{p}$.
Corollary: Hence, if $p -1 = 2^m \times n, $ where $n$ is odd, then the number of solutions is $ (2^m-1) \times n $, which is odd.

Proof of hint without using primitive elements.
If there exists $ k^ a \equiv -1 \pmod{p}$:
(Proof by algebraic manipulation)  Show that $$ 2 \sum_{i=1}^{p-1} ( k^i \pmod{p})   = \sum_{i=1}^{p-1} (k^i + k^{i+a} \pmod{p} )  = \sum_{j=1}^{p-1} p = (p-1)p. $$
Hence $ \sum_{i=1}^{p-1} (k^i \pmod{p}) = \frac{p-1}{2} \times p$.
If no such $a$ exists, then consider $ v = ord_p (k)$.
(Proof by contradiction) Show that $ v$ is odd, and a factor of $ p-1$.
(Proof by algebraic manipulation) Show that
$$ \sum_{i=1}^{p-1} ( k^i \pmod{p} = \sum_{j=0}^{\frac{p-1}{v}-1} \sum_{i=1}^v (k^{jv + i} \pmod{p} = \frac{p-1}{v} \times \sum_{i=1}^v (x^i \pmod{p}).$$
Observe that if $ p-1 = 2^m \times n$ with $n$ odd, then $ 2^m \mid \frac{p-1}{v} \mid \sum_{i=1}^{p-1} (k^i  \pmod{p})$, but $ 2^m \not \mid \frac{1}{2} (p-1)p$, so these 2 values can never be equal.

Hint using primitive elements. This was originally the easier way to approach. However, now that I've written out the steps which could be followed via algebraic manipulation, you should just review the above.
Consider a primitive element $g$.
Let $ k = g^b$.
Let $ p-1 = 2^m \times n$, where $n$ is odd.
Then $k$ satisfies the conditions iff $ 2^m \not \mid b$.
If $2^m \not \mid b$, then there exists $a$ such that $ ba = \frac{p-1}{2} \times o$, where $o$ is odd. This $a$ satisfies $k^a \equiv -1 \pmod{p}$, and the above pairing argument works.
If $ 2^m \mid b$, show that $2^m \mid S(k)$ while $ 2^m \not \mid \frac{1}{2} p (p-1)$, in a similar manner to the above. Hence these terms are not equal.

The description of the solution set as powers of $g$ that were not multiples of $2^m$, felt hard to motivate directly. (E.g. how can we tell that if $g^b$ doesn't work, then neither does $g^{2b}, g^{3b}, \ldots$?)
Whereas finding the $k^a \equiv -1 \pmod{p}$ condition was quite direct especially after considering small cases. Hence, that was my initial hint.

A: If $S(n)=\tfrac12p(p-1)$ then also $S(n^{-1})=\tfrac12p(p-1)$, where $n^{-1}$ denotes the inverse of $n$ mod $p$. This shows that solutions come in pairs, except those for which $n=n^{-1}$. Of course $n=n^{-1}$ holds only for $n=\pm1$, and a quick check shows that $S(1)=p-1$ and $S(-1)=\tfrac12p(p-1)$.


text:
Q: ActiveRecord::Relation - query executed yet? Suppose I have the following models:
class Foo < ActiveRecord::Base
  has_many :bars
end

class Bar < ActiveRecord::Base
  belongs_to :foo
  scope :blue, where(color: 'blue')
end

If I have an instance of Foo, there are several ways to retrieve all of the blue Bar models associated with it. My question relates to determining whether or not the bars relation of a given foo has already been loaded.
This will execute a database query regardless of whether or not the full collection of bars is already loaded into memory:
foo.bars.blue.all
This won't execute a query if the bars were included by the query that loaded the foo. If they weren't loaded it will load all of the bars and then enumerate.
foo.bars.select { |b| b.color == 'blue' }
How can I determine whether or not a relation has been loaded without causing it to execute a query?
foo.bars.some_method_to_determine_whether_or_not_they_are_in_memory_thanks
Any ideas?
EDIT:
just to clarify, this is the sort of outcome I wish to achieve:
class Foo < ActiveRecord::Base
  has_many :bars

  def blue_bars
    if bars_already_loaded?
      # enumerate
    else
      # use the scope
    end
  end

  def red_bars
    ...
  end

  ...
end


text:
Q: Palindromic numbers, and $3$. Let $x \in \mathbb{Z}$, and $x'$ be the palindrome of $x$.
Why is it that $3 \mid (x - x')?$

A: Hint :
The number $abc$ is equal to $100a+10b+c$, the palindrome number $cba$ is equal
to $100c+10b+a$

A: This is not true.  For example, take $x = 13$.  Its palindrome is $x' =31$.  Then $x+x' = 44$, which is not divisible by 3.

A: Maybe you should precise the question? What is the palindrome of x?
If $x= 110$, $x'= 011$, $x+x' = 121$.
However it is true that if $x = \sum_{i=0}^{n} 10^i x_i$ and $x' = \sum_{i=0}^{n} 10^i x_{n-i}$,
then
\begin{equation}
x-x' = \sum_{i=0}^{n} (10^i - 10^{n-i})x_i
\end{equation}
Now, if $i \ge n-i$, you can see that $10^i - 10^{n-i} = 10^{n-i}(10^{2i-n} - 1)$.
Otherwise, if $i \le n-i$, $10^i - 10^{n-i} = 10^{i}(1 - 10^{n-2i})$.
In all cases, $10^i - 10^{n-i}$ is of the form, $p (10^{q} - 1)$. You probably know that the rest of the division of a power of $10$ by three is always $1$.
Thereforem $3 | (10^i - 10^{n-i})$ for all $i$, and then $3|(x-x')$


text:
Q: Как работают каналы Go Недавно начал изучать Go. На данный момент изучаю каналы. У меня вопрос, почему в этой программе значение в канал передается:
package main

import (
    "fmt"
)

func f (c chan string){
    fmt.Println(<-c)
}

func main() {
    //r := bufio.NewReader(os.Stdin)

    c := make(chan string)

    go f(c)

    //text, _ := r.ReadString('\n')
    //fmt.Println(text)
    fmt.Println("Hello")
    c <- "jhj"
}

А в этой нет
package main

import (
    "bufio"
    "fmt"
    "os"
)

func f (c chan string){
    fmt.Println(<-c)
}

func main() {
    r := bufio.NewReader(os.Stdin)

    c := make(chan string)

    go f(c)

    text, _ := r.ReadString('\n')
    fmt.Println(text)
    //fmt.Println("Hello")
    c <- "text"
}

A: На самом деле значение в канал передается в обоих случаях. То, что вы наблюдаете, является классической гонкой (race condition).
Вы запускаете функцию f в отдельной горутине, которая блокируется на чтение из канала c. Как только вы записываете в канал какую-либо строку (jhj в первом случае и text во втором), функция разблокируется и продолжает выполнение. Проблема в том, что main тоже продолжает выполнение после записи в канал параллельно с функцией f на другом ядре процессора и успевает завершится до того, как выполнится fmt.Println в функции f. Но это никак не гарантируется и поэтому и называется гонкой.
Более того, даже исполнение на одном процессорном ядре не гарантирует, что функция fmt.Println внутри f выполнится раньше, чем завершится main. Как правильно заметил @Ainar-G, вам нужно добавить синхронизацию и дождаться завершения f. Вот один из вариантов как это можно сделать:
package main

import (
    "bufio"
    "fmt"
    "os"
    "sync"
)

var wg sync.WaitGroup

func f(c chan string) {
    fmt.Println(<-c)
    // сигнализируем о завершении функции
    // по сути делаем wg.Add(-1)
    wg.Done()
}

func main() {
    r := bufio.NewReader(os.Stdin)

    c := make(chan string)

    wg.Add(1) // говорим что будем дожидаться завершения одной функции
    go f(c)

    text, _ := r.ReadString('\n')
    fmt.Println(text)
    c <- "text"
    // ждем завершения функции f
    // Wait вернется, когда счетчик внутри wg станет равным 0
    wg.Wait()
}

A:
Ни ваш первый, ни второй вариант не даёт гарантий работы.  Всё потому
что ваш main не ждёт выполнения работы.  Добавьте
синхронизацию между f и main.  Самое
примитивное — добавить в конец функции
main код select{}, который заблокирует
выполнение main.


text:
Q: Dell Laptop won't  shutdown / restart by itself I recently upgraded to ubuntu 11.10 64-bit on my Dell Studio 1569. Before this I ran ubuntu 11.04 64-bit.
Every time I shutdown, or restart it goes through the usual processes, and shows no error
( I watch the shutdown messages by pressing the Page Down key).
When it gets to the point where it says "Will now halt," or "will now restart" it fails to do so.
This is a bit annoying since at this point I have to manually cut the power by holding down the power button. I never had any issue like this in 11.04. Also, hibernation no longer works. It was extremely slow in 11.04 (Slower than a cold boot) but it worked. Now nothing works. Please help!

A: Try this in a terminal:
sudo gedit /etc/default/grub

Change the line:
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash"

with:
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash noapic"

save the file and finally again in the terminal:
sudo update-grub

Restart your laptop and after the next boot check if your laptop is power down by itself.


text:
Q: is there any way to create savepoint without using transaction? I have some queries such as update, delete.. etc.
Before i run them i want to create savepoint (without using transaction). But "how?" I don't know because savepoint is part of transaction. Is there another way to achieve this job?

A: No there is no way to create a save point without a transaction.
In absence of a transaction the concept is meaningless.
If you are looking at reducing locking that will be generated due to the transaction, have a look at snapshot isolation.


text:
Q: Invariant names and submodels of forcing extensions EDIT: There are serious problems with the definition below; see the comment thread below for those problems and some thoughts on addressing them. I'm leaving the question up for now since I think the idea is still interesting, but it is definitely broken at the moment.

Suppose $\mathbb{P}$ is a forcing notion and $\nu$ is a $\mathbb{P}$-name. Say that a $\mathbb{P}$-name $\mu$ is $\nu$-invariant if, whenever $G, H$ are $\mathbb{P}$-generic and $\nu[G]=\nu[H]$, then $\mu[G]=\mu[H]$. OK fine, that's nonsense, but it's easy to fix: formally, $\mu$ is $\nu$-invariant if whenever $\mathbb{Q}$ is a forcing notion and $\gamma_0,\gamma_1$ are $\mathbb{Q}$-names which are forced to be $\mathbb{P}$-generic and have $\nu[\gamma_0]=\nu[\gamma_1]$, then it is forced that $\mu[\gamma_0]=\mu[\gamma_1]$.
Say further that a name $\mu$ is hereditarily $\nu$-invariant if it and each name in its transitive closure is $\nu$-invariant, and let $HI_\nu$ denote the class of hereditarily $\nu$-invariant $\mathbb{P}$-names.
If $G$ is $\mathbb{P}$-generic, then it's not hard to show that $\{\mu[G]: \mu\in HI_\nu\}$ is a model of ZF; call it "$V[G]_\nu$". My question is this:

Does the model $V[G]_\nu$ have a snappy description as HOD of something, or as a symmetric submodel? By Grigorieff we know that it is such a model; but I don't immediately see how to describe it nicely as such.

(I'm particularly interested in the case when $\nu$ is a name for a set of reals, if that matters.)
I'm interested in the $HI_\nu$-construction because it gibes nicely with ideas from computability theory - specifically on a recasting of Steel forcing I've used, but also other things - and it makes a couple arguments I'm working on nicer. Of course, it has no broader mathematical value since there are provably no models of this form which aren't of better-known forms; but it's still something I find neat.

A: The original definition has a problem with the hereditary requirement, unless your name is something particularly nice, e.g. a name for a subset of the ground model. But in the latter case, you just get a model of $\sf ZFC$, since you essentially get $V[A]$ for some $A\subseteq V$.
In the comments you suggest instead considering something which is invariant under interpreting some subset of $\nu$ correctly, but this turns out to be quite similar to just the usual symmetric extensions: you have a name, and you consider all the automorphisms which preserve it (not necessarily actual equality, generic equality is all the same here), and then you look at things which get preserved when some subset of $\nu$ is being interpreted "correctly" rather than the whole set.
This just translates to an automorphism group of $\Bbb P$, and some normal filter of subgroups. At least in the "relatively intuitive case".


text:
Q: Issues loading data patterns from CSV I try to load data patterns into neo4j from cvs files using cypher command lines. I have two data files, one containing objects, the other containing object parts.
Object file:
ID
ABC-DE
DEF

Part file:
ID  ParentID    Level   Size
ABC ABC-DE  1   3
DE  ABC-DE  1   2
AB  ABC 2   2
BC  ABC 2   2
DE  DEF 1   2
F   DEF 2   1
A   AB  3   1
B   AB  3   1
B   BC  3   1
C   BC  3   1
D   DE  3   1
E   DE  3   1

Cypher command lines used to load data:
LOAD CSV WITH HEADERS FROM 'file:///path_to_file/object.csv' as csvLine FIELDTERMINATOR '\t' CREATE (:Object { Name: csvLine.ID})  RETURN count(*);
LOAD CSV WITH HEADERS FROM 'file:///path_to_file/part.csv' as csvLine FIELDTERMINATOR '\t' MATCH (o:Object {Name: csvLine.ParentID}) MERGE (p:Part {Name: csvLine.ID}) ON CREATE SET p.Size = csvLine.Size CREATE (o) -[:hasPart {Level: csvLine.Level}]-> (p) RETURN count(*);
LOAD CSV WITH HEADERS FROM 'file:///path_to_file/part.csv' as csvLine FIELDTERMINATOR '\t' MATCH (o:Part {Name: csvLine.ParentID}) MERGE (p:Part {Name: csvLine.ID}) ON CREATE SET p.Size = csvLine.Size CREATE (o) -[:hasPart {Level: csvLine.Level}]-> (p) return count(*);

The first two command lines execute properly, creating 2 and 3 nodes respectively and corresponding links. The third command line only creates 4 nodes: AB, BC, D and E. Apparently, only nodes linked to existing nodes are created and linked.
From the CSV file content, we can see that parent nodes are listed before child nodes, we could therefore have expected that nodes A, B and C could have been created and linked to AB and BC accordingly.
Is the current behavior of CSV loading the expected one, which prevent of loading such patterns or is there an issue in my code or a bug?
This issue exists with both neo4j 2.1.7 and neo4j 2.2.0-M04.

A: So I think your issue here is that cypher batches up many updates into a single transaction and then commits them.  How many it puts into a transaction is configurable with USING PERIODIC COMMIT.  I could be wrong, but I think normally it would treat the entire data load as a big transaction.
For you, this is problematic because when you're on, say, row #6, you might need to be referring back to a node that would have been created on row #3.  Except that won't work; if the transaction hasn't committed yet because cypher is batching up a bunch of results) then the not-yet-committed result may not be available for a subsequent query running.
So you have a few options; one would be to do a two-pass IMPORT on that part file.  On your first pass you might do this:
LOAD CSV WITH HEADERS FROM 'file:///path_to_file/part.csv' as csvLine FIELDTERMINATOR '\t'
MERGE (p:Part {Name: csvLine.ID}) ON CREATE SET p.Size = csvLine.Size CREATE (o) -[:hasPart {Level: csvLine.Level}]-> (p) return count(*);

(This first one would assure all parts exist in the DB)
Then on the second pass you might do this:
LOAD CSV WITH HEADERS FROM 'file:///path_to_file/part.csv' as csvLine FIELDTERMINATOR '\t' MATCH (o:Part {Name: csvLine.ParentID}) MATCH (p:Part {Name: csvLine.ID}) CREATE (o) -[:hasPart {Level: csvLine.Level}]-> (p) return count(*);

(This would just link them with relationships)
Another option would be to do something like USING PERIODIC COMMIT 1 but I don't think that would be a good idea; there's transaction overhead, and that would drastically slow your data load if you have a fair amount of data.
EDIT If I were you, I'd do the two-pass import.  Also, in general it's not a good idea to rely on record ordering in flat files like this, they tend to be messy.  Finally, if you do two-pass import on your part file, note that you don't need your object file at all!  Any object that's implicated will be created via the part file, and the object file doesn't add any extra properties than what part references.


text:
Q: $\mathcal S(\mathbb R^n) \hat \otimes_\pi \mathcal S(\mathbb R^m) \simeq \mathcal S(\mathbb R^{n+m})$? If $S(\mathbb R^n)$ is the Scwartz space of smooth rapidly decaying functions equipped with the topology generated by the family of semi-norms
$$\mathcal N_p (\varphi)= \sum_{|\alpha|, |\beta| \leq p} \sup_{x\in \mathbb R^n} |x^\alpha \partial^\beta \varphi (x) |\, ,$$
Is it true that $\mathcal S(\mathbb R^n) \hat \otimes_\pi \mathcal S(\mathbb R^m)\simeq \mathcal S(\mathbb R^{n+m})$, where $\mathcal S(\mathbb R^n) \hat \otimes_\pi \mathcal S(\mathbb R^m)$ is the completion of $\mathcal S(\mathbb R^n) \otimes \mathcal S(\mathbb R^m)$ for the topology $\pi$ defined by the family of semi-norms
$$\mathcal N_{p,q} (\varphi\otimes \psi)=\mathcal N_p(\varphi)\mathcal N_q (\psi)\, .$$

A: Yes, if you understand the tensor product topology in the right way.
Since the spaces are nuclear, inductive and projective tensor products coincide.
The result is theorem 51.6 of Treves: Topological vector spaces, distributions, and kernels.
Added later:
Attention: The description of  seminorms on the tensor-product given in the question is not sufficient to specify a locally convex topology on the tensor product. There are many satisfying this description; all between the the projective one and the the inductive one and even more. See the source I have given, or many other books.


text:
Q: Spring-Data-Neo4j: Repository findAll() method exception `at org.neo4j.kernel.TopLevelTransaction.markAsRollbackOnly` I am trying to use Spring-Data-Neo4j , Version = 3.2.1.RELEASE. When i fetch the nodes using repository findAll() method, i got the exception as Follow:
java.lang.NullPointerException
at org.neo4j.kernel.TopLevelTransaction.markAsRollbackOnly(TopLevelTransaction.java:93)
at org.neo4j.kernel.TopLevelTransaction.failure(TopLevelTransaction.java:86)
at org.neo4j.cypher.internal.spi.v2_1.TransactionBoundQueryContext.close(TransactionBoundQueryContext.scala:65)
at org.neo4j.cypher.internal.compiler.v2_1.spi.DelegatingQueryContext.close(DelegatingQueryContext.scala:38)
at org.neo4j.cypher.internal.compiler.v2_1.spi.ExceptionTranslatingQueryContext.org$neo4j$cypher$internal$compiler$v2_1$spi$ExceptionTranslatingQueryContext$$super$close(ExceptionTranslatingQueryContext.scala:34)
at org.neo4j.cypher.internal.compiler.v2_1.spi.ExceptionTranslatingQueryContext$$anonfun$close$1.apply$mcV$sp(ExceptionTranslatingQueryContext.scala:34)
at org.neo4j.cypher.internal.compiler.v2_1.spi.ExceptionTranslatingQueryContext$$anonfun$close$1.apply(ExceptionTranslatingQueryContext.scala:34)
at org.neo4j.cypher.internal.compiler.v2_1.spi.ExceptionTranslatingQueryContext$$anonfun$close$1.apply(ExceptionTranslatingQueryContext.scala:34)
at org.neo4j.cypher.internal.compiler.v2_1.spi.ExceptionTranslatingQueryContext.org$neo4j$cypher$internal$compiler$v2_1$spi$ExceptionTranslatingQueryContext$$translateException(ExceptionTranslatingQueryContext.scala:152)
at org.neo4j.cypher.internal.compiler.v2_1.spi.ExceptionTranslatingQueryContext.close(ExceptionTranslatingQueryContext.scala:34)
at org.neo4j.cypher.internal.compiler.v2_1.spi.DelegatingQueryContext.close(DelegatingQueryContext.scala:38)
at org.neo4j.cypher.internal.compiler.v2_1.executionplan.ExecutionWorkflowBuilder$$anonfun$runWithQueryState$1.apply(ExecutionPlanBuilder.scala:164)
at org.neo4j.cypher.internal.compiler.v2_1.executionplan.ExecutionWorkflowBuilder$$anonfun$runWithQueryState$1.apply(ExecutionPlanBuilder.scala:164)
at org.neo4j.cypher.internal.compiler.v2_1.TaskCloser$$anonfun$1.apply(TaskCloser.scala:43)
at org.neo4j.cypher.internal.compiler.v2_1.TaskCloser$$anonfun$1.apply(TaskCloser.scala:41)
at scala.collection.TraversableLike$$anonfun$flatMap$1.apply(TraversableLike.scala:251)
at scala.collection.TraversableLike$$anonfun$flatMap$1.apply(TraversableLike.scala:251)
at scala.collection.immutable.List.foreach(List.scala:318)
at scala.collection.TraversableLike$class.flatMap(TraversableLike.scala:251)
at scala.collection.AbstractTraversable.flatMap(Traversable.scala:105)
at org.neo4j.cypher.internal.compiler.v2_1.TaskCloser.close(TaskCloser.scala:40)
at org.neo4j.cypher.internal.compiler.v2_1.ClosingIterator$$anonfun$close$1.apply$mcV$sp(ClosingIterator.scala:67)
at org.neo4j.cypher.internal.compiler.v2_1.ClosingIterator$$anonfun$close$1.apply(ClosingIterator.scala:67)
at org.neo4j.cypher.internal.compiler.v2_1.ClosingIterator$$anonfun$close$1.apply(ClosingIterator.scala:67)
at org.neo4j.cypher.internal.compiler.v2_1.ClosingIterator$$anonfun$translateException$1.apply(ClosingIterator.scala:72)
at org.neo4j.cypher.internal.compiler.v2_1.ClosingIterator.decoratedCypherException(ClosingIterator.scala:102)
at org.neo4j.cypher.internal.compiler.v2_1.ClosingIterator.translateException(ClosingIterator.scala:70)
at org.neo4j.cypher.internal.compiler.v2_1.ClosingIterator.close(ClosingIterator.scala:66)
at org.neo4j.cypher.internal.compiler.v2_1.ClosingIterator$$anonfun$failIfThrows$1.apply(ClosingIterator.scala:96)
at org.neo4j.cypher.internal.compiler.v2_1.ClosingIterator.decoratedCypherException(ClosingIterator.scala:102)
at org.neo4j.cypher.internal.compiler.v2_1.ClosingIterator.failIfThrows(ClosingIterator.scala:91)
at org.neo4j.cypher.internal.compiler.v2_1.ClosingIterator.next(ClosingIterator.scala:44)
at org.neo4j.cypher.internal.compiler.v2_1.PipeExecutionResult.next(PipeExecutionResult.scala:169)
at org.neo4j.cypher.internal.compiler.v2_1.PipeExecutionResult.next(PipeExecutionResult.scala:35)
at scala.collection.Iterator$$anon$11.next(Iterator.scala:328)
at scala.collection.convert.Wrappers$IteratorWrapper.next(Wrappers.scala:30)
at org.neo4j.cypher.internal.compiler.v2_1.PipeExecutionResult$$anon$1.next(PipeExecutionResult.scala:77)
at org.neo4j.helpers.collection.IteratorWrapper.next(IteratorWrapper.java:47)
at org.neo4j.helpers.collection.IteratorWrapper.next(IteratorWrapper.java:47)
at java.lang.Iterable.forEach(Iterable.java:74)
at com.harmeetsingh13.service.impl.PersonServiceImpl.getAllPersons(PersonServiceImpl.java:48)
at com.harmeetsingh13.controller.PersonController.makeFriends(PersonController.java:55)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:781)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:721)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)

This exception is related to transaction. When i search on google there are so many question about this exception, but some solve problem using @Transactional anotation. I am also trying to use this annotation, but still facing the same error. following are my code and configuration.
@Service
@Transactional
public class PersonServiceImpl implements PersonService{

@Autowired
private RepositoryPerson repositoryPerson;
@Autowired
private Neo4jTemplate template;

@Override
public Person save(Person entity) {
    return repositoryPerson.save(entity);
}

@Override
public Person findPersonByProperty(String property, Object value) {
    return repositoryPerson.findBySchemaPropertyValue(property, value);
}

@Override
public List<Person> getAllPersons() {
    Result<Person> persons = repositoryPerson.findAll();
    List<Person> personsList = new ArrayList<>();
    persons.forEach(person -> personsList.add(person));
    return personsList;
}
}

Configuration:
@Configuration
@EnableTransactionManagement
@ComponentScan(basePackages={"com.harmeetsingh13.entities", "com.harmeetsingh13.maintainrelationship"})
@PropertySource(value="classpath:properties/db.properties")
@EnableNeo4jRepositories(basePackages = "com.harmeetsingh13.repository")
public class Neo4jConfig extends Neo4jAspectConfiguration{

@Resource
private Environment env;

public Neo4jConfig() {
    setBasePackage("com.harmeetsingh13.entities");
}

@Bean(name="graphDatabaseService")
public GraphDatabaseService getGraphDatabaseService(){
    GraphDatabaseFactory databaseService = new GraphDatabaseFactory();
    return databaseService.newEmbeddedDatabase(env.getProperty("db.store.directory"));
}

private JtaTransactionManagerFactoryBean neo4jTransactionManagerFactoryBean() throws Exception {
    JtaTransactionManagerFactoryBean factoryBean =
            new JtaTransactionManagerFactoryBean(getGraphDatabaseService());
    return factoryBean;
}

@Override
@Bean(name= {"transactionManager"})
public PlatformTransactionManager neo4jTransactionManager() throws Exception {
    ChainedTransactionManager transactionManager = new ChainedTransactionManager(neo4jTransactionManagerFactoryBean().getObject());
    return transactionManager;
}
}

When i trying to run test case, the test case run successfully. Following is the code of my test case.
@Test
@Transactional
public void findAllNodes(){
    Result<Person> persons = actorRepo.findAll();
    persons.forEach(person -> System.out.println(person));
}

A: See https://jira.spring.io/browse/DATAGRAPH-531
It only happens with an embedded neo4j database; not the REST variant.
In short, ensure that you convert everything into a List/Collection etc. before passing result objects on to the next layer
See below for a sample test method
try (Transaction graphDBTransaction = graphDatabaseService.beginTx()) {

  final Collection collection = personRepository.findAll().as(Collection.class);
  final int size = collection.size();

  assertThat("Total number of persons in test data-set should be 5!", size, equalTo(5));
  graphDBTransaction.success();
}


text:
Q: Scaling from local VM minikube/microk8s testing to testing on real cluster on AWS All -
I am a K8s newbie. I am trying to get a test a setup going with the following intention – I want to be able to have a setup configuration that I can use without much modification regardless of whether I use microk8s/minikube to run K8s or EKS on AWS. Is this possible?
Specifically, I want to setup a cluster with N components. For local testing each of these components may ask for small amount of resources for local VM testing (like 2GB disk, 1GB RAM, dns resolution locally etc.) while for the EKS testing these components will be requesting much larger resources (255GB disk, 8GB RAM, real load balancer instead of just dns resolution in EKS etc.)
Are there some resources to help me accomplish that? Any links to articles/books will help on this topic


text:
Q: echo %JAVA_HOME% works in cmd, but not in git bash Windows 10 user. I recently installed git for the first time, but ran into a peculiar issue. I was told that I needed to set the JAVA_HOME environment variable if I wanted to use java within git.
I was able to get JAVA_HOME properly changed for command prompt, but I couldn't get the same change to show up in git bash. Typing in echo %JAVA_HOME% would return a proper path in command prompt, but it would return %JAVA_HOME% in git bash.
I went into system settings and changed the system variable so that JAVA_HOME was pointing to my jdk. I updated the PATH variable in both system and environment variables to point to the bin and the jdk. I closed and reopened both git bash and command prompt. I restarted my machine, and even reinstalled both git and my jdk. I took my jdk from Java 10.0.2 down to the latest java 8 (171).
None of it has worked. I've gone through countless SO posts. What am I doing wrong?

A: Turns out, git uses a completely different syntax to do echo.
I had been doing echo %JAVA_HOME% when I should have been doing echo $JAVA_HOME.
I couldn't see that I was supposed to be using $ and not % sign because the symbols looked so similar in my font. I only found out after copy/pasting an answer out of frustration into bash and having it magically work when it hadn't worked prior.
But yes, the answer is to use $ and not % because they mean completely different things. Git bash uses $, command prompt uses %. You'd think they'd just use the same symbol to get the job done.


text:
Q: Bootstrap dropdown doesn't work on mobile Dropdown on my website doesn't open on mobile devices. I've followed many tips and tricks posted on the web but still unable to find a workaround!
This is my html:

        <button style="padding: 0 8px 10px 8px; font-face: sans-serif;color:#fff; font-weight: 700;font-size: 13px;text-transform: uppercase;opacity: 1;background-color: Transparent;border: 0pt" data-toggle="collapse" >About</button>

About Us

Team

FAQ

Demo

CSS imports:

  <link href="lib/bootstrap/css/bootstrap.min.css" rel="stylesheet">
  <link href="lib/bootstrap/css/bootstrap-responsive.css" rel="stylesheet">

JS:

A: Add Jquery to your script section.. bootstrap required to work well..


text:
Q: Where is the PHPUnit report schema used by Jenkins? I am having problems getting Jenkins to parse a xunit.xml report file when there are exceptions in the tests. The XML looks well-formed so I can't see any problem just by looking at it. Is there a xsd file somewhere that I can compare my xml against to see what actually causing the file to be unparsable?
About my setup:
I set up a nightly job in Jenkins for a PHP project. We are using Cakephp 1.3 therefore we are still using SimpleTest instead of PHPUnit. The only way I could figure out to easily produce the report xml while using simpletest was to use stagehand_testrunner (http://redmine.piece-framework.com/projects/stagehand-testrunner). In my build script I did something like:
cakerunner --cakephp-app-path=src/app --log- junit=build/test-results/junit.xml -R src/app/tests
This works great, however jenkins is unable to parse the junit.xml if there were exceptions thrown in the tests.

A: This was silly of me. I believe that stagehand-test runner already formats the resulting xml in JUnit format. I was trying to convert a JUnit xml report from PHPUnit to JUnit.
In Jenkins I needed to use the option "Publish JUnit test result report" instead of "Publish testing tools result report" The latter is for use with other testing frameworks to convert them to JUnit format. Since I already have a file in JUnit format, I do not need to convert it.
I need to verify this but I believe it to be the case.
I will be glad when we move to CakePHP 2.0 and use PHPUnit.

A: xUnit Plugin can solve this issue.


text:
Q: How to start using Xmonad on Ubuntu 12.04 LTS? I have installed Xmonad 0.10-3
Lightweight X11 window manager written in Haskell along with libraries and documentation on my Ubuntu 12.04 LTS system.
I expected some interface/menu to run this application but nothing seen. I am also unable to find the related documentation.
Please guide how to start using Xmonad?

A: If you've installed XMonad via the Ubuntu package, you should be able to select XMonad as an option when you log into your system in the same way that you would choose any other window manager like Gnome or Unity.
Once you're in, you'll find that the default configuration is highly minimal. I would recommend following a tutorial to start out. The XMonad site (http://xmonad.org/) has a variety of documentation, including this getting started tutorial: http://xmonad.org/tour.html.
A large part of the joy of XMonad is the ability to roll your own very customized configuration. I found that the best way to figure out what is possible is to take a look at what others are doing. The XMonad site has a page with screenshots and many different example configuration files: http://www.haskell.org/haskellwiki/Xmonad/Config_archive.
Or, you may be interested in checking out my own commented and documented configuration, which includes installation instructions and a walkthrough of its features. I have made this available on GitHub: https://github.com/davidbrewer/xmonad-ubuntu-conf.
Above all, give it a little time! XMonad can be daunting at first but once I got used to it I couldn't imagine going back to a more conventional window manager for my daily work.


text:
Q: uniform distribution value on [−0.6, −0.3] ∪ [0.3, 0.6] in R I have a binary matrix with 0 and 1s and I want each non-zero element substituted by a uniform distribution value on [−0.6, −0.3] ∪ [0.3, 0.6] in R.
Can anyone please help how can I achieve this?

A: Yes sample(c(1,-1),100,replace=T)*runif(100,0.3,0.6).

A: If your binary matrix looks like this:
set.seed(1)
m <- matrix(rbinom(16, 1, 0.5), 4)

m
#>      [,1] [,2] [,3] [,4]
#> [1,]    0    0    1    1
#> [2,]    0    1    0    0
#> [3,]    1    1    0    1
#> [4,]    1    1    0    0

Then you can replace its elements like so:
m[m != 0] <- runif(sum(m), 0.3, 0.6) * sign(rnorm(sum(m)))

m
#>            [,1]       [,2]      [,3]      [,4]
#> [1,]  0.0000000  0.0000000 0.3636428 0.4955021
#> [2,]  0.0000000  0.4140106 0.0000000 0.0000000
#> [3,] -0.5152856 -0.5332336 0.0000000 0.3376665
#> [4,] -0.5975718 -0.5804116 0.0000000 0.0000000


text:
Q: Laravel 5.6 database sessions not working My app has been working with file-based sessions just fine. However, after switching to the database driver my sessions stopped working. This is exactly what happens:

*

*The user opens the login page (a session gets created in the sessions table with user_id = NULL)

*The user fills in his\her login credentials and submits the form (the session in the database acquires a user_id = 1)

*The system tries to redirect the user to a post-login page, however by that time the session has been terminated (the session has user_id = NULL)
To switch to the database driver I only did the following (the app was already working with file-based sessions):
Created the sessions table using:

*

*php artisan session:table

*composer dump-autoload

*php artisan migrate
Configured config/sessions.php as follows:

*

*'driver' => env('SESSION_DRIVER', 'database')

*'connection' => 'mysql'

*'table' => 'sessions'

*'domain' => 'test.local'
My .env file:

*

*DB_CONNECTION=mysql

*SESSION_DRIVER=database
routes.php
Route::group(['domain' => 'test.local', 'middleware' => 'web'], function() {
    Route::group(['domain' => 'test.local', 'middleware' => 'auth'], function() {
        // post-login routes...
    }

    // show the login form
    Route::get('/login', 'Auth\LoginController@showLogin');

    // submit the login form
    Route::post('/login', 'Auth\LoginController@submitLogin');
}

Am I missing something? Any help is much appreciated.


text:
Q: posting a text message in a listview android tutorial I'm working on my first app which is basically a simple app containing a registration system and the ability to post a text message on a "feed" , "wall" page
I successfully did the registration system, now i only need to know how to get the text written in the "post something" box and place it on the feed page so everyone can see it.
This is the code:
I just did a text to add a text in a listview but the app is crashing before even opening
Main:
package com.example.ali.bla;

import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.Arrays;

public class MainActivity extends ActionBarActivity {

    private ListView mainListView ;
    private ArrayAdapter<String> listAdapter ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Find the ListView resource.
        mainListView = (ListView) findViewById( R.id.mainListView );

        // Create and populate a List of planet names.
        String[] planets = new String[] { "Mercury", "Venus", "Earth", "Mars",
                "Jupiter", "Saturn", "Uranus", "Neptune"};
        ArrayList<String> planetList = new ArrayList<String>();
        planetList.addAll( Arrays.asList(planets) );

        // Create ArrayAdapter using the planet list.
        listAdapter = new ArrayAdapter<String>(this, R.layout.simplerow, planetList);
        // Set the ArrayAdapter as the ListView's adapter.
        mainListView.setAdapter( listAdapter );
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            new Intent(MainActivity.this, post.class);
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

this is post class where i want to extract text written by usrs and add it in the listview :
package com.example.ali.bla;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class post extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_post);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_post, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

these are the xml files:
main:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <ListView android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/mainListView">
    </ListView>

</RelativeLayout>

row:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent">

    <TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/rowTextView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:textSize="16sp" >
    </TextView>
</LinearLayout>

and for the post:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="com.example.ali.bla.post">

   <EditText
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:id="@+id/post"
       android:hint="share with us !"/>

</RelativeLayout>

Thank you


text:
Q: Redshift - Divide by zero error I am having issues with the below that keeps throwing "Divide by zero" error
Given below is the query I am using:
select cust_name,
sum(case WHEN sale_date > CURRENT_TIMESTAMP-14 AND sale_date < CURRENT_TIMESTAMP then 1 else 0  END) AS "0_2_sales_count",
sum(case WHEN sale_date > CURRENT_TIMESTAMP-28 AND sale_date < CURRENT_TIMESTAMP-14  then 1 else 0  END) AS "2_4_sales_count",
("0_2_sales_count") - ("2_4_sales_count") as "load_volume_diff_0_2_2_4",
(("0_2_sales_count" - "2_4_weeks_load_volume")/"2_4_sales_count"::float) * 100  as "load_volume_diff_percent_0_2_2_4"
from sales
group by cust_name;

I have zeroesfor different customers in "0_2_sales_count" and "2_4_sales_count" columns. Could anyone advice how could I handle this above error. I have tried using case when column = 0 but still the same problem occurs.
I am using Amazon Redshift DB.
Thanks

A: You could check for 0 in  "2_4_sales_count"  using a case and use the proper code for each situation
select cust_name,
      sum(case WHEN sale_date > CURRENT_TIMESTAMP-14
          AND sale_date < CURRENT_TIMESTAMP then 1 else 0  END) AS "0_2_sales_count",
        sum(case WHEN sale_date > CURRENT_TIMESTAMP-28
          AND sale_date < CURRENT_TIMESTAMP-14  then 1 else 0  END) AS "2_4_sales_count",
      ("0_2_sales_count") - ("2_4_sales_count") as "load_volume_diff_0_2_2_4",
      CASE WHEN "2_4_sales_count"::float = 0
          THEN 0 ELSE (("0_2_sales_count" - "2_4_weeks_load_volume")/"2_4_sales_count"::float) * 100  END as "load_volume_diff_percent_0_2_2_4"
from sales
group by cust_name;

A: Try with case when like case when "2_4_sales_count"::float =0 then 1 end
select cust_name,
sum(case WHEN sale_date > CURRENT_TIMESTAMP-14 AND sale_date < CURRENT_TIMESTAMP then 1 else 0  END) AS "0_2_sales_count",
sum(case WHEN sale_date > CURRENT_TIMESTAMP-28 AND sale_date < CURRENT_TIMESTAMP-14  then 1 else 0  END) AS "2_4_sales_count",
("0_2_sales_count") - ("2_4_sales_count") as "load_volume_diff_0_2_2_4",
(("0_2_sales_count" - "2_4_weeks_load_volume")/case when "2_4_sales_count"::float =0 then 1 end) * 100  as "load_volume_diff_percent_0_2_2_4"
from sales
group by cust_name;

A: Presumably, the problem is in this row:
(("0_2_sales_count" -"2_4_weeks_load_volume") / "2_4_sales_count"::float) * 100  as "load_volume_diff_percent_0_2_2_4"

I would write this as:
(("0_2_sales_count" - "2_4_weeks_load_volume") * 100.0 / nullif("2_4_sales_count", 0.0) as "load_volume_diff_percent_0_2_2_4"

The simplest solution for divide-by-zero is nullif().


text:
Q: where to download the bootcamp software for windows when updating/installing OSX Lion? As it says on the cd that after installing the windows insert your OSX disk and run the bootcamp updater that'll install all the drivers and updates to use your mac machine in Windows environment ...
After installing OSX Lion, when I installed Windows 7 on my machine I did as I mentioned above and it deleted the OSX Lion from my machine ... strange behaviour ... and this is because the CD i got was the bootcamp updater for OSX Snow-Leopard ... so this might have cause this strange action ...
when i look for the current release of bootcamp update so on website the most updated release of bootcamp is of early 2011, so if any one tell me where to download the bootcamp software for windows that is compatible with OSX Lion?

A: Both the MacBook Air / Mac Mini (which can lack a CD/DVD drive as shipped) and Macs running Lion now simply download their BootCamp drivers from within the Boot Camp Assistant.

A: The early 2011 drivers will work. I just went thru installing boot camp on a Mac over the weekend on OS X Lion and that was the download that Lion's Boot Camp Assistant linked to.
Here is Apple's official Boot Camp on OS X Lion FAQ on Apple Support. One of the items on that article takes you to this additional article that basically confirms that you should follow the steps on the Boot Camp Assistant (the ones that take you to the early 2011 drivers). Hope this helps.


text:
Q: How do I 'addChild' an DisplayObject3d from another class? (Papervision3d) Im kind of new in the whole papervision scene.
For a school assignment I'm making a panorama version of my own room using
a cube with 6 pictures in it. It created the panorama, it works great.
But now I want to add clickable objects in it. One of the requirements
is that my code is OOP focused. So that's what I am trying right now.
Currently I got two classes
 - Main.as (Here i make the panorama cube as the room)
 - photoWall.as (Here I want to create my first clickable object)
Now my problem is: I want to addChild a clickable object from photoWall.as
to my panorama room. But he doesn't show it? I think it has something to do with
the scenes. I use a new scene in Main.as and in photoWall.as. No errors or warnings are reported
This is the piece in photoWall.as were I want to addChild my object (photoList):
    private function portret():void
{
    //defining my material for the clickable portret
    var material : BitmapFileMaterial = new BitmapFileMaterial('images/room.jpg');
    var material_list : MaterialsList = new MaterialsList( { front: material, back: material } );

    // I don't know if this is nessecary? that's my problem
    scene = new Scene3D();

    material.interactive = true;

    // make the clickable object as a cube
    var photoList : DisplayObject3D = new Cube(material_list, 1400, 1400, 1750, 1, 4, 4, 4);

    // positioning
    photoList.x = -1400;
    photoList.y = -280;
    photoList.z = 5000;

    //mouse event
    photoList.addEventListener( InteractiveScene3DEvent.OBJECT_CLICK, onPress);

    // this is my problem! I cannot see 'photoList' within my scene!!!
    scene.addChild(photoList);

    // trace works, so the function must be loaded.
    trace('function loaded');
}

Hope you guys can help me out here. Would really be great!
Thanks,
Sandor

A: you have to render before you can se anything.
missing:
viewport.startRender()

A: No I already rendered everything in another class.
I figured it out, the answer is: I have to make this class a displayobject3d.
that's it. everything you addchild on the stage now is a displayobject3d.
for details or code..just ask.
view the result of my little project here :
http://www.sandorkerst.com/papervision/bin


text:
Q: Entity Framework Linq Group by DateRange I have an application that records page visits and I need to be able to query by day by week and by month, sample output of a table query is as follows (each row represents a visit:
Visits result set
DateTimeLanding | PageViews
2016-05-12      | 2
2016-05-16      | 3
2016-05-16      | 8
2016-05-16      | 3
2016-05-17      | 7
2016-05-19      | 4
2016-05-28      | 6
2016-05-28      | 3
2016-05-30      | 1

If I want to query this result set for daily visits I do this:
var visitData = visits.GroupBy(v => v.DateLanding)
                            .OrderBy(g => g.Key)
                            .Select(g => new { From = g.Key, Count = g.Count() });

                    visitNodes.Num = visits.Count().ToString();
                    visitNodes.Nodes = visitData.Select(p => new ReferralTrafficNode()
                    {
                        MetricDateTimeFrom = p.From,
                        MetricDateTimeTo = p.From.AddDays(1),
                        Value = p.Count
                    }).ToList();

This works fine for daily visits as I can group date.
How can I group the result set into groups of 7 days to get weekly visit data?
Essentially I need to be able to group by a date range

A: If you change your group by to this:
v => v.DateLanding.AddDays(-(int)v.DateLanding.DayOfWeek)

This should group by the Sunday of the week selected.


text:
Q: Delegate on more than one event in a table created dynamically with jquery First of all, I'm sorry if this is a silly question, but I've been looking for several days and I can't find a solution.
The fact is that I have two different tables (with different id's) in my page that are created dynamically (with PHP and retrieved information from phpMyAdmin). The last  of every row in table one, includes 6 (2 hidden) different buttons (a elements) to handle different events. Those events are triggered by jQuery functions contained in my file edit_user.js
One of those events, erases the row from where the element was clicked, and adds the information into the second table as a new row.
As well as in table1, the last  of table2 includes 2 different buttons (a elements too) with different functionalities. One of these features does the exact opposite of the functionality commented before : Returns the row in question to Table1.
Everything works fine, except for those newly inserted rows, because the a elements don't do anything.
I read about delegation and changed the way my file listens to those clicks, but I still can't get it to work:
    $(document).ready(
            function() {
                // Set handlers for myTable
                $('table#myTable td').on('click','a.userErase',erase)
                .on('click','a.userEditable',edit)
                .on('click','a.userSuspend',suspend);

                // Set handlers for suspTable
                $('table#suspTable td ').on('click','a.userErase',erase)
                .on('click','a.userResume',resume);
            });

My problem is basically with two functions, resume and suspend, because those are the one that create new rows in the tables, but I suppose that they are not delegating because new rows call different functions:
Table1

Table2

For better understanding, I have the following functions in each table:
Table1

*

*edit

*change password

*suspend

*erase

*accept_edit (only visible when edit is selected)

*cancel_edit (only visible when edit is selected)

Table2

*

*resume

*erase

I generate the new rows with a code like this (it is working good but the handler not get to the event):
    // create a row with the info to add in suspendedTable
    var html = "

"+ pName
                            + "

 "+ pSurname
                            + "

 "+ pEmail
                            + "

 "+ pUsername
                            + "
	 "
                            + "
\n"

                $('#suspTable tr:last').after(html);

The functionality is ok, if I refresh the page everything works fine, but until that moment, I can't get those new lines to work properly.
Is there a way to call for the function directly from those newly generated lines (like onClick in JavaScript)? (I tried that but neither did not function).
Thanks in advance,

A: You simply delegated your events too deep. Add the handler on the table and not on the td:
$('table#myTable').on('click','a.userErase',erase)...

Because #myTable stays on the page and the event is bound to it it will catch clicks inside it, for newly created rows too.


text:
Q: /proc/diskstats: No such file or directory Trying to get some disk performance metrics (in particular, using munin), found that  /proc/diskstats does not exist.
Tried yum provides '*/diskstats' but nothing except munin was found.
CentOS release 6.7 (Final)
uname -a
Linux domain.com 2.6.32-042stab112.15 #1 SMP Tue Oct 20 17:22:56 MSK 2015 x86_64 x86_64 x86_64 GNU/Linux

So, how can I fix it?

A: Looks like you are on a Virtual server (VPS). If your VPS is based on OpenVZ, openVZ usually doesn't expose all counters (like /proc/diskstats) to its containers.


text:
Q: Problem with 'System.Xml.IXmlLineInfo' The whole internet is full of such problem:
due to some reason web site become uncompilable with the following error:

The type 'System.Xml.IXmlLineInfo' is
  defined in an assembly that is not
  referenced. You must add a reference
  to assembly 'System.Xml,
  Version=2.0.5.0, Culture=neutral,
  PublicKeyToken=7cec85d7bea7798e'.

It often appear in places that don't have any relationship to xml... In my case it is in the following line of the ascx file:

<%#((Team)Container.DataItem).Href()%>

Or another one:
 Hello, <%=_clu.User.Href(true)%>! ( Exit )

I saw I recommendation to remove all references to library, stop IIS, delete all temp files (I deleted usual temp files from user folder, from window folder, deleted everything from "Temporary ASP.NET Files" folder of all .NET folders...
Nothing helped...
Don't know, how to continue work at all... Reinstall Windows? :(
P.S. I have ASP.NET 4.0 web site
P.P.S. When I try to add reference VS tolds me:

The Web site is already referencing the assembly 'System.XML'.

What is additionaly confuses me is that "XML" is written in upper case. But the 'standard' .NET assembly has "System.Xml"...

A: I've got that problem appeared after including 3rd part library. I had the previous version of library and the new one. I've resolved problem by the following:

*

*rolling back my source code to previous version;

*removed all instances and source code of those 3rd party library (temporary files, etc);

*get the ONLY 1 copy of dll of required library;

*removed references to OLD lib;

*added references to the new one.

A: I has a similar error to this. The resolution was actually stupidly simple.
The problem arrises in that your project has a reference to an assembly running on a different version of the .Net framework. Though fixing this would most probably fix it, it could take a long while to track down (depending on the size of the project).
My solution was to go through the Using clause at the top of the code page and remove any uneeded.
Using clause's found within the code declarations.
Error Using clause
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

The Invalid Using clause
using System.Xml.Linq;

This namespace is a .Net 4 namespance and because of the way .Net works it was trying to load the System.Xml.Linq.dll file, which it did successfully, but then it would throw the error that you've received.


text:
Q: Network manager command line script As RHEL boots up and I login, I'd want to manually run a script which would:

*

*Identify the active ethernet interface (the eth ID being used).

*Ask for, and would let me type the IP address, netmask, gateway and
DNS servers, and save that info to the active ethernet interface
settings.
I can do all this manually through the NM interface but wondering if it is possible through nmcli, and, if so, how?


text:
Q: How to pass relative path to use the File.Delete static function in C#? I've been trying to create a way to upload, download and delete a PDF file. The upload and the download function work fine, but when I try to delete the PDF it doesn't really work as I want it to.
It does work when I use this form:
File.Delete(@"C:\Users\Donovan\1_Test.pdf");
But it doesn't work when I try this:
File.Delete(@"~\1_Test.pdf");
I want to find a way to make the second line of code work, because I work in a team and we don't share the same file path.

A: Use Environment.GetFolderPath to find the user's home directory.
string home = Environment.GetFolderPath(Environment.SpecialFolder.UseProfile);
File.Delete(Path.Combine(home, "1_Test.pdf"));

You might also want to consider putting the file in the folder for temporary files instead. You can find that location with Path.GetTempPath. (Note that windows will not automatically clean up temporary files, so you still need to delete anything you put there after you are done with it.)

A: If you are all using the userpath you can go with this approach:
System.IO.File.Delete(
    Path.Combine(
         Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
         "1_Test.pdf"
    )
);

A: You unfortunately cannot make it work with ~. This only works as a relative path for web applications.
We use a local config file for our application where each developer stores its own preferences and can change these independent of other developers.
Depending on your application (web, desktop, mobile, windows, linux, whatever) you can write a config-object and fill it or use i.e. appsettings in web.config for this purpose.
var basePath = Config.FileBase;
File.Delete(Path.Combine(basePath, "\1_Test.pdf"));

A: Another method:
File.Delete(Environment.ExpandEnvironmentVariables("%USERPROFILE%\\1_Test.pdf"));

A: Try this. I think it works :D
File.Delete(Server.MapPath("~/") + "1_Test.pdf");

A: Have you considered it to put the *.pdf files in a database?


text:
Q: Open .txt file from same directory fails to find the file (FileNotFoundError) - python/kivy I want to open a few files for game in kivy (instructions, about info...), so I don't have to have everything typed in the main.py but using those two methods it gives me an error.
class MenuScreen(Screen):
    try:
        #os.path.dirname(sys.argv[0])
        #fullpath = os.path.join(os.path.dirname(sys.argv[0]), 'navodila.txt')
        #instructions = StringProperty("")

        #with open(fullpath, "r") as inst:
        #    for line in inst:
        #        instructions += line

        instructions = ""
        with open("navodila.txt", "r") as file:
            for line in file:
                instructions += line

    except: instructions = "Instructions failed to load."

    def show_popup_inst(self):
        p = InstructionsPopup(content=Label(text=self.instructions, text_size=self.size))
        p.open()

They both give me the same FileNotFoundError. I've checked at least five times and the file is there.
 Traceback (most recent call last):
   File "C:\Users\Lara\Desktop\KIVY\LARA\Snaky Game\SNAKY REAL\SnakyGame4.py", line 361, in <module>
     class MenuScreen(Screen):
   File "C:\Users\Lara\Desktop\KIVY\LARA\Snaky Game\SNAKY REAL\SnakyGame4.py", line 371, in MenuScreen
     with open("navodila.txt", "r") as file:
 FileNotFoundError: [Errno 2] No such file or directory: 'navodila.txt'

The try, except part is there just because I was working on code after trying reading a file.
Am I using the methods wrong? I've tried writing both of them outside any of the classes but it gave me the same error so I returned it inside in MenuScreen class.

A: It sounds like you want the working directory to be the same as the directory where the script lives.  Here's a technique I use to keep track of relative paths (which revert to the calling path by default).
import os
script_path = os.path.dirname(os.path.realpath(__file__))
with open( os.path.join(script_path,"navodila.txt") , "r") as f:
    do_stuff()

This way you just need to have the script and text file in the same directory and it doesn't matter where exactly they are stored in your filesystem or where you are calling the program from.


text:
Q: Checking a ring is not Cohen-Macaulay While reading a book, I found an example that said that the ring $K[w,x,y,z]/(wy,wz,xy,xz)$ is not Cohen-Macaulay. In order to check this, it is stated to take the quotient by the ideal generated by the non-zero divisor $w-y$, that gives the ring $K[x,y,z]/(y^2,yz,xy,xz)$. The book assures that all the elements of its maximal ideal are zero divisors.
I couldn't follow through this last part: I don't see why this ring would be local (do I need to localize in a maximal ideal?)
You can find this section of the pdf file by looking up "25. Regular local rings Corollary 25.1".

A: If it were local, all its quotients would be local, but factoring out by the ideal generated by $y$ and $z$, you get $K[x]$, which isn't local.
Secondly, the minimal primes of the second quotient are pretty clearly the ideals $(x,y)$ and $(y,z)$, quotienting by them we get $K[z]$ and $K[x]$ respectively, so it becomes clear that among the maximal ideals there are $(x,y,p(z))$ and $(p(x), y, z)$, where the $p$ represents an irreducible polynomial.
It isn't clear to me how $x-1$ would be a zero divisor in $(x-1,y,z)$ in the second quotient.
That doesn't completely rule out that the example isn't Cohen-Macaulay, though, only that the hint appears to have problems. Unfortunately, I'm unfamiliar with Cohen-Macaulay rings and can't tell you straightaway. Perhaps if you provide more info about the work this appeared in.

A: Observe that $(wy, wz, xy, xz) = (w, x) \cap (y, z),$ hence the height of $(wy, wz, xy, xz)$ is $2.$ We have therefore that $R = k[w, x, y, z] / (wy, wz, xy, xz)$ has dimension $2.$ On the other hand, the element $w - y$ is neither a zero divisor nor a unit, hence the sequence $(w - y)$ is $R$-regular. Going modulo $(w - y),$ we have that $R / (w - y) \cong k[x, y, z] / (y^2, yz, xy, xz),$ and each of the generators of the unique homogeneous maximal ideal $\mathfrak m = (x, y, z)$ is a zero divisor. Consequently, there are no regular sequences in $R / (w - y),$ hence it follows that $\operatorname{depth} R = 1 < 2 = \dim R$ so that $R$ is not Cohen-Macaulay.


text:
Q: Problems with MessageBox.Show() I'm new to code and most things work, but I can't get this code to run. Can someone help?
I tried using System.Forms but it showed as missing a namespace. When I used using System.Windows.Forms that message went away. It does not let me use both.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            StreamReader sr = new StreamReader(@"file.csv");
            // for set encoding
            // StreamReader sr = new StreamReader(@"file.csv", Encoding.GetEncoding(1250));

            string strline = "";
            String[] _values = null;
            int x = 0;
            while(!sr.EndOfStream)
            {
                strline = sr.ReadLine();
                _values = strline.Split(',');
                if (_values.Length >= 6 && _values[0].Trim().Length > 0)
                {
                    MessageBox.show(_values[1]);
                }
            }
            sr.Close();

        }
    }
}

A: There is no such namespace System.Forms, the class you were trying to use (MessageBox) is in System.Windows.Forms. By correcting your using statement, the error went away.
Remember, you must have a reference to System.Windows.Forms.dll in your console app to use this class.

A: You need to reference System.Windows.Forms.dll in your project. Here is a detailed instruction how to do that.

A: There is no such namespace as System.Forms there is only a namespace called System.Windows.Forms, wich has the MessageBox class you are talking about. To be able to use it, you need to add a reference to the System.Windows.Forms.dll to to your project (find it in the .NET Tab in the "Add Reference ..." dialog) and it will work. Also note that MessageBox.Show() requires a capital 'S'. Please see below an optimized and fully working version of your code.
using System.IO;
using System.Windows.Forms;

namespace ConsoleApplication7
{
    class Program
    {
        static void Main(string[] args)
        {
            using (StreamReader sr = new StreamReader(@"file.csv"))
            {
                while (sr.Peek() >= 0)
                {
                    string strline = sr.ReadLine();
                    string[] values = strline.Split(',');
                    if (values.Length >= 6 && values[0].Trim().Length > 0)
                    {
                        MessageBox.Show(values[1]);
                    }
                }
            }
        }
    }
}

A: You try use it in Console application first you should add System.Windows.Forms dll in your references (from .Net reference tab) then use it by adding it's namespace.

A: I'm a bit confused here. there is no namespace called System.Forms. It's always System.Windows.Forms. And the MessageBox class is defined in System.Windows.Forms
You need to manually ADD a reference to your project for System.Windows.Forms as you are on a console application and not a Windows Application. Just add the reference.


text:
Q: If $1(0!)+3.(1!)+7(2!)+13(3!) +21(4!) + \cdots $ n terms.... Question( from sequences) :
If $1(0!)+3.(1!)+7(2!)+13(3!) +21(4!) + \cdots $ n terms = $(4000)(4000!)$ Then what is the value of n.
How to proceed in this please suggest , will be of great help to me thanks...

A: It is a telescoping sum.
$$\begin{align}
\sum_{k=0}^n k!(k(k+1)+1)
=& \sum_{k=0}^n k!\big((k+1)(k+2) - 2(k+1) + 1\big)\\
=& \sum_{k=0}^n \big((k+2)! -2(k+1)! + k!\big)\\
=& \sum_{k=0}^n \bigg(\big((k+2)! - (k+1)!\big) - \big((k+1)!-k!\big)\bigg)\\
=& \big((n+2)! - (0+1)!\big) - \big((n+1)! - 0!\big)\\
=& (n+2)! - (n+1)!\\
=& (n+1)(n+1)!\\
\end{align}
$$
So $n = 3999$.

A: The summation is
\begin{align}
S_{n} = \sum_{r=0}^{n} \left( r(r+1) + 1\right) \, r!
\end{align}
and by selecting $n$ values it is seen that
\begin{align}
S_{0} &= 1 \\
S_{1} &= 0! + 3 \cdot 1! = 2 \cdot 2! \\
S_{2} &= 0! + 3 \cdot 1! + 7 \cdot 2! = 3 \cdot 3!
\end{align}
which leads to
\begin{align}
S_{n} = \sum_{r=0}^{n} [ r(r+1) + 1] \, r! = (n+1) \cdot (n+1)!.
\end{align}
For the case of $S_{n} = (4000) \cdot (4000)!$ it is seen that $n = 3999$.

A: Suggestions: I would look for patterns:
$1(0!)=1$
$1(0!)+3(1!)=4$
$1(0!)+3(1!)+7(2!)=18$.
Then I'd try to match this to something that would give $(4000)(4000!)$ for some $n$.  Then I'd start trying to prove some stuff (probably by induction).

A: Your approach should be to write a generic formula with a summation.
Then figure out that each summation element adds a new element but removes the old one.
And if you do the administration properly, you'll find n to be 3999 or 4000 or so.


text:
Q: Avoid removing inner HTML while replacing text I'm trying to highlight the text of HTML elements without removing their inner HTML. Here is an example:

const buttonEl = `<button>

    Icon

  Text
</button>
`;

document.body.innerHTML = buttonEl;

const foundButtonEl = document.querySelector("button");
const elements = [];

elements.push(foundButtonEl);

function addHighlight(elements, text) {
  const regex = new RegExp(text);

  elements.forEach((element, index) => {
    element.innerHTML = element.textContent.replace(
      regex,
      `<mark>$&</mark>`
    );
  });
}

addHighlight(elements, "T");

If you run this example, you'll notice that T will be highlighted, but the  tags will be removed.
How to highlight the text without affecting the inner HTML?

A: You change the inner HTML of button. So one way would be to put a span around your Text and use an id and then use document.getElementById("text") I guess.
See for example

const buttonEl = `<button>

      Icon

    Text

  </button>
  `;

  document.body.innerHTML = buttonEl;

  const foundButtonEl = document.getElementById("text");
  const elements = [];

  elements.push(foundButtonEl);

  function addHighlight(elements, text) {
    const regex = new RegExp(text);

    elements.forEach((element, index) => {
      element.innerHTML = element.textContent.replace(
        regex,
        `<mark>$&</mark>`
      );
    });
  }

  addHighlight(elements, "T");

A: The .textContent property returns (or set) the text content of all children and since the <button> element may contain further nested elements, its strict content might be mixed with promiscuous content coming from other elements like your span icon.
Here in this demo I added a layer that will convert the button content so that every single text node found will be removed and changed to a span.textnode so that later when you'll need to style the text content adding the  it will be strightforward to change ONLY the contents of inner span.textnode elements.
To better show the concept I also added the fontawesome asset and style the icon inside the button.

const buttons = document.querySelectorAll("button");

function addHighlight(buttons, text){
  buttons.forEach(button => {
    initButton(button);
    highlightTextInButton(button, text);
  });
}

function initButton(button){
 //for each child node in button
 for (var i = 0; i < button.childNodes.length; i++) {
    const child = button.childNodes[i];
    //if it's of type TEXT_NODE
    if (child.nodeType === Node.TEXT_NODE) {
      //creates a new span.textnode
      const span = document.createElement('span');
      span.classList.add('textnode');
      //with this same content
      span.textContent = child.nodeValue;
      //removes the text node
      child.remove();
      //adds the new span.textnode
      button.append(span);
    }
  }
}

function highlightTextInButton(button, text){
  const regex = new RegExp(text);
  button.querySelectorAll(':scope > .textnode')
    .forEach(textnode=>{
      const textContent = textnode.textContent;
      textnode.innerHTML = textContent.replace(regex,`<mark>$&</mark>`);
    });
}

addHighlight(buttons, "T");
.textnode{
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css" integrity="sha512-MV7K8+y+gLIBoVD59lQIYicR65iaqukzvf/nwasF0nqhPay5w/9lJmVM2hMDcnK1OnMGCdVK+iQrJ7lzPJQd1w==" crossorigin="anonymous" referrerpolicy="no-referrer" />

<button>

  Text
</button>


text:
Q: Complex Quadrilateral Problem Consider a convex quadrilateral with vertices at $,~,~$ and $$ and on each side draw a square lying outside the given quadrilateral, as in the picture below. Let $,~,~$ and $$ be the centers of those squares:

a) Find expressions for $,~,~$ and $$ in terms of $,~,~$ and $$.
b) Prove that the line segment between $$ and $$ is perpendicular and equal in length to the line segment between $$ and $$.
I think this problem has been asked before, but they don't give any good hints. I don't really know where to start. I tried finding $p$ first by finding $(p-a)$ and $(p-b)$. I tried another way by translating $a$ to the origin. I haven't been able to go farther than this.
I think I have an idea for part $b$ using similar triangles and things, but part a is really confusing.Thank you!
I translated the square with $p$ as its center so that a would be at the origin. So $b$ would then be $b−a$ and $p$ would be $p−a$, right? $p−a$ is half of the diagonal. So then $(p−a)=(b−a)\cdot\frac{\sqrt2}{2}$.
Rotating by $-\frac{\pi}{4}$ would give us $$\frac{(b−a)2}{√2}\cdot e^{−i\frac{\pi}{4}}=\frac{(b−a)\sqrt2}{2}\cdot\left(\frac{\sqrt2}{2}−i\frac{\sqrt2}{2}\right)=\left(\frac{(b−a)}{2}−i\frac{(b−a)}{2}\right)=\frac{b−a−bi+ai}{2}$$
Therefore, $p−a=b−a−bi+ai2$ and when we translate everything back we get $$p=b−a−bi+ai2+a⟹p=b−a−bi+ai+(2a)2⟹p=b+a−bi+ai2.$$ I can do a similar process for the rest of the points, right?
Does it matter which point I translate to the origin?

A: I'll give a hint for part (a). Points like $a$, $b$, $c$ and $d$ on the complex plane can also be thought of as vectors starting at the origin and ending at that point, so that the vector going from $a$ to $c$ is $c-a$; in other words, $a+(c-a)=c$. So to get to the point $p$, I have to go halfway between $a$ and $b$, then make a $90^\circ$ turn to the right and move by that same distance. That is,
$$p=a+\frac{b-a}{2}+(\hbox{right turn by $\frac{b-a}{2}$)}.$$
So how do you get a right turn by a complex number? How do complex numbers relate to rotations?
For reference, this is van Aubel's theorem; a proof can be found in Chapter 1 of Tristan Needham's wonderful text Visual Complex Analysis.


text:
Q: 'is to be' vs 'was to be' with present perfect at the end of the sentence [future seen from the past] DNA testing was to be used by police in the search for the missing Dublin schoolboy. His parents have welcomed the news.
Why 'was to be used' is incorrect in this sentence and 'is to be used' is suggested as correct by the 'Advanced Grammar in Use' book?
Which part of this sentence suggests that we have 'The future from now' instead of 'The future seen from the past' scenario?
I thought that 'was to be' is correct as I wasn't sure whether the search took place in the past or will take place in the future.

A: The next sentence - His parents have welcomed the news. - indicates that the announcement about using DNA testing has only recently been made, so the testing is in 'the future from now'.

A: Either one could be correct, given a fitting context.
However, the second sentence, with the verb "have welcomed", sets a time frame extending up to the present. That means only "is to be used", referring to future use of DNA, is correct.
If the sentence used a perspective in the past about future use of DNA, then "was to be used" might fit.


text:
Q: Rally Apps sdk 1: release dashboard Newbie. In the Rally Apps Catalog there is a Release Dashboard report I would like to display outside of Rally. I would like to combine that report/dashboard with two other standard report in a html page. ie I would like to create a dashboard type reports using Rally Sdk.  is it possible?
how can I create my own charts using the sdk?

A: This is possible.  Please contact Rally support concerning gaining access to loginKey functionality to enable running reports externally (in a wiki, sharepoint portal, etc.).


text:
Q: Volume /mass / density problem If I have a solution that has a volume of 32.5mL, a mass of 40.0g, and a density of 1.23 --- how do I solve for 10mL, 15, 20mL, etc of the same solution?
Thanks!

A: It's unclear what you mean by "solve for", but if you want to find the mass of different volumes just remember that the density remains constant and use $m = \rho v$ where $\rho$ is density, $m$ mass and $v$ volume. Put in different values of $v$ to get different values of $m$ and use a spreadsheet if you're dealing with a lot of numbers.