Show node IDs along with titles in Entity reference Autocomplete list

Question: I'll like to add this functionality to the autocomplete widget in Entityreference field to show node ID next to the titles in the dropdown list. The reason behind the idea is to differentiate between multiple nodes with same title.
Example:

This is a title (3)
This is a title (2)
This is a title (1)

I know the node ID is shown once a selection is made but I like to show it in the dropdown list in order to pick the right node quickly based on the node ID.
Comment: take a look at this http://drupal.stackexchange.com/questions/82165/override-entityreference-autocomplete-and-return-entityfieldquery-output/82665#82665
Comment: @oksana-c check my answer with another easy way
Answer: Install the Views and Entity Reference modules, create a new View and Add a Entity Reference Display:

Then Add in the fields the content title and the nid, click in the nid and check Exclude from display, Save and click in the title and go to rewrite the output of the title as [title] - ([nid])

Go to edit the settings of the format and check the title, this will allow you to search by title.

Save the view.
Go to edit your Entity Reference field and select in the Mode Views: .... (like the following image) and select your View (in this case the name is: articles_with_id) and save the settings:

Then go to see the result:

EDIT: This is now working in Drupal 8, at least in the version 8.3.4.
Comment: OMG, I always wondered what the views option was for. This is filthy!!!
Comment: No, it means it's a really good/impressive solution. Ex: [Alexander Nylander's Filthy Shootout Goal](https://www.youtube.com/watch?v=0fRUV53sOh8)
Comment: The only problem with this solution, is that the entity reference field, once selected, shows the ID twice in the entity edit form, because it is included by default once it is selected.
Comment: @AdrianCidAlmaguer I agree this solution is "sick"! [(idiom)](http://dictionary.reference.com/browse/idiom)
Comment: @NoSssweat I'm learning english now, can you provide me a synonym of filthy please? I can't understand the phrase "This is filthy"
Comment: Incase anyone stumbles across this. Its currently broken in 8.0+ https://www.drupal.org/node/2174633
Comment: Synonym: **Dirty**. I used it as an expression, should be taken **[figuratively and not literally](https://www.youtube.com/watch?v=Wa7TvxC2rgA).**
Comment: @NoSssweat Then is a bad solution?
Comment: @NoSssweat thanks, I learning English too in this site ;-)
Comment: @JohnR is sick in a good way or in a bad way? Remember that I learning english now, and sick is unwell, this confuse me a little ;-)
Comment: @Yuri Yes, I will see if I find a solution for this. thanks
Comment: Does anyone know if this works for the user entity as well. No matter how I seem to set it up it always displays the email address (user) and not firstname / lastname from the associated user entity. Great walk through btw!
Comment: @ShawnMatthews I think that will work, but I never made the test, you can follow the steps and test with users, if this works share here your results ;-)
Comment: @ShawnMatthews this is now working in drupal 8.3.4
Comment: @AdrianCidAlmaguer Im using Drupal 8.6+patch in above url (if I click 'Add Existing Badge', the entity view/autocomplete works). But I'm curious y this dropdown shows in the field's display: https://farm8.staticflickr.com/7856/46769243104_db4bcfa2e6_z.jpg

If I change the field to use the 'Default' Reference Method and pick my 'Badge' type, then there is no dropdown. Settings for that:
https://farm8.staticflickr.com/7816/47492694801_abd94f7970_z.jpg
vs settings for Entity Ref field which causes the dropdown to show up: https://farm8.staticflickr.com/7909/46577339485_e124628460_z.jpg
Comment: Adding to my above comment... in the 'Manage form display' settings of the Badge content type, the "Allow users to add new badges#2" is what adds that dropdown. its smart to recognize to only use Badge content type in the 'Add Existing' autocomplete since my entity ref view specifically filters on Badges, but the 'Add new' button doesn't use this view reference im guessing (since its not an autocomplete), so have to manually pick which content type you want to add. I wonder if there is a fix for this (like a way in the field settings to say 'use Badges in with Add New functionality')
Comment: @armyofda12mnkeys I really don't know, I'm not working with this feature now.
Answer: Create Entity Reference field with the default configuration

The function entityreference_autocomplete_callback_get_matches determines what the output of the autocomplete should be.
function entityreference_autocomplete_callback_get_matches($type, $field, $instance, $entity_type, $entity_id = '', $string = '') {
  $matches = array();

  $entity = NULL;
  if ($entity_id !== 'NULL') {
    $entity = entity_load_single($entity_type, $entity_id);
    $has_view_access = (entity_access('view', $entity_type, $entity) !== FALSE);
    $has_update_access = (entity_access('update', $entity_type, $entity) !== FALSE);
    if (!$entity || !($has_view_access || $has_update_access)) {
      return MENU_ACCESS_DENIED;
    }
  }

  $handler = entityreference_get_selection_handler($field, $instance, $entity_type, $entity);

  if ($type == 'tags') {
    // The user enters a comma-separated list of tags. We only autocomplete the last tag.
    $tags_typed = drupal_explode_tags($string);
    $tag_last = drupal_strtolower(array_pop($tags_typed));
    if (!empty($tag_last)) {
      $prefix = count($tags_typed) ? implode(', ', $tags_typed) . ', ' : '';
    }
  }
  else {
    // The user enters a single tag.
    $prefix = '';
    $tag_last = $string;
  }

  if (isset($tag_last)) {
    // Get an array of matching entities.
    $entity_labels = $handler->getReferencableEntities($tag_last, $instance['widget']['settings']['match_operator'], 10);

    // Loop through the products and convert them into autocomplete output.
    foreach ($entity_labels as $values) {
      foreach ($values as $entity_id => $label) {
        $key = "$label ($entity_id)";
        // Strip things like starting/trailing white spaces, line breaks and tags.
        $key = preg_replace('/\s\s+/', ' ', str_replace("\n", '', trim(decode_entities(strip_tags($key)))));
        // Names containing commas or quotes must be wrapped in quotes.
        if (strpos($key, ',') !== FALSE || strpos($key, '"') !== FALSE) {
          $key = '"' . str_replace('"', '""', $key) . '"';
        }
        /* *** */$matches[$prefix . $key] = '
' . $label .' - ('. $entity_id . ')
';//****
      }
    }
  }
  drupal_json_output($matches);
}

the last line $matches[$prefix . $key] = '
' determines the output and the $entity_id is available which is the ID. You can do what I did in that line (shown by **), simply write:
 $matches[$prefix . $key] = '
' . $label .' - ('. $entity_id . ')
';

you can use $entity_id to fetch other fields and anything you want.
 One More Thing!
Some times it is not a good idea to change the function of the core module (if it is not important to you the above solution is enough).
If you need to override the core function of the entity_reference module, build a small module and name it elabel
it is elabel.info
;$Id;
name = My Entity Reference Label
description = This module creates special Entity Reference Label
package = My Modules
core = 7.x
php = 5.1
files[] = elabel.module

and it is elabel.module
<?php function elabel_menu_alter(&$items){
    unset($items['entityreference/autocomplete/single/%/%/%']);
    unset($items['entityreference/autocomplete/tags/%/%/%']);

      $items['entityreference/autocomplete/single/%/%/%'] = array(
    'title' => 'Entity Reference Autocomplete',
    'page callback' => 'elabel_autocomplete_callback',
    'page arguments' => array(2, 3, 4, 5),
    'access callback' => 'entityreference_autocomplete_access_callback',
    'access arguments' => array(2, 3, 4, 5),
    'type' => MENU_CALLBACK,
  );

    $items['entityreference/autocomplete/tags/%/%/%'] = array(
    'title' => 'Entity Reference Autocomplete',
    'page callback' => 'elabel_autocomplete_callback',
    'page arguments' => array(2, 3, 4, 5),
    'access callback' => 'entityreference_autocomplete_access_callback',
    'access arguments' => array(2, 3, 4, 5),
    'type' => MENU_CALLBACK,
  );
  return $items;

}

function elabel_autocomplete_callback($type, $field_name, $entity_type, $bundle_name, $entity_id = '', $string = '') {
  // If the request has a '/' in the search text, then the menu system will have
  // split it into multiple arguments and $string will only be a partial. We want
  //  to make sure we recover the intended $string.
  $args = func_get_args();
  // Shift off the $type, $field_name, $entity_type, $bundle_name, and $entity_id args.
  array_shift($args);
  array_shift($args);
  array_shift($args);
  array_shift($args);
  array_shift($args);
  $string = implode('/', $args);

  $field = field_info_field($field_name);
  $instance = field_info_instance($entity_type, $field_name, $bundle_name);

  return elabel_autocomplete_callback_get_matches($type, $field, $instance, $entity_type, $entity_id, $string);
}

function elabel_autocomplete_callback_get_matches($type, $field, $instance, $entity_type, $entity_id = '', $string = '') {
  $matches = array();

  $entity = NULL;
  if ($entity_id !== 'NULL') {
    $entity = entity_load_single($entity_type, $entity_id);
    $has_view_access = (entity_access('view', $entity_type, $entity) !== FALSE);
    $has_update_access = (entity_access('update', $entity_type, $entity) !== FALSE);
    if (!$entity || !($has_view_access || $has_update_access)) {
      return MENU_ACCESS_DENIED;
    }
  }

  $handler = entityreference_get_selection_handler($field, $instance, $entity_type, $entity);

  if ($type == 'tags') {
    // The user enters a comma-separated list of tags. We only autocomplete the last tag.
    $tags_typed = drupal_explode_tags($string);
    $tag_last = drupal_strtolower(array_pop($tags_typed));
    if (!empty($tag_last)) {
      $prefix = count($tags_typed) ? implode(', ', $tags_typed) . ', ' : '';
    }
  }
  else {
    // The user enters a single tag.
    $prefix = '';
    $tag_last = $string;
  }

  if (isset($tag_last)) {
    // Get an array of matching entities.
    $entity_labels = $handler->getReferencableEntities($tag_last, $instance['widget']['settings']['match_operator'], 10);

    // Loop through the products and convert them into autocomplete output.
    foreach ($entity_labels as $values) {
      foreach ($values as $entity_id => $label) {
        $key = "$label ($entity_id)";
        // Strip things like starting/trailing white spaces, line breaks and tags.
        $key = preg_replace('/\s\s+/', ' ', str_replace("\n", '', trim(decode_entities(strip_tags($key)))));
        // Names containing commas or quotes must be wrapped in quotes.
        if (strpos($key, ',') !== FALSE || strpos($key, '"') !== FALSE) {
          $key = '"' . str_replace('"', '""', $key) . '"';
        }
        /* *** */ $matches[$prefix . $key] = '
' . $label .'('.$entity_id.')' .'
';
      }
    }
  }

  drupal_json_output($matches);
}

I tried this code and it works perfectly
If there are other type of entity references and you don't need to do this for them, simply add an IF statement and check for bundle or content type.
Answer: (function ($, Drupal, drupalSettings) {
  'use strict';

  Drupal.behaviors.my_module = {
    attach: function (context) {

      function autocomplete_tid_remove(field) {

        var autocomplete_tid = $(field).val();
        var autocomplete_tid_stripped = autocomplete_tid.replace(/(\([^*]+\))(?=.*\1)/,'');
        $(field).val(autocomplete_tid_stripped);

      }

      jQuery('.form-autocomplete').on('click', function () {
        window.currentElement = jQuery(this);
      });

      jQuery('.form-autocomplete', context).once('my_module').on('autocompleteclose', function () {
        autocomplete_tid_remove(currentElement);
      });
    }
  };

})(jQuery, Drupal, drupalSettings);

@Adrian Cid Almaguer answer is great! But shows nid twice as mentioned by @yuri. I was able to overcome this using js.


Sinus curve with jQuery

Question: I found this code snippet and have following questions:

What does the p stand for in function(p)?
{path: new SineWave}
What does this expression mean, what does path stand for?
What is
the stop() goof for in the example code?

js fiddle in firefox only
js
$(document).ready(function(){

window.SineWave = SineWave = function() {
  this.css = function(p) {
    s = Math.sin((p-1)*50);
    x = (100 - p*100) * 10;
    y = s * 20;
    return {top: y + "px", left: x + "px"};
  }
}

window.loop = loop = function(){
        $("#nyan").stop().animate(
        {path: new SineWave},
        50000,
        "linear"

    );
}

loop();
});

Comment: Is fiddle supposed to draw something?
Comment: The example animates a box along a sinus curve
Comment: Doesn't work in chrome, guess because it refuses to run script from raw.github (error from console)
Answer:
What does the p stand for in function(p)?

It's just an argument name.
Then, if you call the function like this.css(123), p will become 123.

What does {path: new SineWave} mean, what does path
  stand for?

I creates an object which has a property "path".
For example
var obj = {
   a: 123
}
obj.a; // 123
abj['a']; // 123

In your case, the value is another object (instead of number 123) which is an instance of SineWave constructor. That means it inherits properties and methods from SineWave.prototype.

What is the stop() goof for in the example code?

.stop() is a jQuery method which stops the currently-running animation on the matched elements.
Comment: Good question! If you go to [jQuery's source](http://code.jquery.com/jquery-2.0.3.js), `jQuery.fn` is extended with `animate` (the method you call), which passes your object to `Animation`, which passes it to `deferred.promise`. And now I'm lost, I don't know enough of jQuery, maybe you should ask it in another question.
Comment: Thank you! I printed p to the console and its value is p=1, then it shrinks to zero. Why ist it 1 and why does it shrink?

Sinus curve with jQuery


How to let a column accept null values as zero (0) in Self-Relation table

Question:
As described in the image, I got a parent-Children relation and since the ParentID not accepting null values (and I can't change to nullabel due to some restriction in the UI I have), how can I remove an existence relation between ReportDataSources in order to change the parent for them (here i want to set the parentId for one of them = 0) how could i do that since i cant change the ParentID directly and setting Parent = null is not valid
public void SetReportDataSourceAsMaster(ReportDataSource reportDataSource)
{
    //Reset Master
    this.ReportDataSources.ToList().ForEach(rds => rds.IsMaster = false);
    //Set Master
    reportDataSource.IsMaster = true;
    //Set Parent ID for the rest of the Reports data sources
    this.ReportDataSources.Where(rds => rds.ID != reportDataSource.ID).ToList().ForEach(rds =>
    {
        //Change Parent ID
        rds.Parent = reportDataSource;
        //Remove filttering data
        rds.FilteringDataMembers.Clear();
        //Remove Grouping Data
        rds.GroupingDataMembers.Clear();
    });
    //Delete parent HERE THE EXCEPTION THROWN AFTER CALLING SUBMITCHANGES()
    reportDataSource.Parent = null;
}

Exception thrown after calling SubmitChanges():

An attempt was made to remove a relationship between a ReportDataSource and a ReportDataSource. However, one of the relationship's foreign keys (ReportDataSource.ParentID) cannot be set to null.
Answer: Can't you make your root element be its own parent? You would have to check it each time you want to recursively find an element ancestor (to avoid unending loops), but I think it would work fine for you.
Comment: +1 Im testing this solution now, and if there is any trick i can do in LINQ avoiding the `selfParent` setting would be better
Comment: I agree this is just a workaround and not a real solution. But my competences with databases are not sufficient ofr me to propose anything else, so...


Various notations in functional analysis.

Question: In most literature on functional analysis the notation for an inner product on an inner product space $H$ is usually denoted $ \langle\cdot,\cdot\rangle:H \times H \mapsto \mathbb{K} $.  However, I have noticed that some authors perfers to write it as $ (\cdot | \cdot)  $. Searching on the internet this leads me to believe that this has something to do with notations in physic, namely the bra-ket which are frequently applied in quantum mechanics.
However what seems interesting to me more is that, even if $H$ is just a Banach space without an inner product, sometimes a functionl on the dual space $H^{\ast}$ of $H$ is denoted as follows:
$$f:H^{\ast} \longrightarrow \mathbb{K} : x \longmapsto f(x) \Longleftrightarrow \langle f,x\rangle: H^{\ast} \times H \longrightarrow \mathbb{K} $$
which actually seems super useful because it has this analogy with the Cauchy  Schwarz inequality:
$$| \langle f,x\rangle  | \leq \| f\|_{\text{op}} \|x\|_{H} $$
since $f$ is bounded. Also if $T^{\ast}$ is the dual operator of $T:H \rightarrow H$ then one also has
$$\langle T^{\ast}f,x\rangle  = \langle f, Tx\rangle $$
which in some sense resembles the notion of an adjoint.
So my question is: what are these notations called and where they come from? In particular do they actually have anything to do with the notion of inner product?
Thanks in advance!
Comment: A difference between the $\left\langle \cdot,\cdot\right\rangle$ notation is that it is bilinear in Banach spaces, but sesquilinear in (complex) Hilbert spaces (i.e. linear in one component, antilinear in the other).
Answer: Riesz representation theorem tells us for every $f \in H^*$ there exists an $y \in H$ such that $f(x) = \langle y,x \rangle$ for every $x \in H$, so this notation makes sense for Hilbert spaces.
Comment: The part on dual space also makes sense if $H$ is just normed.
Comment: It does indeed. On a Hilbert space $H$ this is the Cauchy-Schwarz inequality. If $X$ is a normed space, we call $\langle x, f \rangle := f(x)$ the dual pair.
Comment: There goes the name! Got it, thanks a lot!


SVM Classifier with HOG Features

Question: I am interested in having a system to detect and recognize speed limits from traffic signs. The detection part works fine, meaning that I am able to detect them inside any image. Now I would like to classify the result of the detector.
What is the correct way to do that? For example, I would like to recognize a speed limit of 50. Should I train an SVM with traffic signs of 50 as positive samples and as negative samples use what? Should I use all of the remaining speed limits (20, 30, 40, 60, 70....) as negative training samples? Is this the only way? Is there any other way (again using SVM) to do that? I am using Matlab's svm.
Answer: Your problem is very similar to hand-written digit recognition, which is the famous problem in supervised learning.
Tensorflow has a nice tutorial and a set of packages dealing with it. (https://www.tensorflow.org/versions/r0.7/tutorials/mnist/beginners/index.html#mnist-for-ml-beginners)
The only thing left is you need a set of labeled data: pictures that has digits in it, captured from the signs, labeled by somebody. If you have the detected parts of the images, crop the parts down and ship them to Mechanical Turk (https://www.mturk.com/mturk/welcome). If you don't have $$, you can share the labeling tasks with one or two of your friends/colleagues. 100 labels per day, takes 30 mins a day for about two week to get a sizable dataset.
Answer: Usually those signs have predefined sizes. If you are able to reliably detect them, I would expect some basic OCR system to be able to solve it. More concretely: it should be easy enough to rescale the sign to a predefined size (so that numbers have also the size you can expect), and then segment them based on the knowledge you have about those signs (white numbers on blue background, or black numbers on white background,...). Finally, some pretrained digit recognizer should be able to read them out.
Answer: I would suggest you to divide your system in two different classifiers: one for detecting traffic signals in images. Then I´d train a second classifier to detect numbers characters inside traffic signals, recognizing the whole number or one digit each time. This division makes the job easier for both classifiers and recognizing each digit instead of the whole number also makes it more robust to traffic signs out of your training sample.

SVM Classifier with HOG Features


Where memory segments are defined?

Question: I just learned about different memory segments like: Text, Data, Stack and Heap. My question is:
1- Where the boundaries between these sections are defined? Is it in Compiler or OS?
2- How the compiler or OS know which addresses belong to each section? Should we define it anywhere?
Comment: The C language itself has nothing whatever to say about any of those.
Comment: Since this is tagged embedded, this post [What resides in the different memory types of a microcontroller?](http://electronics.stackexchange.com/questions/237740/what-resides-in-the-different-memory-types-of-a-microcontroller) might be more useful than talk about operative systems.
Answer: This answer is from the point of view of a more special-purpose embedded system rather than a more general-purpose computing platform running an OS such as Linux.

Where the boundaries between these sections are defined? Is it in Compiler or OS?

Neither the compiler nor the OS do this.  It's the linker that determines where the memory sections are located.  The compiler generates object files from the source code.  The linker uses the linker script file to locate the object files in memory.  The linker script (or linker directive) file is a file that is a part of the project and identifies the type, size and address of the various memory types such as ROM and RAM.  The linker program uses the information from the linker script file to know where each memory starts.  Then the linker locates each type of memory from an object file into an appropriate memory section.  For example, code goes in the .text section which is usually located in ROM.  Variables go in the .data or .bss section which are located in RAM.  The stack and heap also go in RAM.  As the linker fills one section it learns the size of that section and can then know where to start the next section.  For example, the .bss section may start where the .data section ended.
The size of the stack and heap may be specified in the linker script file or as project options in the IDE.
IDEs for embedded systems typically provide a generic linker script file automatically when you create a project.  The generic linker file is suitable for many projects so you may never have to customize it.  But as you customize your target hardware and application further you may find that you also need to customize the linker script file.  For example, if you add an external ROM or RAM to the board then you'll need to add information about that memory to the linker script so that the linker knows how to locate stuff there.
The linker can generate a map file which describes how each section was located in memory.  The map file may not be generated by default and you may need to turn on a build option if you want to review it.

How the compiler or OS know which addresses belong to each section?

Well I don't believe the compiler or OS actually know this information, at least not in the sense that you could query them for the information.  The compiler has finished its job before the memory sections are located by the linker so the compiler doesn't know the information.  The OS, well how do I explain this?  An embedded application may not even use an OS.  The OS is just some code that provides services for an application.  The OS doesn't know and doesn't care where the boundaries of memory sections are.  All that information is already baked into the executable code by the time the OS is running.

Should we define it anywhere?

Look at the linker script (or linker directive) file and read the linker manual.    The linker script is input to the linker and provides the rough outlines of memory.  The linker locates everything in memory and determines the extent of each section.
Answer: For your Query :-
Where the boundaries between these sections are defined? Is it in Compiler or OS?
Answer is OS.
There is no universally common addressing scheme for the layout of the .text segment (executable code), .data segment (variables) and other program segments. However, the layout of the program itself is well-formed according to the system (OS) that will execute the program.
How the compiler or OS know which addresses belong to each section? Should we define it anywhere?
I divided your this question into 3 questions :-
About the text (code) and data sections and their limitation?
Text and Data are prepared by the compiler. The requirement for the compiler is to make sure that they are accessible and pack them in the lower portion of address space. The accessible address space will be limited by the hardware, e.g. if the instruction pointer register is 32-bit, then text address space would be 4 GiB.
About Heap Section and limit? Is it the total available RAM memory?
After text and data, the area above that is the heap. With virtual memory, the heap can practically grow up close to the max address space.
Do the stack and the heap have a static size limit?
The final segment in the process address space is the stack. The stack takes the end segment of the address space and it starts from the end and grows down.
Because the heap grows up and the stack grows down, they basically limit each other. Also, because both type of segments are writeable, it wasn't always a violation for one of them to cross the boundary, so you could have buffer or stack overflow. Now there are mechanism to stop them from happening.
There is a set limit for heap (stack) for each process to start with. This limit can be changed at runtime (using brk()/sbrk()). Basically what happens is when the process needs more heap space and it has run out of allocated space, the standard library will issue the call to the OS. The OS will allocate a page, which usually will be manage by user library for the program to use. I.e. if the program wants 1 KiB, the OS will give additional 4 KiB and the library will give 1 KiB to the program and have 3 KiB left for use when the program ask for more next time.
Most of the time the layout will be Text, Data, Heap (grows up), unallocated space and finally Stack (grows down). They all share the same address space.
Answer: The sections are defined by a format which is loosely tied to the OS.  For example on Linux you have ELF and on Mac OS you have Mach-O.
You do not define the sections explicitly as a programmer, in 99.9% of cases.  The compiler knows what to put where.

Where memory segments are defined?


Blocking facebook on company network

Question: Our ISP forced us to use their router that doesn't have any option to block certain URL/IP like our 3Com OfficeConnect router has.
Is there any other easy way to implement this without an intelligent router (we are also using a D-Link 1016 switch). Or shall we buy a more recent 3Com router?
Thanks.
Comment: There's a number of ways to do this, but without knowing much about your network's configuration or your budget I don't think anyone can really give an appropriate recommendation.  One thing that will be fairly consistent though, is that you should have another piece of hardware between the clients you are trying to block and the Internet.
Comment: I dont think so, they can force you to use their router, because all what they can check is MAC, so you can use your one and fake MAC
Comment: Don't.  Or do you really want to demoralise your staff?
Comment: @TomO'Connor (and everyone) ordinarily I agree with the sentiment, but I had a recent run-in today that justifies the blocking for another reason; browse-by infections. Most users don't want to be blocked, but on the other hand they don't want to take responsibility for safe web browsing and keeping systems protected. There are vulnerabilities that lead to infections and data theft without the user ever knowing. Sometimes the blocking of sites helps prevent this, so you're protecting users from themselves with filtering.
Answer: OpenDNS, or another (and possibly more controlled) option is to build a proxy server between your network and the router. You can do something open source like Squid and an addon for blocking or you can purchase any of many commercial solutions for blocking websites by category.
If you're going to be blocking websites, it's generally better in my experience to use a proxy filter instead of your router since the proxy can log traffic and be used to extract reports.
Comment: +1 I'd also talk it over with management and determine how you want to implement this: I've had better results by quietly logging activity and when/if warranted, address with problem users individually, as most employees were not an issue. An over-zealous blocking policy can often lead to bad morale, or worse, employees looking to bypass through upstream proxies, tethering 3G phones, etc.
Comment: I suppose if you have the machine statically configured, you could point it to whatever DNS server you want so it wouldn't get influenced by OpenDNS.
Comment: I was assuming this was coming from management in the first place, but what you're bringing up is a topic that makes a lot of sysadmins squirm...censorship in the workplace is not a comfortable thing. But on the other hand it's amazing how often assuming people won't abuse privileges works against you. But again that's been my experience.
Comment: It can go either way, depending on the culture, but the majority of my clients that decided to 1) notify the staff 2) monitor the activity 3) react accordingly found that #1 alone deterred excessive facebook/time-wasting and that only a very small minority were actually abusing their privileges.  Obviously adult/hate/gambling/drugs, etc. categories are blocked outright as there's no place in the workplace for that.
Comment: @Bart: Thanks, what do you mean with _(and possibly more controlled)_?
Comment: @devdept: you would have finer control over what you block and monitor.
Comment: @Bart: is it possible to exclude one machine from OpenDNS filtering if I setup it on the router?
Answer: I am assuming this also means you have virtually ZERO protection on your network other than NAT.   NAT is not a true firewall (but does a good job...)
Check out the PFSense project - Free OpenSource and very good. www.PFSense.org add the Squid support and you are golden.
Another simple project - (both free or paid) would be Untangle. Easier - imho.
These can each operate in a transparent mode - allowing you to lock down your network but also protect it.
Answer: Use OpenDNS.

Blocking facebook on company network


Fingerstyle finger economy - how to play phrases that require index finger on high strings?

Question: Is this fingering correct/optimal?

    1    4
    4   4
    3  4
      2

E|--5-------
B|--7----7--
G|--7---7---
D|-----7----
A|----------
E|----7-----
Answer: Different styles fit different people, so correct or optimal has many answers. I would have used:
<code>2*    4
4    3
3   2
   1

* or 1 if strings are inadvertently muted
</code>
(I'm assuming we're talking left hand fingers here, fingerstyle guitar usually means the that the right hand fingers are used to strum.)
Comment: I have to agree here - in playing the guitar there is rarely a 'correct' fingering, unless you want to match exactly how the original artist played. Use whatever works best for you.


Excluir um item e adicionando novamente começando índice por contar 1 {ERRO}

Question: Quando você adiciona nome, idade e a quantidade vai contar pelo índice ,mas quando você clica prar excluir apaga tudo quantidade fica = 0 , nome e idade =  por "vazios"
ai certinho, mas quando adiciono novamente, a quantidade começa por 2 (índice) mas quero começar por 1
Por que ficou por 2 ?
tentei varias coisas aqui não sei o que fazer, o que faço?

let a = []

function adicionar() {
  var nome = document.getElementById("nome")
  var idade = document.getElementById("idade")
  var r = document.getElementById("res")
  if (nome.value == "" && idade.value) {
    alert("Por favor digite o seu nome e sua idade!")
  }
  if (nome.value.length && idade.value.length) {
    a.push(nome)
    r.innerHTML += ` <tr><th scope="row">${a.length}</th><td>${nome.value}</td><td>${idade.value}</td>`
  }
}

function excluir() {
  var n = [nome, idade]
  v = "vazio"
  z = []
  z.slice(n)
  document.getElementById("res").innerHTML = `<th scope="row">${z.length}</th><td>${v}</td><td>${v}</td>`
}

    Agenda

        Quantidade
        Nome
        Idade

  <button class="btn btn-danger" type="button" onclick="excluir()">Excluir</button>
  <button class="btn btn-warning" type="button" onclick="editar()">Editar</button>

Adicione por aqui!

    <input type="text" id="nome" name="nome" placeholder="NOME">
    <input type="number" name="idade" id="idade" placeholder="IDADE">
    <button class="btn btn-primary" type="submit" id="btn" onclick="adicionar()">Adicionar</button>

Answer: Mostra 2 porque a função excluir não muda o array a (ele continua tendo os elementos, o problema é que a função adicionar só adiciona os dados no array, porém imprime apenas o último adicionado).
Se a ideia da função excluir é limpar tudo, então basta zerar o array (atribua a um array vazio, por exemplo).
Eu também deixaria uma função separada para atualizar a tabela.

let dados = [];

function adicionar() {
  var nome = document.getElementById("nome").value;
  var idade = document.getElementById("idade").value;
  if (nome == "" || idade == "") {
    alert("Por favor digite o seu nome e sua idade!");
    return; // se não foi preenchido, sai da função
  }
  // se está ok, adiciona nos dados
  dados.push({ nome, idade });
  atualizaTabela();
}

function excluir() {
  dados = [];
  atualizaTabela();
}

function atualizaTabela() {
  var r = document.getElementById("res");
  if (dados.length == 0) {
    r.innerHTML = '
0	vazio	vazio	';
  } else {
    r.innerHTML = '';
    for (var i = 0; i < dados.length; i++) {
      r.innerHTML += `<tr><th scope="row">${i + 1}</th><td>${dados[i].nome}</td><td>${dados[i].idade}</td>`;
    }
  }
}

    Agenda

        Quantidade
        Nome
        Idade

  <button class="btn btn-danger" type="button" onclick="excluir()">Excluir</button>
  <button class="btn btn-warning" type="button" onclick="editar()">Editar</button>

Adicione por aqui!

    <input type="text" id="nome" name="nome" placeholder="NOME">
    <input type="number" name="idade" id="idade" placeholder="IDADE">
    <button class="btn btn-primary" type="submit" id="btn" onclick="adicionar()">Adicionar</button>

Mudei o nome do array para dados (ainda é meio genérico, mas é melhor do que a, que não diz nada sobre o que é o array). Pode parecer um detalhe besta, mas dar nomes melhores ajuda na hora de programar.
E também coloquei ponto-e-vírgula no final das linhas. Pode parecer "frescura", e sei que o JavaScript "aceita" o código sem ponto e vírgula e "funciona", mas isso evita algumas situações bizarras que podem ocorrer se você não usá-los, como essa e essa (veja mais sobre isso aqui).
Comment: Entendi, muito obrigado pela sua educação e dicas!
Comment: @JulioS Aí é o caso de [fazer outra pergunta](/questions/ask), mas enfim, tem várias formas de fazer, depende do que você precisa (por exemplo, vc precisaria escolher qual vai editar, então teria que ter um campo pra isso, etc)
Comment: @JulioS Mas se já tiver adicionado vários, como vc vai saber qual mudar? O usuário tem que escolher o número, e só depois mudar os dados daquele registro específico
Comment: @JulioS Só pra vc ter uma ideia de como ficaria: https://jsfiddle.net/7pg5ks9t/
Comment: É mais e menos isso , vou fazer no input mas muito obrigado me der uma ideia! , sou iniciante e estou praticando js


jquery creating double validation errors

Question: The issue is duplicate error. For example click 'yes' for the first radio button and then select red only for the first drop down click submit and you will get 2 validations errors in quick succession. How do I remove the second?
Comment: what should you really get as the result here? I see you have written a code to display two alert messages?
Comment: @Jayanga select yes for first and hit submit. see 2 error messages?
Comment: @lukey Don't worry. Your question is clear. You don't want to have both error messages once right. I solved it. Answer is below.
Comment: @LasanthaBandara This works however it submits once i click ok on error?
Answer: Change your click function like this.
<code>$("input:submit").click(function() {

    var retVal = validate(1);

    if (!$("input[name=attendance1]").is(":checked")) {
        alert('Please select preference for 1');
        return false;
    }
    if (!$("input[name=attendance2]").is(":checked") && retVal) {
        alert('Please select preference for 2');
        return false;
    }
    if (!$("input[name=attendance3]").is(":checked") && retVal) {
        alert('Please select preference for 3');
        return false;
    }
});
</code>
This will solve your problem.
Comment: Yes, generally callback functions are executed before form values are posted to the back end. After you click the ok button, it submits.
Comment: When live it does NOT alert me if attendance1, attendance2 or attendance3 are NOT checked then it submits. If I select 'yes' then do not choose colour and shade it will alert me that I have not selected the drop downs but then submits when i click ok


Rounding within a conditional format function

Question: I have the following code that formats my df correctly, only it changes the rounding of my values from being 2 dp to adding 4 zeros to each value. Anyone know how to adjust the function to not add the decimal places?
This is the table
data = ''
index = ['US 2yr','US 5yr','US 10yr','US Ultra']
columns = ['Total Positioning - Z Score',
         'Asset Manager Positioning - Z Score',
         'Levereged Fund Positioning - Z Score',
         'Dealer Positioning - Z Score']
table_6m = pd.DataFrame(data,index=index,columns=columns)

table_6m.iloc[0,0] = 1.72
table_6m.iloc[0,1] = 1.56
table_6m.iloc[0,2] = 0.65
table_6m.iloc[0,3] = -1.26

table_6m.iloc[1,0] = 0.02
table_6m.iloc[1,1] = 0.25
table_6m.iloc[1,2] = -0.11
table_6m.iloc[1,3] = 1.99

table_6m.iloc[2,0] = -2.75
table_6m.iloc[2,1] = 1.49
table_6m.iloc[2,2] = 0.17
table_6m.iloc[2,3] = -0.02

table_6m.iloc[3,0] = 3.03
table_6m.iloc[3,1] = -0.22
table_6m.iloc[3,2] = 0.85
table_6m.iloc[3,3] = -1.50

This is the function to do a cond format
def background_gradient(s, m=None, M=None, cmap='Oranges', low=0, high=0):
    print(s.shape)
    if m is None:
        m = s.min().min()
    if M is None:
        M = s.max().max()
    rng = M - m
    norm = colors.Normalize(m - (rng * low),
                        M + (rng * high))
    normed = s.apply(lambda x: norm(x.values))

    cm = plt.cm.get_cmap(cmap)
    c = normed.applymap(lambda x: colors.rgb2hex(cm(x)))
    ret = c.applymap(lambda x: 'background-color: %s' % x)
    return ret

table_6m.style.apply(background_gradient, axis=None)

Comment: Sorry, I'm not familiar with the styler, I thought you were just trying to round the values in the df.
Comment: Maybe `lambda x: round(norm(x.values), 2)`
Answer: The styler differentiates between the actual value and the display value. For this reason, regardless of the data stored in the DataFrame, you'll need to specify a format style to prevent the default formatting behaviour.
Either set the precision:
(
    table_6m.style
        .apply(background_gradient, axis=None)
        .format(precision=2)
)

Or use a formatting function:
(
    table_6m.style
        .apply(background_gradient, axis=None)
        .format(formatter='{:.2f}'.format)
)

Answer: After you calculate normed, add
normed = normed.round(2)

This will round values to 2 dp.
Comment: This will not work. The styler will still pad to 6 decimal places regardless of the actual value in the DataFrame. Also modifying the `normed` series in the function will not update the DataFrame.


PLS training by cross validation, selection of components and prediction

Question: I know there are plenty of questions on this topic on the site, but I still can't work out how to choose the optimal number of components for the particularities of my PLS model.
I have 1800 observations of 150 variables in my X-matrix and I am trying to predict a single continuous Y-variable. After model training in the pls package (ie the default 10-fold cross validation, starting with 10 components), RMSEP is minimised by 10 components, although when the "one SE" rule is applied, one component only is judged to be the best model (see plot below). In addition, neither of these are more than one SE away from a zero component model. Given the complex nature of the data, I would expect more than one component to be necessary to predict Y. Therefore, is this cross-validation the best approach? How should I proceed?

My eventual aim is to predict Y for an independent dataset. The pls package also allows you to specify which components are used for the predictions. So, as a follow-up question, why would I want to use less components than in my cross-validated model?
Help would be greatly appreciated.
Answer: Some questions that may help digging down to what the actual issue is. I don't think cross validation itself is the problem here - it's probably just exposing problems in the model.

All your tentative models do not show much improvement over the 0 component model: even at 10 latent variables, $RMSE_{CV}$* is still withing 95 % of the $RMSE_{CV}$ always guessing the average $y$ (0 latent variables).
=> What is % explained Y-variance?
=> What is the corresponding training RMSE?
=> How are the errors distributed?
* In my field, usually an RMSE estimated from cross validation is denoted $RMSE_{CV}$, $RMSE_P$ is more-or-less reserved for predictions on a really separate set of samples/cases.
Where does the variance of the RMSE estimates come from: model instability or high variance in the prediction error for different cases?
Keep in mind: it is of course possible that PLSR cannot give a meaningful answer to your problem / is plainly unsuitable for that data. PLSR is a powerful tool, but it is no magic recourse in case there's almost no signal and that drowned in lots of noise.
Does your data allow to check the loadings/latent variables in a way that is independent of RMSE optimization?
E.g., I work with spectra which have high correlation between neighbour variates. If the loadings or coefficients look noisy, I know for sure that the model is overfitting. The opposite is of course not true: they may look good and are spectroscopically perfectly sensible but extract "chemical noise", i.e. variation in the data that is only accidentally related to the analyte (Y) I'm after.
I've certainly had data where I had to say: "We may be able to do something in terms of meaningful predictions for the application with more complex models - and due to the nature of the application complex models will be needed to get there. But this data set is so noisy that we cannot get a stable estimate even for the first latent variable."

Given the complex nature of the data, I would expect more than one component to be necessary to predict Y.

You could try to go for many latent variables, i.e. up to models so complex that they are clearly overfitting.
Plot training and cross validation error to see this.
As explained above, it's good to formulate an idea of what complexity could be suitable for the application. But unfortunately that doesn't guarantee that any given data set contains sufficient information to actually train a sensible model of that complexity.

The pls package also allows you to specify which components are used for the predictions. Why would I want to use less components than in my cross-validated model

Probably the most common use of this feature is to not needing to re-fit the model in order to get predictions with the first n components during optimization of the number of latent variables.
During this optimization, you basically try out models with 1, 2, 3, ..., 10 latent variables. The implementation by pls needs to fit the model only once for 10 latent variables and then extracts the predictions for the less complex models, saving 90 % of (totally redundant) computation over the naive approach of fit 1 lv => predict, fit 2 lvs => predict, ...
Exposing this interface is certainly handy whenever you want to have more fine-grained access than just getting the overall (pooled) performance after running pls' cross valiadation procedure.
Comment: Many thanks for this comprehensive answer. I'll follow your suggested diagnostics to try and work out whether this approach is worth pursuing. Perhaps as you say PLSR is simply unsuitable for this data.


Observable errors with Angular2 beta.12 and RxJs 5 beta.3

Question: Hello,
I am using Angular2 beta 12 running in VS2015. When I update to rxjs from 5.0.0-beta.2 to beta.3 I encounter a range of exceptions generally relating to my promises.
E.g.

Property map does not exist on type Observable<Response>
Property share does not exist in type Observable<Response>
Ambient modules declaration cannot specify relative module name
Ambient modules cannot be nested in other modules or namespaces.

Package.json
{
  "name": "ASP.NET",
  "version": "0.0.0",
  "scripts": {
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "lite": "lite-server",
    "start": "concurrent \"npm run tsc:w\" \"npm run lite\" "
  },
  "dependencies": {
    "angular2": "2.0.0-beta.12",
    "systemjs": "0.19.24",
    "es6-promise": "3.1.2",
    "es6-shim": "0.35.0",
    "reflect-metadata": "0.1.3",
    "rxjs": "5.0.0-beta.3", // beta.2 allowed project to build
    "zone.js":"0.6.6"
  },
  "devDependencies": {
    "gulp": "3.9.1",
    "gulp-concat": "2.6.0",
    "gulp-cssmin": "0.1.7",
    "gulp-uglify": "1.5.3",
    "rimraf": "2.2.8",
    "concurrently": "2.0.0",
    "lite-server": "2.1.0",
    "typescript": "1.8.9"
  }
}

Issue relates to map function in this code:
import {Injectable} from 'angular2/core';
import {Http, Response} from 'angular2/http';
import {Headers, RequestOptions} from 'angular2/http';
import {Observable}     from 'rxjs/Observable';

import {ApplicationVM} from '../../Applications/ViewModels/Application.ViewModel';

@Injectable()
export class ApplicationService {
    constructor(private http: Http) { }

    private _serviceUrl = './../api/';

    getApplications() {
        return this.http.get(this._serviceUrl + "applications/active")
            .map(res => <ApplicationVM[]>res.json())
           // .map((res: Response) => res.json())
            .do(data => console.log(data)) // eyeball results in the console
            .catch(this.handleError);
    }

    private handleError(error: Response) {
        console.log(error);
        return Observable.throw(error.json().error || 'Server error');
    }

}

In another, the problem is with share()
 constructor(private _http: Http) {
     console.log("constructor");
     this.menulist$ = new Observable(observer => this._menulistObserver = observer).share();
     this.menuState$ = new Observable(observer => this._menuStateObserver = observer).share();
     this.menuWidth$ = new Observable(observer => this._menuWidthObserver = observer).share();}

I feel this might be important - a range of rxjs files have underlined red for relative references ../../Observable (example below is in interval.d.ts)
import { IntervalObservable } from '../../observable/IntervalObservable';
declare module '../../Observable' {
    namespace Observable {
        let interval: typeof IntervalObservable.create;
    }
}

My boot.ts
///<reference path="./../node_modules/angular2/typings/browser.d.ts"/>
import {bootstrap}      from 'angular2/platform/browser';
import {ROUTER_PROVIDERS} from 'angular2/router';
import {AppComponent} from './app.component';
import {HTTP_PROVIDERS}    from 'angular2/http';
import 'rxjs/Rx'; // kitchen sink

// Bootstrap the application and reference the required directives
bootstrap(AppComponent, [ROUTER_PROVIDERS, HTTP_PROVIDERS]);

My html page

I'm stumped and would appreciated some assistance.
Thank, Dan.
Answer: Regarding operators, you need to import them manually since they aren't included in the Observable class by default.
For this you can do either:
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/share';

Or (to include all operators):
import {Observable} from 'rxjs/Rx';

Otherwise normally you don't need to define rxjs into your SystemJS configuration in the map block. Including the corresponding bundled file into a script tag is enough.
Comment: I already include the 'kitchen sink' i.e. rxjs/Rx as noted in the original question.  But a very helpful tip for optimising Angular projects.  Thanks.
Comment: Fixed it for me! It's worth noting that the first option (just importing the operators manually) is, as far as I understand, a much more performant option, since those imports will only be used for TypeScript compilation. Thus, it won't result in more code being added to your codebase, as would be the case if you use the second option.
Answer: According to Angular's package.json you should use exactly RxJS 5.0.0-beta.2 https://github.com/angular/angular/blob/master/package.json#L37
Comment: In my team we are experiencing the exact same issue and only for Visual Studio intellisense (webpack TypeScript compiling is fine). While I'm aware that current angular version needs rxjs 5 beta 2, do you know how are those two things related? I.e. why it builds fine, but VS complains? We need that rxjs version because of ngrx-store
Comment: Great! I was wondering where I would find this info of which packages I *should* be using.  Thanks very much.
Comment: beta6 now I believe
Answer: For VS2015 there's a workaround for this problem listed on GitHub here

As work arounds for now, you can replace C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\CommonExtensions\Microsoft\TypeScript\typescriptServices.js with the file in https://raw.githubusercontent.com/Microsoft/TypeScript/Fix8518/lib/typescriptServices.js. First take a local backup though.

IMPORTANT: Be sure you're on VS2015 Update 2 and have TypeScript > 1.8.2 installed
(My VS would not start after replacing the file on Update 1)
I am using rxjs 5.0.0-beta.6 btw.
Comment: Yep you are totally right with Angular RC1 this solution works...my original question was for Angular beta where version rxjs beta 2 was supposed to be used. For rxjs beta 6 with Angular RC it is something to do with missing Typescript functionality which causes lots of build errors. Great to have your feedback for others to see.


Rails : Access other object in a one-to-many association

Question: So here's my code :
class Recipe < ActiveRecord::Base
    has_many :neededingredients
end

class Neededingredient < ActiveRecord::Base
    belongs_to :ingredients
    belongs_to :recipes
end

class Ingredient < ActiveRecord::Base
    has_many :neededingredients
end

And here's my migration :
create_table :recipes do |recipes|
    recipes.string :name, null: false
    recipes.string :indications, null: false
end

create_table :ingredients do |ingredients|
    ingredients.string :ingredient, null: false, uniqueness: true
end

create_table :neededingredients do |neededingredients|
    neededingredients.integer :quantity, null: false
    neededingredients.string :unit
    neededingredients.references :ingredients, foreign_key: true
    neededingredients.references :recipes, foreign_key: true
end

So a Recipe has multiple NeededIngredients. A NeededIngredient has a reference to an Ingredient, and has a quantity and a unit (grams, for example). I'd like to be able to do something like a_recipe.neededingredients to find all neededingredients of a given recipe, or a_needed_ingredient.recipeto get the recipe of a given neededingredient. For some reason, I can't find a way to do this. Is there anything wrong in my migration or in my model ? Thanks for the help !
Comment: did you tried `has_many :through` association https://guides.rubyonrails.org/association_basics.html#the-has-many-through-association
Answer: The key of the issue here is really bad naming / pluralization. I would highly really recommend that you rename this according to the Ruby conventions to avoid confusion and future bugs.
Class names should be CamelCase - NeededIngredient. Do seperate compound words!
Attributes, table names, instance variables, routes, method names and everything else should be snake_case - needed_ingredient or needed_ingredients depending on the context.
This is much easier to read and get right then insanelylongthingwitteninlowercase.
Cramming three different table definitions into a single migration (if that is what you're doing) is a bad idea. Especially since its trivial to generate migrations though the model generator. Having separate migrations lets you run them sequentially and roll them back individually to get it right.
class CreateNeededIngredients < ActiveRecord::Migration[6.0]
  def change
    # there is no need to use super long block argument names
    create_table :needed_ingredients do |t|
      t.decimal :quantity, null: false # yeah decimal
      t.string :unit
      t.references :ingredient, foreign_key: true # this should be singular!
      t.references :recipe, foreign_key: true # this should be singular!
      t.timestamps
    end
    # consider adding a unique index to avoid duplicates
    # add_index: :needed_ingredients, [:ingredient_id, :recipe_id], unique: true
  end
end

Not that the argument to references should be singular since its the name of the foreign key. Rails will deduce the target table by inflection.
You then need to setup a has_many through: association to tie recipe and ingredients together:
class Recipe < ActiveRecord::Base
  has_many :needed_ingredients
  has_many :ingredients, through: :needed_ingredients
end

class NeededIngredient
  belongs_to :recipe # belongs_to is always singular!
  belongs_to :ingredient # belongs_to is always singular!
end

class Ingredient < ActiveRecord::Base
  has_many :needed_ingredients
  has_many :recipies, through: :needed_ingredients
end

And this is not a one-to-many assocation. Its many-to-many. If you need to display the ingredients of recipe you should note that you should loop through the needed_ingredients association and not ingredients.
class NeededIngredient
  belongs_to :recipe # belongs_to is always singular!
  belongs_to :ingredient # belongs_to is always singular!

  # use delegation/proxing to avoid Law of Demeter violations
  def name
    ingredient.ingredient # why isn't this column just called name?
  end
end

class RecipiesController < ApplicationController
  def show
    @recipe = Recipe.include(:ingedients).find(params[:id])
  end
end

# app/views/recipies/show.html.erb

<%= @recipe.name %>

      Name
      Quantity

  <% @recipe.needed_ingredients.each do |i|%>

      <%= i.name %>
      <%= i.quantity %> <%= i.unit %>

  <% end %>

Answer: You use plural instead of singular (in the migration, and in the model), and you should use has_many :through association
Change the following:
class Recipe < ApplicationRecord
  has_many :neededingredients
  has_many :ingredients, through: :neededingredients
end

class Neededingredient < ApplicationRecord
    belongs_to :ingredient
    belongs_to :recipe
end

class Ingredient < ApplicationRecord
    has_many :neededingredients
    has_many :recipes, through: :neededingredients
end

create_table :neededingredients do |neededingredients|
    neededingredients.integer :quantity, null: false
    neededingredients.string :unit
    neededingredients.references :ingredient, foreign_key: true
    neededingredients.references :recipe, foreign_key: true
end

Now you can call (for example): Recipe.first.ingredients, Recipe.first.neededingredients, Ingredient.first.recipes


single page redirect 301 not working according to the rules in .htaccess

Question: redirect 301 /Produkte/Supplements http://xxx.xx/Produkte/Inhaltsstoffe/Proteine

why does this rule also redirects
 /Produkte/Supplements/xyz

to
http://xxx.xx/Produkte/Inhaltsstoffe/Proteine/xyz

?
can't get my head around it.
Answer: Due to apache docs - If the client requests http://example.com/Produkte/Supplements/xyz , it will be told to access http://xxx.xx/Produkte/Inhaltsstoffe/Proteine/xyz instead. This also includes requests with GET parameters.
To workaround this use more complex RedirectMatch rule like so:
RedirectMatch ^\/Produkte\/Supplements$ http://xxx.xx/Produkte/Inhaltsstoffe/Proteine


python 3d A* pathfinging infinite loop

Question: I am trying to adapt an application I found here, I imagined that I just had to add an axis. The problem is that the script seems like it is stuck. Can someone tell me what I did wrong and how I can use A* with a 3d matrix (i j k)?
this is the portion of the A* function I changed
for new_position in [(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]: # Adjacent squares, (-1, -1), (-1, 1), (1, -1), (1, 1)]: # Adjacent squares removed to ignor diagonal movement

    # Get node position
    node_position = (current_node.position[0] + new_position[0], current_node.position[1] + new_position[1], current_node.position[2] + new_position[2])

    # Make sure within range
    if node_position[0] > (len(maze) - 1) or node_position[0] < 0 or node_position[1] > (len(maze[len(maze)-1]) -1) or node_position[1] < 0 or node_position[2] > (len(maze) - 1) or node_position[2] < 0 or node_position[2] > (len(maze[len(maze)-1]) -1):
        continue

    # Make sure walkable terrain
    if maze[node_position[0]][node_position[1]][node_position[2]] != 0:
        continue

it was originally:
for new_position in [(0, -1), (0, 1), (-1, 0), (1, 0), (-1, -1), (-1, 1), (1, -1), (1, 1)]: # Adjacent squares

    # Get node position
    node_position = (current_node.position[0] + new_position[0], current_node.position[1] + new_position[1])

    # Make sure within range
    if node_position[0] > (len(maze) - 1) or node_position[0] < 0 or node_position[1] > (len(maze[len(maze)-1]) -1) or node_position[1] < 0:
        continue

    # Make sure walkable terrain
    if maze[node_position[0]][node_position[1]] != 0:
        continue

this is the whole script with my alterations:
import numpy as np

class Node():
    """A node class for A* Pathfinding"""

    def __init__(self, parent=None, position=None):
        self.parent = parent
        self.position = position

        self.g = 0
        self.h = 0
        self.f = 0

    def __eq__(self, other):
        return self.position == other.position

def astar(maze, start, end):
    """Returns a list of tuples as a path from the given start to the given end in the given maze"""

    # Create start and end node
    start_node = Node(None, start)
    start_node.g = start_node.h = start_node.f = 0
    end_node = Node(None, end)
    end_node.g = end_node.h = end_node.f = 0

    # Initialize both open and closed list
    open_list = []
    closed_list = []

    # Add the start node
    open_list.append(start_node)

    # Loop until you find the end
    while len(open_list) > 0:
        # Get the current node
        current_node = open_list[0]
        current_index = 0
        for index, item in enumerate(open_list):
            if item.f < current_node.f:
                current_node = item
                current_index = index

        # Pop current off open list, add to closed list
        open_list.pop(current_index)
        closed_list.append(current_node)

        # Found the goal
        if current_node == end_node:
            path = []
            current = current_node
            while current is not None:
                path.append(current.position)
                current = current.parent
            return path[::-1] # Return reversed path

        # Generate children
        children = []

        for new_position in [(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]: # Adjacent squares, (-1, -1), (-1, 1), (1, -1), (1, 1)]: # Adjacent squares removed to ignor diagonal movement

            # Get node position
            node_position = (current_node.position[0] + new_position[0], current_node.position[1] + new_position[1], current_node.position[2] + new_position[2])

            # Make sure within range
            if node_position[0] > (len(maze) - 1) or node_position[0] < 0 or node_position[1] > (len(maze[len(maze)-1]) -1) or node_position[1] < 0 or node_position[2] > (len(maze) - 1) or node_position[2] < 0 or node_position[2] > (len(maze[len(maze)-1]) -1):
                continue

            # Make sure walkable terrain
            if maze[node_position[0]][node_position[1]][node_position[2]] != 0:
                continue

            # Create new node
            new_node = Node(current_node, node_position)

            # Append
            children.append(new_node)

        # Loop through children
        for child in children:

            # Child is on the closed list
            for closed_child in closed_list:
                if child == closed_child:
                    continue

            # Create the f, g, and h values
            child.g = current_node.g + 1
            child.h = ((child.position[0] - end_node.position[0]) ** 2) + ((child.position[1] - end_node.position[1]) ** 2)+((child.position[2] - end_node.position[2]) ** 2)
            child.f = child.g + child.h

            # Child is already in the open list
            for open_node in open_list:
                if child == open_node and child.g > open_node.g:
                    continue

            # Add the child to the open list
            open_list.append(child)

def main():

    maze = np.zeros((12,12,12))
    start = (10, 9, 9)
    end = (1, 1, 1)

    path = astar(maze, start, end)
    print(path)

if __name__ == '__main__':
    main()

Answer: A* can work with any number of dimensions; it's a graph traversal algorithm, and no matter how many dimensions your problem space has, connecting one position to another still produces a graph.
You have two problems with generating new nodes, however.

You included (0, 0, 0) in the list, so no change. You keep putting the current position back into the queue for consideration. That's just busy work, because the current position is already in the closed list.
You never subtract from any of your coordinates, you only add. So your x, y and z values can only ever go up. If reaching your goal requires a path around an obstacle, then you have a problem here because all your version can ever do is move in one direction along any given axis.

In a 3 by 3 by 3 3D matrix, with the current position in the middle, there are 3 times 3 times 3 minus 1 == 26 positions you can reach with a single step. Your code reaches just 7 of those, plus one that stays put.
If you extract your tuples in the for new_position in [...] list into a separate variable and add some newlines, and re-arrange them a bit to group them by how many 1s you have in the tuple, you get the following definition. I renamed this to deltas, because it's not a new position, it's the change relative to the old position, or delta. I re-arranged your tuples to make it easier to group them logically:
deltas = [
    (0, 0, 0),  # no change,
    (0, 0, 1), (0, 1, 0), (1, 0, 0), # add to a single axis
    (0, 1, 1), (1, 0, 1), (1, 1, 0), # add to two axes
    (1, 1, 1)  # move in all 3 directions at once.
]

for delta in deltas:
    # ...

You want to drop the first one ((0, 0, 0)), and you need to add -1 versions of the other variants. You need 26 different tuples, but writing those by hand gets to be cumbersome, really fast. You can use itertools.product() to generate these, instead:
from itertools import product

# combinations of -1, 0 and 1, filtering out the (0, 0, 0) case:
deltas = [d for d in product((-1, 0, 1), repeat=3) if any(d)]

Now, your comment next to the loop says:
# Adjacent squares removed to ignor diagonal movement

It's not entirely clear what you mean by this, because your original list of deltas includes diagonals ((0, 1, 1) moves both in the y and z directions, and you have tuples combining movement in the x plus y and the x plus z axes), and even one that moves diagonal by incrementing all 3 axes. If you only wanted to move up, down, left, right, forward, and backward, you want to restrict movement to a single axis at a time, and deltas should be:
# movement without diagonals
deltas = [
    (1, 0, 0), (-1, 0, 0),  # only x
    (0, 1, 0), (0, -1, 0),  # only y
    (0, 0, 1), (0, 0, -1),  # only z
]

Personally, I'd move the whole business of generating new positions to a separate method on the Node class:
def possible_moves(self, map):
    x, y, z = self.x, self.y, self.z
    for dx, dy, dz in DELTAS:
        newx, newy, newz = x + dx, y + dy, z + dz
        try:
            if maze[newx][newy][newz] != 0:
                yield Node(self, (newx, newy, newz))
        except IndexError:
            # not inside the maze anymore, ignore
            pass

This method assumes that there is a DELTAS global variable that defines the possible moves, and is a generator; each time yield is reached a new Node() instance is returned to whatever is using this as an iterator (like a for loop would).
Then just use that method instead of the children = [] list you filled with the for new_position in ...: loop, so directly in the part that uses the original children list:
# Loop through children
for child in current_node.possible_moves(map):

    # Child is on the closed list
    for closed_child in closed_list:
        if child == closed_child:
            continue

    # etc.

python 3d A* pathfinging infinite loop


Problem with UITableViewNavigation, passing of data on segue

Question: I am failing to pass data from UITableView to a UIViewController. Have tried several ways but failing. Getting this error

Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVO)

when I run the project.
See the code below of what I have tried.
//Code on the UITableViewController

class ShonaHymnsUITableViewController: UITableViewController {
    var hymns : [Hymns] = Hymns.fetchHymns()

    //MARK: - UItableViewDataSource
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return hymns.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "hymnCell", for: indexPath) as! HymnsTableViewCell

        let hymn = hymns[indexPath.row]
        cell.hymn = hymn
        return cell
    }

//    MARK: - NAVIGATION
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        self.performSegue(withIdentifier: "ShowHymnDetail", sender: indexPath)
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // TODO: Prepare for Hymn Detal segue
        if segue.identifier == "ShowShonaHymnListing" {
            let shonaHymnListingVC = segue.destination as! ShonaHymnsUITableViewController
            shonaHymnListingVC.hymns = hymns

        } else if segue.identifier == "ShowHymnDetail" {

            let indexPath = tableView.indexPathForSelectedRow
            let selectedHymn = hymns[(indexPath?.row)!]
            let hymnDetailVC = segue.destination as! ShonaHymnsViewController
               hymnDetailVC.hymn = selectedHymn
            }
    }
}

//Code on the ViewController that I want to receive the data
class ShonaHymnsViewController: UIViewController {

    @IBOutlet weak var hymnNumber: UILabel!
    @IBOutlet weak var hymnTitle: UILabel!
    @IBOutlet weak var hymnDetail: UITextView!

    var hymn: Hymns!

    override func viewDidLoad() {
        super.viewDidLoad()

        hymnNumber.text = hymn.hymnNumber
        hymnTitle.text = hymn.hymnTitle
        hymnDetail.text = hymn.hymnDetail

    }

}

This is a hymn book application and I expect the full hymn detail to be shown on the recipient view controller. See image for the setup of the app
Answer: Reverse order of
self.performSegue(withIdentifier: "ShowHymnDetail", sender: indexPath)
tableView.deselectRow(at: indexPath, animated: true)

for this
hymns[(indexPath?.row)!]

to have a valid value
Comment: Thanks. Are you saying are should put the self.override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) at the bottom of
this one: hymns[(indexPath?.row)!]? I have done it and it's still giving the same error.


How to make one MutationObserver listen for changes on multiple elements?

Question: I have implemented the following code for observing changes in class:
$(document).ready(function () {
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    if (mutation.attributeName === "class") {
      var attributeValue = $(mutation.target).prop(mutation.attributeName);
      console.log("Class attribute changed to:", attributeValue);
    }
  });
});

observer.observe(document.querySelector(".xxx"), {
  attributes: true
});  });

JSFiddle link: https://jsfiddle.net/8Lfj0ev3/
Ideally, I want this to listen for changes in all elements with class 'xxx'. But it is only listening to first element with xxx class and ignoring others. How can I fix this?
Comment: Please use **on-site** Stack Snippets for runnable examples, not off-site links. Stack Snippets are the `[<>]` toolbar button; [here's how to do one](https://meta.stackoverflow.com/questions/358992/).
Answer: Two ways to address this:
Multiple observe calls
You can call observe multiple times to watch multiple elements:
$(".xxx").each(function() {
  observer.observe(this, {
    attributes: true
  });
});

Live Example:

$(document).ready(function() {
  var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
      if (mutation.attributeName === "class") {
        var attributeValue = $(mutation.target).prop(mutation.attributeName);
        console.log("Class attribute changed to:", attributeValue);
      }
    });
  });

  $(".xxx").each(function() {
    observer.observe(this, {
      attributes: true
    });
  });
});

setTimeout(function() {
  $(".d1").addClass("x1");
}, 800);
setTimeout(function() {
  $(".d2").addClass("x2");
}, 1600);
setTimeout(function() {
  $(".d3").addClass("x3");
}, 2400);

Watch container's subtree
But another option is to watch the subtree of the nearest container they're all in and then only pay attention to changes if they occurred within a .xxx element:
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    if (mutation.attributeName === "class") {
      var $target = $(mutation.target);                            // ***
      if ($target.hasClass("xxx")) {                               // ***
        var attributeValue = $target.prop(mutation.attributeName);
        console.log("Class attribute changed to:", attributeValue);
      }
    }
  });
});

observer.observe(document.body, {                                  // ***
  attributes: true,
  subtree: true                                                    // ***
});

Live Example:

$(document).ready(function() {
  var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
      if (mutation.attributeName === "class") {
        var $target = $(mutation.target);
        if ($target.hasClass("xxx")) {
          var attributeValue = $target.prop(mutation.attributeName);
          console.log("Class attribute changed to:", attributeValue);
        }
      }
    });
  });

  observer.observe(document.body, {
    attributes: true,
    subtree: true
  });
});

setTimeout(function() {
  $(".d1").addClass("x1");
}, 800);
setTimeout(function() {
  $(".d2").addClass("x2");
}, 1600);
setTimeout(function() {
  $(".d3").addClass("x3");
}, 2400);

In that example the nearest container is document.body, but of course in your real situation there may be something closer to the elements.
Comment: Thank you so much, the first approach worked perfectly!


Android - Samsung: Creating Widget with configuration activity fails

Question: I built an application with the possibility to add widgets to the home screen. The widget is working with my Nexus 6P and a Motorola Moto G3.
With Samsung Phones (Tested with S3 mini (4.1.2), S5, S6 (6.0.1)) the widget is not added at all or TouchWiz crashes.
With another launcher (Nova) the widget is also not created on the S3 mini.
In logcat I don't see any error message at all.
I tried to narrow the problem down as far as possible.
The widget gets created if I remove the android:configure="de.cliff.strichliste.widgets.WidgetConfigurationActivity" from the counter_widget_info.xml. If I want to use a configuration activity TouchWiz crashes on the Samsung S3 mini.
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
    android:minWidth="40dp"
    android:minHeight="40dp"
    android:configure="de.cliff.strichliste.widgets.WidgetConfigurationActivity"
    android:updatePeriodMillis="1800000"
    android:initialLayout="@layout/widget_counter"
    android:resizeMode="horizontal|vertical"
    android:widgetCategory="home_screen"
    android:previewImage="@drawable/widget_preview">
</appwidget-provider>

In the AndroidManifest.xml I register the widget with the following lines:
<receiver
            android:name=".widgets.CounterWidgetProvider">
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
            </intent-filter>
            <meta-data
                android:name="android.appwidget.provider"
                android:resource="@xml/counter_widget_info" />
</receiver>

On the Java side, I've got the following in the WidgetConfigurationActivity:
public class WidgetConfigurationActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        WidgetConfigurationBinding binding = DataBindingUtil.setContentView(this, R.layout.widget_configuration);
        setResult(RESULT_OK);
    }
}

And this in the WidgetProvider class:
public class CounterWidgetProvider extends AppWidgetProvider {
@Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        super.onUpdate(context, appWidgetManager, appWidgetIds);
        Intent intent = new Intent(context, CounterWidgetProvider.class);
        context.startService(intent);
    }
}

Comment: Just a heads up: I noticed some odd behavior I believe is from the tests I ran that caused the TouchWiz crashes. After rebooting, it seems TouchWiz somehow held onto references for widgets that never actually made it to the home screen, and started broadcasting updates for them. I just happened to notice because I ran tests with a pre-existing widget project that updates itself rather frequently, and shows a `Toast` each time. You might want to do a complete uninstall on any device you tested on, to clear that out, before continuing testing.
Comment: Did you find the proper solution? Because I'm facing with the same issue with you and accepted answer didn't work for me.
Comment: @AtaerCaner The solution doesn't work for me also
Answer: From testing on my own Samsung devices, it seems the problem is that TouchWiz chokes if the result Intent doesn't have the App Widget ID attached, even if it's RESULT_CANCELLED.
From the App Widget developer page:

The App Widget host calls the configuration Activity and the configuration Activity should always return a result. The result should include the App Widget ID passed by the Intent that launched the Activity (saved in the Intent extras as EXTRA_APPWIDGET_ID).

It's unclear how exactly you wish to ultimately handle the result, but it's definitely a good idea to go ahead and set a valid result in onCreate(), in case the user backs out of the configuration Activity. For example:
final int id = getIntent().getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, 0);
final Intent result = new Intent().putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, id);
setResult(RESULT_OK, result);


Using MDT to deploy simple images from external SSD to to windows based point of sale terminals

Question: Background
I work with point of sale terminals that are windows based machines. In order to image a customers terminal, we have a copy of their OS on an external SSD and we remove the drive from the POS terminal and use a duplicator to copy the image from the external SSD then pop it back in the terminal and its ready to go.
I know it is possible to use MDT but Im not too sure on the steps to take.  Considering this is such a simple set up Im not sure which steps I can skip or dont necessarily need.
Goal
To have the customers OS on the external SSD uploaded into the MDT computer and anytime we need to image a terminal, hook it up to the MDT computer and just deploy it.  Can anyone speak to this process? Concretely I would like to know the steps I can skip and which ones to follow to the T.
Comment: If this is really as simple as you suggest have you considered a basic (hardware) hard drive duplicator like http://www.newegg.com/Product/Product.aspx?Item=0Y5-0001-00014&cm_re=hard_drive_duplicator-_-0Y5-0001-00014-_-Product
Comment: The whole idea is to not remove the drive. At least thats what were striving for.
Answer: MDT has been designed for remote deployment (going to the system that needs imaged).
Your situation sounds like local deployment (bringing the computer/HDD to you). In that case I would personally use a tool called imagex (a part of ADK/AIK). It is a command line tool that can manipulate WIM files.
I would personally use a batch script that would automatically deploy the image to the drive that is hooked to the computer. Here is an example:

Deploy.bat
imagex /apply X:\Path\to\WIM\File.wim Y Z:\Path\to\apply\image\to
 bootsect /nt60 Z:

Where X is the drive with the WIM file.
Y is the image index
Z:\path... is where you want to deploy the image. It does not have to
be in a folder you can make it at the root of a drive like this H:\
and that will deploy to the root of the H: drive.
Use /nt52 for NTLDR compatible boot sector setup
/nt60 is for BOOTMGR compatible boot loaders

If you were to do remote deployments (like from a CD, DVD, USB, PXE, etc...), just configure the deployment to use your image. It will take care of everything else. You do not need to delete any entries as they will auto disable depending on the type of imaging operation.
If you want to deploy remotely using non PXE methods then here is a link on how to put the MDT system on physical media (CD, DVD, BD, USB, etc...), It is for deployment but you can easily change it for other operation types (image capture, etc...)
http://www.vkernel.ro/blog/creating-an-offline-mdt-deployment-media

TL;DR:
It sounds like a batch script will suit your needs better.
Comment: When you say "Y is the image index" how do you get that/figure it out?
Comment: `Imagex /info x:\path\to\wim.wim`
Comment: Hey, @Mangster If I solved your issue please market as solved. Thank you! :-)
Answer: MDT utilises WDS on Windows Server, so you'd need to have a a VM with this all set up. You'd need to create a WIM image of the OS and put that into WDS.
There's not really a need to use MDT unless all the POS systems are different in terms of manufacturer, hardware etc. You could use WDS on it's own.
You'd also need to have a DHCP server which would provide the PXE boot option to boot into WinPE.
Have a read of this for more info:
https://technet.microsoft.com/en-GB/library/jj648426.aspx


On $\int_0^1\frac{\ln(1-e^{\pi i/3}x)}{e^{-\pi i/3}-x}\ln^3xdx$ and its generalization

Question: Motivation
Consider $$I_n=\int_0^1\frac{\ln(1-\omega x)}{\bar\omega-x}\ln^nxdx=\int_0^1\frac{\omega\ln(1-\omega x)}{1-\omega x}\ln^nxdx$$ where $\omega=e^{i\pi/3}$. It is known that $I_0=\frac1{18}\pi^2$ which can be deduced by integrating directly, and $$I_1=\frac23\zeta(3)-\frac\pi3\operatorname{Cl}_2\left(\frac\pi3\right)+i\cdot\frac1{324}\pi^3,$$ where $\text{Cl}$ is the Clausen Cl function.
I evaluated $I_1$ by using known antiderivative of $\frac{\ln(x-a)\ln(x-b)}{x}$.
One thing I noticed why it is special for $\omega$ is that if we replace it with other complex numbers different from $\pm1$ and $0$, the result of $I_2$ won't be very beautiful, such as $$\int_0^1\frac{\ln(1-zx)}{1-zx}\ln^2xdx,\text{ where $z=i$}$$ The result of the latter involves polylogarithm values that can not be simplified. It equals $$\tiny4 i\Re\operatorname{Li}_4\left(\frac{1}{2}+\frac{i}{2}\right)+\frac{35 \pi  \zeta (3)}{64}+\frac{35}{32} i \zeta (3) \log (2)-\frac{47 i \pi ^4}{1536}+\frac{1}{96} i \ln^4(2)-\frac{5}{192} i \pi ^2 \ln^2(2)+2\beta(4)$$
Also, a CAS knows how to handle $I_2$. It gives the result
$$I_2=\frac{23}{9720}\pi^4+i\left(\frac49\pi\zeta(3)-2\operatorname{Cl}_4\left(\frac\pi3\right)\right)$$
(CAS knows the antiderivative)
So the following question comes out:

For a general $n\in\mathbb N$, does a closed form of $I_n$ exist?

Higher to $n\ge3$, the polylog-styled antiderivative no longer exists. The method  becomes invalid. But the numerically-verified closed form for the real part of $I_3$ still exist.
$$\Re I_3=\frac{43}6\zeta(5)-\frac16\pi^2\zeta(3)-2\pi\operatorname{Cl}_4\left(\frac\pi3\right)$$
A failed attempt is trying to convert $I_n$ to series form: $$\sum_{k=1}^\infty H_k\omega^{k+1}\int_0^1x^k\ln^n\frac1xdx=n!\sum_{k=1}^\infty \frac{H_k\omega^{k+1}}{k^{n+1}}$$and separating it into 6 series. No luck for continuing this method so far.
Edit: I'm not looking for a proof of the result above. I'm looking for a closed form of $I_n$.
Comment: "The result of the latter involves polylogarithm values that can not be simplified." I'm sorry, but the real part of the Tetralogarithm term **can** be simplified.
Comment: But I don't know how to compute higher order integrals either. Generally, n-th order root of unity corresponds to a special kind of log/polylog integrals, log-sine integrals and euler sums. According to my experience, for n=3 there is no sufficient research, maybe other than Borwein's logsine integral theory. Therfore, it's difficult to find the pattern of this kind of integrals using no antiderivative cauculation...
Comment: @FengshanXiong Yes, if you consider $\text{Li}_4(1/2)$ as a simpler form, it can, I agree.
Comment: Yes. That's what I mean. I noticed that some literature I read treats these two as independent terms, which show that this relation is not quite well-known. Maybe there're some generalization of this?
Answer: $$I=-w \int_{0}^{1} \frac{\ln(1-wx)}{1-wx} \ln^n x dx= \int_{0}^{1}\sum_{k=1}^{\infty} w^{k+1} H_k~  x^k \ln^n x ~dx= \sum_{k=1}^{\infty} w^{k+1} H_k \int_{0}^{\infty}  t^n e^{-(k+1)t} dt$$ $$ \implies I= n! \sum_{k=1}^{\infty} \frac{w^{k+1} H_k}{(k+1)^{n+1}}.$$
Comment: Sorry for not expressing correctly. (I'm not a native speaker) Please see my edit. Thanks.


Como acessar o banco de dados diretamente da minha classe modelo num projeto ASP.NET Core?

Question: No ASP.NET Core Mvc eu consigo ter acesso ao DbContext no Controller através da propriedade _context representada pela minha classe MvcNotaContext veja:
private readonly MvcNotaContext _context;

Desta forma eu posso efetuar uma busca no banco de dados na classe controladora:
var nota = await _context.Nota.SingleOrDefaultAsync(m => m.ID == id);

Entretanto, eu possuo uma regra de negocio no meu modelo que necessita obter alguns dados diretamente da base de dados para efetuar a validação, mas, eu não sei como eu poderia obter uma instancia da minha classe MvcNotaContext diretamente na minha classe modelo Nota, e esta classe necessita das opções de configuração DbContextOptions<MvcNotaContext> options para funcionar, sendo que ela é usada no método ConfigureServices na classe Startup de inicialização:
public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddDbContext<MvcNotaContext>(options => options.UseSqlite("Data Source=MvcNota.db"));
}

Minha classe modelo:
public class Nota: IValidatableObject
{
    public int ID { get; set; }
    [Required(ErrorMessage="Titulo não pode ficar vazio.")]
    [DataType(DataType.Text)]
    [Display(Name="Título")]
    public string Titulo { get; set; }
    [Required(ErrorMessage="Conteúdo não pode ficar vazio.")]
    [Display(Name="Conteúdo")]
    [DataType(DataType.MultilineText)]
    public string Conteudo { get; set;}

    IEnumerable<ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
    {
        //Busca dados na base de dados.
        throw new System.NotImplementedException();
    }
}

O acesso ao banco ocorreria no método Validate, respectivamente.

Pergunta
Como eu posso acessar a base de dados diretamente da minha classe modelo (model) em um projeto ASP.NET Core Mvc?
Comment: Não entendi muito bem. A classe Nota é um model ou uma entidade?
Comment: Pode considerar como um Model.
Comment: Se é um model, posso considerar que você esteja utilizando como uma ViewModel junto ao Razor?
Comment: Neste caso não é um ViewModel, é só o Model que representa a tabela nota no meu banco de dados.
Comment: É essa classe que você utiliza no seu DbSet para configurar seu banco?
Comment: Sim exatamente, só tem esta classe. O banco é só uma tabela.
Answer: Instanciar um contexto dentro da sua classe de modelo (que representa uma tabela no banco) não é um padrão interessante, a obrigação do domínio é apenas se validar, e para isso você não precisa fazer uma instancia direta com o banco. Não é uma boa prática uma camada mais interna como a de domínio ser acoplada com uma Unidade de Trabalho.
Se você quer comparar um valor previamente inserido no banco de dados com um novo objeto, faça a consulta antes na sua camada escolhida (recomendo que faça isso em uma camada de serviço) e passe ela como argumento para sua classe de validação, algo como:
var minhaNotaConsultadaDoBanco = await _context.Nota.SingleOrDefaultAsync(m => m.ID == id);

Agora na sua model:
IEnumerable<ValidationResult> IValidatableObject.Validate(Nota minhaNotaConsultadaDoBanco)
{
    //Exemplo:
    if(this.Titulo != minhaNotaConsultadaDoBanco.Titulo) { ... }
}

Caso queira inserir um objeto totalmente novo e fazer o double check, você pode usar a própria instância para chamar o método de validação.
IEnumerable<ValidationResult> IValidatableObject.Validate()
{
    //Exemplo:
    if(this.Titulo != string.Empty) { ... }
}

Chamada:
minhaNotaConsultadaDoBanco.Validate();

Answer: É só você criar uma instância do contexto neste método, exatamente como faria com qualquer outro objeto
IEnumerable<ValidationResult> IValidatableObject.Validate(ValidationContext vCtx)
{
    var optBuilder = new DbContextOptionsBuilder<MvcNotaContext>();
    optBuilder.UseSqlite("Data Source=MvcNota.db");
    var context = new MvcNotaContext(optBuilder.Options);
}

Obs.: Mudei o nome do parâmetro só pra encurtar o código.
Pra isso, obviamente, você precisa se certificar de que há um construtor de MvcNotaContext que receba uma instância de DbContextOptions<T> como parâmetro.
public MvcNotaContext(DbContextOptions<MvcNotaContext> options) : base(options) { }


Check collision between two imported pictures

Question: I'm trying to recreate a game, however all I need is to create a game-over feature that occurs when the player collides or fails to jump over the rock. I've tried to do the check collision yet the player is passing through. What should I do or change in order to display the game over screen when the player collides with the rock? Here is my sample code:
#---  Player Definition
class Player(pygame.sprite.Sprite):
    #- Constructor
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.playing = False
        self.image = pygame.image.load("bcquestchar.png")
        self.rect = self.image.get_rect()
        self.color = BLUE
        self.rect.x = 50
        self.rect.y = 210
        self.goalY= 450
        self.gameover = False
    #- Allows Player to Jump
    def jump(self):
        self.goalY -= 25
    #- Imports & Displays player_image
    def draw(self, screen):
        screen.blit(player_image, [self.rect.x, self.rect.y])

#--- Rock definition
class Rock(pygame.sprite.Sprite):
    #- Constructor
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load("bcrocks.png")
        self.rect = self.image.get_rect()
        self.rect.x = random.randrange (0, 200)
        self.rect.y = 335
    #- Moves Rock
    def move(self):
        self.rect.x -= 3
    #- Imports & Displays rock_image
    def draw(self, screen):
        screen.blit(self.image, [self.rect.x + 700, self.rect.y])
# Loop until user closes pygame
done = False

# How fast the screen updates
clock = pygame.time.Clock()

# Creates player
rock = Rock()
player = Player()
obstacles = pygame.sprite.Group()
obstacles.add(rock)

if pygame.sprite.spritecollide(player, obstacles, False):
    player.gameover = True

#----- Main Program Loop -----#
while not done:
    #movesound.play()
    #- Calls in draw_background function
    draw_background (screen, 0, 0)
    #- Tracks Events
    speed = 1
#--- Main Event Loop
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = False

#- User is playing when M1 is clicked
    elif event.type == pygame.MOUSEBUTTONDOWN:
        player.playing = True

    #- User jumps when playing and has not lost
    if(player.gameover == False and player.playing == True):
        player.jump()

#- Is the player playing?
if(player.playing == True):

    # Jump up when the up arrow is pressed
    if event.type == pygame.MOUSEBUTTONDOWN:
        currently_jumping = True
        going_up = True
        #hopsound.play()

    if currently_jumping == True:
        if player.rect.y < 188:
            going_up = False
        elif going_up == False and player.rect.y > 215:
            currently_jumping = False

        if going_up:
            player.rect.y -= 2
        elif going_up == False:
            player.rect.y += 2

    elif currently_jumping == False:
        if(player.rect.y > 600 or player.rect.y < 0):
            player.gameover = True
        if(player.rect.y < 210):#player.goalY):
            player_moving_up = False

        elif(player.rect.y > 210):#player.goalY):
            player_moving_up = True

        if player_moving_up == True or player_moving_up == True:
            player.rect.y += 1
            player.rect.y -= 1
        player.goalY += 3

    if(timer3 > 120):
        timer3 = 0
        if(player.playing == True and player.gameover == False):
            score += 30

    #--- Draw and Move Rocks
    for rock in obstacles:
        rock.draw(screen)
        if(player.gameover == False):
            rock.move()
            rock.draw(screen)
            #rock.checkCollision(player.x, player.y)
        if pygame.sprite.spritecollide(player, obstacles, False):
            obstacles.remove(rock)
#----- Gameover
        if(player.gameover == True):
            player.goalY = 600
            font = pygame.font.SysFont('Ariel', 50, True, False)
            text = font.render("Game Over", True, WHITE)
            screen.blit(text, [150, 100])

Code edited
Comment: use `pygame.Rect`. It has `colliderect()` metod.
Comment: read this: http://programarcadegames.com/
Answer: Make Rock() also a pygame.sprite.Sprite class and if possible, put in a pygame.sprite.Group(). In that case, you can use if pygame.sprite.spritecollide() to check for detection:
rock = Rock()
player = Player()
obstacles = pygame.sprite.Group()
obsatcles.add(rock)
if pygame.sprite.spritecollide(player, obstacles, False):
    pass #Do something

The good thing about using pygame.sprite.Group() is that you can use that to help detect collisions with the player and any other obstacle. Let's assume you have three items in obstacles, in which they are all rock's:
for rock in obstacles:
    if pygame.sprite.spritecollide(player, obstacles, False):
        obstacles.remove(rock)  #Removes the obstacle

Put the group outside the sprite classes and before the while loop.
For the rock, use this in your init function:
self.rect = self.image.get_rect()

So it would be:
def __init__(self):
     pygame.sprite.Sprite.__init__(self)
     self.image = pygame.image.load("filename.png")
     self.rect = pygame.image.get_rect()

Then add this to your while loop:
for rock in obstacles:
    rock.move()
    rock.draw()

Your final class (excluding the last two functions) would be:
class Rock(pygames.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load("bcrocks.png")
        self.rect = self.image.get_rect()
        self.rect.x = random.randrange (0, 200)
        self.rect.y = 335

Comment: Thank you for replying! So if I were to make Rock() a pygame.sprite.Sprite class, I would do the same like how I did for Player() right?
Comment: Another question, (I apologize) where do I put pygame.sprite.Group()? Under the constructor function for rock?
Comment: I tried to make `Rock()` a sprite class but the `'rock'` object has no attribute `'rect'`. Is this correct ?: `self.rect.x = random.randrange (0, 200)`
Comment: Okay, I used the `self.rect = pygame.image.get_rect()` instead of `self.rect.x` and `self.rect.y` for some reason the module object has no `'get_rect'`
Comment: Cheers, I ran the code but it says `'rock'` object has no attribute `'image'` so it's okay if i put `self.image = pygame.image.load("bcrocks.png")` just above `self.rect = self.image.get_rect()`
Comment: Correct and put it in the constructor function
Comment: Okay! I really appreciate your help, I did everything you suggested and I edited the code above, the rocks don't appear on the screen nor collides with the player?
Comment: You have to keep everything the same but add those two lines, changing the filename to the appropriate one
Comment: Okay so instead of `self.rect = self.image.get_rect()` I replace it with `self.rect = pygame.image.get_rect()` under the rock class? Do I also remove `self.rect.x` and `self.rect.y`?
Comment: Implemented changes above, the rocks seem to still not show up?
Comment: yup i put `rock.draw(screen)` under `#--- Draw and Move Rocks`
Comment: Don't you mean `screen.blit(rock.image, rock.rect)`?
Comment: Under the `class Rock` or down below with the `for rock in obstacles`?
Comment: The function `draw()`
Comment: Oookay, I made the change to `screen.blit(rock.image, rock.rect)` but it still doesn't show up
Comment: Change the parameters of `draw(self, screen)` to `draw(self)`
Comment: I changed the parameters, yet the same error is occuring. Another odd thing is when I first launch the game, it brings it to the game over screen, restarts and then continues


can't locate the css file for a website

Question:
Possible Duplicate:
including css in Django

I have not much experience with web-front.
I'm trying to integrate a forum app into django. ( http://www.pybbm.org )
I succeeded running the app(I can see the forum at http://localhost/forum/ )
But it looks horrible without any css.
I tried including all the css files and less files I find in www.pybbm.org but it doesn't seem to help to make it look better.
Can anyone take a look at where the css files are for the site?
Comment: Where did you try including them?
Comment: I added to my base.html header. with full url to the site's css
Comment: I can see the css applied on my system.
Answer: the abreviation of CSS is Cascading StyleSheet, so it is responsible for the lay-out of the website. A css file is likely stored in a directory called CSS or style or sometimes in the main directory.
What you could do to find the css file is opening the index.html file and search for a file with extension .css.  You can find the line of text at the head of the index.html file.
When you found the .css file, you also see where it is saved, like /main/style/style.css
Problem solved?

can't locate the css file for a website