Is it true that $q(q(x-1)+1)^m = x^m$ has no non-trivial integer solution $x$?

Question: I am currently working on a special function defined by myself and found a special case that shows if $q \in \mathbb{N}$, then$$q(q(x-1)+1)^m = x^m$$ has no non-trivial natural integer solution $x$.
Although I have not extended my work over $\mathbb{Z}$, I believe it also has no solution in $\mathbb{Z}$. Can someone help verify this since the function I'm working on is a bit blurry for me right now.
P.S. Not sure if the equation is significant though.
Comment: Is $q$ a prime number or just any integer? At least there should be $q ≠ 0, 1$.
Comment: any natural number greater than 1
Comment: and obviously cannot be prime
Comment: What trouble are you having extending from the naturals to all of the integers? Why not post your proof for the naturals here?
Answer: It is easy to see what happens when $x=0$. Otherwise $q(x-1)+1 \neq 0$ and hence
$$\sqrt[m]{q}=\frac{x}{q(x-1)+1} \in \mathbb Q$$
This shows that $\sqrt[m]{q} \in \mathbb Z$, and hence $q=k^m$ for some integer.
Then, taking into account that $m$ could be even:
$$k(k^m(x-1)+1) = \pm x \Leftrightarrow \\
k^{m+1}x-k^{m+1}+k = \pm x \Leftrightarrow\\
x(k^{m+1}\pm 1)=k^{m+1}-k
$$
Now, this implies $k^{m+1}\pm 1|k^{m+1}-k$ we get that
$$k^{m+1}\pm 1| (k^{m+1}\pm 1)-(k^{m+1}-k)=k\pm 1$$ and hence
$$|k^{m+1}-1| \leq |k-1| \Rightarrow |k|^{m+1} \leq |k|+2$$
This leads to $|k|=0,1$ or $m=1$, from which the problem is easy to finish.


error correction in declaration of a struct array

Question: Please how can I correct this instruction in c++
const struct { unsigned int xIdx, yIdx, zIdx; } faceIndex[] { {0,1,2}, {2,0,1}, {1,2,0} };

thank you very much
Comment: what is the problem you're having with it? what do you expect it to do?
Answer: Add an equal sign, as in:
const struct { unsigned int xIdx, yIdx, zIdx; }
    faceIndex[] = { {0,1,2}, {2,0,1}, {1,2,0} };

Comment: I used it and I don't have the error yet .I work with visual studio c++ version 6
Comment: Yes but not in this instruction but in
Comment: Well, if you have other errors, you could post other questions (after some personal research, mind you) or update this question. Anyway, don't forget to accept my answer if it answered your initial question.


Jumbotron and background images disappear when the window size changes from full screen to small

Question: Have an issue with my homepage, the jumbotron/background images disappear when the window size changes from full screen to small screen, when it's resized the background/jumbotron images re-appear,how can the images be made responsive ?
Below is the styling:


Does $u_n \rightharpoonup u$ in $L^2(0,T;H^1)$ and $u_n' \rightharpoonup u'$ in $L^2(0,T;H^{-1})$ give something useful?

Question: If $u_n \rightharpoonup u$ in $L^2(0,T;H^1)$ and $u_n' \rightharpoonup u'$ in $L^2(0,T;H^{-1})$ is there any way to extract a strongly convergent subsequence of $u_n$ in some useful space for PDEs? Or some a.e. convergence result?
For example, if we had the time derivatives weakly convergent in the space $L^2(0,T;L^2)$ then we can use Lions-Aubin to get $u_n \to u$ in $L^2(0,T;L^2)$.
Comment: Your last paragraph is wrong. In order to apply Lions-Aubin, you need additionally the weak convergence of the function itself in $L^2(0,T;X)$, where $X$ is compactly embedded in $L^2(\Omega)$.
Comment: @gerw But we already have $u_n \rightharpoonup u$ in $L^2(0,T;H^1)$.
Comment: Ok, so you should rewrite your last paragraph as "if we _additionally_ have..."
Answer: By using Aubin-Lions, you get $u_n \to u$ in $L^2(0,T; L^2(\Omega))$.
Comment: Thanks. I don't know why I assumed we needed $u_n'$ in a stronger space.


How can I assign without using self.attribute = in rails?

Question: SO,
I have been working on this for a while, I posted a much larger question that didn't get any replies, but I'll ask a much simpler one here.
My question is, how else can I assign something without using self.attribute = in the following context:
 def photo_from_url(url)
   remote_photo = open(url)
   def remote_photo.original_filename;base_uri.path.split('/').last; end
   **self.photo = remote_photo**
   self.save
 end

I need to make photo_from_url a class method so I can call it from delayed_job however when I add self, it gives me "no method found photo=".
Please help! Thanks in advance...
Answer: A class method, by definition, does not reference any specific object instance. Therefore, you must have a way to get the object you want to modify. The simplest solution would be to pass a reference of that object into your class method and use that instead of self.
class Foo
  def self.photo_from_url(url, obj)
     ...
     obj.photo = remote_photo
     ...
  end
end

Example usage:
foo = Foo.new # creates a new instance of Foo
Foo.photo_from_url("http://example.com/photo/12341", foo)

Notice how I am calling photo_from_url as a class method? That is because it is operating on the Foo class and not an instance of Foo, which happens to be foo here.

Here is some literature on the difference between class and instance methods:
Class and Instance Methods in Ruby
Comment: Hey Jeremy - thanks for getting back to me. What you suggest looks like it could work, but I have a question (amateur coder here). What are you passing through to obj? An ID maybe?
Comment: An instance of the object that contains the `photo` property that you want to set. I'll add an example usage scenario to my answer.
Comment: What a point passing obj? If you know it you should probably use instance method.
Comment: Hi Jeremy, appreciate your help. Ran with Victors answer as it made most immediate sense, and fitted in best with my existing code. A very huge thanks for your input. I will be reading that material!
Comment: @Victor: I was looking at it from a generic point of view, and not really from an ActiveRecord point of view. My fault.
Answer: Option 1: you want to create new object each time you call this method:
class Photo < ActiveRecord::Base
  def self.photo_from_url(url)
    ...

    new(:photo => remote_photo).save!
  end
end

Option 2: you want to update existing object, then you need to get object id you want to modify:
class Photo < ActiveRecord::Base
  def self.photo_from_url(url)
    ...

    id = # here you find id, e.g. from url
    find(id).update_attributes!(:photo => remote_photo)
  end
end

Comment: Victor, you are an absolute life saver. This worked. Can't thank you enough.


unconfigured columnfamily Cassandra Error while Using POJO

Question: I am following the link below to insert an Person object into Person table resides on Cassandra servers
http://docs.spring.io/spring-data/cassandra/docs/1.0.4.RELEASE/reference/html/cassandra.core.html
But I am having unconfigured columnfamily  error. I have tested several ways to make it possible. Some ways are worked properly. here is the result.
1- RUN PROPERLY
    PreparedStatement statement = session.prepare("INSERT INTO \"tims\".\"Person\" (id, name, age) VALUES (?,?,?)");
int id=1234;
    String name="Ahmet"+id;
    int age=33;
BoundStatement bind = statement.bind(id,name,age);
    session.executeAsync(bind);

2-  RUN PROPERLY
String cql = "insert into \"tims\".\"Person\" (id, name, age) values (2345, 'Ali-updated-2', 39)";
        CassandraOperations cassandraOps = new CassandraTemplate(session);

        cassandraOps.execute(cql);

3- DOES NOT RUN PROPERLY
CassandraOperations cassandraOps = new CassandraTemplate(session);
cassandraOps.insert(new Person(2345, "Ahmet-updated", 33));

Here is the POJO CLASS
package com.ttech.tims.bipcamp.dao.cassandra;

import org.springframework.data.cassandra.mapping.Column;
import org.springframework.data.cassandra.mapping.PrimaryKey;
import org.springframework.data.cassandra.mapping.Table;

@Table(value="Person")
public class Person {

    @PrimaryKey(value="id")
    @Column(value="id")
    private int id;

    @Column(value="name")
    private String name;

    @Column(value="age")
    private int age;

    public Person(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    @Override
    public String toString() {
        return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
    }

}

Answer: I have downloaded the source code of the following API
<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-cassandra</artifactId>
    <version>1.0.6.RELEASE</version>
</dependency>

What I have found is that following method returns value of first column of row
cassandraOps.queryForObject(s, Person.class) has the following method trace.
CqlTemplate-> processOne()

@SuppressWarnings("unchecked")
@Override
public <T> T processOne(ResultSet resultSet, Class<T> requiredType) throws DataAccessException {
    if (resultSet == null) {
        return null;
    }
    Row row = resultSet.one();
    if (row == null) {
        return null;
    }
    return (T) firstColumnToObject(row);
}

I have used other two samples:
Map map = cassandraOps.queryForMap(s);

System.out.println("id:"+map.get("id")+", name:"+map.get("name")+", age:"+map.get("age"));

Person person = cassandraOps.queryForObject(s, new RowMapper<Person>(){

    @Override
    public Person mapRow(Row row, int rowNum) throws DriverException {
        return new Person(row.getInt(0), row.getString(1),row.getInt(2));
    }
});

System.out.println("Person:"+person);

I have found actual solution for the insert statement with keyspace. Updating dependency list with the followings.
<properties>
    <org.springframework.version>4.0.5.RELEASE</org.springframework.version>
</properties>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>${org.springframework.version}</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>${org.springframework.version}</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>${org.springframework.version}</version>
</dependency>

<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-cassandra</artifactId>
    <version>1.3.2.RELEASE</version>
</dependency>


How to delete a comment via an HTTP GET link in an email

Question: On my site, moderators are notified of comments via email whenever a new comment is posted. I would like to offer them a one-click approve/delete feature directly from the email.
There is an approve comment link, so I can easily put that link into the email for them to approve the comment directly.
However comments are deleted via a form - an HTTP post - so I can't do that from a link in an email as far as I know. At least that's how it is on my site - not sure whether the form behaviour is normal or is because I have Mollom installed.
Is there a way to delete a comment directly from a link in an email?
Answer: This will do it.
Obviously you don't want to allow just anyone to delete any comment.
The authentication step is to require the user to be logged in with "administer comments" permission.
Alternatively, you could perhaps use a token in the querystring to check access to delete the comment.
<code>/**
 * Implements hook_menu
 */
function MY_MODULE_menu() {

  $items['action/comment/%/delete'] = array(
    'title' => 'Delete comment',
    'page callback' => 'MY_MODULE_action_comment_delete',
    'page arguments' => array(2),
    'access arguments' => array('administer comments'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

/**
 * Menu callback
 * Delete comment via GET request
 */
function MY_MODULE_action_comment_delete($cid){

  try{
    // Delete the comment
    comment_delete($cid);
    drupal_set_message(t('The comment and all its replies have been deleted.'));
    watchdog('MY_MODULE', 'Deleted comment @cid and its replies.', array('@cid' => $cid));
    // Clear the cache so an anonymous user sees that his comment was deleted.
    cache_clear_all();
  }catch(Exception $e){
    drupal_set_message(t('There was a problem deleting the comment.'));
    watchdog_exception('MY_MODULE', $e);
  }

}
</code>
The path to delete a comment would then be:
http://www.example.com/action/comment/12/delete
Where "12" is the comment cid.
Comment: That looks good, thanks. I'll try it out and accept once I can. The comments are pre-moderated, they don't appear until they are accepted, so I think we won't need to clear the cache.


SYS_CONNECT_BY_PATH equivalent in t-SQL

Question: I need to convert my Oracle query into SQL Server.
The query generates a "management hierarchy" based on usernames. The output will have a management chain with the last element being the current manager.
Table:
EE_USERNAME     MGR_USERNAME
user1       ceo
user2       user1
user3       user2
user4       user1
user5       user2
user6       user3

Sample Output:
user1: ceo
user2: ceo,user1
user3: ceo,user1,user2
user4: ceo,user1
user5: ceo,user1,user2
user6: ceo,user1,user2,user3

My Oracle query for this:
SELECT EMPLOYEE_DATA.* ,  SYS_CONNECT_BY_PATH(MGR_USERNAME, ',') "Path"
FROM EMPLOYEE_DATA
START WITH MGR_USERNAME = 'ceo'
CONNECT BY NOCYCLE  prior  EE_USERNAME = MGR_USERNAME

What would be the SQL Server equivalent of this query?
Comment: You probably want to investigate a recursive CTE.
Answer: ;WITH cte AS (
    SELECT e.*, mgr.EE_USERNAME AS Path
        FROM EMPLOYEE_DATA AS mgr
        JOIN EMPLOYEE_DATA AS e ON mgr.EE_USERNAME = e.MGR_USERNAME
        WHERE mgr.EE_USERNAME = 'ceo'
    UNION ALL
    SELECT e.*, mgr.Path + ',' + mgr.EE_USERNAME AS Path
        FROM cte AS mgr
        JOIN EMPLOYEE_DATA e ON mgr.EE_USERNAME = e.MGR_USERNAME
)
SELECT *
FROM cte
-- OPTION (MAXRECURSION 200)  -- if you need a different value
;

If you are doing a lot of recursion, you should take a look at MAXRECURSION which has a default of 100.
Comment: Thank you, this works!  Is it expected that the query processing time will be much slower than Oracle?
Comment: I am new to Stack Overflow. I cannot find an option to Accept Answer and close thread, could you guide me? Thank you!
Comment: The check mark on the left side. Probably the same perf, ie good but not great and should be avoided except for these types of queries. It uses a very fast temp table under the hood, but with large amounts of data or a lot of recursion it can be slow. Don't forget to look up `OPTION (MAXRECURSION...`
Answer: Charlieface's query omits the functionality provided by Oracle's NOCYCLE directive which says to cease recursion if the same record comes back a second time.
If you want this protection, you can add a Where clause to the recursive section of the CTE query:
Where Instr(mgr.EE_Username,mgr.Path)=0

SYS_CONNECT_BY_PATH equivalent in t-SQL


Fatal error: Uncaught exception

Question: i have this error...

Fatal error: Uncaught exception 'LogicException' with message 'Function 'PHPMVC\LIB\Autoload::autoload' not callable (non-static method PHPMVC\LIB\Autoload::autoload() cannot be called statically)' in C:\xampp\htdocs\mohamaed\MVC\app\lib\autoload.php:11 Stack trace: #0 C:\xampp\htdocs\mohamaed\MVC\app\lib\autoload.php(11): spl_autoload_register('PHPMVC\LIB\Auto...') #1 C:\xampp\htdocs\mohamaed\MVC\public\index.php(9): require_once('C:\xampp\htdocs...') #2 {main} thrown in C:\xampp\htdocs\mohamaed\MVC\app\lib\autoload.php on line 11

the code :
spl_autoload_register(__NAMESPACE__ .'\Autoload::autoload');

Comment: Have you actually read the error message? `PHPMVC\LIB\Autoload::autoload` is not a static method so cannot be called statically
Answer: The error message makes it reasonably clear... you have registered PHPMVC\LIB\Autoload::autoload as a static autoloader callback but this method is not static.
You will need to use the array object method call syntax instead
$autoload = new Autoload(); // pass whatever args this actually requires
spl_autoload_register([$autoload, 'autoload']);

See http://php.net/manual/language.types.callable.php

Fatal error: Uncaught exception


Search with Views not Saving Selected Filters when user tries to go BACK

Question: I've created a search page using Views with exposed filters and the basic search module. The search only returns results for a specific node content type 'resource'. A typical use case would be the following:
User goes to search page, types some text into the exposed search terms block, and also selects some options from the exposed filters that are drop-down menus. They click 'search' and their results are returned on the same page. Pretty standard stuff and I have that all working fine.
A user then clicks a link to a resource node of interest to them and goes to that node's profile page. All fine and dandy.
The problem is when they want to go BACK. I went ahead and added a back button with the following code to my node--resource.tpl.php, which works as you'd expect (it bypasses the browser back button and takes user to main search page again):
<code><input type="button" value="Go Back" onclick="window.history.back()" />
</code>
What happens is it displays the search page again, but no longer with the search term they entered OR the exposed filters they selected. I'd like to change that so when they click the 'back' button the search page still shows their search results from before so they don't have to re-select all their options again.
This seems like pretty basic stuff, but I can't figure out how to do it in Drupal. I imagine it involves session cookies somehow...but how to combine this with Views I do not know.
Thanks for your help!
Comment: Could add.  target="_blank" to the links to force a new window
Comment: @Geoff thanks but that is not ideal to my situation, although it works as a temporary fix I suppose.
Comment: @Geoff see my totally revised question above. Thanks.
Answer: Ok, I solved my own question. To get Views search results to 'stick' you just have to select an option for each filter you want to save and the role that this works for.
In Views > Filters > check the box next to 'remember the last selection' and select which roles this applies to.
Easy. Now when a user clicks the 'back' button I've added to the tpl file it takes them back to their selections.


How can I Change Primary Menu block to certain pages using PHP?

Question: I have navigation menu as follow, no 1. is main navigation and no 2. is sub menu of Cooking Menu.

I want Change navigation menu at Cooking Page as follow.

I want to get sub menus of cooking menu into main navigation and remove Cooking. how can I achieve this ? because i'm new to Drupal.
Answer: I can think into two alternative ways to do that, maybe it helps:
With CSS: Adding those submenu links duplicated in the main level (1) and hiding / showing them depending on the page. Something like:
Home        --> Normal
Find store  --> Normal
Cooking     --> (Visible by default, hidden in cooking page)
  |_Recipes --> (Visible by default, hidden in cooking page)
  |_Videos  --> (Visible by default, hidden in cooking page)
  |_Submit  --> (Visible by default, hidden in cooking page)
Recipes     --> (Hidden by default, set to display block in cooking page)
Videos      --> (Hidden by default, set to display block in cooking page)
Submit      --> (Hidden by default, set to display block in cooking page)
Shop        --> Normal

Another approach could be with blocks: You could have 2 menus, the one in your first image:
Home
Find store
Cooking
  |_Recipes
  |_Videos
  |_Submit
Shop

And another one like the one in your second image:
Home
Find store
Recipes
Videos
Submit
Shop

And then, through both blocks configuration, you can make the first one visible everywhere except in cooking page (e.g. .../cooking), and the second one visible only in cooking page.
Good luck


What are all these symbols in some old sheet music?

Question: Looking at this sheet music of Pietro Antonio Locatelli's "L'arte del violino" Op. 3 we see that the sheet music is pretty old. I have no idea if this is perhaps the original one or not but it does look pretty old. Being an amateur self-taught musician, I am a little confused about some of the music notation here. I am posting an image here of the first page of the first concerto with some markup.

First question, any idea how old this scanned copy is? Could it be the very original one? Or is it much more recent?
Second, about the markups.

What are those symbols marked in red? My intelligent guess is that they are the sharp symbol but they look like the double-sharp symbol instead. So which ones are they? Were the double-sharp symbols used for the sharp symbols back in the day? Second thing about these, they are not very clear and look like double-crosses. Are they really supposed to be double-crosses or is it just a single 'x' with bad copy editing job/deterioration with time?
The purple in the last line is just a trill, right?
The 't' in green, what does that mean? Is that for a trill also? Is yes, then why not just use the same notation as the trill in purple with the appropriate indication of how/which notes to play? How to play this trill?
What is that 'w' like symbol at the end of every line in blue? It looks like a trill but there is no note underneath it so what does it mean?

Thanks.
Comment: The "solo" curvy lines are definitely an indication to perform the solo one octave higher, and it's not intended to be optional like it has been suggested. The author or transcriber made a point of it in the subheading note, which is in very recognizable nearly-modern Italian: "*Dove sono le linee ~~~ si deve sonare un Ottaua più alto*", which translates as: "Where the lines ~~~ are found, it shall be played one octave higher"
Answer: The X's are sharp signs, which means this piece is in D. Note, an X can also mean a double sharp, but in this context (throughout the whole piece), it clearly refers to a sharp.
The t.'s mean trill (this is confirmed by many recordings that I've listened to).
The W's at the end of the line tell where the first note on the next line is. For example, the mark at the end of the first staff is on the D line and the next note is a D.
The W's on the ledger lines in the middle of staves seem to mark the beginning of solos and an optional 8va to set the soloist apart.
Comment: Ooh, nice catch with the end-of-line `w`'s. We always want to train ourselves to sightread far enough ahead that those aren't necessary, but I can definitely see myself using them at times.
Comment: The end of line "w"s (called custodes (singular: custos); latin: guard) were very important in earlier music where the clef (esp. C clefs) would change often (preferring clef changes to ledger lines) so that at the end of lines they would help the performer notice the clef change. Nowadays we would use a courtesy clef at the end of the line to point that out.  The w at the solo parts serves the same purpose, showing the note that would be played if the part were written an octave up.
Comment: Would not the purple marking be a mordant?
Comment: @MichaelScottCuthbert I'm sure you know this already, but for others reading the discussions later, "custodes" are also called "directs" in English, with the stress on the first syllable.
Comment: I don't think the 8va is optional… see @euro-micelli's comment to the other answer about the instruction at the top.
Answer:
Age: Here's the download page. This pdf is the first one (#20529), and there it says it's from ~1733. Locatelli was still alive then so it could very well be the first print.
With the red, green, and blue markings I agree with the others; we have sharps, trills, and continuation indicators (showing the first note of the next line)
The purple markings also seem to indicate the next note; for example in this recording the soloist actually plays the solo passages an octave higher than written. The purple markings (there's one on the middle of the page, too) seem to indicate this.

EDIT: The name of the blue marking is a custos. Right now I can't find any information about using them in the middle of a line but it seems logical that it would mean "play this as the next note", the same way it works at the end of a line. I don't see why it should be optional but who knows...
Comment: The purple marks indeed seem to indicate octava for the duration of the wavy solo line underneath; There is a later solo indication at approximately 1:55 in the video/recording that doesn't have this indication, nor the wavy solo line, and that is played loco.
Comment: My thought is that it (the purple) marks an optional 8va for the duration of the solo to set it apart.
Answer: I can't view your posted image (thanks, Mr. Corporate Idiot Firewall).   Here are my interpretations based on the source score:
"t" may well be a 'turn,' leading into the following notes, for shorter notes, as well as full trills elsewhere. Looks like there's room for performer interpretation :-) .
The "w" at ends of lines appears simply to indicate the movement continues (there's no "w" at each Fine). You'll notice that the meter would be off if that 'w' indicated any note.
Since the piece appears to be in D-maj, and the key signature has "x" on C and F, I'd say that's the sharp sign.
Comment: If you look closer at the "x"s, there are a pair of lines in each direction. So it's a # rotated 45 degrees -- consistent with the theory of it being a sharp sign.
Comment: The slant might be an artifact of handwriting.


How to validate request excel data on NestJs?

Question: I'm trying to validate datatypes and constraints from an excel file (file passed from body request) but I can't do it!. I was reading about class-validator but I think it is not work for me because I'm not receiving a json data just an excel file passed from request body as a file. I've coded a service where I put the logic for read the entire file and add to a array (as my data dto). There is some way to validate every field in this point and return if a problem has been detected? Thanks :)
File Controller:
@Controller('file-parser')
export class FileParserController {
  constructor(private readonly fileParserService: FileParserService) {}

  @Post('upload')
  @UseInterceptors(FileInterceptor('file'))
  UploadExcelFile(@UploadedFile() file: Express.Multer.File) {
    return this.fileParserService.processFile(file);
  }
}

File Service:
processFile(file: Express.Multer.File): void {
    const workBook: XLSX.WorkBook = XLSX.read(file.buffer, {
      type: 'buffer',
      cellDates: true,
      cellNF: false,
    });
    const sheetName = workBook?.SheetNames[0]; // asigne first sheet name of file
    const sheet: XLSX.WorkSheet = workBook.Sheets[sheetName]; // entire sheet information asigned to sheet variable

    const jsonData: StudentDTO[] = XLSX.utils.sheet_to_json(sheet, {
      dateNF: 'YYYY-MM-DD',
    });
    // Add fields validation here
    console.log(jsonData);
  }

Student DTO:
import { IsNotEmpty, IsNumber, IsOptional, IsString, MaxLength } from 'class-validator';
export class StudentDTO {
  id: number;
  @IsString()
  @IsNotEmpty()
  @MaxLength(25)
  studentCode: string;
  @IsString()
  @IsNotEmpty()
  @MaxLength(50)
  studentName: string;
  @IsString()
  @IsNotEmpty()
  @MaxLength(50)
  studentLastname: string;
}

Answer: I solved a similar problem by using a combination of class-transformer and class-validator. Once you have your raw jsonData I called class-transformer.plainToClass() and then class-validator.validate(). Here is roughly what you would need:
const students: StudentDTO[] = plainToClass(
   StudentDTO[],
   jsonData,
   { excludeExtraneousValues: false},
);

const validatorOptions: ValidatorOptions = {
   whitelist: true, // strips all properties that don't have any decorators
   skipMissingProperties: false,
   forbidUnknownValues: true,
   validationError: {
      target: false,
      value: false,
   },
};
const errors = await validate(students, validatorOptions);

Comment: Did this help you Young Al Capone?


Use Riemann Sums to Find Area bounded by Curve

Question: How can I find the area bound by $\;x=0,\, x=1,\;$ the $\;x$-axis ($y = 0$) and $\;y=x^2+2x\;$ using Riemann sums?
I want to use the right-hand sum. Haven't really found any good resources online to explain the estimation of areas bounded by curves, hoping anyone here can help?
By the way, I would like there to be 100 intervals.
Comment: @DonAntonio: I think the asker is referring to Riemann sums to *approximate* error, as in http://mathworld.wolfram.com/RiemannSum.html
Comment: 100 intervals? You know you must take the limit of the Riemann sum when $\,n\to\infty\,$ while *also* the maximal length of subintervals goes to zero, right? So you're definitely going to need way more than 100 intervals...
Comment: Do you mean "right hand sum" to mean using the right endpoint of each $\Delta x$ interval?
Answer: Right Riemann Sums place the right corner of the rectangles on the curve.
Right Riemann Sums are an overestimation of area because of all the extra space that is not under the curve that is still calculated in the area because it is inside the rectangles.
For your problem, we have:
$f(x) = x^{2} + 2x$
With: $a = 0, b = 1$ and $100$ rectangles, we have $\frac{b-a}{n} = \frac{1-0}{100} = \frac{1}{100}$
Our formula now becomes:
$\frac{b-a}{n} [f(0) + f(\frac{1}{100}) + f(\frac{2}{100})+ \cdots + f(\frac{100}{100})]$
$\bullet$ For Left Riemann, plug in all numbers except last.
$\bullet$ For Right Riemann, plug in all numbers except first.
$\bullet$ For Midpoint Riemann, average the numbers and plug those in.
So, using Right Riemann, we have:
$f(\frac{1}{100}) = \frac{1^{2}}{100^{2}} + \frac{2}{100} = \frac{201}{10000}$
$f(\frac{2}{100}) = \frac{2^2}{100^{2}} + \frac{4}{100} = \frac{101}{2500}$
$\cdots$
$f(\frac{100}{100}) = \frac{100^2}{100^{2}} + \frac{200}{100} = 3$
You'll get this set of values using WA.
Now, using the formula above, we have:
$\frac{1}{100}[f(\frac{1}{100}) + f(\frac{2}{100})+ \cdots + f(\frac{100}{100})] = (\frac{1}{100})(\frac{26967}{200}) = 1.34835$
Comparing that with the actual $\int_0^1 (x^{2} + 2x) dx = \frac{4}{3} = 1.33333$, we see, as expected, that we got an overestimate.
You can compare these two with the nice pointer by amWhy at Wolfram Math World.
You should repeat this for left and midpoint and compare so you understand!
Regards
Comment: Thanks for such a detailed answer!
Comment: @CharlesTian: Welcome to MSE and you are very welcome tp our wonderful math community! Regards
Comment: Nice detail and clarification!
Comment: @amWhy: Thanks, those are fun problems.
Answer: For a resource see Mathworld: Riemann Sum.
You can enter the function, the number of intervals ($n = 100; \Delta x = 0.01$), choose "right" from the drop-down menu, and click on "replot" to see your Riemann Sum approximation of area with the curve and intervals graphed.
You'll also find the general formula for the sum: $$\sum_{k = 1}^n f(x_k^*)\Delta x$$
Comment: Thanks for the resource, it's helped a lot :)


exim is not accepting external connections

Question: Update: It's definitely my ISP blocking port 25. I told Exim to listen on a non-standard port, and then checked from a remote computer to that port, and it went through just fine.
So, I guess I have a new question. Is there a good way to get around this?
I no I can't specify a port in the MX record (why didn't anyone think of this when they were coming up with DNS?), but a service that can forward mail to a server on a non-standard port would work.
I've seen no-ip.com has such a service called Reflector. It's not very expensive, but if there are any other, cheaper methods, I'd love to hear about them.
I'm still baffled as to why it just today stopped working, though.

Original Question
I hate asking this, but I've already Googled everything I can think to no avail, but this seems like such a simple thing, so I don't know why I can't figure it out. But, here it goes anyway.
I have a home server set up with Apache for HTTP and Exim for SMTP. I need to be able to accept mail straight to my home computer. Up until today, I had no problems. I don't believe I changed anything on my end, but suddenly, I'm not getting any email.
I checked MX setting in DNS, and they're fine. I checked the port forwarding on my router, and it looks fine (and external connections to Apache are still coming through).
So, I check that Exim is working properly. From localhost, I can telnet into Exim, and it works fine. Additionally, I can telnet into Exim from other computers on the network, and it works fine. However, if I try to telnet from outside, I get Unable to connect to remote host: Connection timed out.
So, I tried to do dpkg-reconfigure exim4-config (I'm on Ubuntu 12.10, by the way), and make sure that everything's set up properly there. No problems. I look in my config and find this:
# listen on all all interfaces?
.ifdef MAIN_LOCAL_INTERFACES
local_interfaces = MAIN_LOCAL_INTERFACES
.endif

Some googling leads me to believe that local_interfaces controls what exim will listen to. So I try to change this according to the exim documentation, and make it this:
# listen on all all interfaces?
#.ifdef MAIN_LOCAL_INTERFACES
#local_interfaces = MAIN_LOCAL_INTERFACES
#.endif
local_interfaces = <; ::0 ; 0.0.0.0

I restart exim, and nothing changes.
So, that's where I'm at now. It's kind of important that I get this fixed soon, so any ideas what else I might check would be appreciated.
P.S. Since commenting won't give my proper formatting, I'm replying here:
lsof -i:25: I'm not really sure what I'm looking for, but here's the output:
COMMAND   PID        USER   FD   TYPE   DEVICE SIZE/OFF NODE NAME
exim4   12386 Debian-exim    3u  IPv6 24476126      0t0  TCP *:smtp (LISTEN)
exim4   12386 Debian-exim    4u  IPv4 24476127      0t0  TCP *:smtp (LISTEN)

P.P.S. According to this page, my ISP blocks port 25 inbound (and outbound). But that page was written several months ago, and the problem just appeared today (or maybe yesterday), so is there any way I can check to see if that's the problem?
Comment: Run `lsof -i:25` to see on which interface exim is listening as a start
Answer:
I'm still baffled as to why it just today stopped working, though.

Maybe your mail server had a busy day yesterday so the ISP noticed your abuse of the ToS?
Notice, that sending mail to another port would probably still conflict with your ISPs terms if it was running on some non-standard port, so I won't give explicit advice or recommend that to you.
I, for example, did receive a warning once from my ISP regarding "excessive" incoming and outgoing mail.
Discussing legitimation for this rule is something to do somewhere else.
You could, however, set up a cheap VPS somewhere to handle mail.
How to process that mail (directly on the VPS, or at home) is your task to evaluate.
Your remote node not necessarily needs to run its own mail server. Using a mail proxy like nginx - or even plain TCP proxying - would be fine, too.
Comment: Contact your ISP and see if there is a whitelist process to remove the port 25 block.  There are more than a few that block port 25 by default because of the spambot problem, and if you demonstrate competence by asking to have it removed for your connection, some have a procedure to do so.  "You never know until you ask."  If they refuse and say TOS violation, then using a VPS to do it is about the next best option.
Answer: I have had a similar problem but not quite the same. My mail server kept getting flagged as a spammer by Spamhaus. I checked everything including outgoing connections on port 25.
None, niente, nada!
I tried to turn off the mail server. Still reported by Spamhaus.
Turned off the router … and no more Spamhaus flagging! Turned it back on and within an hour flagged again.
The router belonged to the ISP so I talked to them and guess what? They did not care. After complaining a couple of times they did the only sensible thing (at least in their opinion, apparently) they blocked port 25 incoming. It did stop the spamming, indeed, but it also rendered my mailserver useless. I complained several times to the ISP, but they did not care.
Luckily, I had other problems with this ISP and had just received a new (cheaper and faster) incoming line. This line had the problem of not having a permanent IP address, which I skirted by automatically updating the DNS on a regular basis.
I have subsequently set up a cheap virtual server at one of the international providers and use that for outgoing mail and as a backup for incoming mail, should my main connection again suffer from port 25 blocking. The reason for using a hosted server for outgoing mail is the fact that almost everyone now blocks incoming mail from ISPs they either consider domestic or are not big enough to be able to complain hard enough for the main mail providers to care. (Google, Microsoft, Mimecast and other, do you listen????)
Comment: Less would be more here. In other words: change ISPs, or stand up a virtual server.


Passing the string argument of a function as a column name

Question: I need to write a function which use the string argument in the body to create the name of the columns.
For instance,
dt1 <- data.table( Col_1999_L = c(6,7,8,9,10),
                  Col_1999_R = c(1,-2,3,-4,5),
                  Col_2001_L = c(-8-3,5, 2,-1),
                  Col_2001_R = c(-1,2,-3,4,5)
)

Here 1999, 2001 represent indeed years.
My output should be like in dt2 where I create new columns where some conditions are checked.
dt2 <- dt1 %>%
  select(c("Col_1999_L", "Col_1999_R")) %>%
  mutate(
    New1 = if_else(Col_1999_L >= 0, "pos", "neg"),
    New2 = case_when(
      Col_1999_L >=0 & Col_1999_R >=0 ~ "pos",
      Col_1999_L >=0 & Col_1999_R < 0 ~ "neg",
    ))
dt2

What I need is actualy to write a function which create for each year a table like the df2.
I tried something like this (which is wrong):
my_function <- function(dt, Year) {
dt %>%
mutate(
      New1 = if_else(Col_"Jahr"_L >= 0, "pos", "neg"),
      New2 = case_when(
        Col_"Year"_L >=0 & Col_"Year"_R >=0 ~ "pos",
        Col_"Year"_L >=0 & Col_"Year"_R < 0 ~ "neg"))
}

my_function(dt1, 1999)

any help on how to write it properly?
Thank you
Answer: We can paste the values, convert to symbol and then evaluate (!!).  If we have a string created, the tidyverse preferred way is to convert to symbol and then evaluate.
library(dplyr)
my_function <- function(dt, Year) {
   nm1 <- rlang::sym(paste0("Col_", Year, "_R"))
   nm2 <- rlang::sym(paste0("Col_", Year, "_L"))
   dt %>%
   mutate(
       New1 = if_else(!! nm2 >= 0, "pos", "neg"),
       New2 = case_when(
         !!nm2 >=0 & !!nm1 >=0 ~ "pos",
        !!nm2 >=0 & !!nm1 < 0 ~ "neg"))
    }

my_function(dt1, 1999)
#    Col_1999_L Col_1999_R Col_2001_L Col_2001_R New1 New2
#1:          6          1         -8         -1  pos  pos
#2:          7         -2         -3          2  pos  neg
#3:          8          3          5         -3  pos  pos
#4:          9         -4          2          4  pos  neg
#5:         10          5         -1          5  pos  pos

Or if we pass the full unquoted column name, then we can make use of curly-curly operator ({{}})
 my_function <- function(dt, colnm1, colnm2) {
      dt %>%
         mutate(New1 = if_else({{colnm2}} > 0, "pos", "neg"),
                New2 = case_when({{colnm2}} >= 0 & {{colnm1}} >=0 ~ "pos",
                      {{colnm2}} >= 0 & {{colnm1}} < 0 ~ "neg"))
  }

my_function(dt1, Col_1999_R, Col_1999_L)
#   Col_1999_L Col_1999_R Col_2001_L Col_2001_R New1 New2
#1:          6          1         -8         -1  pos  pos
#2:          7         -2         -3          2  pos  neg
#3:          8          3          5         -3  pos  pos
#4:          9         -4          2          4  pos  neg
#5:         10          5         -1          5  pos  pos

data
dt1 <- data.table( Col_1999_L = c(6,7,8,9,10),
                  Col_1999_R = c(1,-2,3,-4,5),
                  Col_2001_L = c(-8, -3,5, 2,-1),
                  Col_2001_R = c(-1,2,-3,4,5)
)

Answer: If you are not familiar with the symbol and bang bang operators, you could use get:
my_function <- function(dt,year){
  R <- sprintf("Col_%d_R",year) # same as paste0("Col_",year,"_R") but simplified
  L <- sprintf("Col_%d_L",year)
  dt %>%
  mutate(
    New1 = if_else(get(R,dt) >= 0, "pos", "neg"),  # although get(R) works, use get(R,dt)
    New2 = case_when(
      get(L,dt) >=0 & get(R,dt) >=0 ~ "pos",
      get(L,dt)>=0 & get(R,dt) < 0 ~ "neg",
    ))
}

my_function(dt1,1999)
  Col_1999_L Col_1999_R Col_2001_L Col_2001_R New1 New2
1          6          1         -8         -1  pos  pos
2          7         -2         -3          2  neg  neg
3          8          3          5         -3  pos  pos
4          9         -4          2          4  neg  neg
5         10          5         -1          5  pos  pos


When is android.hardware.usb.action.USB_ACCESSORY_ATTACHED issued?

Question: Is the broadcast android.hardware.usb.action.USB_ACCESSORY_ATTACHED issued when the device is connected, or when the Host opens the endpoint?
Answer: I believe it depends upon how you look at it. The host has to open the endpoint to do the little "AOA Protocol Dance" with the Android device to know that it can support Accessory Mode at all. In other words, some data has to be exchanged before Android knows to send you that Intent. But affer you get that Intent, you use openAccessory to actually associate with the endpoint(s) your code uses. So the answer depends on "which" endpoints you are talking about. Hope this helps!
Comment: Can you point me to where in the Android source this is done?


Close a webform when total seats reach a maximum

Question: I would like to know if it is possible to set-up a specific event registration webform to close automatically when the number of total reserved seats (reserved seats field) reaches a certain maximum.
A little background:
I have a few different event registration forms on my website, each event is held in a different venue with a maximum number of seats. The forms each have a reserved seats field, users can reserve up-to 2 seats(max) per submission. I cannot use the submission limit feature of the webform because the number of submissions do not map directly to the number of total seats that users are reserving.
Is it possible to have the webform calculate the sum of the reserved seats field and close the form when it reaches a certain maximum number? How would I go about setting that up?
Answer: I built a custom handler to process seat reservations. I just wanted to share my code for anyone else looking to do the same thing. @jrockowitz let me know if you want to add this into webform core.
<code><?php
namespace Drupal\webform_reservations\Plugin\WebformHandler;

use Drupal\Core\Form\FormStateInterface;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\webformSubmissionInterface;

/**
* Form submission handler.
*
* @WebformHandler(
* id = "webform_reservations_handler",
* label = @Translation("Reservations Handler"),
* category = @Translation("Form Handler"),
* description = @Translation("Manage maximum seat reservations"),
* cardinality =
 \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_SINGLE,
* results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
* )
*/

class ReservationHandler extends WebformHandlerBase {

 /**
 * {@inheritdoc}
 */

  public function submitForm(array &$form, FormStateInterface $form_state,
  WebformSubmissionInterface $webform_submission) {
  $webform = $webform_submission->getWebform();
  $formid = $webform->id();

//query the db for all submissions of current webform submission
$query = \Drupal::entityQuery('webform_submission');
$query->condition('webform_id', $formid);
$result = $query->execute();

//load all the submissions from the results
$storage = \Drupal::entityTypeManager()->getStorage('webform_submission');
$submissions = $storage->loadMultiple($result);
$submission_data = array();

foreach ($submissions as $submission) {
$submission_data[] = $submission->getData();
}

$current_reserved = 0;

//add up all the values in the 'seats needed' field of each submission and save it to a variable.
for ($i = 0; $i < count($submission_data); $i++){
    $current_reserved += $submission_data[$i]['seats_needed'];
}

//when a registration form is submitted, check if the current reserved seats exceeds the value specifed in the maximum allowed seats field of the form.
if ($current_reserved >= $webform->getElement('max_seats')['#value']) {
    $webform->setStatus('closed');
    $webform->save();

 $message = 'The form has ' . $current_reserved . ' reserved seats, the max seats is currently set to ' . $webform->getElement('max_seats')['#value'] .  ' the form will now be closed';
  } else {$message = 'The form has ' . $current_reserved . ' reserved seats, the max seats is currently set to ' . $webform->getElement('max_seats')['#value'] .  ', the form will stay open';}

//log the output to the drupal logger, to indicate if the webform is still open or closed after each submission.
\Drupal::logger('webform_reservations')->info($message);

}
}
?>
</code>
Answer: You would have to create custom WebformHandler that calculates the sum for a specified element and closes the form.  This handler could be reusable and contributed back to Drupal.
The WebformHandler would allow site builders to select the 'Number' element, specify the allows total per webform, source entity, and/or user and then block the form once the specified limit is reached.
Comment: Okay, I'm kind of new to drupal, is there a guide on how to create custom Webform Handlers? Can you suggest an existing handler that I can look to for example code?
Comment: There are a few articles about Webform Handlers here.
https://www.drupal.org/docs/8/modules/webform/webform-blog-posts-articles-%C2%A0presentations


Can I specialize a class template with an alias template?

Question: Here's a simple example:
class bar {};

template <typename>
class foo {};

template <>
using foo<int> = bar;

Is this allowed?
Comment: @KerrekSB: It's the complete opposite. This would be more like `typedef bar foo;` (though this is not allowed). In my example, `bar` already exists as a type, and `foo` becomes a new name for it. (What you wrote is equivalent to `using bar = foo;`, if that helps.)
Comment: How is this different from `typedef foo bar;`?
Comment: Oh, I see. But then you might as well ask for *any* class definition to be copyable: `class Foo = Bar;` etc. I don't suppose that's possible...
Comment: `using Foo = Bar;`? (Or `typedef Bar Foo;`, if you prefer the old style.) I don't expect my example (if valid) to create a distinct type (please let me know I'm misunderstanding you).
Comment: Hmm, reading this answer: http://stackoverflow.com/questions/6622452/alias-template-specialisation/6623089#6623089 makes me believe this is indeed not possible.
Comment: Interesting. I was thinking about *copying* the type definition, not just aliasing, since I imagine that you'd have to provide (the equivalent of) a full class definition for an explicit specialization. The linked answer does indeed suggest that aliases are not the right tool for the job.
Comment: I wrote a few `define`s that generalize on Aotium's answer, here http://stackoverflow.com/a/14050604/225186
Comment: There is slightly indirect way. see [Section 1.4](http://www.stroustrup.com/template-aliases.pdf)
Answer: $ clang++ -std=c++0x test.cpp
test.cpp:6:1: error: explicit specialization of alias templates is not permitted
template <>
^~~~~~~~~~~
1 error generated.

Reference: 14.1 [temp.decls]/p3:

3 Because an alias-declaration cannot declare a template-id, it is not
  possible to partially or explicitly specialize an alias template.
Comment: Is that clang 3.0?  OK I see from the clang pages that my clang 2.9 won't work.
Answer: Although direct specialization of the alias is impossible, here is a workaround.
(I know this is an old post but it's a useful one.)
You can create a template struct with a typedef member, and specialize the struct.
You can then create an alias that refers to the typedef member.
template <typename T>
struct foobase {};

template <typename T>
struct footype
  { typedef foobase<T> type; };

struct bar {};

template <>
struct footype<int>
  { typedef bar type; };

template <typename T>
using foo = typename footype<T>::type;

foo<int> x; // x is a bar.

This lets you specialize foo indirectly by specializing footype.
You could even tidy it up further by inheriting from a remote class that automatically provides the typedef. However, some may find this more of a hassle. Personally, I like it.
template <typename T>
struct remote
  { typedef T type; };

template <>
struct footype<float> :
  remote<bar> {};

foo<float> y; // y is a bar.

Comment: I think you missed a `` in the `using` statement: `template  using foo = typename footype::type;`
Comment: I have been using this trick, but it does help to have it out here. So, thanks for putting it up. And welcome to StackOverflow!
Comment: Just after writing a long answer with workaround for this limitation, I found your answer that uses the same principle. In any case I wrote in addition a couple of `define`s to make the code shorter. Take a look if you are interested: http://stackoverflow.com/a/14050604/225186
Answer: According to §14.7.3/1 of the standard (also referred to in this other answer), aliases are not allowed as explicit specializations :(

An explicit specialization of any of the following:

function template
class template
member function of a class template
static data member of a class template
member class of a class template
member class template of a class or class template
member function template of a class or class template

can be declared[...]


Make does not follow symbolic links to find files

Question: When I extract files from a tar ball to create a list of files make does not follow symbolic links and keeps extracting the same tar ball for each file specified in the list. Forinstance I have created 2 tar balls with the following commands in linux:
design1 is a directory that holds a link to another directory with c design files
% mkdir design1
% mkdir c_files
% cd c_files/
% touch a.c b.c c.c d.c e.c f.c
% cd ../design1/
% ln -s ../c_files/ .
% cd ..
% gtar zcvf design1.tgz design1/

design2 is the same as design1 except that c_files is a directory and not a link
% mkdir design2
%
% cp -rp c_files design2
% gtar zcvf design2.tgz design2/

Now there are 2 zipped tarfiles design1.tgz and design2.tgz and design1 and design2 directories are removed
% \rm -rf design1 design2

Here's my Makefile:
----------------Begin Makefile -------------------
DESIGN_EXTRACT_DIR := .
DESIGN_TOP1 := c_proj1
FILE_LIST1 := $(strip $(DESIGN_TOP1)).f

DESIGN_TAR_FILE1 := design1.tgz
DESIGN_RELEASE_DIR1 := $(DESIGN_EXTRACT_DIR)/design1

DESIGN_FILES1 =\
$(DESIGN_RELEASE_DIR1)/c_files/a.c   \
$(DESIGN_RELEASE_DIR1)/c_files/b.c   \
$(DESIGN_RELEASE_DIR1)/c_files/c.c   \
$(DESIGN_RELEASE_DIR1)/c_files/d.c   \
$(DESIGN_RELEASE_DIR1)/c_files/e.c   \
$(DESIGN_RELEASE_DIR1)/c_files/f.c   \

IP_EXTRACT1: $(DESIGN_FILES1)

$(DESIGN_FILES1): $(DESIGN_TAR_FILE1)
    gtar zxvfmhC $(DESIGN_TAR_FILE1) $(DESIGN_EXTRACT_DIR)

$(FILE_LIST1): $(DESIGN_FILES1)
    @( rm -f $(FILE_LIST1) )
    @( touch $(FILE_LIST1) )
    @$(foreach file, $(DESIGN_FILES1), `echo $(file) >> $(FILE_LIST1)`)

FL1:    $(FILE_LIST1)

DESIGN_TOP2 := c_proj2
FILE_LIST2 := $(strip $(DESIGN_TOP2)).f

DESIGN_TAR_FILE2 := design2.tgz
DESIGN_RELEASE_DIR2 := $(DESIGN_EXTRACT_DIR)/design2

DESIGN_FILES2 =\
$(DESIGN_RELEASE_DIR2)/c_files/a.c   \
$(DESIGN_RELEASE_DIR2)/c_files/b.c   \
$(DESIGN_RELEASE_DIR2)/c_files/c.c   \
$(DESIGN_RELEASE_DIR2)/c_files/d.c   \
$(DESIGN_RELEASE_DIR2)/c_files/e.c   \
$(DESIGN_RELEASE_DIR2)/c_files/f.c   \

IP_EXTRACT2: $(DESIGN_FILES2)

$(DESIGN_FILES2): $(DESIGN_TAR_FILE2)
    gtar zxvfmhC $(DESIGN_TAR_FILE2) $(DESIGN_EXTRACT_DIR)

$(FILE_LIST2): $(DESIGN_FILES2)
    @( rm -f $(FILE_LIST2) )
    @( touch $(FILE_LIST2) )
    @$(foreach file, $(DESIGN_FILES2), `echo $(file) >> $(FILE_LIST2)`)

FL2:    $(FILE_LIST2)

clean:
    @( rm -rf $(FILE_LIST1)* $(FILE_LIST2)* )

----------------End Makefile----------------------
Now when I run make to create a file list I use the commands make FL1 and make FL2. In the case of FL1 make iterates of gtar as many times as I have files but doesn't do so with FL2. The only difference here is FL1 operates on a link called c_files in design1 while FL2 iterates over c_files as a directory.
Here's what I see:
% make FL1
gtar zxvfmhC design1.tgz .
design1/
design1/c_files
gtar zxvfmhC design1.tgz .
design1/
design1/c_files
gtar zxvfmhC design1.tgz .
design1/
design1/c_files
gtar zxvfmhC design1.tgz .
design1/
design1/c_files
gtar zxvfmhC design1.tgz .
design1/
design1/c_files
gtar zxvfmhC design1.tgz .
design1/
design1/c_files

%make FL2
%

Issue1:
FL1 creates c_proj1.f and FL2 creates c_proj2.f but FL2 doesnt iterate like FL1 and I am not sure how to prevent this iteration especially since I could have large tar ball with hundreds of files.
Issue2:
When DESIGN_FILES1 is a long list because of the number of files then I get the following error because the variable is too long:
make: execvp: /bin/sh: Argument list too long
Is there a way to check the size of the variable and maybe write to a file and process the variable a bit at a time so DESIGN_FILES will not be too long for each iteration. Or is there a better way to do this.
Thanks
Niel
Answer: For me it works the same (iterates once) whether there is a symlink or not. But from the contents it seems that you are only interested in generating file list, so file existence is not really required. If you omit dependency, you may generate file list without even extracting the files.
For the actual file list write the oversized command line error comes from the fact, that the generated command is a single line with multiple subshell calls, which might be too long for the command line indeed:
$ make FL1 --trace
...
Makefile:24: update target 'c_proj1.f' due to: design1/c_files/a.c design1/c_files/b.c design1/c_files/c.c design1/c_files/d.c design1/c_files/e.c design1/c_files/f.c
( rm -f c_proj1.f )
( touch c_proj1.f )
`echo ./design1/c_files/a.c >> c_proj1.f`  `echo ./design1/c_files/b.c >> c_proj1.f`  `echo ./design1/c_files/c.c >> c_proj1.f`  `echo ./design1/c_files/d.c >> c_proj1.f`  `echo ./design1/c_files/e.c >> c_proj1.f`  `echo ./design1/c_files/f.c >> c_proj1.f`

This part can be resolved with a $(file) function (if you happen to use GNU make 4.1+):
.PHONY: $(FILE_LIST1)
$(FILE_LIST1):
        $(file >$@)
        $(foreach file,$(DESIGN_FILES1),$(file >>$@,$(file)))

If an older make is used, this could be done with regular commands, you just need to generate a newline character after each echo to make it work as a separate command. The only tricky part is that it has to be done as a specially crafted variable:
# Note double empty lines below
define newline

endef

.PHONY: $(FILE_LIST2)
$(FILE_LIST2):
        rm -f $@
        $(foreach file,$(DESIGN_FILES2),echo $(file) >> $@$(newline))

Result is now generated in separate shell calls, which should avoid command length limit:
$ make FL2
rm -f c_proj2.f
echo ./design2/c_files/a.c >> c_proj2.f
echo ./design2/c_files/b.c >> c_proj2.f
echo ./design2/c_files/c.c >> c_proj2.f
echo ./design2/c_files/d.c >> c_proj2.f
echo ./design2/c_files/e.c >> c_proj2.f
echo ./design2/c_files/f.c >> c_proj2.f

EDIT:
I was able to reproduce your multiple iteration of extraction. Your tgz file does not actually contain the files you claim to extract, so the files are not there when the first one is trying to be extracted and the extraction continues for the next file (which is also absent). This is also suggested by tar output, which says:
design1/
design1/c_files

instead of:
design1/
design1/c_files
design1/c_files/a.c
design1/c_files/b.c
design1/c_files/c.c
design1/c_files/d.c
design1/c_files/e.c
design1/c_files/f.c

Your tgz only contains a directory symlink and it only extracts a symlink. If the target files do not exist in the target location, it will attempt to re-extract for every file.
EDIT2:
When actual files are not included in the tgz file, but are available through a symlink, there is a chance that they are older than the tgz file itself. In such situation make checks the file timestamp through a symlink and discovers that it needs to be remade - but the file is not actually remade (since it's not included in the tgz). This check is done for every single file, so for every file the archive is extracted:
$ make FL1 -d
...
     Finished prerequisites of target file 'design1/c_files/a.c'.
     Prerequisite 'design1.tgz' is newer than target 'design1/c_files/a.c'.
    Must remake target 'design1/c_files/a.c'.
tar zxvfmhC design1.tgz .
Putting child 0x7fffe11ae730 (design1/c_files/a.c) PID 6286 on the chain.
Live child 0x7fffe11ae730 (design1/c_files/a.c) PID 6286
design1/
design1/c_files
Reaping winning child 0x7fffe11ae730 PID 6286
Removing child 0x7fffe11ae730 PID 6286 from chain.
    Successfully remade target file 'design1/c_files/a.c'.
    Considering target file 'design1/c_files/b.c'.
      Pruning file 'design1.tgz'.
     Finished prerequisites of target file 'design1/c_files/b.c'.
     Prerequisite 'design1.tgz' is newer than target 'design1/c_files/b.c'.
    Must remake target 'design1/c_files/b.c'.
tar zxvfmhC design1.tgz .
...

In general extracting archive in this way is not reliable anyway (image running in parallel with -j), so it would be better to use a group target rule to explicitly point out that this rule generates all the files at the same time:
$(DESIGN_FILES1) &: $(DESIGN_TAR_FILE1)
        tar zxvfmhC $(DESIGN_TAR_FILE1) $(DESIGN_EXTRACT_DIR)

This however is a new feature introduced in GNU make 4.3, so to make it work with previous versions, we could use a phony target that is only used for synchronization, e.g.:
$(DESIGN_FILES1): extract-$(DESIGN_TAR_FILE1)

.PHONY: extract-$(DESIGN_TAR_FILE1)
extract-$(DESIGN_TAR_FILE1):
        tar zxvfmhC $(DESIGN_TAR_FILE1) $(DESIGN_EXTRACT_DIR)

Output:
$ make FL1
tar zxvfmhC design1.tgz .
design1/
design1/c_files

Note that the archive is now extracted only once.
Comment: Thanks for the response. In this snippet I am generating a file list but I use the file list to do a compile so I will need to execute tar and extract the files and the files must exit or the compile will fail.
Answer: I followed your advice and changed the dependency and it resolves the tar issue. The file function in make resolves the length of the variable but I have 2 undesired effect due to it. I have added one more thing to the mix here and I cannot explain the behavior:
On linux:
  % mkdir -p design3/c_files
  % cd design3/c_files
  % touch x.c y.c z.c
  % cd ../..
  % ls ./design3/c_files/*.c >  design3/c_proj3.f

Here's what I have done to the Makefile:
DIR_LIST := design3

IP_EXTRACT1: $(DESIGN_TAR_FILE1)
    gtar zxvfmC $(DESIGN_TAR_FILE1) $(DESIGN_EXTRACT_DIR)

$(DESIGN_FILES1):
    $(MAKE) IP_EXTRACT1

$(FILE_LIST1):  $(DESIGN_FILES1)
    $(file > $(FILE_LIST1))
    @$(if $(strip $(DIR_LIST)), cat $(foreach dir, $(DIR_LIST), $(wildcard $(dir)/*.f)) >> $(FILE_LIST1))
    @$(foreach file,$(DESIGN_FILES1),$(file >>$(FILE_LIST1),$(file)))

This resolves the tar issue but now I have added DIR_LIST and I want to add the list of files in each directory to the file list. It does the right thing but it has a couple of undesired effect:
1) I expect the content of design3/c_proj3.f at the top but it appears in the end.
%make FL1
%more c_proj1.f
./design1/c_files/a.c
./design1/c_files/b.c
./design1/c_files/c.c
./design1/c_files/d.c
./design1/c_files/e.c
./design1/c_files/f.c
./design3/c_files/x.c
./design3/c_files/y.c
./design3/c_files/z.c

I expected x, y, z at the top as there is order dependence but its at the bottom. Also, if I do make FL1 --dry-run after removing c_proj1.f the files a through f gets into it but not x,y,z because that is from a cat shell command. I would prefer no files get created. Is there a way to resolve this?. This is a partial solution so I am not sure if this needs to go back into the question.


chown or chgrp NFSv4 with idmapd error: Invalid argument

Question: I only found 1 or 2 other posting on this, without any solution, so I am creating a new, more specific question for my case.
System set up:
NFS server running NFSv4.
NFS client running RedHat 6, idmapd running with the following in /etc/idmapd.conf:
<code>    [General]
    Verbosity = 7
    Domain = localdomain

    [Mapping]
    Nobody-User = nobody
    Nobody-Group = nobody

    Method = nsswitch
</code>
The issue is chown/chgrp for certain users fail with 'Invalid argument' error, as follows, even though the user exists on local host:
<code># chown oracle m
chown: changing ownership of `m': Invalid argument
# grep oracle /etc/passwd
oracle:x:54321:54321::/home/oracle:/bin/bash

# chown mysql m
# grep mysql /etc/passwd
mysql:x:496:496:MySQL server:/var/lib/mysql:/bin/bash
</code>
Why does idmapd not recognize certain users but it works with others (root, nobody, and even mysql, which is non-standard, are OK)?
Any specific setting I am missing above? I thought when Domain is set to localdomain then everything should just work using local passwd/group files, etc. (And yes, nsswitch.conf lists passwd and group as files)?
Thanks in advance!
Answer: I just wanted to close the loop on this one.
I found the answer. The issue here is when rpcidmapd is on, NFSv4 uses it to do mapping but this means NFS sends username@domainname vs UID/GID to the server.
When the server does not understand this username@domainname (maybe because the server is not set up with the same directory or some other reasons), it does not allow chown/chmod.
Apparently this default behavior is INCORRECT.
In later Linux kernel, this was fixed by the NFS maintainer in the kernel so that default for NFSv4 is to NOT use idmapping.
See the commit here:
http://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/?id=074b1d12fe2500d7d453902f9266e6674b30d84c
To fix this yourself, you can do this (RHEL specific):
<code>echo "options nfs nfs4_disable_idmapping=1" >> /etc/modprobe.d/nfs.conf
</code>
Hope this helps.


Installing pytorch with conda

Question: I've just been trying to dabble in AI in the past few weeks, I've tried installing pytorch with conda and it all seems to work but then I get the error:
ImportError: /home/lp35791/.local/lib/python3.8/site-packages/torch/lib/libtorch_cuda.so: cannot read file data
I've been trawling through the web but can't seem to find the answer to this error. I've uninstalled and reinstalled anaconda and when I made a new environment and installed numpy along with pytorch, numpy imported successfully but pytorch did not. I'm just wondering what the problem is. Any help would be greatly appreciated!
Answer: You seem to have installed PyTorch in your base environment, you therefore cannot use it from your other "pytorch" env.
Either:
directly create a new environment (let's call it pytorch_env) with PyTorch: conda create -n pytorch_env -c pytorch pytorch torchvision
switch to the pytorch environment you have already created with: source activate pytorch_env and then install PyTorch in it: conda install -c pytorch pytorch torchvision
Answer: It seems like you need to reinstall it-
Go to terminal type
pip uninstall pytorch
then again type
pip install pytorch
if you are unable to install you will get solution there itself.
Comment: The user used conda to install pytorch, not pip.

Installing pytorch with conda


SQL Server Refresh Dependencies after Alter Function

Question: According to the ALTER FUNCTION reference:

Alters an existing Transact-SQL or CLR function that was previously created by executing the CREATE FUNCTION statement, without changing permissions and without affecting any dependent functions, stored procedures, or triggers.

I am trying to rename a column, so I found its dependency (UDF) and altered the UDF to not be dependent on that column anymore.
SQL Server 2008, however, did not refresh the dependencies so I still can not rename the column.
Any ideas?  TIA!
Comment: Here is the ,

[Find the Solution here][1]

  [1]: http://stackoverflow.com/a/32858945/1147352
Answer: Apparently the issue was because this is a computed column, and when I ran it as a query (as opposed to via the GUI) I got the following:

Cannot alter column  because it is 'COMPUTED'.

I dropped it and created a new one with the same formula and a different name.


Como enviar mensagens para as abas abertas de um app no chrome

Question: Estou consertando a parte de sincronização entre as abas abertas do meu app e lembrei que o Google Chrome tem uma API que se não me engano faz exatamente o que eu preciso, mandar mensagens internamente em um aplicativo.
Eu dei uma olhada no Google e no Chrome Developers e me confundi todo, então achei que seria melhor perguntar para quem já entende do assunto.
Eu preciso de um código que enviei mensagens para as abas abertas de um app (como já foi dito) e também como seria para receber essa mensagem.
Comment: Não sei quanto à API do Chrome, mas talvez [`window.postMessage`](https://developer.mozilla.org/en-US/docs/Web/API/Window.postMessage) resolva (você precisa de uma referência a cada janela).
Answer: Em um projeto recente foi necessário fazer algo parecido. Ele consistia em um sistema de contabilidade. Quando o usuário selecionasse outra empresa, todas as abas deveriam ser notificadas e atualizadas.
O sistema em questão foi implementado em JSF 2 com PrimeFaces, então usei o componente Push, que, por debaixo dos panos, usa o framework Atmosphere.
Este link contém um tutorial sobre o framework.


Como criar Function no Banco com Migrations ef core?

Question: Eu criei uma function em Postgresql e gostaria que ela fosse gerada junto com o banco de dados na migration inicial.
Tentei da seguinte maneira e nao tive resultados
 protected override void OnModelCreating(ModelBuilder modelBuilder)
 {
            Database.GetDbConnection().CreateCommand().CommandText = "função vai aqui";
 }

Answer: Use o add-migration e personalize a migração.

Às vezes, é útil adicionar uma migração sem fazer alterações no
  modelo. Nesse caso, adicionar uma nova migração cria arquivos de
  código com classes vazias. Você pode personalizar essa migração para
  executar operações que não se relacionam diretamente ao modelo do EF
  Core.

Exemplo de migration personalizada:
public partial class MinhaFuncao : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        var function = @"
                    CREATE FUNCTION MINHAFUNCAO(@ST VARCHAR(1000))
                    RETURNS VARCHAR(1000)
                    BEGIN
                       RETURN('Minha função')
                    END
                ";

        migrationBuilder.Sql(function);
    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {

    }
}

Comment: Olá George,

Eu fiz assim:

 public class ApplicationDbContext : DbContext
    {
       protected override void OnModelCreating(ModelBuilder modelBuilder)
       {
            Database.ExecuteSqlCommand(" sql script da função aqui");
       }
   }

Acha valido?
Comment: @iagosoares é válido sim, pode até por como resposta, seria mais uma opção :)
Comment: Obrigado George!
Desculpe a formatação da resposta, estou aprendendo ainda rsrs
Answer: Uma outra opção encontrada
public class ApplicationDbContext : DbContext
   {
       protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            Database.ExecuteSqlCommand("sql script vai aqui");
        }
   }


vector linear combinations in 3d space

Question:
My text has an example as follows:
Three vectors, V U and W, in three dimension space.
They ask to locate two other vectors:
a) 1/3V + 1/3W + 1/3U
b) 1/2W + 1/2U
the answers:
a) falls in the middle of the triangle whose vertices are W, U, and V.
b) falls midway on the line between W and U
I stare at it and think, "yeah, ok, looks right" but honestly I cannot prove to myself why, and I also cannot think of other examples to look at to reinforce that I really understand this.
I guess the answer for 'a' is something like, "well, the vectors W and U and V are all points on a plane defined by the linear combinations of cW+dU+eV"   Therefore the example c=d=e=1/3 is also going to be on that same plane.    But I'm missing how that sticks it in the middle of that U-W-V triangle.
And similarly for the part-b question, it sounds right, but I don't have a relationship that I can exploit to prove it.
Answer: You can work the other way around. Take part (b), for example.
Given the vectors $W$ and $U$, points on the line joining $w$ with $u$ have position vectors $p = W + k(U-W)$, where k is a scalar.
This is because if you complete the vector addition triangle, $W+\overline{wu} = U$.
When k=0, $p=W$
When k=1, $p=W+U-W = U$.
So as you vary k from 0 to 1 you get points on the line $wu$ (you're doing a linear  interpolation, really).
The midpoint is halfway along the vector from u to w (k=1/2), which shows you that the midpoint i.e. $p = W + (1/2) (U-W)$ = (1/2)W + (1/2) U, which is what part (b) asserts.
Comment: The solution approach solves using  "position function = vector equation"  (W+k(U-W)) = 1/2W + 1/2U.    I'm trying to use same approach for the second example, but I am not sure how to specify the position function.  W + k(U-W) + ???  if I put the third component in terms of d(V-K(U-W), I just wind up with two free konstants that i cannot solve.  If I use the same konstant k to define the third component, k(V-k(U-W)), I wind up with k^2 terms which makes no sense.
Comment: I do not find this convoluted answer helping anyone who is just beginning to learn L.A. This is a challenge question from Strang's book. What really saved me was the excellent video from [khan acad](https://www.khanacademy.org/math/geometry-home/triangle-properties/medians-centroids/v/triangle-medians-and-centroids). The reason why $1/3u+1/3v+1/3w$ is the center of the triangle boils down to a fundamental property of triangles.

vector linear combinations in 3d space


How are the piano keyboard and performer fingers lit in Synthesia cover videos?

Question: Here's one of many videos created using Synthesia music visualization software. The upper part of the screen looks like it's drawn by the software. The lower part looks like it shows a real piano and real performer hands shot on camera.
How does it happen that as "bricks" approach the piano keyboard the keyboard and the hands are being illuminated by light of the same color and matching intensity as if the "bricks" were real and actually emitted light?
Comment: This sounds more like a question for video editing than music practice and theory.  If this is more about music in your eyes, I think we'll need to have some sort of additional context as to why.
Comment: I'd guess that random video editor people would have much lower chance of knowing the answer compared to random music performers.
Answer: When people like Rousseau record their videos, they have a specific lighting pattern setup on their keyboard so the LEDs at the top of the keys light up when pressed, and at the same time as they record the playing with the lights, they record the MIDI and throw it into a Synthesia file or some other software. Then they just overlay it on top in editing.
Basically, they have a keyboard that has LEDs and software that allows them to set up rules for the LEDs and they record a video of them playing, and then overlay the resulting software video on top.
Comment: Are such pianos where keys light up common? What's the purpose for that? I'd guess it distracts the performer and adds stress to their eyes.
Comment: [This video](https://www.youtube.com/watch?v=IZgYViHcXdM) demonstrates what is going on.
Comment: @KevinPanko Thank you. Yeap, as I expected it looks rather distracting.


Proof of monotonicity of conditional expectation

Question: I am trying to show monotonicity of conditional expectation. Namely, if $X\leq Y$ almost surely, and $\mathcal{M}$ is some $\sigma$-algebra then $\mathbb{E}[X|\mathcal{M}]\leq\mathbb{E}[Y|\mathcal{M}]$. I know that $\forall E \in \mathcal{M}$,
$$\int_E \mathbf{E}[Y|\mathcal{M}]-\mathbf{E}[X|\mathcal{M}]dP \geq 0$$
Thus, consider the set of elements for which $\mathbf{E}[Y|\mathcal{M}]-\mathbf{E}[X|\mathcal{M}] < 0$ denoted $G$, on this set, $\int_G \mathbf{E}[Y|\mathcal{M}]-\mathbf{E}[X|\mathcal{M}]dP< 0$ which implies that $G\notin \mathcal{M}$.
I would like to say then that $P(G)=0$, but since $G$ is not in the $\sigma$-algebra I don't even know if it is measurable. What am I missing here? How do I know that this set has zero measure?
Answer: $\newcommand{\field}{\mathscr{M}}$
Let $G$ be defined as you described. You cannot derive $G \notin \field$ -- in fact, because $E[Y|\field] - E[X|\field]$ is $\field$-measurable, it is certain that $G \in \field$.  One correct way to show the monotonicity is via proof by contradiction as follows:
By the definition of $G$, we have that $(E[X|\field] - E[Y|\field])I_G \geq 0$ everywhere.  If $P(G) > 0$, then
\begin{align}
 & P[(E[X|\field] - E[Y|\field])I_G > 0] \\
=& P[[(E[X|\field] - E[Y|\field])I_G > 0]\cap G] + P[[(E[X|\field] - E[Y|\field])I_G > 0]\cap G^c] \\
=& P(G \cap G) + P(\varnothing) = P(G) > 0.
\end{align}
It then follows (as we have just shown that the non-negative random variable $(E[X|\field] - E[Y|\field])I_G$ has positive probability of being positive) by Theorem $15.2$ of Probability and Measure that
$$\int_G (E[X|\field] - E[Y|\field])dP = \int (E[X|\field] - E[Y|\field])I_GdP > 0,$$
which contradicts with $\int_G (E[Y|\field] - E[X|\field])dP \geq 0$.  Therefore $P(G) = 0$, i.e., $E[Y|\field] - E[X|\field]) \geq 0$ almost surely.
Comment: @tornt I think I was trying to matching the condition of the cited theorem precisely.  What you suggested should also work, as it naturally implies that condition.
Comment: For convenience, I cite the theorem used in the answer here: *Suppose $f$ is non-negative, if $\mu[\omega: f(\omega) > 0] > 0$, then $\int fd\mu > 0$*.
Comment: Maybe I'm missing  something, but by the definition of G, don't we have $(E[X|M] - E[Y|M])I_G > 0$? And then assuming $P(G) > 0$, $$\int_G (E[X|M] - E[Y|M])dP$$ would be an integral of a strictly positive function on a set of positive measure, so it should be strictly positive, which contradicts $\int_G (E[Y|M] - E[X|M])dP \geq 0$? Can you explain why it is necessary to show that $P[(E[X|M] - E[Y|M])I_G > 0] > 0$?
Answer: Notice that $E(X|\mathcal{M})$ and $E(Y|\mathcal{M})$ are $\mathcal{M}$-measurable. Therefore, the set
\begin{equation*}
G = \{x | E(X|\mathcal{M}) > E(Y|\mathcal{M})\}
\end{equation*}
is $\mathcal{M}$-measurable.
Now, since $G \in \mathcal{M}$,
\begin{equation*}
0 \leq \int_G (Y - X) \,\mathrm{d}P = \int_G (E(Y|\mathcal{M}) - E(X|\mathcal{M}))\, \,\mathrm{d}P \leq 0.
\end{equation*}
Therefore,
\begin{equation*}
\int_G E(Y|\mathcal{M}) \,\mathrm{d}P = \int_G E(X|\mathcal{M}) \,\mathrm{d}P.
\end{equation*}
And this implies that $P(G) = 0$.


ie "webpage has expired" on back button PHP session problem

Question: On IE when user hits back button they get the classic IE "webpage has expired" message.
I have found that setting the following in my php.ini has solved this.
'session.cache_limiter=private'

However my problem now is when I send forms I include a PHP session value ($_SESSION['token']) in a hidden field. I then check this on the following page to see if token values match
echo "<form ......<input type='hidden' name='token' value='".$_SESSION['token']."' />";

/*on recieving page*/
if($_POST['token']==$_SESSION['token']){/*ok matched*/}
else{/*THIS IS WHERE THE ERROR OCCURS*/}

My problem is since adding this setting to my php.ini file I noticed when sending forms I get my custom page error as for some reason the $_SESSION['token'] value appears to change on the page receiving the form data thus making the if() statement return false? It's happening in all browsers now?
Here is my $_SESSION['token'] code (NOTE when sending my form it lands in the else() but value changes of $_SESSION['token'] something to do with cache perhaps not retaining my $_SESSION values?
session_start()
if(!isset($_SESSION['token']))
{
            $token = md5(uniqid(rand(), TRUE));
            $_SESSION['token'] = $token; /*have to put current session token into this variable for hidden field in <form>*/
            $_SESSION['token_time'] = time();
}
else
{
            /*if token set ie user press back button on browser*/
            $token_age = time() - $_SESSION['token_time'];
            if ($token_age > 1200)
            {
                        /* More than 20 minutes has passed - regenerate. Do this so more likely wont timeout when user taking long time on <form> and token may not get refreshed before time limit*/
                        $token = md5(uniqid(rand(), TRUE));
                        $_SESSION['token'] = $token; /*have to put current session token into this variable for hidden field in <form>*/
                        $_SESSION['token_time'] = time();
            }

}

If any use heres my other php.ini session settings
session.cache_limiter=private
session.cookie_secure=1 ;my wholes site is SSL
session.cookie_httponly=1
session.save_path = /tmp ;directory to store sessions
session.save_handler = files
session.cookie_lifetime = 0 ;persistence cookie dies after browser closed
session.use_trans_sid = 0
session.use_only_cookies=1

Let me just clear something up guys, the reason this whole problem occurs is using the 'session.cache_limiter=private'. If I take this out theres no problem except I get a message in IE when hitting back button on a form page saying "Webpage expired". Is there any suggestions how to avoid that message occuring in IE when hitting the back button?
Comment: How about observing your $token_age?
Comment: Yes I have but its not getting into that if(). Just in the else().
its something to do with that setting session.cache_limiter=private as without it it works but I get "webpage expired message" in IE if I take it out. I am missing something I think as cache appears to get wiped out on each page. Something to do with session.cache_expire I think?
Comment: Have you checked the HTTP headers?
Comment: Not sure how or What to look for?
Comment: One other thing, are you using any ajax on the page? If you do, you should check if there is a script called, that clears the session. Try putting any ajax request out, for a test.
Comment: For the headers you can do that directly with: http://php.net/manual/en/function.get-headers.php from a different script var_exporting the result. There you can see what kind of caching does the server suggest to the browser.
Comment: Let me just clear something up, the reason this whole problem occurs is using the 'session.cache_limiter=private'. If I take this out theres no problem except I get a message in IE when hitting back button on a form page saying "Webpage expired". Is there any suggestions how to avoid that message occuring in IE when hitting the back button?
Comment: I tried using your code on my server (including session settings in php.ini). Didn't have any problems. Everything worked fine just as expected... Not helping, but may be noteworthy...
Comment: That means that the code is OK. It's a server thing than. PHP or Apache/IIS/... settings.
Comment: Or the error occurs in another part of the code that we don't see here...
Comment: You are using `session.cookie_secure=1`. Is your site on a [secure (https) server](http://www.php.net/manual/en/session.configuration.php#ini.session.cookie-secure)? Try turning that one off?
Comment: My whole site is SSL, have now mentioned that in previous question.
Answer: ini_set("session.cache_limiter", "must-revalidate");
Comment: Thanks it has worked guys using the ini_set("session.cache_limiter", "must-revalidate"); replaced ' with " and did the job. How can I put this in my php.ini file now and this is best answer?
Comment: 'session.cache_limiter=must-revalidate'
Comment: Can I put that in my php.ini like 'session.cache_limiter=must-revalidate' or does it have to be in PHP script using ini_set() ?
Comment: Is that a supported option? http://www.php.net/manual/en/function.session-cache-limiter.php
Comment: Just tried the ini_set('session.cache_limiter', 'must-revalidate'); in my PHP code thats causing the same problem
Comment: Noticed with the ini_set these error messages 02-Jun-2011 07:11:38] PHP Notice:  Use of undefined constant 'session - assumed ''session' in ...
[02-Jun-2011 07:11:38] PHP Notice:  Use of undefined constant cache_limiter' - assumed 'cache_limiter'' in ....
[02-Jun-2011 07:11:38] PHP Notice:  Use of undefined constant 'must - assumed ''must' in ....
[02-Jun-2011 07:11:38] PHP Notice:  Use of undefined constant revalidate' - assumed 'revalidate'' in ....
Comment: Those error messages result from the illegal quotemarks in the statement above. Try replacing them manually with ' or ".
Comment: You can put it in your php.ini without problems.
Comment: Thanks problem solved guess it was =must-revalidate rather than =private that was my problem. Thanks @Anze Jarni and @BlaM for your help!
Answer: Is that in HTML code?
<input type='hidden' name='token' value='".$_SESSION['token']."' />

If yes, try:
<input type='hidden' name='token' value='<?PHP echo $_SESSION['token']; ?>' />

:)

I never was too happy with the PHP built-in session functionality. Too many problems for me...
Are you initializing session handling with session_start()?
Are you sure that sessions are using cookies - not any Query-String / POST fields? (Check the generated HTML code in the browser).
Comment: yes I do use session_start() forgot to paste it in my code provided, I have amended my previous question added some more settings which may be causing problems?
Comment: Nope I am obviously echoing HTML  in PHP have amended previous question code again.
Comment: its something to do with that setting session.cache_limiter=private as without it it works but I get "webpage expired message" in IE if I take it out. I am missing something I think as cache appears to get wiped out on each page. Something to do with session.cache_expire I think?


How to implement Instant Notifications to 'follow' or 'like' nodes?

Question: My employer has a social intranet site with 1000s of users, groups, communities and blogs. Users are free to 'follow' or 'like' nodes, blogs and other users, subscribe to communities, join groups etc.
What I'm trying to achieve is the following.

User A posts some content, for the sake of argument a blog.
User B comes along, reads the blog and 'follow's it.
User A needs to be notified that the blog has been followed.
User B needs to be notified in the future that the blog has changed, been added to, modified or even simply 'like'd by another user.

This is all good with small numbers of people involved. However, as mentioned earlier, there are 1000s of people on this site. When a lot of users follow a blog or 'like' something, they all need to be informed of the update and it is here that I'm having the problem. The regular nodeJS module for Drupal seems to blanket broadcast to every active session on the site at that moment, and let Drupal figure out who needs to be told but the load on the server is massive as most of the notifications are unnecessary.
I've had a look at the Actions NodeJS module as well which at first glance seemed to be absolutely ideal as I know I can tell it to just get a list of the users who are followers, loop through each one and tell them that something has happened. The problem with this lies in that the initial event, 'like'ing something for example, does not complete until everyone has been notified so the system hangs until exit.
For example,

User A posts some content.
Users B through X all 'like' that content.
User Y comes along and 'like's it as well.

Users A through X all get told that User Y has liked it but the 'like' operation from User Y's point of view does not complete until the last person has been notified. Again, this is not so much of a problem with a handful of users, but with possibly 1000s this becomes an issue to be dealt with now. If it's just an implementation issue and you know how to solve this, shout up.
Some 'back of a crisp packet' calculations say that the slow part of the process is the looping through of all the relevant users. Accessing the database to get the list of relevant UIDs is pretty quick as is the sending of the actual message.
Am I looking at writing some custom code to handle this? Am I going to be better off handing the work to a separate thread to process the notifications? Is this even possible? Does a module exist already that can perform this task efficiently? This is greenfield by the way. Anything will be considered for this task as performance on the site with the current implementation is 100% toilet. It may be that the current implementation is flawed and the existing modules are perfectly capable of accomplishing this, this is a real possibility. However, from what I've read, I don't think that this is the case.
I don't want to blanket broadcast to the site and let Drupal sort out who needs to see the notification as that means many unnecessary hits on the server but if that's how things are supposed to work, please let me know. I'd much rather just target a list of users and hit them, that seems to me to be the better way forward. All hints, tips, ideas and suggestions are welcome. The NodeJS module allows a system-wide broadcast which is pretty much instant across all open sessions. What I'd love is to be able to harness that performance but with a targeted list of UIDs.
Other info you may need to know.

I have a dedicated Node JS server at my disposal
The main Drupal site has 3 web heads but only using 1 at the moment for testing. Usual behaviour is 'round robin'ned across the 3 servers.
The site is hosted on a private network
No anonymous users allowed; everyone has to log in to use the site so everyone has a UID.
PHP v5.3.3
Drupal v7
NodeJS v0.10.36

Upgrading the software isn't really an option but if it absolutely 100% can not be accomplished any other way, then it becomes an issue for discussion for those on a higher pay grade to me. I've already said that I think things should be upgraded, particularly NodeJS, but there is definite resistance to this, don't ask me why.
Answer: Option 1: Message stack
Have a look at the Community documentation about the Message Stack, which consists of these modules (quotes are from the module's project page):

Message:

The Message module is the core of the message stack. It enables logging and displaying system events in a number of different use cases. Events that are recorded over time are sometimes call activity streams. Exportable messages subtypes can be created for different use cases with custom fields and display (view) modes.

Message Notify.

This module provides a method for sending a message via a notifier plugin. Message Notify comes with plugins for email and SMS and may be extended to other transport mechanisms as required.

Message Subscribe.

With this module, users who subscribe to content will be notified when events occur that involve that content. The module leverages the Flag module, which provides a subscribe functionality to users.

These are the basic components and dependencies of the message stack:

Quite a few popular Drupal distributions already adopted to this Message Stack, such as such as Commerce Kickstart, Drupal Commons, ERPAL and Open Atrium. And it will make you well positioned for Drupal 8 also (because of he modules' object orientated architecture). Even though there is no such a thing as 8.x-dev yet, the Message code repository already does contain something already (not yet for the 2 other modules though). I assume the wip part of the branch name stands for 'Work In Progress'.
If you want to have a closer look at the Message Stack in your own environment, then experiment a bit with the Answers module (disclosure: I'm a co-maintainer), together with the Answers Notification sub-module, which allows logged in users to subscribe to selected questions, so that they receive notifications (using the Message Stack) when Questions receive Answers.
Option 2: Menu badges
A completely different approach is to use the Menu Badges module, which you could use to configure them using the integration of it with the Views module.
Some more details about some views that seem appropriate for your case:

A view of users "following" a node, whereas "following" could be implemented using the Flag module. A variation of this could be "nodes liked by users".
A view of changed nodes followed by the current user.

For more details, refer to my answer to "How to create a basic message - notifications system displaying a real time message counter badge?".
Comment: Thanks for the response, Pierre. I'll take a look at what you've suggested and see if it helps any.
Comment: Mods - Please can you close this question? I haven't accepted it as answered as the given response didn't help but it might help someone in the future.
Comment: @doop_dev : merci for the feedback, sorry it didn't help "**you**". But why would you want your question to be closed? Maybe somebody else might post an answer that does help "**you**". If the question would be closed, nobody will ever be able to answer anymore.
Comment: That's a good point. Mods, ignore me. Pierre is right.
Comment: @doop_dev : aha, good to hear ... But "we" won't ignore you ... at least I won't ... I might even post an additional answer using a different solution.


knockoutjs: prevent event bubbling for elements with no handler

Question: It seems like the binding <event>Bubble: false only works when there's a defined event handler (see Note 4) for <event>.
Here's an example fiddle.
For elements having native handlers for certain events (e.g. click: <textarea>, , <select>, etc.), where the native handler suffices, I would expect setting the binding, e.g., clickBubble: false on them, without having to bind a "bogus" handler, to work.
I guess my question is, is there another knockout way to achieve this without extra bindings?
Answer: The Bubble handlers are not actual binding handlers and are used as options in the event binding (click binding calls event binding).  So, they do not run on their own.
So, you can add a "bogus" no-op handler and use clickBubble or you could certainly choose to create a custom binding to do this for you.
Maybe something like:
ko.bindingHandlers.preventBubble = {
    init: function(element, valueAccessor) {
        var eventName = ko.utils.unwrapObservable(valueAccessor());
        ko.utils.registerEventHandler(element, eventName, function(event) {
           event.cancelBubble = true;
           if (event.stopPropagation) {
                event.stopPropagation();
           }
        });
    }
};

And then just put:
<input data-bind="preventBubble: 'click'" />

You could also enhance it further to accept an array of events, if necessary.
Sample: http://jsfiddle.net/rniemeyer/WcXwZ/
Comment: Thanks, RP. I think the custom binding and use of the `utils` library, as per your fiddle, is far more attractive for multi-ViewModel apps and reusable than shimming bogus handlers on each VM class. I've +1ed your answer and am only giving the question a day or so to saute, to be fair, for other solutions. I won't forget to select the most elegant/useful, honest-engine.


Warning: require_once(PHPUnit/Autoload.php): failed to open stream: No such file or directory in /usr/bin/phpunit on line 49

Question: This is my complete error message:
Warning: require_once(PHPUnit/Autoload.php): failed to open stream: No such file or directory in /usr/bin/phpunit on line 49
Fatal error: require_once(): Failed opening required 'PHPUnit/Autoload.php' (include_path='.:') in /usr/bin/phpunit on line 49
I am using MacOsX10.8 and MAMP. I get this Warning running "./bin/behat ..." in a Symfon2.3 application.
Any suggestion?
Answer: Do it for the file being called on line 49
First check whether the file exist.
Next Check for read permissions on that file and its folders
Comment: I think the issue is "where is PHPUnit in my machine"? Have I a problem of PATH? I've read a lot of other similar questions. It seems to be a problem tied to a wrong installation of PHPUnit. I "solved" adding phpunit to my project, but I think I have an'issue on my machine.


Using an ansible role to create two clusters

Question: I want to setup 2 clusters of zookeepers. Right now I have a template in my zookeeper role that iterates through groups.zookeepers and builds the zookeeper config file to point to all the nodes in the cluster.
What is the right way to write one role and still get 2 separate clusters?
Comment: Could you just remove iteration from the role and apply the playbook to two separate groups independently using `--limit`?
Comment: would it be simpler to just maintain 2 inventories in that case? i was hoping to not run the playbook multiple times
Comment: that's likely to be another run (but with the `-i` flag)—sounds like @udondan's answer is much closer to what you're looking for!
Answer: You can parameterize roles.
Example playbook snippet:
<code>roles:
  - role: your_role
    cluster: A
  - role: your_role
    cluster: B
</code>

OK, after re-reding your question and above comments, I think this might be more of help:
A playbook can have multiple plays in which you can target different hosts.
<code>- name: Cluster A
  hosts: clusterA
  roles:
    - your_role

- name: Cluster B
  hosts: clusterB
  roles:
    - your_role
</code>
Comment: are you saying - in inventory have
    [cluster1]
    node1
    [cluster2]
    node2

and then have
cluster1 map to role zookeeper with variable cluster 'A'?

in that case how do i find all other nodes only in cluster 'A' in my task under the role.
Comment: Think I first misunderstood your question. I updated my answer. Yes, when you then have two different groups in the inventory you can target them separately in two different plays in one playbook.
Comment: I understand  what you are trying to say with targeting the same role at two different groups. My main question I guess is how I can identify other members of the target inside a task in the role
Comment: Do you mean for example in a template to loop over all other hosts of the group? You can access `groups['clusterA']` which holds all the hosts of that group. I think you can not access all hosts of the current processing play, so you would nee to pass the group as a parameter to the role. See http://docs.ansible.com/faq.html#how-do-i-loop-over-a-list-of-hosts-in-a-group-inside-of-a-template
Comment: thanks. that helps.  passing the group name as a parameter would do the trick.
Comment: Actually it is possible to do it w/o passing the group name `vars['play_hosts']` should hold all hosts of the current play.
Comment: This is what I ended up doing in my hosts file
`    [cluster1]
    node1
    [cluster2]
    node2
    [cluster1:vars]
    cluster=1
    [cluster2:vars]
    cluster=2
    [zookeepers:children]
    cluster1
    cluster2
`
then in my task, i filter based on if cluster matches


Return zero records when one value in "WHERE IN (..)" is not found

Question: I have a SQL query that does something like this:
SELECT * FROM myTable WHERE Id IN (574,575,576,577,578,579,580)

This query returns all the records that it can find with one of those seven IDs. If it can't find one of those ID's then it will simply return less records.
What I actually need is that it either returns ALL records, or NONE.
So if it can't find one of the ID's present in the IN clause, then it should return zero records.
I'm building a dynamic query against a view, so I can ONLY add custom queries after the WHERE clause.
How can I do this in one query?
Answer: This seems like an odd request.  But it sounds like you want a non-correlated subquery to count the ids:
select t.*
from mytable t
where Id in (574, 575, 576, 577, 578, 579, 580) and
      7 = (select count(distinct id)
           from mytable
           where Id in (574, 575, 576, 577, 578, 579, 580)
          );

You might not actually want to repeat the values, so:
with t as (
      select t.*
      from mytable t
      where Id in (574, 575, 576, 577, 578, 579, 580)
    )
select t.*
from t
where 7 = (select count(distinct id) from t);

Answer: You can use some fancy joining if you put the values into a table variable
DECLARE @list table(id int)
INSERT @list values(1),(574),(575),(576),(577),(578),(579),(580)
-- remarked row
--INSERT @list values(574),(575),(576),(577),(578),(579),(580)

DECLARE @mytable table(id int)

INSERT @mytable values(574),(575),(576),(577),(578),(579),(580),(581),(592)

SELECT mt.* FROM
  @myTable mt
JOIN @list list on mt.id = list.id
WHERE not exists(SELECT id from @list EXCEPT SELECT id from @myTable)

Result 0 rows returned.
7 rows will be returned if you used the remarked row as testdata instead


Bounded linear operator from orthonormal sequence

Question: I'm working on the following problem:

Suppose $\{e_n\}$ is a complete orthonormal sequence in a Hilbert space $H$. Let $\{c_n\}$ be a sequence of complex numbers.

Prove that there is a bounded linear operator $T$ on $H$ such that $Te_n=c_ne_n$ for each $n$, if and only if $\{c_n\}$ is bounded.
Determine $\|T\|$ when $\{c_n\}$ is bounded.
Determine $T^*$, the adjoint of $T$, when $\{c_n\}$ is bounded.

What I've done so far: I know that if $\{e_n\}$ is a complete orthonormal sequence then any $x\in H$ can be written as $\sum_{1}^\infty\langle x,e_n\rangle e_n$ and $\|x\|^2=\sum_1^\infty|\langle x,e_n\rangle|^2$. Then if $T$ is linear then $Tx=T(\sum\langle x,e_n\rangle e_n)=\sum\langle x,e_n\rangle c_ne_n$. But I'm not sure how to proceed.
Any help on this problem would be greatly appreciated!
Answer: Suppose $(c_n)$ is bounded. $\|\sum c_n\langle x, e_n \rangle e_n\|^{2}=\sum |c_n\langle x, e_n \rangle |^{2} \leq M \sum |\langle x, e_n \rangle |^{2}=M^{2}\|x\|^{2}$ where $M =\sup_m |c_n|$. Hence   $T$ is bounded with$\|T\| \leq \sup_m |c_n|$.
Also $\|Te_n\| =|c_n|$ and this implies (by definition of norm of an operator) that $\|T\| \geq |c_n|$. This is true for each $n$ so we conclude that $\|T\|=\sup_m |c_n|$.
Conversely,  $Te_n=c_n e_n$ show that $|c_n| \leq \|T\|$ for each $n$ so boundedness of $T$ implies that $(c_n)$ is bounded.
$T^{*}$ is given by $T^{*}x=\sum \overline {c_n} \langle x, e_n \rangle e_n $ and I will let you verify it using definitiom of the adjoint.