Time Signature Dilemma, should I change the time signature for my Scherzo?

Question: When I started writing my Scherzo in D, I initially thought of having the time signature be 3/4 since that is a very typical time signature for a scherzo, especially earlier scherzos that are closer to Minuet and Trio. I wrote my entire Scherzo section without even thinking about the time signature. I focused on melody and harmony when writing the Scherzo section of my piece. Only now has this dilemma on the time signature came to me. This is partly due to some people giving feedback that my piece is in the wrong time signature and that it should instead be in 2/4. And now I'm getting feedback saying that I can't use just a single time signature for my piece.
That, the feedback I am getting saying that I can't use just 1 time signature and that I have to instead use both 2/4 and 3/4 is really confusing me. Here is the piece in the original 3/4:

As you can see, everything fits neatly into 3/4, at least with the 3/8 anacrusis. But then, this user Teodor Lontos(who gives detailed comments on my scores) says that the 1 quarter 4 sixteenths figure fits better into 2/4 than 3/4 and that my pickup, my anacrusis, should only be the first eighth note. So far I have no issues. So I change the time signature to 2/4 and save it as a separate file from the original 3/4. Now, I'm noticing a mess. Some of that, I can fix by deleting and readding notes, ties and the key signature change. But, even after that initial cleaning step, some mess still remains, all having to do with one of 2 things, those being:

Accent(like for example, the Neopolitan chord moves from being on a strong beat to being on a weak beat)
Ties, specifically, ties across the measure(for example, the augmented sixth chord moves the cadential 64 and root position tonic to be tied across the measure, leaving a quarter rest at the end of the Scherzo section)

Here is what I'm talking about:

As you might be able to tell, quite a few bars that were neat in the 3/4 version(like for example the triplet bar) are messy in the 2/4 version. Also, in Musescore, it is impossible to have a volta start in the middle of the measure so either I separate it into 2 1/4 measures to get the same playback as in the 3/4 version or have the second ending be abrupt.
So then I tell him about these messy areas in the 2/4 version and he says:

That is because the first bars, you wrote in 2/4 and then later you wrote in 3/4. The correct way to notate it would account for this change in accent.

I then asked him how and he told me that my scherzo can't be in a single time signature, that the first 8 bars fit into 2/4 nicely, but by the ninth bar I need a 5/4(or 3/4 + 2/4) and then the rest of the first section should be in 2/4. This got me confused. My original 3/4 seemed neat, much neater than the 2/4 version. And I don't want to confuse the pianist with multiple time signatures if I don't have to. I personally, usually see time signature changes corresponding exactly to tempo changes. But, maybe that is because I'm used to playing Beethoven. I myself might get confused if I see 2/4 and then a few bars later 3/4, especially if the changes are not at a consistent interval or at important moments of the piece.
Anyway, do I really need to use multiple time signatures for my scherzo? Or is it just fine notated in 3/4 as I originally wrote it?
Comment: I didn't go right through everything but that first score in 3/4 - the D crochet right before the first barline actually feels like the downbeat. You sight singing the first 8 measures or so - it just doesn't feel like 3/4 to me. Of course you *can* notate it that way (you can notate it in 7/16 if you want) but it doesn't feel like a 3/4 melofy. The accents seem to fall in the wrong places. Unless that is the effect you are after. The 2/4 flows a lot more naturally.
Comment: But there are places where the 2/4 places unnatural accents or where the 2/4 makes a previously accented note unaccented. An example of the latter is in measure 24 of the 3/4 version with its accented beat Neopolitan chord. The 2/4 places that Neopolitan onto the weak beat. An example of placing unnatural accents is in measure 33 of the 3/4 version, with the eighth notes leading into the half cadence. The 2/4 places those eighth notes onto beat 1, placing an accent on notes that wouldn't be accented. And there are several other examples of the 2/4 changing accents to not fit the melody.
Answer: Based on your description, even without looking at the music, it seems like you really need two time signatures.  Looking at the music, I can also see very clearly that some things work better in 3/4 and others in 2/4.  The only way it would seem to work in 3/4 alone would be if you were trying to play with expectations, ie, if you want the standard accents of the meter to be contradictory to the implied accents of the actual music, which could be fun.
As others have suggested, you can write it in whichever time signature you think is best, including ones that don't really have a great argument for them, but you have to consider the context for which you are writing.
If you are writing for yourself and yourself alone (no one else is performing it or grading it), then you have free reign and only need to do what you prefer.
If you're writing this for someone else to play, you want to consider two things: 1. What will be the easiest to read?; 2. What will be the best at conveying your intentions to the performer?  These two things are often the same but not always.  You may choose to write something in a way that's a little less easy to read but do a better job of expressing your musical ideas, such as a syncopated, staccato rhythm being expressed as either dotted notes with staccato markings or short notes with rests in between.  It may be easier to read the short notes with rests but it doesn't indicate your desired phrasing as well.
If you're writing this for a class or private instruction, you need to be prepared to argue for your choice in meter, ie, why did you go with one over the other or both, how does this choice affect the performer that has to read it, etc.  In the eyes of academia, there are basically right and wrong choices for how to go about a lot of things, particularly before you get to 20th century music and beyond, but most professors will accept something non-conventional if you're able to put together a really good argument for it.
For myself, when I write things out, I often struggle between writing things based on theory vs. what will be easier to read.  I'm big on theory, so I prefer to right things out in such a way that spells out the theory behind a given section but that may ultimately be harder to read.  This comes up a decent amount when you're writing out things like altered chords, where chord theory would make you want to name everything relative to the chord tone or alteration, instead of naming it based on what will be easiest to read.  In my mind, I would better understand the intention of a piece of music through seeing things spelled out based on the theory but I also understand that using an enharmonic equivalent for a diatonic note is pretty jarring for someone reading the piece.
So you really just need to try to consider who will actually be reading this music and how your choice of meter will impact their interpretation of that music.
Answer: This is a rather opinion based comment (and thus not necessarily appropriate for this board) but I think the 3/4 reads easier. (There are scherzos in 2/4 and 4/4 though.) I would go with whichever time signature you (the composer) thinks represents the basic pulse of the music. There can be short sections with another pulse but don't need signature changes. Long sections (like a trio) may have a different signature.
Answer: I wonder if you called your piece a scherzo because you were hearing your music in a fast 3/4 or if you chose a fast 3/4 because you wanted to compose a scherzo. :) To me, it does not seem secondary to establish this.


Installing lessc with NPM - UNABLE_TO_VERIFY_LEAF_SIGNATURE

Question: I want to install the lessc provided from NPM. (on OSX)
Firstly, I installed the current version of NodeJs: 0.10.15.
It includes NPM.
Now I launch the famous command:
npm install -g lessc
and I obtain this error:
npm install -g lessc
npm http GET https://registry.npmjs.org/lessc
npm http GET https://registry.npmjs.org/lessc
npm http GET https://registry.npmjs.org/lessc
npm ERR! Error: UNABLE_TO_VERIFY_LEAF_SIGNATURE
npm ERR!     at SecurePair.<anonymous> (tls.js:1350:32)
npm ERR!     at SecurePair.EventEmitter.emit (events.js:92:17)
npm ERR!     at SecurePair.maybeInitFinished (tls.js:963:10)
npm ERR!     at CleartextStream.read [as _read] (tls.js:463:15)
npm ERR!     at CleartextStream.Readable.read (_stream_readable.js:320:10)
npm ERR!     at EncryptedStream.write [as _write] (tls.js:366:25)
npm ERR!     at doWrite (_stream_writable.js:219:10)
npm ERR!     at writeOrBuffer (_stream_writable.js:209:5)
npm ERR!     at EncryptedStream.Writable.write (_stream_writable.js:180:11)
npm ERR!     at write (_stream_readable.js:573:24)

On the net, I found a workaround:
npm config set strict-ssl false

But when I relaunch the command, I get now:
npm install -g lessc
npm http GET https://registry.npmjs.org/lessc
npm http 404 https://registry.npmjs.org/lessc
npm ERR! 404 'lessc' is not in the npm registry.
npm ERR! 404 You should bug the author to publish it
npm ERR! 404
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, or http url, or git url.

npm ERR! System Darwin 12.4.0
npm ERR! command "node" "/usr/local/bin/npm" "install" "-g" "lessc"
npm ERR! cwd /Users/me
npm ERR! node -v v0.10.15
npm ERR! npm -v 1.3.5
npm ERR! code E404

I'm very new to NodeJs world and its packager.
Is there something I can do to manage to install lessc?
Maybe I forgot some env variables.
Answer: Ok, the issue was trivial:
Actually I was inspired by this Play plugin.
And the shown command is:
npm install -g lessc  // lessc nonexisting

instead of
npm install -g less

Now, with the workaround specified above, that works.


Como reconhecer o botão "voltar" nativo do dispositivo android em um aplicativo.

Question: gostaria de saber como eu faço para detectar em uma aplicação que o usuário clicou no botão "Voltar" nativo do dispositivo. Pois eu preciso realizar uma ação caso isso aconteça.
Answer: Através do método:
<code>@Override
public void onBackPressed() {
   //aqui você controla o voltar fisico do aparelho
}
</code>
Comment: Ah ok Leonardo. Muito Obrigado.


Loops and how to check if input is a number

Question: so i'm new to python and to coding in general and I have some difficulties about a use of loops.
Here is the following code (prints are in french but I guess no translation is needed)
n = input ("Saissisez le nombre totale de bonnes notes obtenues")
n = int(n)
if n > 0:
    a = n+1
    b = n*a
    c = b/2
    print("Vous avez accumulez au total la somme de :", c, "€")
    print("Bien joué :)")
    input()

else:
    print("Vous n'avez pas rentré de nombre entiers correctes. Veuillez réessayer.")
    n = input ("Saissisez le nombre totale de bonnes notes obtenues")

So what I want to do is to create a loop for the "else" in order to ask the question again (the input) until a number superior to 0 is selectioned.
It would be also cool if it doesn't "error" when I type a letter instead of a number for example.
Thanks in advance ! (and sorry for this stupid question)
By the way the input in the "if" is to avoid the window to close instantly.
Answer: To ensure the user gives you an interger greater than 0:
is_integer = False
n = ''
while not is_integer:
    n = input("Saissisez le nombre totale de bonnes notes obtenues")

    if type(n) == int and n > 0:
        is_integer = True
    else:
        print('Not an integer greater than 0')

Answer: Your best bet is to define your overall procedure as a function and have it call itself.
def myProcedure():
    n = input('Give me a number')
    ...
    if repeat_condition:
        myProcedure()
    else:
        finish up

As for your number error, use a try block
try:
    float(n)
    ...
except ValueError:
    myProcedure()


General formula of $\prod_{i=1}^{n}(a^ib+1)$

Question: Is there any general formula of the following product?. Thank you in advance.
$$\prod_{i=1}^{n}(a^ib+1)$$
Comment: Have you tried developping this expression for low values of n?
Comment: Does your product iterate over $i$? I.e. should the expression under the product be "$i = 0$"? Also, unlike your tag suggests, this is not an infinite product.
Answer: check out the q-Pochhammer-symbol, it might be what you're looking for.
https://en.wikipedia.org/wiki/Q-Pochhammer_symbol
Comment: Thank you for the answer.
Comment: You're very welcome. :)


Is it possible to add angularized html tags and attributes in a directive based on model data in Angularjs?

Question: I want to build a directive that will build form inputs based on a nested object of settings that include the input type, model to bind, and html attributes. I have been pounding my head and, perhaps, am close to concluding that this is something Angular is not equipped to do. I would like to build a directive that could take an array of objects like:
[{
    "label":"When did it happen",
    "model": $scope.event.date,
    "element":"input",
    "type": "date",
    "options":{
       "class":"big",
       "required": true,
     },
  },{
    "label":"How did it happen?",
    "model": $scope.event.cause,
    "element":"textarea",
    "options":{
      "cols":45,
      "rows":55,
    },
  },{
    "label":"How many times did it happen?",
    "model": $scope.event.times,
    "element":"input",
    "options":{},
  }],

I have struggled through many different aspects of directives. I keep running across a few issues.

Neither the template nor the controller directive functions have access to any sort of scope that could reach any sort of data--most especially my array I've made. This means that I can't decide how to build my DOM (i.e. tag types and attributes) until later.
All compiling is done before the linking function. I am able to manipulate the DOM in the linking function but none of it is angularized. This means if I add a required attribute angular's ngValidate is not aware of it. If I try and change the tag type, I reset lose my model binding etc.

It seems that this is just the way angular runs. Is there no good way to affect the DOM tag types and attributes based on model data without specifying everything out specifically?
Answer: How about something like this:
$scope.event = {
    date: new Date(),
    cause:'It was the colonel in the kitchen with the revolver',
    time:5, //...
    $metadata: data
};

Where data here is simply the array you have already shown. (apart from the model property which would just be a string representing the property of the event, like so:
{
    "label":"When did it happen",
    "model":'date',
    "element":"input",
    "type": "date",
    "options":{
      "class":"big",
      "required": true,
     }
}

Then your directive would simply access the property given it on the parent scope. (event) And process the metadata into a usable template. Which could then get compiled.
Here is such a directive, and the directive...
myApp.directive('contentForm',function($compile,$interpolate){
  var template = "{{label}}<{{element ||'input'}} {{options}}"+
             " ng-model='{{root+'.'+model}}'></{{element}}>";

  function linkerFunction(scope,element,attrs){
    if(!scope[attrs.contentForm])return;
    var metadata = scope[attrs.contentForm].$metadata || false;
    if(!metadata)return;
    element.html(getHtml(metadata,attrs.contentForm));
    $compile(element.contents())(scope);
  }
  return {
    restrict: 'A',
    replace: true,
    link:linkerFunction
  };
  //interpolate the template with each set of metadata
  function getHtml(metadata,root){
    var interpolation = $interpolate(template);
    var html = '';
    if(angular.isArray(metadata)){
      for(var i = 0; i < metadata.length; i++){
        metadata[i].root = root;
        metadata[i].options = processOptions(metadata[i].options);
        html += interpolation(metadata[i]) + '
'
      }
    }else{
      html = interpolation(metadata);
      metadata.options = processOptions(metadata.options);
    }
    return html;
  }
  // parse object into html attributes
  function processOptions(options){
    var result = '';
    for(var key in options){
      if(options.hasOwnProperty(key)){
        result += ' '+key+"='"+options[key]+"'"
      }
    }
    return result.trim();
  }
});

You'd probably want to change the template. I seem to have forgotten to put in a type. But that should be fairly straight forward. I hope this helps!
Comment: This is incredible. You are the man Caleb. I spent way too much time on this before you came to my aid. I learned a lot. Thanks soooooo much.


How do I access "this" with a nested class, in Java?

Question: Consider this example.
public class myclass {

public void...
public int ...

    private class my_nested_class {
          Intent i = new Intent(this, List.class);
    }

}

I would like "this" to be myclass.  How can I do that? "this.super"? But that doesn't work.
Comment: maybe you wanto to tag it also with android?
Comment: Every nested class has its own 'this'.  What you mean is `how do I access the enclosing outer class instance' and its answered here: http://stackoverflow.com/questions/1816458/getting-hold-of-the-outer-class-object-from-the-inner-class-object
Answer: It's myclass.this.
By the way, class names start with a capital letter in Java, you should rename your class MyClass.


Increase content size of UIWebView using Javascript

Question: I have a translucent toolbar over the bottom of my UIWebView.  The trouble is, if there is a link at the bottom of the page, I can't press it because the webview will always bounce back down to the bottom.
I don't want to shrink the webview and use a solid colour toolbar, and UIWebViews interface doesn't open much up.
What I would like to do, ideally, is to actually increase the size of the web page by one toolbar height, so that I can scroll that extra bit and have all the content above the toolbar, but when scrolling down I will be able to see the page content through the toolbar.  I could use the stringByEvaluatingJavaScriptFromString: function of UIWebView.
I'm very rusty on JavaScript- is it possible for me to do this?  Increase the window height or something?
I tried:
 [webView stringByEvaluatingJavaScriptFromString: [NSString  stringWithFormat:@"window.resizeBy(0,%d);", TOOLBAR_HEIGHT] ];

but it didn't do anything.
Any pointers welcome.
Thanks.
Answer: I found my solution here- leaving the question open as it may be useful to others.
How to increase the page height by X pixels by using only javascript
Answer: If you're using the UIWebView to display HTML, I would argue that it's cleaner to fix this with CSS:
body {
  padding-bottom: 50px;
}


tcpdf - HTML table showing up way too small

Question: I'm using tcpdf (http://www.tcpdf.org/) to generate PDFs of some tables and images.  The images are loaded without an issue, but I'm having issues with the writeHTML() function.
I can't seem to control the font sizes or table width/height through the HTML, so I end up with a tiny, tiny, tiny table that you have to print of and squint at to even attempt reading.
I've tried editing the table itself, CSS, even putting the table itself inside an h1, but nothing is changing the font size.  I have the font size in tcpdf set to 16, but this also has no affect.  Has anyone else run into this issue?
Comment: can you provide an example of the code you're using?
Answer: So, anyways -- apparently tcpdf's HTML engine gives the  tag precedence over any CSS, or other size-adjusting tags.  After removing all of the  tags from the HTML and using pure CSS, everything cleared up.


ReactJS conditional dispatch reducer action

Question: I am dispatching actions with a dispatch function from within child components available via context api.
<code>const NotificationProvider = (props) => {
  const [state, dispatch] = useReducer((state, action) => {
    switch (action.type) {
      case "ADD_NOTIFICATION":
        return [...state, {...action.payload}];
      case "REMOVE_NOTIFICATION":
        return state.filter(el => el.id !== action.id);
      default:
        return state
    }
  }, []);
</code>
How can I keep (maximum) only latest 3 elements from the state?
Answer: Add the payload to the front of the notifications and then slice off the rest (this way you also have latest notifications upfront.
<code>    case "ADD_NOTIFICATION":
        return [{...action.payload}, ...(state.slice(0,2))];
    }
</code>


Can I print an image from a separate content type in my page--front.tpl.php?

Question: This is a question in reference to Drupal 7, using the Zurb Foundation base theme framework. I've created a specific content type that only has an image field in it for purposes of making the image itself content manageable by the user so they can add/remove as they'd like.
I thought that I could access that image with the following code in my page--front.tpl.php file per my Googling of the subject, however, I'm getting no output at all.
<?php print render(field_view_field('node', $node, 'field_my_image_field', array('label'=>'hidden')));
  ?>

I've also attempted several different variations of this to no avail.
How can I access and print out the contents of that field from that content type into my custom page template?
Answer: You can embed a view inside your front page template, insert this code in propper region. You'll need an image view
// Get the embeded view and render it.
drupal_render(views_embed_view('VIEW_NAME', 'DISPLAY_ID'));

replace VIEW-NAME and DISPLAY_ID with your data, you can find those values in last column on your image view
Answer: if you want to display any custom field from specific content type , you can refer below code : please change your content type name in $type variable in below code here my content type name is "portfolio" , you will get all fields value from that particular content type.
$type = "portfolio";
//$test = array();
$nodes = node_load_multiple(array(), array('type' => $type));
foreach($nodes as $products){
 print_r($products);
}

Hope it helps.
Comment: What does the $products variable represent? I'm assuming that this has something to do with your image field, but I'm not following you here - it's not clear.
Comment: Hello, here $products variable you can give any name , try to print that variable , you can give any variable name there like $test then it should look like  foreach($nodes as $test){  print_r($test); }  , try this code you will surly get your field , you will get your custom image field uri then you need to convert it in url using drupal's function like file_create_url , for example , $main_image = file_create_url($test->yourcustomimagefieldname['und'][0]['uri']); , so this function will create image url
Comment: This returns an error:

Error messageNotice: Undefined index: uri in include() (line 11 of sites/all/themes/my_theme/templates/page--front.tpl.php).
Comment: try to do  foreach($nodes as $test){ print_r($test); } and check if you are getting image field or not ?
Comment: check in admin that your field has image uploaded or not,if there will be no image then on doing print_r you will not get anything for that field. in my project i have field like this http://prntscr.com/flfhxz , so when i will run my code it will do print_r like image this http://prntscr.com/flfijd because in admin my field has value . please share your print_r screenshot , because above mention code works perfect for me.
Comment: Here's the whole thing and I can't get it to work:

 $type));
          foreach($nodes as $bg){
          print_r($bg);
          }
          $main_image = file_create_url($bg-> field_chp_background_image['und'][0]['uri']);
      ?>
Comment: btw- I *do* have an image in the field.
Comment: Hi, you have added $main_image outside loop please add it inside loop , try this code ` $type));
      foreach($nodes as $bg){
          print_r($bg);
          $main_image = file_create_url($bg->field_chp_background_image['und'][0]['uri']);
      }?>`
Comment: unfortunately, this does not work.
Answer: Here is what was ultimately the solution in our case in the event that anyone else runs in to this same problem again in the future.
Ultimately, the solution was to load the image from the node directly. Many thanks to my man Mike for helping get to the bottom of this.
<?php
      $type = "homepage_hero_background"; // content type machine name
      $nodes = node_load_multiple(array(), array('type' => $type));
      foreach ($nodes as $bg) {
        $uri = $bg->field_chp_background_image['und'][0]["uri"]; // field machine name
        $main_image = file_create_url( $uri );
      }
      ?>


Disable ordering in entity reference (user)

Question: I have an entity reference of widget type = autocomplete. It's a collection of users where you can add multiple users.
Now I would like to disable the ordering of the users. So you can't order the users and the text Show row heights isn't show. Here you can see how it is now:

I tried to follow this tutorial but I'm stuck at the last step, he can't find the  element['#field_name'] = 'myfield'.
This is what I have so far from the tutorial: (I'm using a custom module named other)
function other_theme_registry_alter(&$theme_registry) {
    if (isset($theme_registry['field_multiple_value_form'])) {
        $theme_registry['field_multiple_value_form']['type'] = 'module';
        $theme_registry['field_multiple_value_form']['theme path'] = drupal_get_path('module', 'other');
        $theme_registry['field_multiple_value_form']['function'] = 'other_theme_field_multiple_value_form';
    }
}

/**
 * Theme function override for multiple-value form widgets.
 *
 * @see theme_field_multiple_value_form()
 */
function other_theme_field_multiple_value_form($variables) {
  $element = $variables['element'];
  $output = '';

  // The first condition is the override.
  if (($element['#cardinality'] > 1 || $element['#cardinality'] == FIELD_CARDINALITY_UNLIMITED) && isset($element[0]['#nodrag'])) {
    die;
    $table_id = drupal_html_id($element['#field_name'] . '_values');
    $required = !empty($element['#required']) ? theme('form_required_marker', $variables) : '';

    $header = array(
      array(
        'data' => '' . t('!title !required', array('!title' => $element['#title'], '!required' => $required)) . "",
        'class' => array('field-label'),
      ),
    );
    $rows = array();

    // Sort items according to weight
    $items = array();
    foreach (element_children($element) as $key) {
      if ($key === 'add_more') {
        $add_more_button = &$element[$key];
      }
      else {
        $items[] = &$element[$key];
      }
    }
    usort($items, '_field_sort_items_value_helper');

    // Add the items as table rows.
    foreach ($items as $key => $item) {
      // We don't want the weight to render.
      unset($item['_weight']);
      $cells = array(
        drupal_render($item),
      );
      $rows[] = array(
        'data' => $cells,
      );
    }

    $output = '
';
    $output .= theme('table', array(
      'header' => $header,
      'rows' => $rows,
      'attributes' => array(
        'id' => $table_id,
        'class' => array('field-multiple-table'),
      ),
    ));
    $output .= $element['#description'] ? '
' . $element['#description'] . '
' : '';
    $output .= '
' . drupal_render($add_more_button) . '
';
    $output .= '
';
  }
  elseif ($element['#cardinality'] > 1 || $element['#cardinality'] == FIELD_CARDINALITY_UNLIMITED) {
    $table_id = drupal_html_id($element['#field_name'] . '_values');
    $order_class = $element['#field_name'] . '-delta-order';
    $required = !empty($element['#required']) ? theme('form_required_marker', $variables) : '';

    $header = array(
      array(
        'data' => '' . t('!title !required', array('!title' => $element['#title'], '!required' => $required)) . "",
        'colspan' => 2,
        'class' => array('field-label'),
      ),
      t('Order'),
    );
    $rows = array();

    // Sort items according to '_weight' (needed when the form comes back after
    // preview or failed validation).
    $items = array();
    foreach (element_children($element) as $key) {
      if ($key === 'add_more') {
        $add_more_button = &$element[$key];
      }
      else {
        $items[] = &$element[$key];
      }
    }
    usort($items, '_field_sort_items_value_helper');

    // Add the items as table rows.
    foreach ($items as $key => $item) {
      $item['_weight']['#attributes']['class'] = array($order_class);
      $delta_element = drupal_render($item['_weight']);
      $cells = array(
        array(
          'data' => '',
          'class' => array('field-multiple-drag'),
        ),
        drupal_render($item),
        array(
          'data' => $delta_element,
          'class' => array('delta-order'),
        ),
      );
      $rows[] = array(
        'data' => $cells,
        'class' => array('draggable'),
      );
    }

    $output = '
';
    $output .= theme('table', array(
      'header' => $header,
      'rows' => $rows,
      'attributes' => array(
        'id' => $table_id,
        'class' => array('field-multiple-table'),
      ),
    ));
    $output .= $element['#description'] ? '
' . $element['#description'] . '
' : '';
    $output .= '
' . drupal_render($add_more_button) . '
';
    $output .= '
';

    drupal_add_tabledrag($table_id, 'order', 'sibling', $order_class);
  }
  else {
    foreach (element_children($element) as $key) {
      $output .= drupal_render($element[$key]);
    }
  }

  return $output;
}

function other_field_widget_form_alter(&$element, &$form_state, $context) {
  if (isset($element['#field_name'])) {
    var_dump($element['#field_name']);
    switch ($element['#field_name']) {
      case 'field_co_authors': die;
        $element['#nodrag'] = TRUE;
      default:
        break;
    }
  }
}

As you can see I have a switch but the text is never equal to field_co_authors. The two fields that are an entity reference and can have multiple values don't show... .
Am I doing something wrong or is there another way to do this?
Answer: $element['#field_name'] doesn't seem to be set for entityreference fields, this worked for me:
function other_field_widget_form_alter(&$element, &$form_state, $context) {
  if ($context['instance']['field_name'] == 'field_co_authors') {
    $element['#nodrag'] = TRUE;
  }
}

This is how I've modified the theme funciton:
function other_field_multiple_value_form($variables) {

  $element = $variables['element'];
  $output = '';

  if ($element['#cardinality'] > 1 || $element['#cardinality'] == FIELD_CARDINALITY_UNLIMITED) {
    $table_id = drupal_html_id($element['#field_name'] . '_values');
    $order_class = $element['#field_name'] . '-delta-order';
    $required = !empty($element['#required']) ? theme('form_required_marker', $variables) : '';

    $header = array(
      array(
        'data' => '' . t('!title !required', array('!title' => $element['#title'], '!required' => $required)) . "",
        'colspan' => 2,
        'class' => array('field-label'),
      ),
    );
    $rows = array();

    if (!isset($element[0]['#nodrag'])) {
      $header[] = t('Order');
    }

    // Sort items according to '_weight' (needed when the form comes back after
    // preview or failed validation)
    $items = array();
    foreach (element_children($element) as $key) {
      if ($key === 'add_more') {
        $add_more_button = &$element[$key];
      }
      else {
        $items[] = &$element[$key];
      }
    }
    usort($items, '_field_sort_items_value_helper');

    // Add the items as table rows.
    foreach ($items as $key => $item) {
      $item['_weight']['#attributes']['class'] = array($order_class);
      $delta_element = drupal_render($item['_weight']);
      $cells = array(
        array('data' => '', 'class' => array('field-multiple-drag')),
        drupal_render($item),
      );
      if (!isset($element[0]['#nodrag'])) {
        $cells[] = array('data' => $delta_element, 'class' => array('delta-order'));
      }
      $rows[] = array(
        'data' => $cells,
        'class' => array('draggable'),
      );
    }

    $output = '
';
    $output .= theme('table', array('header' => $header, 'rows' => $rows, 'attributes' => array('id' => $table_id, 'class' => array('field-multiple-table'))));
    $output .= $element['#description'] ? '
' . $element['#description'] . '
' : '';
    $output .= '
' . drupal_render($add_more_button) . '
';
    $output .= '
';

    if (!isset($element[0]['#nodrag'])) {
      drupal_add_tabledrag($table_id, 'order', 'sibling', $order_class);
    }
  }
  else {
    foreach (element_children($element) as $key) {
      $output .= drupal_render($element[$key]);
    }
  }

  return $output;
}

UPDATE:
To change the "Add another item" text, I think you'll need to implement a form alter. Assuming the node type is page, this is how to do it:
function other_form_page_node_form_alter(&$form, &$form_state, $form_id) {
  $language = $form['field_co_authors']['#language'];
  $form['field_co_authors'][$language]['add_more']['#value'] = t('Add another user');
}

or you can use the general hook_form_alter if you need this in multiple content types.
There is some discussion on drupal.org about adding the appropriate alter function to drupal core here: Add hook alter to override field_multiple_value_form()
Comment: Thanks, that works. But the problem is that I set the button (add another item) to "Add another user" but he overwrites it with "Add another item"..
Comment: @nielsv: I'm afraid you can only do it with a hook form alter:

I rather update to original answer...
Answer: You could hide the drag handle and the "show row weights" text using css. Also, you could use hook_form_alter() where you can add your own validation function to reset the weight field to 0 (just in case someone changes the value using firebug / inspector)
Answer: I suggest you you can do it by jquery, simple and quick.
add js that load only in this page by drupal_add_js
then worte
  $('.field-multiple-drag').remove();

in your coustom module
in hook_form_alter
if($form_id=='your_form_name'){
drupal_add_js(drupal_get_path('module', 'yourmodule') . '/removesortable.js');
}

then in js file
//removesortable.js
(function($) {
    Drupal.behaviors.yourmodule = {
        attach: function(context) {
        $('.field-multiple-drag').remove();
    }
  }
})(jQuery);

and enjoy :)


Maintain file permissions when extracting from a zip file using JDK 5 api

Question: I am using java.util.Zip and java.util.ZipEntry to successfully extra a zip file's contents to disk.  I would like to maintain the file permissions set when extracting on a *nix file-system.
Can anyone point me to the "correct" way to do this?
Comment: I know this is an rather old post but have you solved that issue ?
I'm having the same problem right now ; It only seems to affect an executable file so far... when I unzip it "by hand" the permission is correct
Comment: I have not in fact solved it.  My last approach vector was going to be to pull apart apache's ant task for manipulating zip files and determine what they are doing.
Comment: Ant can do that only since 1.8, using the new feature of Java.io.File in java 6 (see my answer below)
Answer: I think it is actually impossible to keep the permissions correctly.
Permissions are very OS specific: while POSIX file permissions allow the user to set whether you can read, write or execute a file for the file owner, the group and others, the NTFS file system has a similar system but the concept for an execute permission is inexistant. And the early FAT/FAT32 file syste, do not have file permissions at all (a part from the read-only attribute).
Being cross-platform, it would be difficult for java to set the permission properly on the newly created (unzipped) files depending on the underlying OS....
That said, Java 6 has a new java.io.File class that allows you to set permissions (with methods like setExecutable(), setReadable(), etc...)
These helped me a lot, especially the setExecutable() which was my main concerned when having to unzip executables on a Linux file system. And you don't have to bother about figuring out what OS you are running on as the method will simply do nothing if running under Windows or other systems without the concept of executable files.
Comment: I know this thread is getting quite old but your answer helped me. I was trying to extract a ***.app on Mac Os but the resulting application would launch, I changed permissions of the actual launcher file inside it using the setExecutable() method and it seems to be working perfectly ! Thanks for the help :)
Answer: The unix permissions are stored in the zip, either in the entry external attributes, or in the extra fields (using the "Asi" extra field, tagged with the 0x756E id). java.util.zip.ZipEntry exposes the extra fields and the Asi field could be read if there is one, but the external attributes are not accessible. So it's not possible to restore the files permissions in all cases using only the JDK zip implementation.
Fortunately the Apache Commons Compress project has its own ZipFile implementation which parses the external attributes, the permissions are exposed with the ZipArchiveEntry.getUnixMode() method. Then with Ant's PermissionUtils class and the Java NIO API, the permissions can be applied back to the file extracted with:
Files.setPosixFilePermissions(path, PermissionUtils.permissionsFromMode(entry.getUnixMode()));

Answer: Look at Apache Commons Compress and look at TarArchiveEntry, that should preserve the file permissions like you want it to.
TarArchiveEntry entry = tarInput.getNextTarEntry();

Here are the javadocs.  I think I've gone Commons mad...
Comment: There is also ZipArchiveEntry https://commons.apache.org/proper/commons-compress/zip.html
Comment: does TarArchiveEntry work on zips as well as tar files?  they are not the same, right?
Comment: I agree with Cheeso - what does this have to do with zip files ?
Answer: As tracked in this OpenJDK bug: https://bugs.openjdk.java.net/browse/JDK-6194856:

The "standard" zip file format does not have any way to store
  "executable file" meta-information, since it was originally designed
  for MS-DOS filesystems.
In order to preserve Unix information like file modes, the zip
  handling code would have to handle extensions to the zip file format.
  Other zip implementations have such extensions.
There are some extensions to the file format that would allow maintaining
  this kind of information, but it can never be guaranteed (there is no
  requirement that zip files contain such "extended" metadata) and it
  would be a lot of work to implement and (especially!) test.

Also see this answer:
Can i store unix permissions in a zip file (built with apache ant)?
Non-standard Java libraries may implement this (such as apache-commons).
Answer: Essentially, you can't STORE (unix) file permissions in Zip/Jar files, so you can't preserve them when extracting your jar (they were lost when the jar was created to begin with). See this question: creating a jar file - preserving file permissions
If you need the file permissions preserved in the archive and restored when extracting, you need to consider the alternative .tar or .tar.gz / .tar.bz2 format, which is also natively supported by most Java build tools (Ant, Gradle, Maven...)
Comment: This is not entirely accurate. Extra fields are commonly used for the purposes of file permission preservation.
Comment: Thank you @Cameron  I do realize that this answer is no longer the most accurate, and even may not have been when written years ago. Still it's not a bad answer that deserves the -1's since then (not implying you did :-) ). It would be more helpful to the community to provide a newer answer that reflects the best answer to this question, today, if you can expand on your comment ? I'd happily upvote it and delete mine.
Answer: I actually sat there looking over these answers and was stuck with this issue but then I realized I was doing something rather silly.
I was extracting to a temp folder, then using FileUtils.copyDirectory to copy the files from the temp folder to the new folder.
Instead of doing a copy, I changed to a move operation. now it worked.
I can confirm, on Ubuntu Linux 22.04, this maintains file permissions.
Uses:
implementation group: 'org.rauschig', name: 'jarchivelib', version: '1.2.0'
import org.rauschig.jarchivelib.ArchiveFormat;
import org.rauschig.jarchivelib.Archiver;
import org.rauschig.jarchivelib.ArchiverFactory;
import org.rauschig.jarchivelib.CompressionType;

  public static void unzip(File zipFile, File targetDirectory) throws IOException, IllegalAccessException {
    Archiver archiver = ArchiverFactory.createArchiver(ArchiveFormat.ZIP);
    archiver.extract(zipFile, targetDirectory);
  }

  public static void unTarGz(File tarFile, File targetDirectory) throws IOException {
    Archiver archiver = ArchiverFactory.createArchiver(ArchiveFormat.TAR, CompressionType.GZIP);
    archiver.extract(tarFile, targetDirectory);
  }

Answer: If you use Apache Commons Compress , you can set the readonly flag using the external attributes.
The flag will be preserved after extraction in windows.
zipEntry.setVersionMadeBy(0x0000); // 00 is for MSDOS/Windows
zipEntry.setExternalAttributes(zipEntry.getExternalAttributes() | 0x00000001L); // First bit = 1 -> Readonly flag in windows

for more information please refer to the ZIP format spec. https://pkware.cachefly.net/webdocs/APPNOTE/APPNOTE-6.3.9.TXT


Coluna condicional baseada em varias linhas dplyr

Question: Tenho esse df:
structure(list(id = c("R054", "R054", "R054", "R054", "R054",
"GT68U", "GT68U", "GT68U", "GT68U", "GT68U", "G001", "G001",
"G001", "G001"), car1 = c("sim", "sim", "sim", "sim", "sim",
"sim", "nao", "sim", "nao", "nao", "nao", "nao", "nao", "nao"
)), row.names = c(NA, -14L), class = c("tbl_df", "tbl", "data.frame"
))

Gostaria de criar uma nova coluna baseada nos valores de car1 para o conjunto de linhas de cada id.
Caso o id sempre tenha car1 "sim" ou "nao" a nova coluna  apenas replica a informação. Caso o id tenha "sim" ou "nao" a nova coluna deve apresentar "nd". De forma que ficasse assim:
id      car1    output
R054    sim     sim
R054    sim     sim
R054    sim     sim
R054    sim     sim
R054    sim     sim
GT68U   sim     nd
GT68U   nao     nd
GT68U   sim     nd
GT68U   nao     nd
GT68U   nao     nd
G001    nao     nao
G001    nao     nao
G001    nao     nao
G001    nao     nao

Tentei usar a função mutate
df %>%
  group_by(id)%>%
  mutate(output = case_when(car1 == "nao" & car1 == "nao" ~ "nao",
                            car1 == "sim" & car1 == "sim" ~ "sim",
                            car1 == "sim" & car1 == "nao" ~ "nd",
                        TRUE ~ 0))

mas recebo o erro
Error: must be a character vector, not a double vector
Run rlang::last_error() to see where the error occurred.
Answer: Utilizei o group_by + mutate + case_when + all para verificar se todas as ocorrências do id determinado era de sim/não e os que fossem mistos seriam valores faltantes e preenchidos com nd.
library(dplyr)

df %>% group_by(id)%>%
  mutate(output = case_when(
    all(car1 == 'sim')  ~ 'sim',
    all(car1 == 'nao') ~ 'nao',
    TRUE ~ 'nd'
  ))

Saída:
   id    car1  output
   <chr> <chr> <chr>
 1 R054  sim   sim
 2 R054  sim   sim
 3 R054  sim   sim
 4 R054  sim   sim
 5 R054  sim   sim
 6 GT68U sim   nd
 7 GT68U nao   nd
 8 GT68U sim   nd
 9 GT68U nao   nd
10 GT68U nao   nd
11 G001  nao   nao
12 G001  nao   nao
13 G001  nao   nao
14 G001  nao   nao

Answer: @lmonferrari já respondeu como usar o dplyr::case_when no seu caso; esta é outra opção, usando ifelse e unique:
library(dplyr)

df %>%
  group_by(id) %>%
  mutate(output = ifelse(length(unique(car1)) == 1, car1, "nd"))

Se no grupo houver só um valor para car1 (seja qual for), unique terá comprimento 1; nesse caso, output é preenchido com o valor correspondente de car1, caso contrário, com "nd".
Para ficar registrado, eis o equivalente com data.table:
library(data.table)

setDT(df)

df[, output := ifelse(length(unique(car1)) == 1, car1, "nd"), id]
# ou, usando data.table::fifelse, bem mais rápido:
df[, output := fifelse(length(unique(car1)) == 1, unique(car1)[1], "nd"), id]

Answer: Apesar de a pergunta pedir uma solução dplyr, aqui fica uma solução R base, em uma linha, com a função ave.
df$output <- ave(df$car1, df$id, FUN = function(x) if(all(x == x[1])) x else "nd")


remove escape sequences from string in php

Question: I'm working with a mysqldump file that has escaped character sequences. I need to know the length of a string as its database value, but the dump has escape characters in it, which add length to the string.
I've used stripslashes() which properly un-escapes single- and double-quotes, but it doesn't touch the \r\n.
I'm concerned there are other escaped character sequences in there that I'm not aware of. Is there a function I can use that will give me the true length of the string as it would be in the database? If I have to build my own function, what other sequences should it handle?
Comment: Actually, stripslashes changes `\r\n` into `rn`. That adds 2 to the length of the string, which is a correct value, because `\r\n\` are actually two characters in the string, even though they aren't literally `rn`. Hm...
Answer: The strip c slashes() function does exactly that:
stripcslashes('foo\r\n');

Answer: You can use substr_count() to count characters in a string. Simply count how many backslashes are in the string:
$string = "... mysqldump string here ...";
$backslashes = substr_count($string, '\\');

That'll give you a rough count. To be 100% accurate, you'd have to count how many double backslashes there are, to account for literal backslashes, and adjust the count as appropriate.


Date Range Search in Datatables using PHP Ajax

Question: I am using Date Range Search in Data tables using PHP Ajax. It provide start / end date pick function in format YYYY-MM-DD. I took this code from webslesson.info
I want to have format like "YYYY-MM-DD HH:MM:SS". How can I modify it.
Comment: you can't make this format to "YYYY-MM-DD HH:MM:SS" because this is a datepicker not time picker you can make this like "YYYY-MM-DD"
Comment: You have to use datetimepicker for the format you want...
Comment: Did you try to manipulate the date picker?
Comment: When your question contains code, you should include the code in the question, not link it. Please do that.
Answer: For that you need to change date range format of datepicker
here is the working code
$('.input-daterange').datepicker({
  format: "YYYY-MM-DD"
 });

Comment: @kumar,
using that code it shows date like "YYYY-November-Wednesday"
Comment: Then what you want basically can you please explain in details
Comment: Ok. I have SYSLOG tables that have DATE TIME column as well which records time in "YYYY-MM-DD HH:MM:SS" format. Therefore I need to add search option which have such format so search can be made. I used same code from internet (link is given in first post) but it provide date picker in YYYY-MM-DD only, and dueto this search does not work


What's the point of winning the opening tip off in basketball?

Question: In basketball, if you get the ball during the opening tip off, the other team gets the ball at the start of the 2nd and 3rd quarter and you only get the ball at the start of the 4th quarter.
So there is no advantage to winning the opening tip off and no disadvantage to losing the tip off because both teams start with the ball an equal amount of times. If that's the case, why even have a tip off? Why not just start the game the same way you'd start every other quarter?
Answer: In FIBA rules, and assuming no other event caused a jump ball situation, then the possession at the beginning of the next periods would be.
team A wins Jump:
Team B starts 2nd period.
Team A Starts 3rd period.
Team B Starts 4th period.
(Not A, B, B, A) as claimed in question.
There are 2 reasons why winning the tip is useful

leading versus chasing (can be considered an advantage, first to score)
as teams alternate possession and therefore the chance to shoot, the clock in that period counts down.  It can be that Team A began the period  and also had the last chance to shoot in a period. Uneven number of possessions.
Jump ball situations normally do happen so the right to start the last period may end up team A again.

So having first possession is a small advantage.
Comment: out of sheer curiosity, do you have any stats that correlates winning the tip-off and scoring first?
Comment: No I dont have such stats. Turnover stats may be irrelevant in this case.  Given that 99.999% of the time without the ball you dont score and both team can potentially produce turnovers.   Turnovers most likely do not change the size of  the small advantage of first possession .  Quantifying this small advantage is however another exercise.
Comment: This reminds me of [deferring a reception](https://sports.stackexchange.com/questions/12798/what-is-the-estimated-point-value-of-deferring-after-winning-the-coin-toss) in the NFL. I do consider your second point more interesting because of number of possessions: a team could finish a quarter with a 2-for-1 AND end up with possession for the start of the next quarter.
Comment: http://www.racketracer.com/2015/05/12/analytics-of-optimal-2-for-1-strategy-in-nba-basketball/ talks about 2-for-1 opportunities, in which the average differential is +0.74 points for each 2-for-1 shot. This may be outside the scope of this question, but it is something for consideration.
Answer: If you look at probability models there is a weight on importance of each quarter of the game.  The 4th quarter has almost a 40% impact on the game (when it should be 25%).   I don't remember the exact percentage and it wasn't memorable but having an extra possession in the 4th quarter led to an increase in win probability in close games - threshold is 10 points I think -  and a substantial increase in probability in even games.
So the tip off means almost nothing to stat geeks that work for teams for the first quarter possession but the 4th quarter possession is valued so high that it makes it an important thing for a lot of teams.  Now there are still a lot of NBA teams that half-ass the tipoff because they aren't looking for the .85% (just making that up) edge but other teams do care.
I know this is more of a comment but just too long but maybe someone can reference the MIT article that I read about this a few years ago.  But to sum it up the later in the game you get the more valuable possessions are in their correlation to win probability and you can't get later than the 4th quarter.
In other leagues - not NBA - that us alternating possessions the tip off is even more important because it is a half possession advantage per game.  Any coach would want a .55 point lead.
Answer: I can't speak to the NBA, but in college and high school, the possession arrow is set by who wins the tip-off. So, if team A wins the tip and there's no violation that causes a jump ball call from the ref, team B should get the ball at the beginning of the next quarter, then the arrow would flip to team A.
I can't remember off hand, but there are other instances that cause a possession arrow to flip, not just a jump ball or the end of a quarter/half. I do know if a ball get's stuck between the rim and backboard is one and I believe a double technical goes to the possession arrow.
Comment: This is correct, but doesn't really answer the question - what's the advantage of winning the opening tip-off as it all cancels out in the long run?
Comment: Apologies, I guess I wasn't clear with my answer.

The statement preceding the question is not true; Team A and B do not alternate the start of each period. Who get's the ball on 2nd and subsequent periods is set by the alternating possession arrow (or possession arrow for short). (NCAA 17-18, Rule 6.3.5)

The questions themselves are invalid, since the statements they are made off of are incorrect. The possession arrow being established is the reason for the 'tip-off', and subsequent periods' possession is awarded based off whom the possession arrow indicates should receive possession.
Comment: @BrianWendel "Who get's the ball on 2nd *and subsequent periods* is set by the alternating possession arrow." Not entirely true. 6.2.1 states "A jump ball is a method of putting the ball into play at the beginning
of the game or any extra period(s)." Since there are two halves in an NCAA game (before extra period(s) are played, if necessary), the only time the possession arrow matters is for the start of the 2nd half (not "and subsequent periods").
Comment: @user257138 true for college, but high school does have a 3rd and 4th. I should have further clarified that from my original statement. But to continue the original point, there are situations in a game where possession is awarded via the possession arrow; if the ball becomes lodged between the rim and backboard, that goes to the possession arrow. There are a handful of other instances where the arrow matters, and by extension, the tip-off.
Answer: I did find a study on this.  There is a slight advantage to winning the opening tip.  The NBA team that wins the opening tip wins the game 52.5% of the time.  Winning the opening tip results in a win more often for the home team than the away team.
Comment: Welcome to Sports SE. Can you provide a link to the study you're referring to?


Turning a html input value into a $variable for a download function

Question: This site has been immenselly helpful to me so far, but it seems I've finally come up against a problem.
The question how to put a variable in a html input has been asked and awnsered before, but there's an issue I just can't seem to get to work.
<?php
if(isset($_POST['file_name'])){
    $file = $_POST['file_name'];
    header('Content-Disposition: attachment; filename="'.$file.'"');
    readfile('uploads/'.$file);
    exit();
}
?>
<form action="force_download.php" method="post" name="downloadform">
  <input name= "file_name" type="hidden" value="test.txt" />
  <input type="submit" value="Download">
</form>

The above code is being used to download the the text file "test.txt" One of many text files in my upload folder.
My issue?
How do I turn the value test.txt into a variable? A previous awnser I've read would be this:
<input type="hidden" name="file_name" value="<?php echo htmlspecialchars($file); ?>" />

The problem is that when I do that, it downloads force_download.php instead of any of my files.
I only started coding a few days ago, so yeah... sorry for the newbie question.
Comment: not really sure what you are  asking but perhaps file_get_contents()
Comment: Duplicate of: http://stackoverflow.com/questions/171318/how-do-i-capture-php-output-into-a-variable
Comment: you mean you want the form action to be the file name inserted in the input by the user?
Comment: The above code is used to download a file from my website. Right now I'm downloading test.txt. This works fine! I get the test.txt no problem.
However, I've got multiple files on my website, and I'd like all of them to have a download button. I figured, to do this I had to turn my value="test.txt" into a value=$file code.

I tried doing this with the line you see underneath my main code. However this results in me downloading a "force_download.php" file, instead of any of the files I've uploaded on my website.
Comment: You need to use javascript in order to change a DOM object's property
Comment: Oh god, that sounds really complicated. Haven't had java yet. Well thanks for the advice guys. I'm afraid I'm going to fail my grade, but so be it.

There's still a lot I need to learn. =)
Comment: What code are we seeing? is it "force_download.php"?
Comment: Oh yes indeed it is! My mainfile intranet.php contains this code which links to the force_download.php that you see in my original post.
http://pastebin.com/ZDGZ6eH2

As you can (hopefully) see. This code is used to display any uploaded .txt, .docx and .pfd files I've uploaded to my "Uploads" folder. Then at line 17 it referes to force_download.php
Comment: @DennisDekker It just sounds complicated, it really isn't. And note that java and javascript are two entirely different languages :P
Comment: Y'know what guys. I spend a good 60 hours over the past 6 days working on this intranet. I've learned so much in this time, but it's past midnight now and the only thing keeping me awake is the stress.

I'm going to bed, have my assessement tomorrow and get feedback. With a little luck they'll give me a chance to try again next week, so I'll be sure to keep lurking around this thread.

Just wanted to let you know that I really appreciate the quick replies! Makes the love the internet even more!

-Dennis
Answer: Here is one suggestion, you might need to do some ajustments.
In the file calling this one you posted the code to:
(if I understood good: intranet.php)
<form action="force_download.php" method="post" name="downloadform">
<?php
$path = "./filesfolder/"; // this you need to change to your files folder

function createDir($path)
{
    if ($handle = opendir($path))
    {
        while (false !== ($file = readdir($handle)))
        {
            if (is_dir($path.$file) && $file != '.' && $file !='..')
                printSubDir($file, $path, $queue);
            else if ($file != '.' && $file !='..')
                $queue[] = $file;
        }
        printQueue($queue, $path);
    }
}
function printQueue($queue, $path)
{
    foreach ($queue as $file)
    {
        printFile($file, $path);
    }
}
function printFile($file, $path)
{
    if ($file=="thumbs.db") {echo "";}
    else
    {
    echo "
<input name= \"".$file."\" type=\"hidden\" value=\"".$file."\" />";
    }
}
createDir($path);
?>
<input type="submit" value="Download">
</form>

This will generate the html for all files it finds, with the clickable link to each file. In this case you don't need the  in the file you posted (which I think is force_download.php)
Answer: Here a function I wrote and use for a while, please consider adding the a routine for the correct contect-type as well:
function downloadFile($fullPathToFile, $renameFile=''){
        if(is_file($fullPathToFile)){
            $path_parts = pathinfo($fullPathToFile);
            $dirname =  $path_parts['dirname'];
            $basename = $path_parts['basename'];
            $extension = $path_parts['extension'];
            $filename = $path_parts['filename'];
            $filesize = filesize($fullPathToFile);

            if(!empty($renameFile)){
                $extension = preg_match("/\.([^\.]+)$/", $renameFile, $matches);
                $extension = preg_replace('/\./', '', $matches[0]) ;
            }
                    /*Change the following one line to type of files or comment out*/
            header("Content-Type: text/plain");
            header ("Content-Length: " . $filesize );
            header("Pragma: ");
            header("Cache-Control: ");
            if($renameFile){
                header("Content-Disposition: attachment; filename=\"$renameFile\"");
            }else{
                header("Content-Disposition: attachment; filename=\"$basename\"");
            }
            ob_clean();
            flush();
            readfile($dirname.'/'.$basename);
            die();
        }
        else {
            echo 'no such file or directory';
        }
}


Graphical artifacts with OpenGL?

Question: I'm not sure if its called a graphical artifact but see this:
http://img835.imageshack.us/img835/9785/anomoly.png
You will notice 6 pixels on the black outline that are out of place.
My application allows zooming in and when I render I do this:
RENDER:
// Set an orthogonal projection matrix
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(GetCameraX() - ((float)controls.MainGlFrame.Dimensions.x) * scene[current.currentScene].camera.ScaleFactor
        / 2, GetCameraX() + ((float)controls.MainGlFrame.Dimensions.x) * scene[current.currentScene].camera.ScaleFactor / 2,
        GetCameraY() - ((float)controls.MainGlFrame.Dimensions.y) * scene[current.currentScene].camera.ScaleFactor / 2,
        GetCameraY() + ((float)controls.MainGlFrame.Dimensions.y) * scene[current.currentScene].camera.ScaleFactor / 2,
        -1.0f, 1.0f);

    // Set the model matrix as the current matrix
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    hdc = BeginPaint(controls.MainGlContext.mhWnd,&ps);

    //start OGL code

Camera struct looks like this:
struct SceneCam {
    double x;
    double y;
    double tempX;
    double tempY;
    double ScaleFactor;

};

I suspect this might be the issue since what I use to do is just set a top left coorinate system and GlTranslate all my geometry, but I thought doing it this way was more proper. The artifacts are random, and rarely happen but I still want to get rid of them.
Thanks
Render:
void CGlEngine::RenderShapes()
{

    // Set an orthogonal projection matrix
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(GetCameraX() - ((float)controls.MainGlFrame.Dimensions.x) * scene[current.currentScene].camera.ScaleFactor
        / 2, GetCameraX() + ((float)controls.MainGlFrame.Dimensions.x) * scene[current.currentScene].camera.ScaleFactor / 2,
        GetCameraY() - ((float)controls.MainGlFrame.Dimensions.y) * scene[current.currentScene].camera.ScaleFactor / 2,
        GetCameraY() + ((float)controls.MainGlFrame.Dimensions.y) * scene[current.currentScene].camera.ScaleFactor / 2,
        -1.0f, 1.0f);

    // Set the model matrix as the current matrix
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    hdc = BeginPaint(controls.MainGlContext.mhWnd,&ps);

    //start OGL code

    glClear( GL_COLOR_BUFFER_BIT);

for(unsigned int currentlayer = 0; currentlayer < scene[current.currentScene].layer.size(); ++currentlayer)
{

    for(unsigned int i = 0; i < scene[current.currentScene].layer[currentlayer].Shapes.size(); i++)
    {

        //render shape here
        scene[current.currentScene].layer[currentlayer].Shapes[i].Render();

    }

}

for(int i = 0; i < TempBuffers.size(); ++i)
{
    if(scene[current.currentScene].layer[TempBuffers[i].layer].Shapes[TempBuffers[i].shape].Contour[0].DrawingPoints.size() > 1)
    {

    glColor3f(0,0,0);
    glBindBufferARB(GL_ARRAY_BUFFER_ARB,controls.MainGlFrame.BufferVBO);
    glBufferDataARB(GL_ARRAY_BUFFER_ARB,sizeof(GLdouble) * scene[current.currentScene].layer[TempBuffers[i].layer].Shapes[TempBuffers[i].shape].Contour[0].DrawingPoints.size() * 2
        ,(GLdouble*)(&scene[current.currentScene].layer[TempBuffers[i].layer].Shapes[TempBuffers[i].shape].Contour[0].DrawingPoints[0]),GL_STATIC_COPY);

        glEnableClientState(GL_VERTEX_ARRAY);

    glBindBufferARB( GL_ARRAY_BUFFER_ARB, controls.MainGlFrame.BufferVBO);
    glVertexPointer( 2, GL_DOUBLE, 0, (char *) NULL );      // Set The Vertex Pointer To The Vertex Buffer

    if(scene[current.currentScene].layer[TempBuffers[i].layer].Shapes[TempBuffers[i].shape].connected)
    {
            glDrawArrays(GL_LINE_LOOP, 0, scene[current.currentScene].layer[TempBuffers[i].layer].Shapes[TempBuffers[i].shape].Contour[0].DrawingPoints.size());
    }
    else
    {
        glDrawArrays(GL_LINE_STRIP, 0, scene[current.currentScene].layer[TempBuffers[i].layer].Shapes[TempBuffers[i].shape].Contour[0].DrawingPoints.size());

    }

    glColor3f(1,0.5,0.5);
    //glDrawArrays(GL_POINTS, 0, layer[TempBuffers[i].layer].Shapes[TempBuffers[i].shape].Contour[0].DrawingPoints.size());

    glDisableClientState(GL_VERTEX_ARRAY);

    glBindBufferARB( GL_ARRAY_BUFFER_ARB, 0);
    }
}
/*
    glColor3f(0,0,0);
    glLineWidth(2);
    */
/*
    if (ObjectBuffer.Contour[0].UserPoints.size() > 0)
    {

        glBegin(GL_LINES);
        for(unsigned int i = 0; i < ObjectBuffer.Contour[0].DrawingPoints.size() - 1; ++i)
        {
            glVertex2d(ObjectBuffer.Contour[0].UserPoints[i].UserPoint.x,ObjectBuffer.Contour[0].UserPoints[i].UserPoint.y);
            glVertex2d(ObjectBuffer.Contour[0].UserPoints[i + 1].UserPoint.x,ObjectBuffer.Contour[0].UserPoints[i + 1].UserPoint.y);
        }
        glEnd();
    }
*/

    //end OGL code
    glFlush();
    Sleep(1);

    SwapBuffers(hdc);

    EndPaint(controls.MainGlContext.mhWnd,&ps);

}

Resize:
void CGlFrame::resize(HWND mainWindow,CGlContext *context, float rightRemainder)
{
    RECT clientRect;
    GetClientRect(mainWindow,&clientRect);

if(!hasstarted)
{
    context->killOGL();
    context->init(framehWnd,
        context->format);
    hasstarted = true;
    //Generate a VBO
    glGenBuffersARB(1,&BufferVBO);

}

SetWindowPos(framehWnd,NULL,toolWidth,tabHeight,
            (static_cast<int>(((clientRect.right - clientRect.left) - toolWidth) - rightRemainder) ) + toolWidth,
            (static_cast<int>((clientRect.bottom - clientRect.top) - tabHeight - paramHeight) ) ,NULL);

int width;
int height;
RECT newwin;
GetClientRect(framehWnd,&newwin);
width = newwin.right - newwin.left;
height = newwin.bottom - newwin.top;

Dimensions.x = width;
Dimensions.y = height;
glViewport(0, 0, width, height);

glShadeModel(GL_SMOOTH);
glHint(GL_PERSPECTIVE_CORRECTION_HINT,GL_NICEST);
glEnable(GL_POLYGON_SMOOTH);
glEnable(GL_LINE_SMOOTH);
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
//glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);

glEnable(GL_MULTISAMPLE_ARB);
glEnable(GL_BLEND);
glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glClearColor( 1.0f, 1.0f, 1.0f, 0.0f );
glLineWidth(2);
glPointSize(5);

}

Shape render:
void CGlShape::Render()
{
    if(!render)
    {
        return;
    }
glColor4f(MainShapeColor.r,MainShapeColor.g,MainShapeColor.b,MainShapeColor.a);
if(Gradient.active)
{
    glEnable(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D,Gradient.TextureId);
}
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);

glBindBufferARB( GL_ARRAY_BUFFER_ARB, ObjectVBOInt);
glVertexPointer( 2, GL_FLOAT, 0, (char *) NULL );       // Set The Vertex Pointer To The Vertex Buffer
glBindBufferARB( GL_ARRAY_BUFFER_ARB, TextureCoordsVBOInt);
glTexCoordPointer( 2, GL_FLOAT, 0, (char *) NULL );     // Set The Vertex Pointer To The Vertex Buffer

glDrawArrays(GL_TRIANGLES, 0, ObjectVBOCount);

glDisableClientState(GL_TEXTURE_COORD_ARRAY);

glBindBufferARB( GL_ARRAY_BUFFER_ARB, 0);
glDisable(GL_TEXTURE_2D);

for(int i = 0; i < Contour.size(); ++i)
{
    glColor4f(Contour[i].Outline.OutlineColor.r,
        Contour[i].Outline.OutlineColor.g,
        Contour[i].Outline.OutlineColor.b,
        Contour[i].Outline.OutlineColor.a);

glBindBufferARB( GL_ARRAY_BUFFER_ARB, Contour[i].Outline.OutlineVBO);
glVertexPointer( 2, GL_FLOAT, 0, (char *) NULL );       // Set The Vertex Pointer To The Vertex Buffer
glDrawArrays(GL_TRIANGLES, 0, Contour[i].Outline.OutlineSize);
glBindBufferARB( GL_ARRAY_BUFFER_ARB, 0);
}
glDisableClientState(GL_VERTEX_ARRAY);

}

Edit
I managed to solve it by rendering the outlines twice with a gltranslation of 0.00001. This works but causes overdraw, I wish I had a better solution.
Answer: Given their placement (right where two triangles butt up against each other), I'd guess that it's a simple matter of floating point rounding so the two objects don't "hit" against each other exactly.
At a guess, drawing the black section as a couple of GL_TRIANGLE_STRIPs instead of individual GL_TRIANGLES would stand a decent chance of fixing the problem (also stands a decent chance of improving performance a bit since it reduces the number of vertices you need to give it).

Graphical artifacts with OpenGL?


Find the number of other values of n for which $S_{n}$ = r is

Question: Consider an arithmetic progression whose first term is $4$ and
the common difference is $-0.1.$ Let $S_{n}$ stand for the sum of the first
n terms. Suppose r is a number such that $S_{n}$ = r for some n. Then
the number of other values of n for which $S_{n}$ = r is
I am getting $S_{n}$ as $$\frac{n}{2}(8.1-0.1*n)$$
Next how to process further?
Comment: Equate the expression for $S_n$ to $r$ and solve the quadratic equation.
Comment: @DevanshKamra What are you talking about? Did you try your own idea? It is not really a trivial problem.
Comment: @peter.petrov What's the problem? He needed other values of $n$ where $S_n$ is equal to $r$, he has the expression for $S_n$, equating it to $r$ would give a quadratic equation in the form of $n$ solving which would give the values of $n$ where $S_n=r$. I don't see what you find troubling here.
Comment: @DevanshKamra OK, solve it yourself first and you will see what is troubling here.
Answer: Let's rewrite your expression as $$S_n=\frac{81n-n^2}{20}$$  Now if the sum of the first $m$ terms equals the sum of the first $n$ terms, we have $$\frac{81n-n^2}{20}=\frac{81m-m^2}{20}$$
Can you finish it now?
EDIT
We have $n+m=81$ or $m=81-n$.  But $m$ must be a positive integer for this to make sense.  So there is $1$ solution if $1\leq n\leq80$ and no solution if $n\geq81$.
P.S.
To be absolutely complete, I should note that the case $m=n$ is not possible.
Comment: can u say why are u writing this "if the sum of the first m terms equals the sum of the first n terms"
Comment: I get $n=\dfrac{8.1\pm \sqrt{72.9-0.8r}}{0.2}$. What's wrong in this?
Comment: @DevanshKamra The problem is that it involves an unknown value $r$.  You should be able to answer the question instantly, just knowing the value of $n$.
Comment: @DevanshKamra how can u conclude ans from this?
Comment: @Silverstalon That's the question, isn't it?  $S_n$ is the sum of the first $n$ terms, and we're asked how many values of $m$ are there such that $S_n=S_m$
Comment: @saulspatz So are you saying that the value of $n$ won't depend on $r$?
Comment: @DevanshKamra No, I'm saying that you shouldn't have to solve a quadratic.  Please read my answer.
Comment: @saulspatz my bad! I have not gone through your solution deeply! .Thanks. after getting m+n =81 ...how to conclude ?
Comment: @Silverstalon Both $m$ and $n$ must be positive, so ...
Comment: @Silverstalon See my edit.
Comment: @saulspatz yes got it. I was wasting my time towards no of  pairs rather solution. the ans must be $0$ or $1$
Comment: @Silverstalon That's right.  If this answered your question, you should accept it by clicking the check mark, so that your question no longer shows as unsolved.


What is the size of shared memory page?

Question: On Linux, for each process, I can check /proc/PID/statm file.
It's numbers contain values of:

Total program size, in kilobytes
Size of memory portions, in kilobytes ??????
Number of pages that are shared

Which is great, but how do I know how much is a page?
Answer: 99% of the time a page is 4096 bytes.
Answer: On most common hardware (like AMD64 and i386), a memory page is 4 kilobytes. If I remember correctly, Sparc and some other architectures can do bigger pages, like 8kb.
Answer: I'm not a Linux god (by any means) but typically page sizes are 4Kb.  There's a pagesize command that should tell you what it is set to on your system.  This gives the output of the getpagesize() function.
Comment: Actually, there is only the POSIX getpagesize() *function*. I am not aware of a pagesize command on Linux.
Comment: Yeah, function (not method).  Thanks.  Brain on auto there.  Thought I remembered a pagesize command somewhere...  Maybe was on Solaris or HP-UX...
Comment: Thanks, wrote "program" : #include
void main(){printf("%d\n",getpagesize());}

and it returned 4096. thank you.
Comment: Really? You could have saved yourself some trouble there. If you're not on something other that your average Intel / AMD machine, it's always the same...
Comment: @wzzrd - I feel really bad about assuming something that "happens on average, usually, nearly always".

What is the size of shared memory page?


How to fetch the status of Internet security setting(Display mixed content) using javascript or c# code

Question: Is there any way to detect the internet security setting using javascript or through C# code
Answer: I think it depends on Browser and OS how you can do this and most of all, if you like to do it from within the browser or not.
You can do it for example for Windows/IE using JScript. But ususally not within the browser, because you will have to read the registry.


Is it possible to disable clients not supporting SNI in nginx?

Question: By default nginx serves https requests with multiple certificates by using SNI. The fallback for clients not supporting SNI will be the default_server or first vhost which has been configured.
I want nginx to not serve clients which don't support SNI.
For instance, if I check a site with the ssl test on ssllabs.com, the certificate sent by SNI will be shown, but also the fallback certificate without SNI support will be shown.
I'm in search of something like strict-sni in HAProxy.
I'm not using nginx+.
Answer: Did you try to create a  server block with the IP address as server_name using ssl_reject_handshake on from nginx version 1.19.4 and above?
This should prevent answers the the IP without SNI.
Comment: This is extremely new; and most of us will not take a mainline nginx, but will wait for a stable 1.20.
Comment: This is not part of the requirements of the OP. Question asked, answer given. Even if probably more than 2 years late :D
Comment: I will try it, when a compatible version is in the repository of my distro. Until then you sadly need to wait for me to accept your answer. :(
Comment: You can also compile from source code instead of using a repository package.


if $g$ is a lie algebra what is $g^*$?

Question: Iam trying to learn what a coadjoint orbit is but I can't since everywhere I look  the definition involves $g^*$.Something that I googled and didn't find anything. I am not even sure what $g^*$. Is it just the dual vector space of our the vector space $V$ of $g$. Is it somehow a lie algebra?, or even maybe even something dual to the notion of lie algebra. Can anyone explain
Thanks in advance
Comment: $g^*$ is the dual space of $g$. The algebra $g$ acts on $g^*$ via the coadjoint action, so $g^*$ is a $g$-module. The Lie group $G$ which has $g$ as Lie algebra also acts on $g^*$, and the *coadjoint orbits* are the orbits of $G$ acting on $g^*$.
Answer: A Lie algebra ${\frak g}$ is in particular a vector space, and $\frak{g}^*$ denotes the dual vector space.
It does not come with any canonical Lie algebra structure, we just think of it as a vector space.
Comment: It has a Poisson bracket, though.
Answer: Here $\mathfrak{g}$ also denotes the adjoint module, given by the adjoint representation $ad\colon \mathfrak{g}\rightarrow \mathfrak{gl}(\mathfrak{g})$. It is a $\mathfrak{g}$-module. Its dual module is denoted by $\mathfrak{g}^{\ast}$. So I would answer the title question as follows:
"If $\mathbb{g}$ is a Lie algebra - then $\mathfrak{g}$ and $\mathfrak{g}^{\ast}$ are $\mathfrak{g}$-modules".

if $g$ is a lie algebra what is $g^*$?


CORS error when sending request to ASP.NET Web API

Question: I am trying to send a request from an angular application and an ASP.NET web API both running in localhost on two different ports. When sending a request from the angular app(frontend) to the Web API I am getting a CORS error that "No 'Access-Control-Allow-Origin' header is present on the requested resource".
I tried a lot of ways to try to solve this issue like enabling cors in the WebApiConfig class, custom headers in the web.config and intercepting pre-flight checks but still, the issue occurred.
WebApiConfig.cs
var corsAttr = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(corsAttr);

Web.config
<system.webServer>
    <httpProtocol>
    <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Content-Type,
            Access-Control-Allow-Headers, Authorization, X-Requested-
            With, X- AuthToken" />
        <add name="Access-Control-Allow-Methods" value="GET, POST, PUT,
                 DELETE, OPTIONS" />
   </customHeaders>
   </httpProtocol>
   <modules runAllManagedModulesForAllRequests="true">
     <add name="HandleOptions" type="OptionsModule" />
   </modules>
 </system.webServer>

Comment: take a look at https://stackoverflow.com/questions/18619656/enable-cors-in-web-api-2 Mosharaf Hossain answer worked for me
Comment: Also have look at [this](https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api).
Comment: @AmitBaranes tried it but the error still occurs
Comment: @Nik That was the first document I read
Answer: It seems that the site you requested doesn't allows any resources to be accessed from any other domain. Means the site you have requested has not implemented CORS (cross origin request sharing).
Temporary solution:
You can use a proxy (https://crossorigin.me/https://google.com), all you need to do --> just append https://crossorigin.me/ before your url and for more details
Check HERE .
Second and permanent solution:
That you have to implement cross origin resource sharing for the site you are requesting resources from.
Third one:
3rd is you can disable CORS from your browser (https://alfilatov.com/posts/run-chrome-without-cors/).
Check these sites for more details1,2
Comment: The problem is that I have implemented CORS on my api but it still doesn't work.
Comment: kindly check this one: https://stackoverflow.com/questions/29024313/asp-net-webapi2-enable-cors-not-working-with-aspnet-webapi-cors-5-2-3
Comment: I have tried all of these but the problem still persists
Comment: https://stackoverflow.com/questions/42199757/enable-options-header-for-cors-on-net-core-web-api
Comment: is last url helpful because i'm not able to find any issue in your code.
Answer: I see that you declared EnableCors in both WebApiConfig.cs and Web.config.
This usually gives cors error saying something like:
'....origin 'www.example.com' blocked by cors policy due to multiple No 'Access-Control-Allow-Origin'('*','*').'

You should uncomment in either web-api.config or web.config and try.
Answer: This error you will get using different port numbers between MVC and Web Rest API. So you have to change post or get request header allows methods "true". So if you have to change in web API two places then, you can resolve this error in MVC with web Api

Go to App_Start folder and open WebAPIConfig.cs file.
Just add this line "config.EnableCors();  with namespace "using system.web.http;
Go to api controller and add this line in top of Controller, "[EnableCors("","","*")], Inside all double quotation need to add star * symbol.
You can add Action method level in same code.
[EnableCors("","","*")] in controller code.


Irreducible polynomials representation

Question: Can anyone prove it? I should prove the existence and unique:
Let p be an irreducible polynomial of k[x] of degree m. Prove that every element of k[x]/(p) can be represented uniquely by an expression of the form
a1x^(m−1) + a2x^(m−2) + · · · + am−1.

(Existence.) Every element of k[x]/(p) can be represented as described. This just means that
each equivalence class of k[x]/(p) contains an element of the kind shown.
(Uniqeness.) Each equivalence class contains exactly one element of the given kind. As usual assume there are two such elements in a class and show they must be the same. So assume that f = a1x^(m−1) + a2x^(m−2) + · · · + am−1 and
g = b1x^(m−1) + b2x^(m−2) + · · · + bm−1 are in the
same equivalence class and prove that ai = bi for 1 ≤ i ≤ m − 1, i.e., that f = g in k[x].

Thanks in advance!
Answer: Existence : If you have a polynomial with degree $m$ or more, you can divide it by $p$ with remainder. The remainder has the same equivalence class and degree at most $m-1$
Uniqueness : If $f$ and $g$ are polynomials with maximum degree $m-1$, then the difference $f-g$ also has maximum degree $m-1$. Since $f-g$ must be divisible by $p$, it follows $f=g$.

Irreducible polynomials representation


Passar variável pelo ConverterParameter

Question: Tenho o seguinte trecho de código:
Visibility = "{Binding TipoDestinatario, Converter={StaticResource conversorTipoDestinatario}, ConverterParameter=}.

Precisaria passar uma variável booleana pelo ConverterParameter=, alguém saberia como fazer?
Answer: SeuChapeu, até aqui não consegui usar Binding para o ConverterParameter. Como você precisa passar uma variável, uma sugestão viável é usar o MultiBinding:
XAML

        <MultiBinding Converter="{StaticResource VisibilidadePedidoConverter}">
            <MultiBinding.Bindings>
                <Binding Path="Pedido.Situacao" />
                <Binding Path="PodeFecharPedido" />
            </MultiBinding.Bindings>
        </MultiBinding>

Converter
using System;
using System.Windows.Data;

namespace CSharp2.Capitulo10.Wpf.Produtos.Converters
{
    public class VisibilidadePedidoConverter : IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            try
            {
                var podeVisualizar = (System.Convert.ToInt32(values[0]) == 1) && System.Convert.ToBoolean(values[1]);

                return podeVisualizar ? System.Windows.Visibility.Visible : System.Windows.Visibility.Hidden;
            }
            catch
            {
                return System.Windows.Visibility.Visible;
            }
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotSupportedException("Not implemented");
        }
    }
}

Comment: como faço pra passar um valor que vem de um método que está no presenter?
Comment: Bem, uma alternativa é o método ser void e manipular diretamente o valor que você precisa:
public void Initialize()
{
    Contact = LoadContactFromDatabase();
}

public Contact Contact { get; set; }

Passar variável pelo ConverterParameter


Event Viewer ID for start events

Question: What is the Event ID code in the Windows Event Viewer that will tell me:
Server has started
IIS has started
Is there a place online where I can look these things up?
Thanks!
Chris
Answer: Well, you surely know about Microsoft Technet and their effort of an Event ID search. The site eventid.net (free and paid contents) might also be no news for you.
You specifically asked about a list of Event-IDs. That now depends on your Windows (and IIS) version which you didn't provide. The free Windows 2003 Server Security Guide (see technet under Security Products and Technologies) lists quite a few of them and the second edition of the Windows Security Resource kit has a lot of information on auditing and event ID's. It is not free (see amazon.com) but worth a read.
Some general info on auditing can be found in the Security Monitoring and Attack Detection Planning Guide.

Event Viewer ID for start events


session set in folders php mysql

Question: i have this code:
$username = $_POST["username"];
$password = $_POST["password"];

if(mysql_num_rows($result80)>0)
 {
    $row80 = mysql_fetch_assoc($result80);
    $_SESSION["loginmng"] = 1;
    $_SESSION["username"] = $username;
    $_SESSION["password"] = $password;
    $fname = $row80["fname"];
    $lname = $row80["lname"];
    $userid = $row80["id"];
 }

and every thing is ok because i tryed to echo the session and its work in the same page (index.php)
now i have this check:
if(($_SESSION["loginmng"]!=1)||(!isset($_SESSION["username"]))||(!isset($_SESSION["password"])))
{
   header("Location: index.php");
}

when i put this into new folder:
newfolder/index.php
the check is not working right,when i have logged in , and the session is set....when i am tring to echo $_SESSION["loginmng"] and the other sessions,,its values is empty like no session setted and the header is got run ...and go to index...i have put session_start(); in the first php line too
i tryed too:
if($_SESSION["loginmng"]!=1)
{
  header("Location: ../index.php");
}

and the same thing...like no session set, what may be the problem
Comment: are you 100% sure the session is started? `session_start()` on top?
Comment: Can you put all the code from both files, to get a better view?
Comment: I don't quite understand your problem yet, but I do want to save you from a mistake that cost me many hours.  If you ever echo anything, than you cannot redirect with header("Location: ...")
Comment: Is session_start() at the top of the code in the first chunk?
Comment: @MihaiIorga thank you man , for truth i forgot session_start(); i didnt look good for the file , and i thought that session start is included , thank you all for your help
Answer: A PHP session variable is used to store information about, or change settings for a user session. Session variables hold information about one single user, and are available to all pages in one application.
PHP Session Variables
When you are working with an application, you open it, do some changes and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are and what you do because the HTTP address doesn't maintain state.
A PHP session solves this problem by allowing you to store user information on the server for later use (i.e. username, shopping items, etc). However, session information is temporary and will be deleted after the user has left the website. If you need a permanent storage you may want to store the data in a database.
Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID. The UID is either stored in a cookie or is propagated in the URL.
Starting a PHP Session
Before you can store user information in your PHP session, you must first start up the session.
Note: The session_start() function must appear BEFORE the  tag.
Comment: A security measure (not related exactly to your question): If you gonna store the user details as usernames and passwords in session variables, store them not in plain text, but encrypted, or hashed with, let`s say sha1() function, then compare/assign the hash with the hashed value from database.
Answer: Maybe you forgot to add session_start(); on top of the file.
To make session start on each page you need to start the session on each page.
session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.

session set in folders php mysql


Can we create instance method with out self

Question: I am trying to create class that having one instance method, is it possible to create instance method without self.
class A():
    def display():
        print("Hi")

a = A()
a.display()

I am getting like this: Type Error: display() takes no arguments (1 given)
Comment: can you elaborate on your usecase, why do you want an instance method (not static method!) without self?
Answer: For an instance method, you need to add a parameter that represents the instance itself. It MUST be present and it MUST be the first parameter of the method - that's mandatory, you cannot change this. It can be called whatever you want, although self is the standard used by the community, which you should also follow.
class A():

    def display(self):
        print('Hi')

Now, as you probably noticed, we're not doing anything in particular with the instance in the display method. To avoid this redundancy, we need to use a different type of method.
A method which does not take an instance as an argument is called a static method and is represented by the @staticmethod decorator directy above the function definition:
class A():

    @staticmethod
    def display():
        print('Hi')

Both snippets will run without errors and, producing the same output when you execute the following code:
a = A()
a.display()

But the second version is preferred - because explicit is better than implicit.
Comment: plus the second can be called with `A.display` instead of `A().display`. Plus you cannot call an instance method from a staticmethod but you can call a staticmethod from a staticmethod!
Answer: Using @staticmethod will work... but I won't recommend it for beginner uses
Usually function define an object behavior so you'll need the object itself using self !
Comment: Yaaa I know about staic method will work for this but it will not work on ay instance or any c lass variables and methods.My question is can we create instance method with out self or not
Comment: No as the method you try to call referes to an object as mentionned by @jfaccioni
Answer: As others have pointed out, an instance method must have at least one parameter, as the object itself is passed (implicitly) as the first argument. But why?
This def statement, like any other, defines a function, not a method. So where does the method come from? Let's go step by step.
class A:
    def display(self):
        print("Hi")

If we look directly in the dictionary that stores a class's attributes, we see that display is bound to an instance of function.
>>> type(A.__dict__['display'])
<class 'function'>

We get the same result if we try to access the attribute using the normal dot syntax:
>>> type(A.display)
<class 'function'>

But something ... different ... happens if we try to access that function via an instance of the class:
>>> type(A().display)
<class 'method'>

Where did the method come from? Anytime you access an attribute, the machinery that handles such access looks to see if the result has a __get__ method. The function type provides such a method, so instead of getting the function itself back, you get the result of calling that function's __get__ method. That is, A().display is really the same as A.display.__get__(A(), A). And what __get__ returns is an object that does two things:

Saves a reference to the instance A()
Saves a reference to the function A.display.

When you try to call this object, what it does is takes any arguments passed to it, and passes the saved reference to A() along with those arguments to the function A.display. That is,
a = A()
a.display() == A.display.__get__(a, A)(a)

An that's why display gets defined with one more argument than is seemingly necessary.

Others have also mentioned static methods. What does @staticmethod do? staticmethod is another type, whose instances wrap a function. The staticmethod definition of __get__, though, doesn't do anything other than return the underlying function, not any kind of new method object. So given
class A:
    @staticmethod
    def display():
        print("Hi")

we can see that display is an instance of static method, not a function:
>>> >>> type(A.__dict__['display'])
<class 'staticmethod'>

and that the __get__ method returns the function itself, whether the attribute is accessed via the class
>>> type(A.display)
<class 'function'>

or an instance
>>> type(A().display)
<class 'function'>