forms in ruby on rails, passing variables between one form to another

Question: I'm attempting to pass variables between forms and unfortunately i'm not managing
in my index.html.erb, i have a text field named SearchInput and i would like to pass this variable to the next form search.html.erb so that i may populate some data accordingly. How may i go about this please?
In my index.html.erb i have the following
<% form_tag (:action => 'search') do %>
I'm really clueless on how to go about on this please, any tips would be really appreciated
Answer: It sounds like you could benefit from reading up on the interactions between Model, View and Controller in a MVC framework like Rails. I suggest the official Getting Started Guide
Here's the relevant details as it relates to your question:
When receiving a HTTP request Rails will route the request to a controller action based on the url path. The controller than builds the appropriate response by evaluating view templates in the context of the request. The standard flow in Rails is the controller will extract information from the params hash to query the database for the information required to construct the view. Instance values set in the controller (variables with names starting with '@') will be available to the views rendered by this controller during this action.
Forms in general, direct the client's web browser to send a POST request to the specified url when the submit button is clicked. This request contains the form's fields and their values as data in the header.
Rails interprets the form data and any other parameters in the params hash. Which you can access in the controller or view of any action. The generally accepted place to access the params hash is in the controller.
Lets walk through the process of what's actually happening. The following is in terms of running a server in development assuming we're talking about a controller for products, and you've set up routes correctly.

User enters http://localhost:3000/products into their address bar to initiate a GET request.
Rails routes this request to the index action of products controller.
Rails will execute ProductsController#index (the index method located in app/controllers/products_controller.rb)
Unless you explicitly render or redirect the request, Rails will render the products/index template (app/views/products/index.html.erb) which contains a small form that submits to the search action of ProductsController. Form code will look like this:
<% form_tag(:action => 'search') do %>
  <%= text_field_tag "SearchInput" %>
  <%= submit_tag %>
<% end %>

User fills in the SearchInput field and submits the form as a POST request to http://localhost:3000/products/search
Rails routes this request to the search action of the products controller.
Rails executes ProductsController#search, the params hash contains the value the user entered into the SearchInput field with the SearchInput key. Here's a very simple example of using the form input to perform a search.
def search
  @products = Product.find_by_name(params["SearchInput"])
end

Unless you explicitly render or redirect the request, Rails will render the products/search template (app/views/products/search.html.erb) Example search view:
<% if @products.empty? %>
  No products found
<% else %>
  <% @products.each do |product| %>
    <%= link_to product.name, product_url(product)%>

  <% end %>
<% end %>

Comment: No problem, just remember the search action in the solution is very simple and will only find an exact match. In practice you'll want to use a proper search plugin like ferret, sphinx, solr, xapian, etc.
Answer: Form data is passed as part of the params[..] hash. So you can access most of the data passed through a form in that manner.
In your case, your view
<form action="..." method="...">
  <input type=".." name="search_input" ... />
  ...
  ...
  <button>submit</button>
</form>

would be grabbed via, your controller
def action_name
  @collection = Model.find(:conditions => {:column_name => params['search_input']})
  ...
  ...
end

Comment: im afraid i'm really not understanding this being very new to ruby on rails..
in which files to i put which please? :s
Comment: I expanded the example a bit, hope that helps.
Answer: Here's how you can pass a parameter around via the link_to method in order to, say, go to another form in order to create a new object with the passed parameter. This strategy would allow you to pass variables among actions in your controller and create objects with predefined attributes:
Say you have a variable called @foo that you want to pass to your new controller action, and your new view contains a form for your user to fill out.  In which case, you can use
<%= link_to "Link Text", new_widget_path(:foo => @foo) %>

which would store @foo in params[:foo], allowing you to use params[:foo] in your controller.
Clicking on Link Text will direct Rails to the new action of your WidgetController. You can have
def new
  @widget = Widget.new(:foo => params[:foo])
end

which would define a new Widget object with the :foo attribute pre-filled with params[:foo].
Then, in your new.html.erb view file, you can allow the user to create a new Widget object with this pre-defined foo attribute already filled out via a hidden form field:
 <%= form_for(@widget) do |f| %>
  <%= f.label :other_attribute %>

  <%= f.text_field :other_attribute %>
  <%= f.hidden_field :foo %>
  <%= f.submit %>
<% end %>

Allowing the user to create a new Widget object with a custom other_attribute and the foo attribute already filled out!


Save Audio File after apply Filter(AVAudioUnitEQ) and finally save it as mp3?

Question: I am so Frustrating to save the Audio File After Apply the Filter. The filter only applicable for the AVAudioPlayerNode which mean during Playing in the player the filter is perfect to apply but how can i save this ? I am so struggle last 3 days, Please any help will be appreciate.
 These below codes are i used,
engine = [[AVAudioEngine alloc] init];
<code> - (void)setupEQ
{
      NSLog(@"setupEQ");

      unitEq = [[AVAudioUnitEQ alloc] initWithNumberOfBands:12];
      unitEq.globalGain = 3.0;
      AVAudioUnitEQFilterParameters *filterParameters;
      filterParameters = unitEq.bands[0];
      filterParameters.filterType = AVAudioUnitEQFilterTypeParametric;
      filterParameters.frequency = 31;
      filterParameters.bandwidth = 1.0;
      filterParameters.gain = [[[filter_arr objectAtIndex:index_filter] objectForKey:@"filter_freq_31.5hz"] floatValue];
      filterParameters.bypass = FALSE;

      filterParameters = unitEq.bands[1];
      filterParameters.filterType = AVAudioUnitEQFilterTypeParametric;
      filterParameters.frequency = 63;
      filterParameters.bandwidth = 1.0;
      filterParameters.gain = [[[filter_arr objectAtIndex:index_filter] objectForKey:@"filter_freq_63hz"] floatValue];
      filterParameters.bypass = FALSE;

      filterParameters = unitEq.bands[2];
      filterParameters.filterType = AVAudioUnitEQFilterTypeParametric;
      filterParameters.frequency = 125;
      filterParameters.bandwidth = 1.0;
      filterParameters.gain = [[[filter_arr objectAtIndex:index_filter] objectForKey:@"filter_freq_125hz"] floatValue];
      filterParameters.bypass = FALSE;

      filterParameters = unitEq.bands[3];
      filterParameters.filterType = AVAudioUnitEQFilterTypeParametric;
      filterParameters.frequency = 250;
      filterParameters.bandwidth = 1.0;
      filterParameters.gain = [[[filter_arr objectAtIndex:index_filter] objectForKey:@"filter_freq_250hz"] floatValue];
      filterParameters.bypass = FALSE;

      filterParameters = unitEq.bands[4];
      filterParameters.filterType = AVAudioUnitEQFilterTypeParametric;
      filterParameters.frequency = 500;
      filterParameters.bandwidth = 1.0;
      filterParameters.gain = [[[filter_arr objectAtIndex:index_filter] objectForKey:@"filter_freq_500hz"] floatValue];
      filterParameters.bypass = FALSE;

      filterParameters = unitEq.bands[5];
      filterParameters.filterType = AVAudioUnitEQFilterTypeParametric;
      filterParameters.frequency = 1000;
      filterParameters.bandwidth = 1.0;
      filterParameters.gain = [[[filter_arr objectAtIndex:index_filter] objectForKey:@"filter_freq_1khz"] floatValue];
      filterParameters.bypass = FALSE;

      filterParameters = unitEq.bands[6];
      filterParameters.filterType = AVAudioUnitEQFilterTypeParametric;
      filterParameters.frequency = 2000;
      filterParameters.bandwidth = 1.0;
      filterParameters.gain = [[[filter_arr objectAtIndex:index_filter] objectForKey:@"filter_freq_2khz"] floatValue];
      filterParameters.bypass = FALSE;

      filterParameters = unitEq.bands[7];
      filterParameters.filterType = AVAudioUnitEQFilterTypeParametric;
      filterParameters.frequency = 4000;
      filterParameters.bandwidth = 1.0;
      filterParameters.gain =[[[filter_arr objectAtIndex:index_filter] objectForKey:@"filter_freq_4khz"] floatValue];
      filterParameters.bypass = FALSE;

      filterParameters = unitEq.bands[8];
      filterParameters.filterType = AVAudioUnitEQFilterTypeParametric;
      filterParameters.frequency = 8000;
      filterParameters.bandwidth = 1.0;
      filterParameters.gain = [[[filter_arr objectAtIndex:index_filter] objectForKey:@"filter_freq_8khz"] floatValue];
      filterParameters.bypass = FALSE;

      filterParameters = unitEq.bands[9];
      filterParameters.filterType = AVAudioUnitEQFilterTypeParametric;
      filterParameters.frequency = 16000;
      filterParameters.bandwidth = 1.0;
      filterParameters.gain =[[[filter_arr objectAtIndex:index_filter] objectForKey:@"filter_freq_16khz"] floatValue];
      filterParameters.bypass = FALSE;

      filterParameters = unitEq.bands[10];
      filterParameters.filterType = AVAudioUnitEQFilterTypeLowPass;
      filterParameters.frequency = 16857;
      filterParameters.bypass = FALSE;

      filterParameters = unitEq.bands[11];
      filterParameters.filterType = AVAudioUnitEQFilterTypeHighPass;
      filterParameters.frequency = 205;
      filterParameters.bypass = FALSE;

      [engine attachNode:unitEq];
}

audioFile = [[AVAudioFile alloc] initForReading:[NSURL fileURLWithPath:[NSString stringWithFormat:@"%@",[self audio_file_path:mp3FileName]]] error:&playerError];
            [self setupPlayer];
            [self setupEQ];

            AVAudioMixerNode *mixerNode = [engine mainMixerNode];
            [engine connect:audio_player_node to:unitEq format:audio_file.processingFormat];
            [engine connect:unitEq to:mixerNode format:audio_file.processingFormat];
</code>
These are samples it works fine. But how can i store the audio file with this same frequencies? and the audio file should be in mp3 format. In apple they only target the saving file as m4a.
Comment: I got answer from this link which i share the answer http://stackoverflow.com/questions/35660501/save-the-audio-file-in-the-background/35739362#35739362
Answer: try this, when you play the file, and you have to play the whole file again to get the effect saved.
<code>AVAudioFormat  * commonFormat = [[AVAudioFormat alloc] initWithCommonFormat:AVAudioPCMFormatFloat32 sampleRate:44100 channels:2 interleaved:NO];

AVAudioFile *outputFile = [[AVAudioFile alloc] initForWriting:[NSURL URLWithString:[self filePath1]] settings:commonFormat.settings error:&error];

[unitEq  installTapOnBus:0 bufferSize:4096 format:commonFormat block:^(AVAudioPCMBuffer *buffer, AVAudioTime *when)
 {

     if (outputFile.length < file.length)
     {//Let us know when to stop saving the file, otherwise saving infinitely
         NSError *error;

         NSAssert([outputFile writeFromBuffer:buffer error:&error], @"error writing buffer data to file, %@", [error localizedDescription]);

     }else{
         audioEngine = nil;
         [unitEq removeTapOnBus:0];//if we dont remove it, will keep on tapping infinitely

     }

 }
];
</code>
Comment: I tried this before but nothing execute after the installTapOnBus with no response. Let me try again.
Comment: Instead of `mixerNode` try `unitEq `
Comment: K friend Let me check..
Comment: Nope. It doesn't work. I will update the issue Please check it out and let me know the issue..


How to validate dynamic form in React Native?

Question: So, at first, i initialize empty state for required count ( if users gives input as 5 and submit i will be initialize the empty state with 5 state ),
Then by using this, i am looping to create dynamic form ( am using map ), now how to validate the form !
My initial state formation :
state = {usersDetails: []};

componentDidMount(){
    this.setInitialRow()
}

setInitialRows(){
        const seats = this.props.selectedSeats;
        let newRow = [];
        for(let i=0;i<seats.length;i+=1){
            newRow.push(
                {"seatName": seats[i].name,
                "passenger": [{
                    "name":"",
                    "gender": "",
                    }]
                })
        }
        this.setState({usersDetails: newRow})
    }

So from the above, i got my states and by using this am looping by this way:
 {this.state.usersDetails.map((s, i) =>{

             <TextInput
                    style={{ borderBottomWidth: 1, borderColor: '#f0eff4', height: 40 }}
                    placeholder="Enter Name"
                    onChangeText={(text) => this.handleNameChange(text,i)}
             />

             <TextInput
                    style={{ borderBottomWidth: 1, borderColor: '#f0eff4', height: 40 }}
                    placeholder="Enter Age"
                    onChangeText={(text) => this.handleAgeChange(text,i)}
             />
}

So , as per this i will be getting 5 pairs of above! Now how to validate the input fields on each pair ?
I tried this :
handleSubmit(){

        let row = this.state.usersDetails;

        function isNameEmpty(r){
            return r["passenger"][0].name === ''
        }
        function isAgeZero(r){
            return r["passenger"][0].age == 0
        }

        let isNameFail = row.find(isNameEmpty)
        let isAgeFail = row.find(isAgeZero)

        if(isNameFail || isAgeFail){
            // ToastAndroid.show('Please fill the Passenger Details',0.2)
        }else{
            console.log(row);
        }
    }

From this function, am getting toast warning ! But, how to display error message under the respective textInputs ?
Answer: This might help just to have an idea of how this will be done
class App extends Component {

  componentDidMount() {
    this.getDynamicInputs();
  }

  state = { userDetails: [], item_views: [], errorViews: [] };

  updateState = (index, value) => {
    const userDetails = [...this.state.userDetails]; //make a copy of array
    userDetails[index] = value;
    this.setState({ userDetails: userDetails });
  };

  getDynamicInputs() {
    const inputData = [];
    const errorViews = [];
    for (let i = 0; i < count; i++) {
      inputData.push(
       <>
        <TextInput
          key={i}
          style={{ borderBottomWidth: 1, borderColor: "#f0eff4", height: 40 }}
          placeholder="Enter Name"
          onChangeText={(val) => this.updateState(i, val)}
          value={this.state.userDetails[i]}
        />
        { this.state.errorViews[i] && this.state.errorViews[i].error ? <Text>Required Field</Text> : null}
      </>
      );
      errorViews.push( { error: false } );
    }
    this.setState({ item_views: inputData, errorViews: errorViews });
  }

  validate(){

   const errorViews = _.clone(this.state.errorViews);

   for (let i = 0; i < count; i++) {
     if( this.state.userDetails[i] === "" ){
       errorViews[i].error = true;
     }
   }
   this.setState({errorViews});
  }

  render() {
    console.log(this.state.userDetails);
    return <View style={styles.app}>
            {this.state.item_views}
           <Button onPress={() => this.validate()}>Validate</Button>
          </View>;
  }
}

const styles = StyleSheet.create({
  app: {
    flex: 1,
    backgroundColor: "pink"
  }
});

export default App;

Comment: I understand this, but according to your answer - the error message will be rendered immediately ! But, i want when this to happen when user tries to navigate by clicking on a button ! I should be showing error only when user clicks on next button ! hope you understand !
Comment: I got your point, please check I have updated my anwer


Converting SocketError value to a string message

Question: Having a SocketError value, how can it be converted to the respective string message?
Background and Example:
A failing call to e.g. Socket.Receive will throw a SocketException with e.g. Message "An existing connection was forcibly closed by the remote host" and SocketErrorCode == SocketError.ConnectionReset. However, calling Socket.ReceiveAsync will only give a SocketError == SocketError.ConnectionReset.
Having this SocketError.ConnectionReset (or any other value), how can I get the corresponding message?
Comment: I'd peek into the BCL source code to see how they obtain the message. None of the usual socket Win32 functions return a message.
Comment: SocketException.ErrorCode is an integer, for example 10053 which means WSAECONNABORTED, which can be found here: http://msdn.microsoft.com/en-us/library/windows/desktop/ms740668%28v=vs.85%29.aspx But I don't know of any machine-readable table of codes to texts, or stump of programming.
Answer: It can be done

using the FormatMessage API function (casting the SocketError to an int),
or simpler, by
new Win32Exception((int) mySocketError).Message


detector confidence

Question: the situation is as follows: Say, I am going to answer a multiple choice question based on suggestion of my two friends. One gives correct answer 60% percent of the times, the other gives correct answer 40% of the times. Is there any way I can answer a question correctly more than 60% of the time? (in a long run average leaving aside natural variability)
Comment: Are you assuming that the two "correctnesses" are independent of each other?
Comment: yes. and my supplementary concern is that if I always follow what the 60% guy tells me, will I not be amplifying the difference between their confidence.
Comment: You may need to describe the question a little more, for example, how many choices?  If it's more than a "True/False" question, e.g., "which of the following is correct: a, b, c", if one of the friends is wrong, can we assume they choose a wrong answer with equal probability from the set of wrong answers?  Also, I think with "True/False" questions you're doomed, but I'm just being intuitive when I state that.
Comment: Actually, I think you're stuck no matter what; when A (60% probability of being correct) and B (40% probability of being correct) disagree, you're more likely to be right by going with A, and when they agree, you're still going with A, so you always go with A.
Comment: It's based on Ryan Baker's course - big data in education. He goes past this point while explaining detectors.
Comment: I've seen this in either a home work or a quiz somewhere.
Answer: Intuitively, I figured that person B's didn't help, since there was no correlation.  However, I went back to Bays to solve it more rigorously and found an (at least interesting to me) result.
assume N choices, all of which are equally probable
P[ans is 1 | A says 1 AND B says 1] = P[ A says 1 AND B says 1 | ans is 1 ] P[ ans is 1 ] / P[ A says 1 and B says 1 ]
PP[ans is 1 | A says 1 AND B says 1] = (3/5) (2/5) (1/N) / ( (3/5) (2/5) (1/N) + (N-1) (1/N) (1/(N-1)) (2/5) (3/5) ), explanation below
PP[ ans is 1 | A says 1 AND B says 1] = 1 / 2
The other 1/2 chance is spread over all other (the incorrect) answers, but if there are only two choices (i.e. true/false), then in the event that A and B agree, you can guess either, it does not matter.  You have less confidence if B agrees.
*explanation of P[]
since A is right 3/5 and B is right 2/5,
P[ A says 1 AND B says 1 | ans is 1 ] = P[ A 1 | ans 1 ] P[ B 1 | ans 1 ] = (3/5) (2/5)
since the a priori probability of answer 1 is 1/N,
P[ A says 1 and B says 1 ] = P[ A says 1 AND B says 1 | ans is 1 ] P[ ans is 1 ] = (3/5) (2/5) (1/N)
P[ A says 1 and B says 1 ] = P[ A 1 and B 1 | ans 1 ] P[ ans 1 ] + P[ A 1 and B 1 | ans NOT 1 ] P[ ans NOT 1 ]
since there are N-1 ways for the answer to not be 1, each with a priori probability 1/N, but only a (1/(N-1)) chance to be wrong in such a way to suggest the answer is 1, and the probabilities of being wrong are A 2/5 and B 3/5,
P[ A says 1 and B says 1 ] = (3/5) (2/5) (1/N)  + (N-1) (1/N) (1/(N-1)) (2/5) (3/5)

detector confidence


Number format in Pentaho Data Integration

Question: I'm using Pentaho Data Integration Version: 22.214.171.124-28.
Steps used in transformation:

Table input (Connection: MySQL database)
Select values
Insert/ Update (Connection: MySQL database with the same data types as the input)

The input table has a column containing DOUBLE values.
I want to always keep two digits after the '.', examples:
<code>1587.657 -> 1587.65
32.5 -> 32.50
693 -> 693.00
0 -> 0.00
</code>
I tried to change the format in the Select values step selecting 0.00 in the meta-data format field. It works when I click on preview. The problem is when I check the output table nothing happens.
Any suggestions?
Comment: What data-type you have specified for the column and which data-type you have specified in meta-data tab ?
Comment: The data-types for both input and output tables are 'DOUBLE'.
In the meta-data type I selected 'Number'.
Answer: you have to match the meta data format in select value with the fields in the output, so you will get the result you expect
meta data format : Number (0.00)
output : Number (0.00)
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Are there any easier ways to update a site than following the official instructions?

Question: For tech people (like sys admins) the are the official instructions about How to update Drupal Core for how to update a site. But what if the user is inexperienced and just wants to maintain the site by installing security updates?
I can follow these steps myself but if I'm not available it's important that anyone (in the organization I'm volunteering for) can do it.
So, are there any easier ways to update a Drupal 7 site than following the official instructions?
Comment: Welcome to Drupal Answers! _Easier way_ is rather subjective. Drupal.org lists many way to update Drupal core; which one is easier for you depends from you, or from what the domain provider offers you. If you have SSH access to the site, that would make thing easier, if you know how to handle a site using a remote shell.
Comment: I don't think it's a good idea to let "anyone" do the updates. Whatever way you choose, it involves someone logging into the server, and uploading files there. Whether it's from Git or rsync or just plain FTP, I wouldn't trust a non-techy person to correctly navigate the server structure and copy the files to the correct place, and not mess anything up. Even if you choose to go with Drush, this requires at least a minimal knowledge of using the terminal and navigating through the file system through command line.
Answer: If you have access to ssh in your server install drush (drupal shell) http://docs.drush.org/en/master/install/
This will only need to be done once and and then it will be easy to apply drupal core updates from the command line
drush up drupal

or any other module updates
drush up views

But I would recommend applying ALL security patches at once (core and modules security updates) using
drush upc --security-only

all the above commands will do all the necessary actions as described in the instructions that you linked above and in case of a bad update the updates are reversed with error messages displayed.
To learn drush read https://www.ostraining.com/blog/drupal/drush/ but the installation instructions might be a little outdated. You can also learn more drush commands at drushcommands.com


Server 2012 R2 Run Program from Task Scheduler not running program

Question: I have a scheduled task that I am trying to run a program (a DB backup program).  For reasons unknown I am unable to actually get the program to run, even though the task log says everything was run complete on schedule.
What am I doing wrong?  I've changed settings, used a UNC path to the program, tried different admin accounts, used the NETWORK SERVICE account.  No success.  Seems like it has to do with security permissions to run the program, but I can't solve it.
Can someone help figure out how to run this program from Task Scheduler?  Thank you!
-OS: Server 2012 R2
-If I run the task while logged in (manually or on schedule while logged in), everything runs fine.
-The DB Backup Program has a log, but nothing in the log states anything even started when the task runs logged out.
-The DB Backup Program does not have a UI.
-The DB Back Program is intended to be run by the task scheduler and is run by other users around country successfully.
-The user set to run the task is a admin with full admin credentials.  The task was also attempted to be run by the local built-in admin with no result.
-The program, folder and parent folders all allow permission to the admin group.
General:
User: Admin Account
Run whether user is logged on or not
Run with highest privilages
Configure for: Vista, Server 2008
Triggers:
Daily, 3am, Enabled
Actions:
Start a program: "C:\Program Files (x86)\Rock Gym Pro\Backup.exe"
Conditions:
Start the task only if the computer is on AC Power
Stop if the computer switches to batter power
Settings:
Allow the task to be run on demand
Stop if the task runs longer than 3 days
If the running task does not end when requested, force it to stop
History:
3:00AM - Task Scheduler launch task "\RGP Backup" , instance "C:\Program Files (x86)\Rock Gym Pro\Backup.exe"  with process ID 3496.
3:00AM - Task Scheduler started "{206e1cd6-db27-49f7-b143-ca1228f59c74}" instance of the "\RGP Backup" task for user "DOMAIN\Admin".
3:00AM - Task Scheduler launched action "C:\Program Files (x86)\Rock Gym Pro\Backup.exe" in instance "{206e1cd6-db27-49f7-b143-ca1228f59c74}" of task "\RGP Backup".
3:00AM - Task Scheduler successfully completed task "\RGP Backup" , instance "{206e1cd6-db27-49f7-b143-ca1228f59c74}" , action "C:\Program Files (x86)\Rock Gym Pro\Backup.exe" with return code 0.
3:00AM - Task Scheduler successfully finished "{206e1cd6-db27-49f7-b143-ca1228f59c74}" instance of the "\RGP Backup" task for user "DOMAIN\Admin".
Comment: Did you give the Admin Account (that you describe above) "log on as a batch" and "log on locally" rights?
Comment: Still searching for an answer.

Right now I am running this task with the admin always logged in (machine locked) so that it can run daily.  It won't run unless I am logged in.
Comment: The Default Domain Controller GPO Policy is active and has both "Allow Log On Locally" and "Log On as Batch Job" include the BUILTIN\Administrators security group, which the Admin account is a member of.
Comment: Sorry for the long hiatus.  You mention the Default Domain Controller GPO, but unless this server that you're running the task on is a DC, then that won't apply to it; I'm assuming it is, but I have to check.  So, if it's not a DC, create a new GPO that grants these rights to the user in question and scope it to the server in question and try again.  Let me know when you get a chance to update/check.
Comment: The server is our DC.--I did end up solving this by having the task start a different program that accomplishes the same task.  The different program runs fine, so it is something with the Backup.exe program that does not work as expected under the task scheduler.
Answer: i´ve been trying hard to make similar software run OK when you choose:
Run whether user is logged on or not
It resulted with 2 different software (SyncBack and synctoy) that the problems were in both cases third party soft related problems (not soft problems but things to take into account).
As an example, if you created a Task to run:
"C:\Program Files (x86)\Rock Gym Pro\Backup.exe"
as domain\user1 , With some parameters lik -R "MyBackup", but you configured the task from another user like domain\administrator,
and also set "parameters like -R "MyBackup"" as administrator, software creates "MyBackup" config file under administrator folders (usr/administrator/appdata/roaming/...), so when the task executes as doman\user1 ,  the program search for "Mybackup" config file in user1 folder.
As result, no file exist in user1 appdata or whatever folders, because you never configured the software from user1, so nothing happen.
To solve this, you have to logon as that user, in the server, in order the folders be created, test the script from that user (If you want with scheduled task, with the "Run whether user is logged on or not" option activated,), and then you configure the task from administrator user and then set to run as user1.
That way when task run the software will find the "MyBackup" files and execute with no problem.
That was my problem, hard to find because there weren´t logs of this anywhere (or i couldn´t find them), just nothing happened when you run the task and finally says "Task Executed Successfuly".
Please let me know if i helped...Sorry my english im from Argentina.
Comment: Thank you.  The task was setup under the server admin, to be run under the server admin.  I did end up solving this by having the task start a different program that accomplishes the same task. The different program runs fine, so it is something with the Backup.exe program that does not work as expected under the task scheduler.
Comment: Thanks! for those who are having similar issue:
TL;DR: login first to the machine with the user that will be use to run the task scheduler
Answer: I guess that the task is running in case there is a user logged in, and when you change the task options to 'run whenever there is a logged-on user or not', it does not.
The history logs show that the task is running, but you cannot see it running or interact the user-interface of the task, since it is set to run even if there is no user logged in.
Tasks that have user-interface should be set to run only in case a user is logged on. (Who will interact the user interface if there is no user logged in?)
Probably, this is not the answer you expect to receive :-(, but I hope it clarifies the issue.
Comment: Thank you for the info.  The task does not have a user interface.  I have run this task on another server before without issue (actually about 900 different companies run this task in a similar fashion).  When I tried to run it on a Server 2012 machine, it says it runs, but will not unless I am logged in.  It is a MySQL backup function that runs via a Backup.exe program that is intended to be run in the background at night via task scheduler.

I'm at a loss as to why it won't run unless I leave the admin account logged in.
Answer: I did end up solving with a workaround, though not a direct solution.
The program C:\Program Files (x86)\Rock Gym Pro\Backup.exe apparently is a program that actually starts the program C:\Program Files (x86)\Rock Gym Pro\RockGymPro.exe with the argument /backup
So instead of starting the action that didn't work:
Start a program: "C:\Program Files (x86)\Rock Gym Pro\Backup.exe"
My new action is:
Start a program: "C:\Program Files (x86)\Rock Gym Pro\RockGymPro.exe /backup"
Everything works fine now.  No changes to any other settings or user accounts/pwds.
Answer: On the server running the script, DISABLE the Local Security Policy --> Security Options --> Network Access:  Do not allow storage of passwords and credentials for network authentication
This allowed our Scheduled task to control services on the remote servers in the environment.
Answer: I Have the same issue.
I schedule tasks using a fixed admin user.
The issue doesn't show for all tasks and i'm not able to see a pattern.
To have tasks starting regularely i worked around to let a RDP session open for the fixed admin user.


$\mathbb P(\sup_{t\in[0,1]}|W_t|\le1)$ for Brownian motion

Question: What is $\mathbb P(\sup_{t\in[0,1]}|W_t|\le1)$ for $W_t$ a Brownian motion? Without the absolute value, we have $\mathbb P(\sup_{t\in[0,1]}W_t\le c)=1-\sqrt{2/\pi}\int_c^\infty e^{-x^2/2}dx$ for all $c\ge0.$ (The proof I know of uses the strong Markov property.) However, I have no idea how to proceed when we have the absolute value.
Comment: This is equivalent to asking what is $\Bbb{P}(\tau \ge 1)$, where $\tau$ is the first time that $W_{t}$ hits $\pm 1$. See https://math.stackexchange.com/questions/907126/distribution-of-two-sided-boundary-stopping-time-of-brownian-motion for some information on this.
Answer: There is a nice solution to this using the reflection principle. To find the probability that $\sup_{t\in [0,1]} |W_t|\le 1$, let
\begin{align}
E&=\{|W_1|< 1\}
\\
E_u&=E\cap \{\sup_{t\in [0,1]} W_t>1\}
\\
E_d&=E\cap \{\inf_{t\in [0,1]} W_t<-1\}
\end{align}
In words, $E$ is the easier to calculate event that $W_t$ ends between $-1$ and $1$, while $E_u$ (resp. $E_d$) is the bad event whose probability we must subtract where $W_t$ crosses the upper (resp. lower) boundary sometime before $t=1$.
Fortunately, $\def\P{\mathbb P}\P(E_u)=\P(E_d)$ can be computed easily with the reflection principle. If you take a path in $E_u$, and reflect the portion of the path after it first hits the horizontal line of heigh one across that line, the the result is an arbitrary Brownian motion path $\hat W_t$ for which $1<\hat W_1<3$. Since this this process is reversible and probability preserving, we have $$\P(E_u)=\P(E_d)=\P(1<W_1<3)$$
Unfortunately, the answer is not as simple as
$$
 \P(E)-\P(E_u)-\P(E_d)
$$
because in subtracting out the bad events, the events where a path crosses both barriers has been doubly subtracted, so they must be added back in. These events come in two flavors: let
$$
E_{ud}=E\cap \{W_t \text{ first hits $1$, then later hits $-1$}\}\\
E_{du}=E\cap \{W_t \text{ first hits $-1$, then later hits $1$}\}
$$
Now, applying the reflection principle twice (see image for illustration of the $E_{ud}$ case), you can show
$$
\P(E_{ud})=\P(E_{du})=\P(3<W_1< 5)
$$
These two events must be added back in, so we currently are at
$$
\P(E)-\P(E_u)-\P(E_d)+\P(E_{ud})+\P(E_{du})
$$
But it does not stop there: the triply bad events $E_{udu}$ and $E_{dud}$ now must be subtracted out, and then the qudaruply subtracted events must be subtracted out, and so on to infinty. This is a variation of the princple of inclusion exclusion.
In summary, we have
$$
\boxed{\P\big(\sup_{t\in [0,1]} |W_t|\le 1\big)
=\P(|W_1|\le 1)+2\sum_{k\ge 1}(-1)^k\;\P(2k-1<W_1<2k+1)\;\;}
$$
Put another way, let $f(w)$ be a the unqiue function on the reals satisfying $f(w)=1$ for $-1<w\le 1$ and for all $w\in \mathbb R$, $f(w+2)=-f(w)$. Then
$$
\P\big(\sup_{t\in [0,1]} |W_1|\le 1\big)=\mathbb E[f(W_1)]=\int_{-\infty}^\infty f(x)\phi(x)\,dx
$$
where $\phi(x)$ is the pdf of $W_1$.
Comment: Shouldn't it be $\mathbb{P}(3<W_1<5)$ instead of $W_t$? And similarly in the boxed final equation, $W_1$ everywhere on the RHS instead of $W_t$?
Comment: Indeed it should. As a thank you, here's a cookie:
Comment: Thanks for the cookie! I am having difficulty in computing $\mathbb{P}(E_{ud})=\mathbb{P}(|W_1|\leq 1, \tau_1<\tau_{-1}\leq 1)$. But then I am not able to apply reflection principle twice to obtain the answer. Could you please help me on this?
Comment: Does the picture help?
Comment: Thank you very much! This was very helpful. I understand it now.


dual ISP firewall cluster in linux

Question: For the past couple of weeks i have been trying to figure out how to make firewall cluster, each having different ISP.
I have found few guides on how to do it with one ISP using technologies like keepalived and conntrackd. For example this one.
Is there a way to use keepalived for ISP failover? For example if ISP1 goes down the backup firewall takes over with ISP2? And if not what are the other options?
If there are any questions I'm happy to answer.
Answer: put the two ISPs on the same firewall/cluster.
play with route priority to define the main and backup ISP.
when an ISP goes down, the route is removed and the remaining ISP is used.
puting ISPs on separate instances complexify the failover.

dual ISP firewall cluster in linux


Queue for more producer (thread) single consumer (thread)

Question: I'm trying to find solution for more threads writing to a queue and a single thred is reading from it.
I found ConcurrentQueue it has TryDequeue(T) that is thread safe but I'm not sure if Enqueue(T) is thread safe too when writing to the queue from more threads.
Any idea?
Answer: Yes, the whole point of the concurrent collections is that they're thread-safe. It's fine to write to ConcurrentQueue<T> from multiple threads.
From the documentation:

All public and protected members of ConcurrentQueue<T> are thread-safe and may be used concurrently from multiple threads.


How can I calculate a Point $P \in E(a, b, \mathbb{F}_p)$ of order $3$

Question:
Let $$E(a, b, \mathbb{F}_{p} ) = y^2 = f(x) = x^3 + ax + b$$
  Find for $E(-4, 0, \mathbb{F}_{541} )$ all points of order $2$ and one point of order $3$.

In this case the points of order $2$ are easy to calculate, because these are the roots of polynom $f(x)$ (where $y = 0$).
$$x^3 - 4x = (x - 2)(x + 2)$$
Thus $2P :=\{ (0,\,0), (2,\,0), (-2,\,0)\}$
Now, how can I calculate a Point $P : 3P = \mathcal{O}$?
I only deduce that:
$$3P =  P + P + P \implies P + P = -P \implies 2P = -P$$
How can I continue here to find $P$?
Comment: The given polynomial has degree four in $\;x\;$ , but all your symbols and even tagging say "Elliptic Curves" ...how come?
Comment: $$x^3 - 4x = (x - 2)(x + 2)$$  ...how come?
Comment: @Darío   Ah, now we're talking. :)
Comment: @DonAntonio Sorry, it was a typing error :)
Comment: @DonAntonio $x^3 - 4x = x(x^2 - 4) \implies x((x-2)(x+2))$ because $\pm 2$ is root of $x^2 - 4$ then it is also from $x((x-2)(x+2)) = x^3 - 4x$. it is right?
Comment: Hmmm....I still am confused. According to your notation, $\;a=-4\,,\,b=0\;$ , so the equation should be $\;y^2=x^3-4x^2\;$ (which by the way has singular points...). Perhaps you meant $\;y^2=x^3+a\color{red}x+b\;$ ,and thus $\;a=-4,\,b=0\implies y^2=x^3-4x\;$ ?
Comment: @DonAntonio Sorry! I correct the error
Comment: Any ideas??????
Comment: @DonAntonio You were right to guess that there was a typo, but the curve $y^2 = x^4 + ax^2 + b$ is an elliptic curve, provided that the discriminant $16 b (-a^2 + 4 b)^2$ is nonzero (so the curve is nonsingular).  It's just not in Weierstrass form.
Comment: @Quasicoherent I don't think the usual definition makes room for that, though I agree that the algebraic geometry definition (irreducible curve of genus one) could apply. Anyway, and by the use of the coefficients, it was *almost sure* a cubic was due instead of a quartic or whatever in this case.
Answer: By eye: input in values for $\;x\;$  and find out, for example with the help of  Legendre's symbol and quadratic reciprocity, whether you have a solution. To actually find the solution may be way messier, but at least you'll already know whether there exists one or not. For example (note that $\;541=1\pmod4\;$):
$$x=3\implies 3^3-4\cdot3=15\;,\;\;\left(\frac{15}{541}\right)=\left(\frac3{541}\right)\left(\frac5{541}\right)=\left(\frac{541}3\right)\left(\frac{541}5\right)=$$
$$=\left(\frac13\right)\left(\frac15\right)=1\cdot1=1\implies \text{there exists}\;\;\sqrt{15}\pmod{541}$$
After some work (you can use the web for this), one finds $\;\sqrt{15}=\pm189\pmod{541}\;$  ,so we have the solutions  $\;(3,189),\,(3,-189)=(3,352)\;$
You can do the above for several values of $\;x\pmod{541}\;$ , but it is going to take a while...and then you have to check what their order in the group is carrying on the operation... You can use the web to make calculations easier, or you can even build a computer program to do the calculations, but it is going to be weary. Why do you think there's a point of order three, btw?
Answer: In general one can use division polynomials to compute the coordinates of the $n$-torsion points of an elliptic curve.  In this example, the third division polynomial is
$$
\psi_3 = 3x^4 + 517x^2 + 525 = 3(x^2 + 148)(x^2 + 385)
$$
and its roots give the $x$-coordinates of the $3$-torsion points.  Since $x^2 + 148$ and $x^2 + 385$ have no roots in $F = \mathbb{F}_{541}$, then there are no nontrivial $3$-torsion points defined over $F$.  Let $\alpha$ be a root of $x^2 + 148$ and let $K = F(\alpha) \cong \mathbb{F}_{541^2}$.  Then $\psi_3$ factors over $K$ as
$$
\psi_3 = 3(x - \alpha)(x + \alpha)(x - 178 \alpha)(x + 178 \alpha)
$$
so the $x$-coordinates of the $3$-torsion points are $\pm \alpha, \pm 178 \alpha$.  Unfortunately the $y$-coordinates of these points are not defined over $K$, so letting $\beta = \sqrt{\alpha^3 - 4\alpha}$ and $L = K(\beta) \cong \mathbb{F}_{541^4},$
we find that the nontrivial $3$-torsion points of $E$ are
$$
(\alpha, \pm \beta), \ (-\alpha, \pm 52 \beta), \ (178 \alpha, \pm 86 \beta), \ (-178\alpha, \pm 144\beta) \, .
$$
Another more elementary approach would be to use your equation $2P = -P$.  Writing $P = (x,y)$, then $-P = (x,-y)$.  The coordinates of $2P$ can also be expressed in terms of $x$ and $y$ (see here), and equating these with the coordinates of $-P$ will give you a system of equations to solve.  (I think the equation you get for the $x$-coordinate will be $\psi_3 = 0$, so the two approaches should be equivalent.)


Eclipse IDE showing error for Composite Primary Key classes in JPA

Question: I have an Entity class with composite PK as below:
using @Embeddable and @EmbeddedId annotations.
/** The primary key class for the uom_conversion database table. */
@Embeddable
public class UomConversionPK implements Serializable {
    private static final long serialVersionUID = 1L;

    @Column(name="product_id", insertable=false, updatable=false)
    private int productId;

    @Column(name="base_uom_id", insertable=false, updatable=false)
    private int baseUomId;

    @Column(name="to_unit_id", insertable=false, updatable=false)
    private int toUnitId;
    //getters, setters
}

And the Entity which is using it is:
/** The persistent class for the uom_conversion database table. */
@Entity
@Table(name="uom_conversion")
public class UomConversion implements Serializable {
    private static final long serialVersionUID = 1L;

    @EmbeddedId
    private UomConversionPK id;
}

Here Eclipse is displaying error: "UomConversionPK cannot be resolved to a type"

In another project I'm using Entities with composite PK without any errors.
Now this seems to be a JPA facet problem, wondering why Eclipse is not able to resolve UomConversionPK or am I doing something wrong ?
Comment: Are you importing `com.itsys.erp.server.dal.entities.UomConversionPK` in your `UonConversion` class?
Comment: Both UomConversion and UomConversionPK classes are in same package. And this error is occurring in other Entity classes as well - having composite PK.
Comment: Are you positive they're in the same package? Eclipse can see your `UomConversionPK` class, but it's not visible from within `UomConversion` without an explicit import, which suggests it's actually in a different package.
Answer: Well this error do occur sometimes for @EmbeddedId annotation, though not always, when creating JPA entities from tables using JPA Tools.
In my case this problem was not resolved until I set the following to Ignore and then back to Error:
Windows -> Preferences -> Java Persistence -> JPA -> Errors/Warnings -> Attribute -> Embedded ID classes should implement hashcode() and equals().
This error occurs even if Embeddable class do have hashcode() and equals() method implementation. May be this works for you as well.
Comment: Thanks, this worked and saved a lot of my time and effort! Seems this to be an eclipse bug.
Comment: BTW, it's under the Type field group for `@IdClass` (not embedded ID)...


Why is my pinky rotated towards the ring finger when it is on the fretboard?

Question:
As you can see the pinky is twisted towards the ring finger causing it to mute strings.
Is there a way to fix this?
Comment: Probably because your whole hand needs to be moved so your thumb is lower, moving all fingers to a better position. It shouldn't then be problematic. And why you need all four on the same string? I can't see why.
Comment: I am confused by your description as it appears that it is rotated away from the ring finger.
Comment: If you hold your hand in the same position without the guitar, you'll notice your pinky does the same thing. That's how our hands are built.
Answer: Your fingers radiate out from your wrist in fan-like lines...

Open your hand with your fingers relaxed, they should be slightly spaced apart, palm facing you. then bend your pinky over to lay flat against your palm. If your hand is like mine, your pinky should be more or less folded over its metacarpal bone and pointing to the center of your wrist at an angle relative to the middle finger.
The pinky is aligned at an angle to the wrist that's why it leans over.
Comment: I've seen other people not having this issue and I probably tried every fretting hand positions, but it's still muting when I reach out far on 4-6th strings

is this just a genetic thing that made my pinky more rotated than the other people's pinky? are there exercices to make my pinky less "rotated" when it's bent?
Comment: @MichaelXu, can you give string/fret numbers for what your fingering with pinky and then what is getting muted by mistake. Not clear if you mean the pinky note is muted or another string/fret.
Comment: it's the other string behind the pinky's note
Comment: OK, then I agree with Tim's comment above, about lowering your thumb to get more in the middle of the back of the neck. Just look up proper hand position, you will see what to do. You need to get the part of you palm, where the finger start, up a bit from the neck, with a sort of arch to the whole hand. Also, the whitening of your fingernail tips seem to show you're squeezing really hard. You shouldn't need to. When you get the hand position better, you shouldn't need to squeeze hard and will get less unintended muting.
Answer: There are a few things I notice in your picture:
Your thumb is behind your index finger - move it so it's more in line with your middle finger.
It looks like the bottom of the neck is really close to the palm of your hand right at the base of your fingers.  You need to arch your hand more by placing your thumb lower on the back of the neck.
Finally, you want to have your wrist straighter - when the wrist is bent you limit your reach.
I'm going to attach a couple of pictures so you can see - my thumb is below the halfway point of the back of the neck, and you can see how much clearance there is from my palm.  My wrist is bent in these, but it's just because I'm alone and holding
Answer: You may just be born that way.  Everyone's fingers are different. A little off-topic, I happened to have injured my pinky a long time ago by rupturing the pulley and dislocating my finger.  I was not being smart and carried something way too heavy in my hand.  Now it looks almost exactly like yours and it used to be straight.  My advise is to not worry about it and play like natural for you.  You may need to adjust your thumb position a little bit or use your ring finger more. A side story, I was in a guitar store one day and met a man who had chopped off his two middle fingers the week he was supposed to travel out west to play professionally.  I have a soft spot for anyone that has had a hand injury and plays an instrument, especially that guy.  Keep playing and doing what you love!
Comment: That story sounds like Tony Iommi from Black Sabbath.
Comment: I thought of the same thing when he told me that haha
Answer: A little rotation is natural and should not be viewed a something to "fix" unless it is impeding your development and technique.
Many electric guitarists play with the fingers a little flatter, on the pad rather than on the tip.  For classical this approach would not work since you typically want to hear the string just under your finger and playing flat fingered will dampen the adjacent string.
Based on the picture It does seem that your hand is cramped a little.  Someone else has suggestion that your thumb is too close to the index finger.  It is hard to see the angle of your wrist but that could also be too bent, causing you to curl the fingers more than you need to.  Play with the arm posture, and the thumb placement.  If you don't care about classical technique try playing flat fingered.  Tiny adjustments until you get a goo comfortable feel.  But the pinky will never be completely parallel to the other fingers and perpendicular to the fret board.  That may be an unreasonable expectation.
And clip your finger nails.  They are like daggers.


What are the most common uses for stereo channels on a mixer?

Question: Obviously, by definition, a stereo source can be plugged into a stereo channel.  However, because I've never had a reason do that, I can't see the need to plug in stereo sources as common enough to warrant the number of stereo channels on so many mixers.
So I assume that there are uses for these channels that I am just not seeing (or I'm too narrow sighted to see the usefulness of being able to plug a stereo source into a single channel of a mixer).
What are the most common uses for a mixer's stereo channels?
This question also applies to stereo effect returns (which I also can't see a common use for because I neither use stereo effects nor notice others often using them).
Edit: Some of the answers and comments seem to be taking umbrage at the second sentence of the first paragraph. The sentence was not meant to suggest that I think that no valid use cases exist outside of mine.  I recognize that my usage is keeping me from seeing other use cases, which is a shortcoming of my own and the reason that I posted this question.  I apologize for inadvertently wording the question so provocatively.
Edit 2: I titled this question poorly (I'm hesitant to change it now since it has got so many views), but the intent was to ask "What are the benefits of a stereo mixer channel over 2 mono mixer channels?"  I seem to have thought that simply asking for a list of uses for stereo channels would make those benefits clear, but it's probably more helpful to receive answers to the underlying question directly.
Comment: As you said, you've "never had a reason do that". But there are lots of instruments that provide stereo output, and lots of effect pedals too. Many stand-alone electronic instruments have stereo outputs, such as synthesizers, drum sequencers, but also portable workstations (eg. Akai MPC). For all those cases, having 2 separate channels is not only pointless, but also a distraction, if not even a problem: not only you need to limit inputs for instruments that have stereo outputs if you don't have enough channels, but you also need *two* separate channels to consider for *each* stereo input.
Comment: I'm not sure I'm understanding what you're asking, but English is not my native language so I might be *lost in translation*. What do you mean by "need to warrant the number of stereo channels"?
Comment: In other words, if the main function of stereo channels is not commonly used, then it seems like the channels themselves should not be so commonly found.  I realize that my premise--stereo sources are not commonly used--might be incorrect.
Comment: Edited the OP, hopefully clarified that sentence.
Comment: Not necessarily pointless, the other side of that is one might prefer the flexibility of two mono channels with the ability to group them if needed.  A stereo channel can only be used as that, two mono channels can be used independently.
Comment: Again, as you said, "one ***might*** prefer". If you want, and if you can, nothing and nobody prevent you to use two separate channels. Take for instance a very possible band setup: drums (at least 6-8 channels), bass, percussions (at least 2), rhythm guitar, lead guitar, lead vocals, backing vocals (usually, 1 to 3); you've already got 12-16 channels. Then you realize that there are keyboards (each keyboard has its own sound, and usually there are at least two) and that the lead guitar has a stereo output. Supposing you only have a 16 bank mixer, what would you sacrifice?
Comment: In the case above, you get at least 3 stereo inputs (4, if you include pan mics for the drums), for which having separate controls doesn't usually make a lot of sense. From an 8-people band, you could have from 12 to 22 channels. Yes, having total control over the overall mix is certainly a good thing, but is it effective? Vendors *must* provide a common ground for all possible situations, and providing stereo inputs is a *huge* benefit that impacts on user choice, not only economically but also practically. If I've to mix 8 stereo keyboards, having 16 channels instead of 8 is a nightmare.
Comment: Thanks for sharing your perspective and for all the helpful insight.
Comment: I've done a lot of live sound work, and I literally have never been to a gig where they didn't want either a DJ or a cd playing before the show, between acts etc. I've also done some radio work, and even the most talky program wants ads and theme music playing in. In short, stereo channels are used a lot.
Answer: It's a common misconception that the point of stereo speakers is mostly to be able to pan individual signals to have different strength in the two output channels and thus achieve "locations in the stereo spectrum". Sure that can be done, and in the 60s it was sometimes done extremely, but it was neither the original idea nor is it considered good practice today to pan mono signals strongly to one side (except as a special effect).
The main point of stereo is to create a sense of immersion. Our ears are actually not very picky with differences in signal strength (3 dB more doesn't sound a lot louder, but is actually twice as much power!), but they are very sensitive to phase relations. In particular, if every part of the mix you're hearing has the same phase relation between both ears, the ears notice that and interpret it as: the entire ensemble is crammed together at a single spot in the room, or very far away. This is so even if there is some panning going on and there are actually multiple PA speakers broadcasting the signal.
Acoustic instruments spread in a concert hall without amplification will have lots of different reflections, timing differences etc. going on. There are also phase differences between the different parts of a single instrument. That's why many instruments, perhaps most notably piano, benefit so much from stereo microphoning: if you listen to both channels of a stereo piano recording, you may well wonder what's the point, because each individually actually sounds very similar to the other. But pan them to 100% L/R and listen to them together and it feels like the instrument is suddenly much bigger and/or closer, without needing to be any louder. Even for essentially "monopole" instruments like brass, the phase effects of the room come into play, which is why at least reverb should almost always be in stereo: mono reverb sounds more like the instrument has some kind of sympathetic strings on it, rather than an actual room where you're together with the musicians.
If the channels are mixed together, phase differences can actually cause problems (some frequencies may be cancelled). In a studio production, it can make sense to mix the stereo image to adjust width, but live there's little point to either having the channels anything but 100% L/R, or applying different EQ to them, so then a stereo channel works just as well as two mono channels, while being easier to control and taking up less space.
Comment: To add to this great answer, it is almost impossible to make two (analogue) filters exactly the same, and hence the phase might be shifted differently if the stereo channel is EQ'ed. That's why the EQ sections are often rudimentary for stereo channels, even in high-end mixers. Avoid using the parametric EQ if the stereo signal is routed through two fully panned mono channels (unless you have to...).
Comment: @user1079505 I was mostly talking about sampled instruments and effects. The stereo microphoning would then have been done in the studio (and in the studio you typically record into an audio interface rather than a mixer, and possibly use outboard mic preamps which can just as well plug into a stereo channel). IMO it seldom makes sense to set up proper stereo pairs for live amplification, but when you do it then yes, you'd generally use two mono inputs. (Which can with a digital mixer anyway be linked and thus used as a single stereo channel.)
Comment: I think this is leaving out the important fact that many stereo sources that would be plugged into a stereo mixer channel are not hard panned at the source and/or have internal panning controls. Effect returns are the primary example (normally I would expect keyboards to come through a DI box into separate adjacent XLR inputs). Another thing is that mono sources can be enhanced with stereo effects processing, which means wider penning on the effect returns can often complement a centrally panned mono source.
Comment: @ToddWilcox what is "hard-panned at the source" supposed to mean? In case of synths, the two channels will typically be two different channels of the signal processing chain, e.g. one with the chorus' variable-delay on it, the other not. In case of sampled instruments, they will correspond exactly to the channels of whatever was sampled – in case of piano, the mics probably _will_ have been hard-panned there. In case of a reverb FX-return, they will also correspond to the hard-panned virtual mics of the IR. In many cases, anything but 100% L/R panning for such sources will cause phase issues.
Comment: What I mean is that the output of a stereo reverberator is going to have content all across the sound field. Same with sampled instruments. Like a piano sample won't have the highest key 100% right, and middle C will be in the middle. Whatever. Edit your answer or don't. I just wanted to contribute my experience with why using stereo inputs on mixers is viable for most line level stereo sources.
Comment: @ToddWilcox but that's basically the whole point of my answer. The very concept of a "sound field" measured by pan-values of individual mono sources is wrong.
Comment: I'm sure you're right
Comment: @user2821 yes. Fortunately, stereo sources usually _need_ any narrow-band or otherwise parametric fine tuning, like microphone channels often do! And of course, this isn't a problem at all with digital EQs; those can be made to behave literally identical on any number of channels.
Comment: You mention stereo microphoning , but the mic inputs on mixers are typically only on mono channels only, so connecting two mics requires using two channels.
Answer: Even though you don't use them, there are plenty of 'stereo' sources (I'll mention  the difference between most of these and a true stereo image later) and plenty of effects with 'stereo' outputs, often derived from a mono input.  A sampled piano may pan low notes to the left, high notes to the right. A guitar effects pedal might send a different delay to each side of its output.  And there are many more ways in which 'stereo' outputs are used to give an effect of spaciousness.
Maybe you deal mostly with PA systems, filling large areas with the sound from microphones?   In many spaces it's arguable that 'stereo' is unnecessary, ever counter-productive.  It's enough of a job to achieve full coverage, let alone worrying about giving everyone in the audience a well-balanced 'stereo' experience.  Even in the simple  case of a pair of speakers, one each side of the stave, only a small middle section of the audience will hear both speakers equally.  Most will get more from one side than the other.
Why am I fussing over what 'stereo' actually is?  Well, listen to a quality broadcast of a classical concert.  The aim will be to create a 3-dimensional 'solid' (and that's what 'stereo' means) image of the entire orchestra.  Surprisingly, perhaps, this IS achievable with just two channels.  It's a wonderful experience, but not a part of most of today's multi-tracked music production.
Then there's all the clever stuff that can be done with binaural recordings, specifically designed for listening to through headphones.
https://en.wikipedia.org/wiki/Stereophonic_sound
Comment: Yes! In fact I would go a bit further and say that even in today's multi-tracked music production, and even with live PA systems, the kind of effects that classical concert recordings adjust so carefully are still important and the main reason for stereo.
Answer: There are many stereo sources that can benefit from stereo channels on a mixing board. Among them are keyboards with a stereo out, computers/software samplers/synths, any instrument going through an effect or multi effect with a stereo out and also any stereo audio source that might be incorporated into a performance, such as pre-recorded backing tracks.
That being said, providing stereo channels is also a way for a manufacturer to beef up the number of available inputs without raising the number of channel preamps provided. For example, a 12 input board may have 4 mono inputs with preamps and 4 pairs of stereo inputs which usually don't have preamps. You end up with 12 inputs but only 8 channels.
Bottom line, I think it's a combination of convenience and economics.
Comment: @cheaterpushups yes. Home usage, especially nowadays, means using electronic instruments that already provide stereo outputs. Most electronic musicians have lots of instruments in their setups that have stereo outputs, and if you're also mixing on your own having ***half*** of the controls means that you can better focus on music making than about mixing. Consider the simple case of panning: if you've 2 controls for the "stereo image", you usually need two hands, even for a simple side-by-side panning. Also, having 2 separate chans from a stereo input is ***not*** the same as a stereo channel.
Comment: @SteveMansfield Thanks, I think that's the idea!
Comment: I've noticed home use mixers with, for example, 4 stereo channels and 2 mono channels.  Is it fairly common to be using more stereo than mono sources?
Comment: It probably depends on the type of music you make, the instruments you play, how many of you there are, whether you're recording or rehearsing or performing… — but I suspect stereo sources are pretty common. For example, my home 'studio' has several keyboards, synth modules, a guitar FX unit, a bass FX unit… all stereo. The only mono source is a mic (which doesn't go through my mixer anyway).
Comment: This should be the accepted answer as it actually answers the question!
Answer: Well, assuming you have a stereo PA arrangement, obvious stereo sources are keyboards (which have both stereo sampled sounds and stereo effects) and other virtual instruments.  The most obvious stereo effect return is reverb since a spatial impression of reverb really warrants separate channels.  Another effect with an obvious need for stereo effect returns is a Leslie emulator since Leslie speakers have a complex spatial response.
Answer: It is quite common for presenters to use stereo sources when the mixer is used for presentations in schools, halls, and businesses.  Often presenters will play pre-recorded songs or videos which are in stereo.  And while I recognize that it is unlikely they'd need 4 channels for this, it's equally unlikely that they'd need 12 channels for mics.
Many smaller systems like the Fender PD250 output sound in stereo, as well.
Answer: Common uses are naturally stereo sources such as: synthesizers, effect returns, music players ("mp3 players").
You seem to ask "why do other people have these uses even though I and my friends don't". Maybe it's due to the kind of music you make.
But there's another side to the question: what's the point of having a single stereo channel instead of 2 x mono, one panned to each side? With a combined stereo channel, you can control the volume level, EQ, sends etc. exactly equally for both sides at the same time. You only turn ONE single knob for each adjustment, ONE single fader for level, ONE single mute button, etc. and the exact same thing is applied to both sides of the stereo channel. This is both handy and saves components, but in addition to that, exactly equal processsing is required for retaining the stereo image. And since these are for line-level sources, mic preamps can safely be left out from those channels without affecting general usability.
Answer: To an extent, it will be dependent on what the mixer will be used for. Mixing, obviously, but into a P.A. will often have different requirements from mixing into a recording desk - its other main use.
Often, the sound balance from P.A. speakers will come out as mono - at least that way, wherever the audience is in the room, all will be receiving the same mix. With that in mind, having stereo inputs seems superfluous. But, if the output from whatever instrument is being mixed is stereo, and there are two inputs for that channel, it makes sense that left and right both get fed into that channel.
In other P.A. situations, stereo can be used - as stereo. When I have the chance to use my own gear at a gig, I'll set up so the sound from keys is stereo. Leslie panning can then be heard, as can other effects. The audience may not notice (or care!), but I love it ! Without the facility, those effects aren't possible.
Mics are generally mono - one mouth producing one voice into one channel. O.k., that can still be panned left or right, but, as you say, there's no need for stereo channels for that. But, from a convenience and economic point of view, sometimes having another channel 'free' for another mic or mono instrument is a bonus.
For inputting to a recording desk, stereo has many advantages over mono. An awful lot of effects are now stereo, even when, say, input is a mono guitar. Here, a mono input robs us of the opportunities to pan. In my studio, there are at least half a dozen keyboards up (let alone modules) and ready at any time, all stereo, all stereo inputted, and without all the extra stereo inputs on mixers, I'd be setting up a heck of a lot more mono mixers, which would then mean a lot more knob twiddling, too.
So, since adding some extra channels to an already stereo mixer is fairly inexpensive, why not?
Answer: Depending on the application, there are many reasons for stereo inputs. One example is stereo sources like iPods, radio feeds, etc. It can also be used to input stereo instruments, keyboards being the best example. It could also include mono instruments that are running through stereo effects.
In addition, stereo channels are a cheap way to add additional channels because they don't require an additional faders or other controls.
Answer: For keyboardists, almost everything is stereo. A pair of two-tier stacks eats up 4 stereo channels without breaking a sweat. (How's that for a mixed metaphor?)
Also, I get the impression that in many cases it allows a mixer manufacturer to claim lots of input channels without having to build in a lot of (costly and breakable) faders.  Most low-end mixers I've seen with stereo inputs omit the EQ, and effects controls on those channels.


Does $\operatorname{rank}\left(A^n\right)=\operatorname{rank}\left(B^n\right)$ imply $\operatorname{rank}(A)=\operatorname{rank}(B)$

Question: Let $A,B$ be two $d\times d$ matrices, and $n\in\Bbb N$ s.t. $A^n,B^n\neq 0$. If $\operatorname{rank}\left(A^n\right)=\operatorname{rank}\left(B^n\right)$, then when can we conclude that $\operatorname{rank}(A)=\operatorname{rank}(B)$?
Thanks.
Comment: yet again, that is explicitly excluded.
Comment: Any nilpotent matrix satisfies $A^n =0$ for some $n$. So pick any two different nilpotent matrices.
Answer: Let $A = \begin{bmatrix}0 & 1 & 0 & 0 \\ 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 1 \end{bmatrix}$
and $B = \begin{bmatrix}0 & 0 & 0 & 0 \\ 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 1 \end{bmatrix}$. Then $\text{rank}(A^3) = \text{rank}(B^3)=1$ but $\text{rank}(A) \ne \text{rank}(B)$.

Edit after user26857's comment:
By the rank-nullity theorem, we can think about the nullities of these matrices instead of their ranks.
It suffices to think the about the Jordan decomposition of a matrix $A$. Suppose the Jordan blocks corresponding to eigenvalue $0$ have sizes $m_1, \ldots, m_K$. Then $K$ is the nullity of the matrix. More generally, can check that the nullity of $A^n$ is $$\text{nullity}(A) = \min\{n, m_1\} + \min\{n, m_2\} + \cdots + \min\{n, m_K\}.$$
If we let $m'_1, \ldots, m'_{K'}$ denote the sizes of the Jordan blocks of $B$ corresponding to eigenvalue $0$, then we have the following.
$$\text{nullity}(A) = \text{nullity}(B) \iff K = K' \text{ (same number of Jordan blocks for eigenvalue $0$)}$$
$$\text{nullity}(A^n) = \text{nullity}(B^n) \iff \sum_{k=1}^K \min\{n, m_k\} = \sum_{k=1}^{K'} \min\{n, m'_k\}.$$
Not sure if this is helpful to the OP or not...
Comment: @user26857 Thanks, added a few more comments
Comment: Actually the question is "when can we conclude that $\operatorname{rank}(A)=\operatorname{rank}(B)$?". But I can admit that this is too general and probably hard to find out some reasonable conditions.
Comment: Thanks! This is helpful, although not the kind of 'slick proof' I was expecting...


CSS: How add hover effect to ::slotted in Shadow DOM root and

Question: I have have shadow DOM element,

     <slot name="item">   </slot>

I wanted to have hover effect to "Icon" how to write hover effect for slot element ?
Comment: slotted content is styled in **lightDOM** See: https://stackoverflow.com/questions/61626493/slotted-css-selector-for-nested-children-in-shadowdom-slot/61631668#61631668
Comment: Note: your code is not the result of slotting content; slotted content is **reflected** to a ```` NOT copied or moved
Answer: This only works with css in the Shadow Dom.
I found it here: https://codepen.io/smspp/pen/EzYGpa
::slotted(*:hover)


How to drop column(s) from multiple data frames (number can vary) using loops in R

Question: Assume there are multiple data.frames Sales_1, Sales_2, ..., Sales_max where _max can be dynamic...
all these data sets have some common columns like "ID" which I need to drop!!
Can this be done using a for loop in R?
maybe something like this
for(i in 1:max){
Sales_**i**$ID=NULL #basically I am looking to resolve the variable as data frame name while using the loop
}

Comment: Possible duplicate of [How to remove certain columns in multiple data frames in R?](https://stackoverflow.com/questions/27399814/how-to-remove-certain-columns-in-multiple-data-frames-in-r)
Answer: If you have all data.frames in a list. Then you can use lapply, regardless of the datafram name:
myNames <- c("john", "fred", "steph","joe", "val")
sales   <- c(1000, 2000, 3000, 4000, 2000)

# Start with some example data:
mynrow <- 6
Sales_1 <- data.frame(ID=1:mynrow, seller=sample(myNames, mynrow, TRUE), amount = sample(sales, mynrow, TRUE))
Sales_2 <- data.frame(ID=1:mynrow, seller=sample(myNames, mynrow, TRUE), amount = sample(sales, mynrow, TRUE))
Sales_3 <- data.frame(ID=1:mynrow, seller=sample(myNames, mynrow, TRUE), amount = sample(sales, mynrow, TRUE))

Sales <- list(Sales_1, Sales_2, Sales_3)

lapply(Sales, function(x) x[-1])

Comment: Absolutely the right way to go about this in my humble opinion. Working with separate datasets like `Sales_1` - `Sales_(n)` makes for complicated code later.
Answer: This will do it:
# Start with some example data:
Sales_1 <- data.frame(id=c(1,2,3), name=c("john", "fred", "steph"))
Sales_2 <- data.frame(id=c(4,2,1), name=c("joe", "val", "kerry"))
Sales_3 <- data.frame(id=c(1,2,3), name=c("jane", "aaron", "don"))

numberOfSalesDataframes <- 3 # Set this to the number of Sales dataframes you have

for (i in 1:numberOfSalesDataframes) {

  # These two lines of code will remove column "id"
  command <- paste0("Sales_", i, "$id", "  <- NULL")
  eval(parse(text=command))

  # Copy the two lines of code from above to remove another column, and so on..
  # command <- paste0("Sales_", i, "$another_column_you_want_to_remove", "  <- NULL")
  # eval(parse(text=command))

}

Sales_1
Sales_2
Sales_3

Comment: namin object `max` is a very bad practice
Comment: @PoGibas great point. Edited and fixed
Comment: man this worked ... thanks a lot .. you are a savior I was searching for a long time for this solution...
Comment: @RishikeshBayya no problems. Please accept the answer so the question does not clog up the unanswered section
Answer: You can use eval and substitute as follows
Sales_1 <- data.frame(id = 1:3, other_stuff = letters[1:3])
Sales_2 <- data.frame(id = 4:6, other_stuff = letters[4:6])
Sales_3 <- data.frame(id=  7:9, other_stuff = letters[7:9])

dfs <- sapply(ls()[grepl("^Sales\\_\\d+$", ls())], as.symbol)
for(sym in dfs)
  eval(substitute(x$id <- NULL, list(x = sym)))

Sales_1
#R   other_stuff
#R 1           a
#R 2           b
#R 3           c
Sales_2
#R   other_stuff
#R 1           d
#R 2           e
#R 3           f
Sales_3
#R   other_stuff
#R 1           g
#R 2           h
#R 3           i


Como fazer uma meta description e meta keywords única, em um documento PHP que só tem 1 header pra todas as páginas

Question: Recentemente eu aprendi como deixar um site estático um pouco dinâmico, colocando o footer e header em um único documento para todas as páginas. Mas pra cada página eu preciso de uma meta description e meta keywords diferentes. Como faço isso?
O script que eu usei:
<?php
function carrega_pagina(){
(isset($_GET['p'])) ? $pagina = $_GET['p'] : $pagina = 'home';
if(file_exists('page_'.$pagina.'.php')):
    require_once('page_'.$pagina.'.php');
else:
    require_once('page_home.php');
endif;
}

function gera_titulos(){
(isset($_GET['p'])) ? $pagina = $_GET['p'] : $pagina = 'home';
switch ($pagina):

    case 'contato':
        $titulo = 'Contato - BizarroNEWS';
        break;

    case 'privacidade':
        $titulo = 'Privacidade | BizarroNEWS';
        break;

    case 'ultimasnoticias':
        $titulo = 'Últimas Notícias | BizarroNEWS';
        break;

    default:
        $titulo = 'BizarroNEWS | Home';
        break;

endswitch;
return $titulo;
}

Documento index.php:
<?php
require_once('funcoes.php');
require_once('header.php');
carrega_pagina();
require_once('footer.php');
?>

Eu tenho 3 documentos chamados header.php, index.php e footer.php.
O header.php so tem o header da página, footer.php só tem o footer, e o index.php só tem o comando PHP que está chamando o arquivo funcoes.php (primeiro script que colei na pergunta), header.php e footer.php.
E tenho mais documentos chamados page_home.php, page_ultimasnoticias.php, page_contato.php e page_privacidade. Dentro deles só o conteudo da página, sem footer e sem header.
Comment: Sim, é relevante, caso contrário não teremos a menor noção do que você fez e como modificar para atender sua necessidade.
Comment: @AndersonCarlosWoss Atualizei a pergunta.
Comment: @DiogenesSilva como a página está sendo carregada na URL? Assim? `http://127.0.0.1/pagina.php`
Comment: @JorgeMatheus Eu to usando o server Apache. O URL fica assim: http://localhost/site/?p=home, http://localhost/site/?p=contato...etc
Comment: Se você já tem essa lógica toda para mudar o título, qual a dificuldade de fazer exatamente a mesma coisa para os META? `$titulo="contato"; $keywords="formulário, fale conosco, SAC... $description="Uma linda e aconchegante página de contato, com todos os campos e botões que você espera"`
Comment: @Bacco Não é bem isso, eu não sei colocar uma META description e keywords unica para cada página, sendo que eu só tenho 1 header para todas.
Comment: Se você muda o título, está mudando o header. Basta aplicar a mesma lógica nas tags meta. (o título faz parte do header).
Answer: Basta aproveitar o que já tem, aliais o seu gera_titulos esta mais para um get_titulos, quero dizer, seria mais interessante se a propria função gerasse tudo, até o o HTML, e sinceramente nem tem necessidade de separar em funções, afinal só vai usar uma vez
exemplo seria algo como:

funcoes.php (para qualquer coisa que for usar, não precisa das funções que você criou)
init.php (vai conter o que checa as paginas e cria as variaveis)
header.php (vai gerar o metas e title)
footer.php (vai gerar o rodapé)

init.php
<?php

$pagina = empty($_GET['p']) ? 'home' : $_GET['p'];

switch ($pagina):
    case 'contato':
        $titulo = 'Contato - BizarroNEWS';
        $keywords = 'Fale Conosco, Localização, Endereço';
        $descricao = 'Formulário de contato, mapa e telefones';
        break;

    case 'privacidade':
        $titulo = 'Privacidade | BizarroNEWS';
        $keywords = 'GDPR, Privacy, Privacidade, Proteção de dados';
        $descricao = 'Entenda seus direitos e como usamos seus dados';
        break;

    case 'ultimasnoticias':
        $titulo = 'Últimas Notícias | BizarroNEWS';
        $keywords = 'News, Newsfeed, Notícias';
        $descricao = 'Saiba tudo que acontece no Bizarro';
        break;

    default:
        $titulo = 'BizarroNEWS | Home';
        $keywords = '';
        $descricao = 'Home page';
        $pagina = 'home';
endswitch;

header.php

<title><?php echo $titulo; ?></title>
<meta name="keywords" content="<?php echo $keywords; ?>">
<meta name="description" content="<?php echo $descricao; ?>">

index.php:
<?php
require_once 'init.php';
require_once 'funcoes.php';
require_once 'header.php';
require_once 'page_' . $pagina . '.php';
require_once 'footer.php';

Claro que como você vai receber tudo no index.php você poderia reduzir bem as coisas, afinal são coisas simples, não precisa destes includes todos, muita coisa poderia ser resolvida ali no index.php mesmo, por exemplo:
index.php
<?php

$pagina = empty($_GET['p']) ? 'home' : $_GET['p'];

switch ($pagina):
    case 'contato':
        $titulo = 'Contato - BizarroNEWS';
        $keywords = 'Fale Conosco, Localização, Endereço';
        $descricao = 'Formulário de contato, mapa e telefones';
        break;

    case 'privacidade':
        $titulo = 'Privacidade | BizarroNEWS';
        $keywords = 'GDPR, Privacy, Privacidade, Proteção de dados';
        $descricao = 'Entenda seus direitos e como usamos seus dados';
        break;

    case 'ultimasnoticias':
        $titulo = 'Últimas Notícias | BizarroNEWS';
        $keywords = 'News, Newsfeed, Notícias';
        $descricao = 'Saiba tudo que acontece no Bizarro';
        break;

    default:
        $titulo = 'BizarroNEWS | Home';
        $keywords = '';
        $descricao = 'Home page';
        $pagina = 'home';
endswitch;
?>

<title><?php echo $titulo; ?></title>
<meta name="keywords" content="<?php echo $keywords; ?>">
<meta name="description" content="<?php echo $descricao; ?>">

<?php require_once 'page_' . $pagina . '.php'; ?>

Rodapé

Comment: @DiogenesSilva editei a resposta do colega Guilherme acima, veja se ficou mais fácil de entender agora a solução
Comment: O problema é que eu não sei como colocar uma description e keyword unica para cada página, sendo que eu só tenho 1 header pra todas as páginas. Eu preciso saber como colocar essas META Tags em cada página. E eu vou ter que fazer isso sempre, sendo que por dia eu crio umas 2 páginas para o meu site de noticias. Obs: A variavel no documento header.php deveria se chamar $titulo, assim como está no init.php.
Comment: @Bacco Eu vi, eu consigo alterar o valor delas usando as variaveis, mas eu não sei como colocar um comando que gere essas meta tags únicamente para cada página. Eu sou do tipo que aprende fazendo, e ainda não aprende a fazer esse tipo de coisa, me desculpe.
Comment: Show! +1 pela elaboração/criação dos `includes`
Comment: @Bacco Entendi sim. Só tenho 2 perguntas, eu não sei se existe algum tipo de regra sobre as páginas que estão com o nome "page_" na frente de cada uma (coloquei esse nome pq me disseram), 1° eu tenho que renomear todos os meus documentos e colocar o "page_" na frente deles? 2° Tem algum problema eu colocar um titulo de uns 100 characteres no case que está dentro do switch?
Comment: O que está no case tem que ser igual o que está no `p=` do link usado. Tem que ser identico. Essas outras duvidas já seriam separadas do que foi perguntado (e respondido).
Comment: @DiogenesSilva  1. Não existe regras, `page_` é uma ideia, poderia ser uma pasta também, ou poderia ser qualquer outro método de organização mirabolante 2. Para o PHP não tem, mas no google buscador o titulo tem limite de 70 caracteres (se eu não me engano), então para exibir nos buscadores não adiantar por algo muito grande, o descripition tem limite de 160 se eu não me engano para o Google.
Comment: @DiogenesSilva você teria que ver no seu fonte original como estão os links `` e usar o que estiver depois do ´p=` no case, mas isso só você olhando no seu código fonte. Não teriamos como deduzir o que é mais certo no seu caso, só você olhando o fonte mesmo
Comment: @Bacco Certo, acho que aqui já estou mudando o foco da pergunta que fiz inicialmente, se for o caso eu crio outra pergunta. Obrigado!
Comment: @DiogenesSilva lembrando ainda que se for coisa muito vaga, tem o chat da rede, acho que seus pontos já dão acesso
Answer: Atenção: O exemplo só servirá para o case citado pelo autor .
Você pode pegar a página atual que está sendo usada através do parâmetro p usando $_GET['p'] e fazer a verificação de acordo com a necessidade, gravando assim o valor em uma constante para poder ser usado nas páginas que conterá o meta.
Na sua página index.php:
  <?php
    $str = $_GET['p'];
    switch($str) {
        case 'teste':
        define('TITULO',' o titulo é teste');
        break;
        case 'home':
        define('TITULO',' o titulo é home');
        break;
        default:
        define('TITULO','nenhum titulo');
        break;
    }

    include "teste2.php";
 ?>

No seu arquivo que contém as metas tags, (no meu caso, é o arquivo teste2.php) ficaria assim:
<?php

    echo "Aqui está o titulo em outra pagina:: ".TITULO;
 ?>

 <meta name="description" content="<?php echo TITULO?>" />

OBSERVAÇÕES:
1 - Usei um exemplo de URL citado pelo autor: http://127.0.0.1/site/?p=home
2- Note que importei o arquivo (include "teste2.php") no final da página index.php.
3- Use o DevTools do navegador para ver como a tag meta ficou, no meu caso está assim:  http://prntscr.com/kni7vc
Comment: Eu comecei a estudar PHP bem recentemente, como exatamente eu faço isso?
Comment: @DiogenesSilva reeditei a resposta.


how detect form is submitted?

Question: I use Drupal 7 and the Webform module.
How can I know if a form is submitted or not? I need this to show either error messages or success message after form submission in form page.
I prefer not to write a module because I think it is unnecessary to write a module for a very small task.
Some more info to further explain my question:

I already know about the setting for Webform per form. This setting is located "Content > Webforms(tab) > Edit(your form) > Webform(tab) > Form settings" (where you can add the confirmation message or redirect to a Custom URL).
Actually I render my webform in my node--contact.tpl.php and I use the Webform Validation module for my form validations. And with the form_get_errors function I get errors and loop through them and show them. And if submission is successful I show form successful submission message. I just don't know how to detect whether form is submitted or not.
Comment: *"[If the question is about code you wrote, for which you want to write better code, or you want to understand why it doesn't work, show the code you are using, or the part of the code that is relevant for the question.](http://drupal.stackexchange.com/help/on-topic)"* - If it's submitted, it's submit handler is fired, what's your exact problem with it? And everything you do in Drupal you do using modules, either your own, or contributed by others.
Answer: There a setting for Webform per form. This setting is located "Content > Webforms(tab) > Edit(your form) > Webform(tab) > Form settings". You can add the confirmation message or redirect to a Custom URL.
Comment: I already know that actually I render my webform in my node--contact.tpl.php and I use webform validation module for my form validations.and with form_get_errors function I get errors and loop through them and show them. And if submission is successful I show form successful submission message. I just don't know how to detect whether form is submitted or not.
Comment: @majid8911 Any submitted form data should be in "Results" tab
Comment: sorry ! I didn't get you. where is results tab??
I'm new to drupal ! sorry if it seems stupid question !
I compared my webform object data after and before submission there wasn't any differences which I can detect form is submitted !
Comment: @majid8911 It located "Content > Webforms(tab) > Edit(your form) > Results(tab)". You can check them under "Submissions" or "Table" section.
Answer: I solved this problem with drupal_get_messages() function !
the result of this function is different for when form is submitted and also for when form is not submitted.

how detect form is submitted?


Why Cross-Validation score is less than the Test Score?

Question: I have a data set 1035 x 16, implemented random forest regressor algorithm after all the possible feature processing techniques, test/ train split is 20/80, for cross validation I used 5 K-Folds and  following are the results:
Test Score : 72.82762577833321
Training Score: 97.38484784016136
Validation score : [0.63171505, 0.64145713, 0.67557705, 0.66368883, 0.6085836 ]
Validation score avg : 64.42043307160208

I know model is over-fitting but how I can interpret,  the Cross Validation score is less than Test score .
when the Cross Validation score is less than Test score ?
when the Cross Validation score is greater than Test score ?
which is  better ?
Comment: Are there *any* differences between how you make predictions when validating vs testing?
Answer: The same condition happened to me many times. I believe it is normal to get such results, as cross validation score is basically a "test score". It is also the average of the k-folds so it is a more stable score than just the final test score, which is a single score. So, for me it is okay to get such result. But I fear it is a little an opinion, rather than a concrete answer.
Answer: A high training score and low validation score signals overfitting as you've also mentioned. And, overfitting means your test results is subject to high variance, which naturally explains the large difference between the test and validation sets.
Answer: Training score is more than the validation score when the model overfits. Typically, the validation score is less than the training score, because model fits on training data, and validation data is unseen by the model.
Overfitting happens when a model learns the detail and noise in the training data to the extent that it negatively impacts the performance of the model on new data.
But sometimes validation score can be more, it just means your validation data is easier to classify. In this case, try to take a bigger validation dataset, or use multiple fold cross-validation and this case should disappear.
I hope this helps.
Comment: I am asking for test and validation score
Comment: @zack Generally, the term "validation data" is used interchangeably with the term "test data" and refers to a sample of the dataset from training the model. You typically use cross-validation just to find the best hypermeters for the model to train(on train data). Hence, it would not make much sense to compare the cross-validation score and test scores. You assess your model performance based on train and test scores.
Answer: I ran into a problem as this recently. It is possible that there is some innate order in your dataset, e.g. time series, or rows are sorted by a certain column. When you do train-test split, the dataset is shuffled by default. However, cross_validate do not shuffle dataset by default.
To avoid the problem, you can use shufflesplit when generating cross validation data splits.
cv = ShuffleSplit(n_splits=5, test_size=0.25, random_state=0)
cv_results = cross_validate(model, data, target, cv=cv)

or any other way to explicitly tell cross_validate to shuffle dataset before split, e.g. use K-Folds cross-validator and pass shuffle=True.
Answer: Depending on your dataset splitting, It is assumed you used 80% for the training and 20% for the test sets. You used 5-fold cross-validation with your training set (80%).
So, it means the validation set is a set that was split from the training set in k-fold processing.
Your training and validation results show that your model is over-fitting (as you mentioned).
Cross-validation scores might be lower than test scores based on some conditions:

Small size of dataset.
Training data does not represent the validation data.
Training data represents the test set rather than the validation set.
The test set contains easier data to predict than the validation set.

Cross-validation scores might be higher than test scores if you can solve the condition above and some more conditions are considered:

Complexity of your model.
Try to shuffle your data when splitting it.
Ensure your train and test set come from the same distribution.
Add drop-out or regularization layer.

Even most people said a validation score higher than a test score is considered good model learning. But no one can guarantee it. A good model can result in higher testing accuracy than the validation accuracy.


What is Safety Play?

Question: I found this rule

2-8 Safety Play Prior to any shot except the break, you may declare a
  safety. On a safety, your inning ends after the shot regardless of
  whether you pocket any ball. If you do not declare a safety and you
  pocket a ball on an obvious shot, your inning continues and you must
  shoot again. A safety must meet the requirements of Rule 1.19, Legal
  Shot, or it is a foul. (AR p. 77, 103)

at this site: http://www.playcsipool.com/uploads/7/3/5/9/7359673/2014-2015_official_rules_of_csi.pdf
I'm not sure I understand the rule. Why would you ever call "safety" instead of calling a random ball in pocket on the off chance that you make it?
Answer: Because after a safety, you're hoping to leave the balls in such a situation that it's difficult for your opponent to pot anything, so they make a mistake which opens up the table. The last thing that you want to happen is that you leave the cue ball (e.g.) tight on the rail behind a couple of other balls and then you have to take another shot.

What is Safety Play?


Neo4j : Query with relation filter

Question: I've to write one cypher for schema where all nodes are having multiple relations in between them.
So I want to filter the nodes lets say, first search nodes which have relation HELPSin between theme. Then on Check if those nodes also have KNOWSrelation in between them then return all nodes with all other relations(including HELPS & KNOWS). Right now to filter the relation I'm using below cypher:

MATCH (a)-[r:HELPS]->(b)
WITH distinct a,b
MATCH (a)-[rs:KNOWS]-(b)
RETURN a,b LIMIT 25

Is there any provision to do so Like

MATCH (a)-[r:HELPS AND KNOWS]->(b)
WITH DISTINCT a,b
path = (a)-[*]-(b) //To get all other relations in between filtered nodes.
RETURN rels(path),nodes(path)

Thanks.
Answer: The below will get all other relations between a and b , apart from helps and knows.
    MATCH p = (b)<-[KNOWS]-(a)-[HELPS]->(b)
    WITH a,b
    MATCH a-[r]->b
    WHERE NOT type(r) IN ['HELPS', 'KNOWS']
    RETURN r

Comment: It will not give all other relation if A & B are not consecutive nodes ie.
A->B->C->D->E
Comment: you asked other relations between a and b as per the question and comment@GovindMantri
Comment: you can always modify the answer according to your needs.. if you dont want the relationship directional you can use a-[r]-b in the second match case
Comment: Sorry forgot to mention that one in above query!! my scenario is :
It will not give all other relation if A & B are not consecutive nodes ie.
A->B->C->D->E then I want to get all relations (paths) from A-D using that common relation which can be HELPS/KNOWS
Answer: i don't think there is any AND operation for this type of query
you can use
MATCH (a)-[:HELPS]->(b)-[:KNOWS]-(a)
WITH  DISTINCT a , b
MATCH a-[r]-b
WHERE NOT type(r) IN ['HELPS', 'KNOWS']
RETURN r

Comment: And how about getting all (Other) relations  in between and b
Comment: @GovindMantri hmm!! need one match then again

Neo4j : Query with relation filter


Como enviar emails com PHPmailer em localhost sem module ssl

Question: Olá pessoal gostaria de saber se existe a possibilidade de enviar email localhost usando a biblioteca PHPmailer sem ter que instalar o module SSL no apache e PHP? Já tentei diversas técnicas mas até agora para todas é necessário o SSL instalado.
Comment: Olá José, bem-vindo! Por favor separa a pergunta e a solução. Coloca a solução como resposta, clicando no botão aqui em baixo para responder.
Comment: Estou votando para fechar esta pergunta como fora de escopo porque isso não é uma perguinta, é uma postagem, que não confere com o propósito do SO.
Comment: Tópico alterado para se enquadrar no escopo
Comment: Neste site não adicionamos RESOLVIDO no titulo. Se a pergunta não estivesse fechada, o correto seria postar a solução e aceitá-la em seguida.
Comment: [Como responder às próprias perguntas](http://pt.stackoverflow.com/help/self-answer).
Comment: Consegui responder. É que enquanto estava com pendência a opção para responder estava desabilitada.
Answer: Consegui, em fim, enviar email com a classe phpmailer, em localhost, sem a necesidade de instalar ssl na máquina. Essa dica foi testada agora em janeiro de 2017.
Para poder enviar email com phpmailer localmente, basta, editar o arquivo 'class.smtp.php' e, logo após a linha:
public function connect($host, $port = null, $timeout = 30, $options = array()){
static $streamok;
    //This is enabled by default since 5.0.0 but some providers disable it
    //Check this once and cache the result

inserir o código:
if (count($options) == 0){
  $options['ssl'] = array('verify_peer' => false, 'verify_peer_name' => false, 'allow_self_signed' => true);
}

espero ter ajudado!!


UILocalNotification - Need to vibrate for a longer duration during the alert / notification

Question: Overview

In my iOS project, I am using UILocalNotification,
when a notification is fired, a custom sound is played.
the custom sound plays for about 20 seconds,
the phone vibrates only once at the start

What I want to do:

Presently the phone vibrates only once at the start. I want it to vibrate repeatedly for 20 seconds just like in Apple's alarm / Timer app before the user pressed on the action button ?

Question

During the alert is it possible to make the phone to vibrate for the 20 seconds before the user can attends to the notification or clicks on the action button ?

Problem

Since my app doesn't have any control till the user presses on the action button I am not sure how I can make it vibrate
The app might be closed when the notification is pops

Is there a way to do this ?
Answer: Schedule a timer that invokes the vibration function several times with some delay between calls. Don't forget to add an option to disable the vibration, cause you might get your app rejected from the app store because of this.
Comment: thanks for the reply, I have a doubt, the app is supposed to serve as an alarm, so how can i run a timer because might not even be running when the notification is fired.