text:
Q: How does this diode improve the common mode conducted noise? This image was taken from UCC28881 (page 16)

The desciption in the body says:

A half-wave rectifier is chosen and implemented by diode D2 (1N4937). It is a general purpose 1-A, 600-V
  rated diode. It has a fast reverse recovery time (200 ns) for improved differential-mode-conducted EMI noise
  performance. Diode D3 (1N4007) is a general purpose 1-A, 1-kV rated diode with standard reverse recovery
  time (>500 ns), and is added for improved common-mode-conducted EMI noise performance. D3 can be
  removed and replaced by a short if not needed.

My question is how does D3 improve the EMI noise performance ?


text:
Q: Fade animation while scrolling I'm new here and i'd like to know, in this case, how to get the appearing effect while scrolling that this site is using:
http://psec.com.ar/home
Can anybody help me to get this?? Please! My biggest doubt is how to apply the animation at the exact moment when you scroll down over the element.
Thanks a lot everyone!

A: it depends on your coding level, to achieve this effect you need to use javascript. An easy way is to find a framework like bootstrap that by reading their docs you will see that it is pretty is to adapt it to your project. If you don't want to use bootstrap, then a simple code example will be like this:
give the elements you want the effect to apply the class-name animation-element
 // store the animation-element elements in a variable

  var $animation_elements = $('.animation-element');
   var $window = $(window);

  function check_if_in_view() {
    var window_height = $window.height();
    var window_top_position = $window.scrollTop();
    var window_bottom_position = (window_top_position + window_height);

    $.each($animation_elements, function() {
      var $element = $(this);
      var element_height = $element.outerHeight();
      var element_top_position = $element.offset().top;
      var element_bottom_position = (element_top_position + element_height);

      //check to see if this current container is within viewport
      if ((element_bottom_position >= window_top_position) &&
        (element_top_position <= window_bottom_position)) {
        $element.addClass('in-view');
     } else {
       $element.removeClass('in-view');
     }
    });
  }

   $window.on('scroll resize', check_if_in_view);
   $window.trigger('scroll');

You need jquery for this, this adds a class in-view if the element is in view then you can use whatever css animations you need for the effect!
I hope this will help you

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I create an automated chrome browser script? (Refreshes page when text is displayed.) I'm trying to create a bot for a game in the chrome browser that will automatically refresh the page when text is displayed, and also wait and refresh the page after other text is displayed...but I can't seem to figure it out.  What could I use to create a script like this?  Thank you!

A: Not very far from this question: https://stackoverflow.com/questions/2385500/search-document-innerhtml.  What I would do in the extension code:

*

*Create a function to search for your test and refresh the page if the text is found.

*Call this function when the page is printed for the first time (just in case).

*Add an event listener for DOM changes: https://stackoverflow.com/questions/3219758/detect-changes-in-the-dom


text:
Q: Using Excel XLSX as configuration file, how to read it fastest from .NET 4.x I am using Excel as a user editor for software configuration files, think tables of configuration data for the software. I use extensive validation before the configuration is used in the software (an Office VSTO .NET addin for Visio).
Unfortunately reading the file via Excel automation is slooooooooooooooooooooow, exporting to CSV makes for superfast reading if the config but then I end up with a file for every worksheet.
Much better is to read the Excel file, no interim steps that complicate the process, but what is the fastest way to do so?
I do not need to write to the config file, only read it. If the validation of the config data fails the entire configuration is rejected until the user/admin fixes the data by hand and tries to re-read the Excel file.
I do not use any of the special features of Excel (Charts etc etc), the only special things I'd like to read (another advantage over working with multiple CSV files):

*

*The color of certain cells

*The name of certain cells

Thank you for sharing your knowledge and experience!


text:
Q: REGEX match for portions of a document between two headers I'm trying and failing to write a python compliant REGEX that captures multiple parts of a document. My code will actually be in Python, but right now i've only tried on regex101.com to get the expression right. (unsuccessfully obviously :) )
My text that is file-based, looks something like this:
<#
.SYNOPSIS
This is the synopsis text, that is a multiline
synopsis - I want to match all of this text
as a capture group.
.PARAMETER
This a another block of
multiline text that I want to capture
.SOMEOTHER HEADER
And some other multiline text
#
I'd like to capture 2 groups (the header and the body text), globally. (i.e for each section).
My ultimate aim is a python array of dictionaries like;
[
{'header':'SYNOPSIS', 'text': }
{'header':'PARAMETER', 'text': }
]
The header section is always anchored to the beginning the line, with '.' and followed by uppercase TEXT. The body of the section includes any words and non-word characters including CR/LF (windows based).
The Header names are not guaranteed to be fixed literals, or in a specific order. Nor do I know how many headers might exist.
Right now it looks like this
(^\.[A-Z]+)([\n\W\w]+)
Right now I can match the header followed by a body, but I'm having a hard time telling REGEX to essentially 'stop looking when you hit the next .HEADERTEXT'.
I've created a Regex101 https://regex101.com/r/YqibeH/4 if its of use (not sure how this might work out). . .
My psuedo code says something like,
Find all lines beginning with ^.[A-Z] as a capture group, then continue to match all text (multiline) after the header as a second capture group. Stop capturing just before the next header that begins ^.[A-Z]
Any help greatly appreciated.

A: I believe what you're looking for is look aheads. Additionally the search you were doing is greedy and should be changed out for a lazy quantifier. That being said. This should work.
^\.\w+[\n\W\w]+?(?=^\.\w+|^#>)
https://regex101.com/r/YqibeH/7
^\.\w+ Greedily captures your header text.
[\n\W\w]+? Lazily searches for your body text.
(?=^\.\w+|^#>) until it looks ahead and finds either a line beginning with another header text or a line beginning with a header closing tag.
Note that if the greedy quantifier + would be used rather than +? it would continue matching until the last possible instance it could match.

A: text = '<#\n.SYNOPSIS\nThis is the block of code that I would like to have matched along with the .SYNOPSIS header, ' \
       'as this block belongs to SYNOPSIS\n .NOTES\n This block needs to belong with\nNOTES ' \
       'header\n.SOMEOTHERHEADER\nAnd resulting text\n\n#> '
pattern = "(\.[A-Z]+\n)+"
import re

print(re.split(pattern, text))

If I got your problem right, I solved it in the following way. This way you have a list with all the elements that you need to be appendend to your dictionary by cleaning the string, of course.


text:
Q: Adding another key to AOSP build I have two different Android devices from two different vendors. Each has their own customized AOSP build (which I manage). I've one set of system-signed apps to install on both devices. I'd like to avoid having to sign each APK separately for each device.
I can do this by replacing the system certs in the AOSP builds (target/product/security/platform.{pk8,x50.pem}). But this would mean re-signing any vendor-supplied apps for each device. I'd like to avoid that.
How can I add a second system cert to each build? I'd sign my own apps with the matching key and have single APKs that would install on both devices. Vendor apps could retain their existing signature matching the original system key.

A: You should your key files (pk8 and x509,pem) in the target/product/security/your_new_key.{pk8,x50.pem} directory and use this phrase in Android.mk files of your application:
LOCAL_CERTIFICATE := you_new_key

This app will then be signed using your new key.
For more info search about default keys present in AOSP (shared, media, ...)


text:
Q: How to return value from Component to VF page? I have requirement to return sobject from Component's repeat loop to main page in which component is used. And in main VF page i want to just display the field and its value.
Note: all this happening on page Load.
I am not sure whether it's possible or not?
Thanks In Advance.

A: It is possible. There's article describing how to achive that.

A: i got solution for this now ,
I used variable attribute from the component and in var attribute there is a type tag in which i selected Sobject and hence i was able to solve my problem. it was as simple.
So, From the VF page i can Access the value using value of "var" (new Attribute created in Component) which i passed in Component.


text:
Q: Minimal polynomial of $T$ and $[T]_B$ are same Definitions:
$(1)$ Let $V$ be finite dimensional vector space over $F$ and $T\in L(V,V)$. The minimal polynomial of $T$ is monic generator of ideal $$
M_T = \{f\in F[x] \mid f(T)=0\}.
$$
$(2)$ Let $A\in M_n(F)$. The minimal polynomial of $A$ is monic generator of ideal
$$
M_A = \{f\in F[x] \mid f(A)=0\}.
$$

Claim: Let $B$ be any basis of $V$. If $A=[T]_B$, then minimal polynomial of $T$ and $A$ are same.

My attempt: Let $m_T$ and $m_A$ be minimal polynomial of $T$ and $A$, respectively. We show
$$
[f(T)]_B = f([T]_B) = f(A),
\qquad \forall f \in F[x].
$$
Let $f = \sum_{i=0}^n a_i \cdot x^i \in F[x]$. Then
$f(T) = \sum_{i=0}^n a_i \cdot T^i$.
Since $[P]_B + [Q]_B = [P + Q]_B$, we have
$$
[f(T)]_B = \left[ \sum_{i=0}^n a_i \cdot T^i \right]_B
= \; \sum_{i=0}^n \, [a_i \cdot T^i]_B.
$$
Since $[c\cdot P]_B=c\cdot [P]_B$, we have
$$
\sum_{i=0}^n [a_i \cdot T^i]_B = \sum_{i=0}^n a_i \cdot [T^i]_B.
$$
Since $[P \circ Q]_B = [P]_B \cdot [Q]_B$, we have $$
\sum_{i=0}^n a_i \cdot [T^i]_B
= \sum_{i=0}^n a_i \cdot ([T]_B)^i
= f([T]_B) = f(A).
$$
Thus $[f(T)]_B = f(A)$, $\forall f\in F[x]$. It's easy to check,
$$
f(T) = 0 \iff [f(T)]_B = f(A) = 0,
$$
which implies $M_T = M_A$. Hence, $m_T=m_A$.
Is my proof correct?


text:
Q: Django Rest Framework custom readonly field dependant on related model supposing a models.py like:
class User(AbstractUser):
    pass

class Notification(models.Model):
    value = models.CharField(max_length=255)

class NotificationUserLink(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    notification = models.ForeignKey(Notification, on_delete=models.CASCADE)
    active = models.BooleanField(default=True)

The point behind normalizing instead of just having a user field on the Notification itself is for when I want to send the same Notification to hundreds of people I only need 1 Notification object. Suppose I also have an endpoint in views.py like below where the user can see all their notifications and only their notifications, which is achieved by filtering the queryset.
class NotificationViewSet(viewsets.ModelViewSet):
    serializer_class = serializers.NotificationSerializer
    model = Notification
    lookup_field='pk'
    def get_queryset(self):
        user = self.request.user
        return Notification.objects.filter(notificationuserlink__user=user)

Now the "user" and "notification" pair on the NotificationUserLink model form a candidate key (they are unique together. currently just by business logic but I'll add the actual constraint to the db at some point).
Therefore, given a user in the request, each Notification (in the filtered queryset) will have 1 and only 1 NotificationUserLink to that User. Therefore, from the User's perspective, that notification is either active or it isn't, depending on the "active" field on the NotificationUserLink.
What I want to accomplish is to include that field ("active") in the serialization of the Notification. I.e. if the user hits this endpoint they should see notifications like:
[
{
    "value": "Bob commented on your post",
    "active": False
},
{...}, ...
]
etc

I think that to achieve this I will need to override the "list" method on the view. But I don't know how. The serializer is being passed a queryset in the list method so I'm not sure how to inject data into that.
The serializer currently just looks like so:
class NotificationSerializer(serializers.ModelSerializer):
    class Meta:
        model=Notification
        fields=("value",)

A: You can annotate the status of the link like this in your queryset:
Notification.objects.filter(
    notificationuserlink__user=user
).annotate(
    active=F('notificationuserlink__active')
)

And then you can add a read-only field active field in your serializer:
class NotificationSerializer(serializers.ModelSerializer):
    active = serializers.BooleanField(read_only=True)
    class Meta:
        model = Notification
        fields = ("active", "value",)


text:
Q: mapbox moveend trigger on click only Ive build a map with custom markers and popups just like in this mapbox-tutorial. Besides I have a custom menu with links to fly to those locations and open the associated popups with moveend-event. This works fine so far.
Now I also have a link which zooms out again to fit all markers in viewport. But this also triggers the moveend-event if it gets clicked.
To understand what I mean: See fiddle and click "Washington" then "SF" then "Show all". I dont understand why moveend triggers with "Show all".
Heres a fiddle
HMTL

      Washington
      San Francisco
      Show all

JS
var map = new mapboxgl.Map({
    container: 'map',
    style: 'mapbox://styles/mapbox/light-v10',
    center: [-100, 37.8],
    zoom: 0
});

var bounds = new mapboxgl.LngLatBounds();

var geojson = {
    type: 'FeatureCollection',
    features: [{
            type: 'Feature',
            geometry: {
                type: 'Point',
                coordinates: [-77.032, 38.913]
            },
            properties: {
                title: 'Mapbox',
                description: 'Washington, D.C.'
            }
        },
        {
            type: 'Feature',
            geometry: {
                type: 'Point',
                coordinates: [-122.414, 37.776]
            },
            properties: {
                title: 'Mapbox',
                description: 'San Francisco, California'
            }
        }
    ]
};

geojson.features.forEach(function(marker, index) {

    // create a HTML element for each feature
    var el = document.createElement('div');
    el.className = 'marker';
    el.id = 'marker' + index;
    // make a marker for each feature and add to the map
    new mapboxgl.Marker(el)
        .setLngLat(marker.geometry.coordinates)
        .setPopup(new mapboxgl.Popup({
                offset: 25
            }) // add popups
            .setHTML('
' + marker.properties.title + '

' + marker.properties.description + '
'))
        .addTo(map);
    bounds.extend(marker.geometry.coordinates);
});

function fitmarkers() {
    map.fitBounds(bounds, {
        padding: 120,
        speed: 1.6
    });
}

fitmarkers();

function triggermarker(id) {
    map.on('moveend', function() {
        $(id).trigger('click');
    });
}

function fadeoutpopup() {
    if ($('.mapboxgl-popup').length) {
        $('.mapboxgl-popup').fadeOut(300, function() {
            $(this).remove();
        });
    };
}

$('.link').click(function() {
    $('span').removeClass('active');
    $(this).addClass("active");
    fadeoutpopup();
    var markerid = $(this).data('id');
    map.flyTo({
        center: [$(this).data('lat'), $(this).data('lng')],
        zoom: 11,
        speed: 3
    });
    triggermarker(markerid);
});

$('.showall').click(function(f) {
    fitmarkers();
    fadeoutpopup();
});

A: What browser are you using? Why would triggering a moveEnd be a problem? In case you already are moving, this movement has to end, so that the new movement can start (zoom out to show all markers)
When checking your fiddle, it did only work for me after changing the padding to a smaller value than 120:

function fitmarkers(){
    map.fitBounds(bounds, {padding: 10, speed: 1.6});
}

Please see the working code below:
(Please be aware, that you have shared your Mapbox access token. I have removed it from below code, but others could use it to generate cost for you)

<!DOCTYPE html>

<meta charset="utf-8" />
<title>Display a map</title>
<meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />

<link href="https://api.mapbox.com/mapbox-gl-js/v2.0.0/mapbox-gl.css" rel="stylesheet" />

Washington
San Francisco
Show all


text:
Q: Expected number of distinct values selected from binomial distribution The first part of the question (Finding expected number of distinct values selected from a set of integers) has been answered a few times.
Can someone provide a solution if we're drawing from a binomial distribution instead of a uniform distribution?
In other words, let X1,X2,X3,…,Xk be independent Binomial (n,p) random variables. What is the expected number of distinct values in the set {X1,…,Xk}?


text:
Q: TortoiseSVN - recover deleted revision Unfortunately one of my team members has deleted a specific revision from the svn physical folder location db/revs.
Is it possible to recover the particular revision if we know the deleted revision number?

A: Your repository is now corrupted and you'll need to restore from backup. You cannot recover from other revisions.
Why do your team members have write access to the repository on the server's filesystem in the first place?  Fix that before attempting to recover, because if you don't you'll find yourself going through this same exercise.


text:
Q: How would I use a list of lists containing the keys of a json to reference values in the json I currently have a python function that goes through a json and returns the keys as a list of lists. For example, if a json was like
{'employee':{
     'info':{'name':'bob' , 'id':4 },
     'department':{'name':'sales' , 'floor':1}}}

it would return a list like
[[['employee'], ['info'], ['name']],
 [['employee'], ['info'], ['id']],
 [['employee'], ['department'], ['name']],
 [['employee'], ['department'], ['floor']]] .

If I wanted to look up, for example, the employees name, is there a way I could reference the list to make its corresponding entry from a list of lists into something like
json['employee']['info']['name']?

A: I don't think there is a built-in method but you can use reduce creatively for this purpose:
>>> from functools import reduce
>>> d = {'employee': {'info': {'name': 'bob', 'id': 4}, 'department': {'name': 'sales', 'floor': 1}}}

then
>>> path =[['employee'], ['info'], ['name']]
>>> reduce(lambda sub_dict, key: sub_dict.get(key[0]), path, d)
'bob'

or
>>> path = [['employee'], ['department'], ['name']]
>>> reduce(lambda sub_dict, key: sub_dict.get(key[0]), path, d)
'sales'


text:
Q: what is the difference between ArrayList and ArrayList>? ArrayList<Integer> al = new ArrayList<Integer>();
al.add(new ArrayList());

when i try to add ArrayList in the above code it is not possible, but when i use the below code it is possible.Can i know why
ArrayList<ArrayList<Integer>> al1 = new ArrayList<ArrayList<Integer>>
al1.add(new ArrayList());

A: In the first snippet al is an ArrayList of Integers - so you can't add an ArrayList to it as an element.
In the second snippet al1 is an ArrayList of ArrayLists of Integers, so an ArrayList is a valid element to add to it.


text:
Q: MVC cant upload file Im fairly new to .NET Core MVC and trying to create a simple application where a user can upload a file and it saves to a home folder, currently i've followed a tutorial which at least seems to be a step in the right direction. however my post method isn't being hit when I click the submit button. does anybody have any insights as to why this is?
Here is my controller code:
 namespace GraduateOutcomesConverter.Controllers
{
public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }

    public IActionResult Privacy()
    {
        return View();
    }

    [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
    public IActionResult Error()
    {
        return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
    }

 [HttpPost("UploadFiles")]
    public async Task<IActionResult> FileUpload(List<IFormFile> files)
    {
        long size = files.Sum(f => f.Length);
        var filePaths = new List<string>();
        foreach (var formFile in files)
        {
            if(formFile.Length > 0)
            {
                var filePath = Path.GetTempFileName();
                filePaths.Add(filePath);

                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    await formFile.CopyToAsync(stream);
                }
            }
        }
        return Ok(new { count = files.Count, size, filePaths });
    }

And my View
 @{
ViewData["Title"] = "Home Page";
 }

Welcome

Please Upload An Excel File.

<input type="file" name="datafile" style="margin-left: 10px; margin-top:
 15px; vertical-align: top; font-size:18px; background-color: white; margin-
left:160px; margin-top:15px; width:250px; height:40px /">

 <form method="post" enctype="multipart/form-data" asp-
controller="UploadFiles" asp-action="FileUpload">

Please Upload An Excel File.

    <input type="file" name="files" multiple />

        <input type="submit" value="Upload" />

 </form>

Any help would be much appreciated
Thanks

A: The given  controller name to form element is Invalid. You probably need to change it to Home
Your current code
 <form method="post" enctype="multipart/form-data" asp-
controller="UploadFiles" asp-action="FileUpload">

It should be;
<form method="post" enctype="multipart/form-data" asp-
controller="Home" asp-action="FileUpload">


text:
Q: Create a plot to see the distribution relationship between groups of data in R I have a table like the one below and i want to create a plot in R to see the relationship in T1 and T2 based on counts. on x-axes to have samples with T1 and on y-axes samples with T2 and see the line of counts.A scatter plot would be useful?
Sample  Time  counts
001_T1   T1    26,629,556
001_T2   T2    20,755,896
002_T1   T1    26,081,538
002_T2   T2    28,675,076
003_T1   T1    25,459,034
003_T2   T2    25,531,900
004_T1   T1    29,062,968
004_T2   T2    26,612,567
005_T1   T1    26,689,387
005_T2   T2    28,428,044


text:
Q: Visual studio installer msi is not updating UI Strange issue, but it is bothering me.
When I tried to deploy msi package is not completely updating the previous version. but the version is been updated in control panel but not UI (changes made in UI is not reflecting).
DetectPreviousVersion = True;
RemovePreviousVersion =True;
Installallausers=true;

The product version is higher number than previously installed version, and changed the product code for each higher version.
upgrade code of the previous installed version and new version are same.
If I remove the previous version manually and then install the latest version then I could see the changes in UI.

A: Proper versioning of your DLL's and EXE's would prevent this.
File Versioning Rules

At the core of any installer is the actual installation of files.
  Determining whether to install a file is a complex process. At the
  highest level, this determination depends on whether the component to
  which a file belongs is marked for installation. Once determined that
  a file should be copied, the process is complicated if another file
  with the same name exists in the target folder. In such situations,
  making the determination requires a set of rules involving the
  following properties:
•Version
•Date
•Language

A: possibly duplicate question:
but for viewers the answer is adding an extra property to msi package using orca.
REINSTALLMODE=amus

amus-updates the all files on upgrade
omus- updates files that are only changes as installer identifies
refer to original answer here

A: Older versions of Visual Studio setups used to effectively uninstall all the old files and then install the product and it's files. VS 2008 and later require you to update the file version of files that you want to overwrite in the upgrade.


text:
Q: Accidentally created directory named "~" (tilde) I managed to make a directory literally named ~.
(Apparently, Python's os.mkdir('~/something') does this.)
How do I remove it without nuking my home?
Also, if it helps, I have my real /home on a separate partition. And the duplicate ~ is located in (the real ) ~.

A: Escape the ~ with \~ or use single quotes '~'.
so you can
rmdir ~/\~

or
cd ~ ; rmdir '~'

A: What python giveth, python taketh away:
$ python -c 'import os; os.makedirs("~/foo")'; tree; python -c 'import os; os.removedirs("~/foo")'; tree
.
└── ~
    └── foo

2 directories, 0 files
.

0 directories, 0 files

If you did os.mkdir, you could undo it with os.rmdir (and similarly for os.makedirs and os.removedirs).

A: You can either escape the directory name using a backslash like this (assuming you're operating in the parent directory of the one you want to delete):
rmdir \~

Or you can use relative paths with a dot as the current directory (also when located in the parent directory):
rmdir ./~

Or you can use the full absolute path:
rmdir /home/USERNAME/~

And no worries, rmdir can only remove empty directories. If you accidentally mistype the command and the path would evaluate to your real home directory, it is not in danger because it contains files:
$ rmdir directory_with_files
rmdir: failed to remove 'directory_with_files': Directory not empty

A: find command can do such miracles. The command
ls -i

will give you inode number of files or directory.
Then you can use find to delete such files or directory using:
find . -inum <inode-number> -delete #for a file

and
find . -inum <inode-number> -exec rm -rf {}\; #for directories

A: What should have been done
You should have performed home=os.path.expanduser("~") first and then os.path.join(home,"something"). The ~ is treated as text in python and doesn't expand like it does in bash or other shells.
$ python -c 'import os;home=os.path.expanduser("~"); os.mkdir(os.path.join(home,"something"))'

$ ls -ld ~/something
drwxrwxr-x 2 xieerqi xieerqi 4096 7月  12 21:00 /home/xieerqi/something/

How to get rid of it
In addition to the already mentioned methods, we can use hex value for ~ from the ascii table of characters, which unlike actual ~ doesn't expand to user's home directory on command line (In case you're wondering, when tilde appears at the beginning of a word, it expands to user's home directory. Compare ls ~ and ls $'\x7e').
Here's how it would work:
# Make the directory
$ mkdir ./~
$ stat ./$'\x7e'
  File: './~'
  Size: 4096        Blocks: 8          IO Block: 4096   directory
Device: 801h/2049d  Inode: 5768019     Links: 2
Access: (0775/drwxrwxr-x)  Uid: ( 1000/ xieerqi)   Gid: ( 1000/ xieerqi)
Access: 2017-07-12 21:05:31.382828424 -0600
Modify: 2017-07-12 21:05:31.382828424 -0600
Change: 2017-07-12 21:05:31.382828424 -0600
 Birth: -

# and remove it
$ rmdir ./$'\x7e'
$ ls $'\x7e'
ls: cannot access '~': No such file or directory


text:
Q: maven when to use clean over compile When running mvn clean install
It will clean target directory, compile and run tests.
However it does not run any of the clean options unless its explicitly stated? e.g.  this will not clean the target directory
mvn install
So I often run clean just to be sure its always fresh.
If I make a code change do I need to always clean if wanting to verify the new code changes?.
compile is part of the default life cycle which runs when I type mvn install doesnt this do the same thing?  Whats the main benefit of clean?

A: The clean goal removes any of the output files located in target/ or wherever else you've specified them.
Incremental compilation is a thing in Maven - which is why other goals don't automatically assume clean - but it is often considered to be unreliable at best.  For sanity's sake, it is best to always clean your workspace so that you don't get bizarre class collisions.

A: clean command clean your target (your projects build location).
install command build your package and put it into your maven local repository also thats why other project can use your projects as library from maven local repository.
and compile just compile the source code of the project.
So If you use mvn clean install it will first clean your build directory then compile your project and build target directory with compiled files and then put it into your maven local repository. So you can use your projects files to others project from your maven local repository.
and mvn clean compile will first clean your build directory and then compile your project and build target directory with compiled files


text:
Q: Python Texttable I am trying to build a table for an exercise using texttable.
tab.add_row(row) = ["Match1", Team1_matches[1], Team2_matches[1], max(Team1_matches[1],Team2_matches[1])]

I am getting this:
  tab.add_rows(row) = ["Match1", Team1_matches[1], Team2_matches[1]]
SyntaxError: can't assign to function call

A: You assigned the list of elements to tab.add_row(row), that's why you got the SyntaxError
The correct way use Texttable is:
# create a list with the elements and assign it to row
row = ["Match1", Team1_matches[1], Team2_matches[1], max(Team1_matches[1],Team2_matches[1])]
# insert a row into table by invoking add_row() of the TextTable object tab.
tab.add_row(row)


text:
Q: $|x-\frac{1}{2}|^{1+1/n}\rightarrow |x-\frac{1}{2}|$? I want to show that $C^1[0,1]$ isn't a Banach Space with the norm:
$$||f||=\max\limits_{y\in[0,1]}|f(y)|$$
Therefore, I want to show that the sequence $\left \{ |x-\frac{1}{2}|^{1+\frac{1}{n}} \right \}$ converges to $|x-\frac{1}{2}|$, but I can't find $N$ in the definition of convergence. Could anyone give me an idea?
Thank You.

A: You have, using the Mean Value Theorem,   the inequality
$$
1-e^t\leq |t|,\ \ \ \ t\leq0.
$$
Then, for $t\in[0,1]$ and $x>0$,
$$
|t^{1+x}-t|=|t|\,|t^x-1|\leq |t|\,|e^{x\log t}-1|\leq x\,|t\log t|\leq \frac xe.
$$
So
$$
\left|\,\left|x-\tfrac12\right|^{1+\tfrac1n}-\left| x-\tfrac12\right|\,\right |\leq\frac1{ne}
$$

A: To show $\left|x-\frac12\right|^{1+1/n}=\left|x-\frac12\right|\left|x-\frac12\right|^{1/n}\to \left|x-\frac12\right|$ pointwise, which is clear when $x=\frac12$, it suffices to show that when $0<t<1$, $t^{1/n}\to 1$.  Note that $(t^{1/n})$ is bounded above by $1$ and monotone increasing, so it has a limit $L$, with $L>0$.  The subsequence $(t^{1/(2n)})$ must converge to the same limit $L$, and the sequences of squares of this subsequence must converge to $L^2$, implying that $L^2=L$.  Hence $L=1$.
From the above, we have monotone pointwise convergence of the sequence to $\left|x-\frac12\right|$.  By Dini's Theorem, the convergence is uniform, hence convergence in the given norm.


text:
Q: An exception occurred while executing 'INSERT INTO tag (name, task_id) VALUES (?, ?)' with params ["qw", null]: Please help me to resolve this error:
I have two entities, Task and Tag, in TaskType  pretend add N tags, but when I keep generates the following error:

An exception occurred while executing 'INSERT INTO tag (name, task_id) VALUES (?, ?)' with params ["qw", null]:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'task_id' cannot be null

Task:
class Task
{
/**
  * @var integer
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @var string
 *
 * @ORM\Column(name="description", type="string", length=255)
 */
private $description;

/**
 * @ORM\OneToMany(targetEntity="Tag", mappedBy="task", cascade={"persist", "remove"})
 */
private $tags;

public function __construct() {
    $this->tags = new ArrayCollection();
}

/**
 * Get id
 *
 * @return integer
 */
public function getId()
{
    return $this->id;
}

/**
 * Set description
 *
 * @param string $description
 *
 * @return Task
 */
public function setDescription($description)
{
    $this->description = $description;

    return $this;
}

/**
 * Get description
 *
 * @return string
 */
public function getDescription()
{
    return $this->description;
}

/**
 * Set tags
 *
 * @param string $tags
 *
 * @return Task
 */
public function setTags($tags)
{
    $this->tags = $tags;

    return $this;
}

/**
 * Get tags
 *
 * @return string
 */
public function getTags()
{
    return $this->tags;
}

/**
 * Add tag
 *
 * @param \AppBundle\Entity\Tag $tag
 *
 * @return Task
 */
public function addTag(\AppBundle\Entity\Tag $tag)
{
    $this->tags[] = $tag;

    return $this;
}
// public function addTag(Tag $tag)
// {
//     $this->tags->add($tag);
// }

/**
 * Remove tag
 *
 * @param \AppBundle\Entity\Tag $tag
 */
public function removeTag(\AppBundle\Entity\Tag $tag)
{
    $this->tags->removeElement($tag);
}
}

Tag:
class Tag
{
/**
 * @var integer
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @var string
 *
 * @ORM\Column(name="name", type="string", length=255)
 */
private $name;

/**
 * @ORM\ManyToOne(targetEntity="Task", inversedBy="tags")
 * @ORM\JoinColumn(name="task_id", referencedColumnName="id")
 */
private $task;

/**
 * Get id
 *
 * @return integer
 */
public function getId()
{
    return $this->id;
}

/**
 * Set name
 *
 * @param string $name
 *
 * @return Tag
 */
public function setName($name)
{
    $this->name = $name;

    return $this;
}

/**
 * Get name
 *
 * @return string
 */
public function getName()
{
    return $this->name;
}

/**
 * Set task
 *
 * @param \AppBundle\Entity\Task $task
 *
 * @return Tag
 */
public function setTask(\AppBundle\Entity\Task $task = null)
{
    $this->task = $task;

    return $this;
}

/**
 * Get task
 *
 * @return \AppBundle\Entity\Task
 */
public function getTask()
{
    return $this->task;
}
}

TaskType:
class TaskType extends AbstractType
{
/**
 * @param FormBuilderInterface $builder
 * @param array $options
 */
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('description')
        ->add('tags', 'collection', array(
            'type'         => new TagType(),
            'allow_add' => true,
            'allow_delete' => true,
            'prototype' => true,
            'by_reference' => false,
        ))
        ->add('submit','submit');
    ;
}

/**
 * @param OptionsResolverInterface $resolver
 */
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'DeteccionBundle\Entity\Task'
    ));
}

/**
 * @return string
 */
public function getName()
{
    return 'task';
}
}

Controller:
public function newAction(Request $request)
{
    $task = new Task();

    //SE AGREGAN UN NUMERO DE Tags PARA LA task
    // $tag1 = new Tag();
    // $tag1->setName = 'tag1';
    // $task->getTags()->add($tag1);
    // $tag2 = new Tag();
    // $tag2->setName = 'tag2';
    // $task->getTags()->add($tag2);
    // end dummy code

    $form = $this->createForm(new TaskType(), $task);

    $form->handleRequest($request);

    if ($form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->persist($task);
        $em->flush();

        return $this->redirect($this->generateUrl('cpu_show', array('id' => $entity->getId())));
    }

    return $this->render('DeteccionBundle:Task:new.html.twig', array(
        'task' => $task,
        'form' => $form->createView(),
    ));
}

I appreciate your help

A: You should auto-set the task in your addTag like...
/**
 * Add tag
 *
 * @param \AppBundle\Entity\Tag $tag
 *
 * @return Task
 */
public function addTag(\AppBundle\Entity\Tag $tag)
{
    $this->tags[] = $tag;
    $tag->setTask($this);

    return $this;
}


text:
Q: NoMethodError in Nutritions#new - undefined method '' for nil:NilClass I have an error in my nifty_scaffold...
For some reason (didn't change any standard code, checked the routes.rb, ...), creating a new nutrition won't work.
Could anyone explain me how and what the solution is?
I think i have included all necessairy code...
The error in detail is:
undefined method `generated_methods' for nil:NilClass
Route contains:
map.resources :nutritions

View: New
<% title "New Nutrition" %>
<%= render :partial => 'form' %>

<%= link_to "Back to List", nutritions_path %>

View: _form
<% form_for @nutrition do |f| %>
  <%= f.error_messages %>

    <%= f.label :name %>

    <%= f.text_field :name %>

    <%= f.label :description %>

    <%= f.text_area :description %>

    <%= f.label :ammount %>

    <%= f.text_field :ammount %>

    <%= f.label :unit %>

    <%= f.text_field :unit %>

    <%= f.label :kcal %>

    <%= f.text_field :kcal %>

    <%= f.label :protein %>

    <%= f.text_field :protein %>

    <%= f.label :carb %>

    <%= f.text_field :carb %>

    <%= f.label :fat %>

    <%= f.text_field :fat %>

    <%= f.label :type %>

    <%= f.text_field :type %>

    <%= f.label :class %>

    <%= f.text_field :class %>

<%= f.submit "Submit" %>

<% end %>

And my nutrition controller
  def new
    @nutrition = Nutrition.new
    #raise @progress.inspect (debug porpose, didn't help)
  end

And this is the full Trace
C:/ruby/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support/whiny_nil.rb:52:in method_missing'                      C:/ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/attribute_methods.rb:352:inrespond_to?' C:/ruby/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support/core_ext/array/wrapper.rb:14:in wrap' C:/ruby/lib/ruby/gems/1.8/gems/actionpack-2.3.5/lib/action_view/helpers/active_record_helper.rb:174:inerror_messages_for' C:/ruby/lib/ruby/gems/1.8/gems/actionpack-2.3.5/lib/action_view/helpers/form_helper.rb:1012:in error_messages' D:/Workspace/Aptana/UltimateJournal/app/views/nutritions/_form.html.erb:3:in_run_erb_app47views47nutritions47_form46html46erb_locals_form_object' C:/ruby/lib/ruby/gems/1.8/gems/actionpack-2.3.5/lib/action_view/helpers/form_helper.rb:499:in fields_for' C:/ruby/lib/ruby/gems/1.8/gems/actionpack-2.3.5/lib/action_view/helpers/form_helper.rb:282:inform_for' D:/Workspace/Aptana/UltimateJournal/app/views/nutritions/_form.html.erb:2:in _run_erb_app47views47nutritions47_form46html46erb_locals_form_object' C:/ruby/lib/ruby/gems/1.8/gems/actionpack-2.3.5/lib/action_view/renderable.rb:34:insend' C:/ruby/lib/ruby/gems/1.8/gems/actionpack-2.3.5/lib/action_view/renderable.rb:34:in render' C:/ruby/lib/ruby/gems/1.8/gems/actionpack-2.3.5/lib/action_view/base.rb:306:inwith_template' C:/ruby/lib/ruby/gems/1.8/gems/actionpack-2.3.5/lib/action_view/renderable.rb:30:in render' C:/ruby/lib/ruby/gems/1.8/gems/actionpack-2.3.5/lib/action_view/renderable_partial.rb:20:inrender' C:/ruby/lib/ruby/gems/1.8/gems/actionpack-2.3.5/lib/action_controller/benchmarking.rb:26:in benchmark' C:/ruby/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support/core_ext/benchmark.rb:17:inms' C:/ruby/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support/core_ext/benchmark.rb:10:in realtime' C:/ruby/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support/core_ext/benchmark.rb:17:inms' C:/ruby/lib/ruby/gems/1.8/gems/actionpack-2.3.5/lib/action_controller/benchmarking.rb:26:in benchmark' C:/ruby/lib/ruby/gems/1.8/gems/actionpack-2.3.5/lib/action_view/renderable_partial.rb:19:inrender' C:/ruby/lib/ruby/gems/1.8/gems/actionpack-2.3.5/lib/action_view/template.rb:205:in render_template' C:/ruby/lib/ruby/gems/1.8/gems/actionpack-2.3.5/lib/action_view/renderable_partial.rb:44:inrender_partial' C:/ruby/lib/ruby/gems/1.8/gems/actionpack-2.3.5/lib/action_view/partials.rb:184:in render_partial' C:/ruby/lib/ruby/gems/1.8/gems/actionpack-2.3.5/lib/action_view/base.rb:267:inrender' D:/Workspace/Aptana/UltimateJournal/app/views/nutritions/new.html.erb:3:in _run_erb_app47views47nutritions47new46html46erb' C:/ruby/lib/ruby/gems/1.8/gems/actionpack-2.3.5/lib/action_view/renderable.rb:34:insend' C:/ruby/lib/ruby/gems/1.8/gems/actionpack-2.3.5/lib/action_view/renderable.rb:34:in render' C:/ruby/lib/ruby/gems/1.8/gems/actionpack-2.3.5/lib/action_view/base.rb:306:inwith_template' C:/ruby/lib/ruby/gems/1.8/gems/actionpack-2.3.5/lib/action_view/renderable.rb:30:in render' C:/ruby/lib/ruby/gems/1.8/gems/actionpack-2.3.5/lib/action_view/template.rb:205:inrender_template' C:/ruby/lib/ruby/gems/1.8/gems/actionpack-2.3.5/lib/action_view/base.rb:265:in render' C:/ruby/lib/ruby/gems/1.8/gems/actionpack-2.3.5/lib/action_view/base.rb:348:in_render_with_layout' C:/ruby/lib/ruby/gems/1.8/gems/actionpack-2.3.5/lib/action_view/base.rb:262:in render' C:/ruby/lib/ruby/gems/1.8/gems/actionpack-2.3.5/lib/action_controller/base.rb:1250:inrender_for_file' C:/ruby/lib/ruby/gems/1.8/gems/actionpack-2.3.5/lib/action_controller/base.rb:945:in render_without_benchmark' C:/ruby/lib/ruby/gems/1.8/gems/actionpack-2.3.5/lib/action_controller/benchmarking.rb:51:inrender' C:/ruby/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support/core_ext/benchmark.rb:17:in ms' C:/ruby/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support/core_ext/benchmark.rb:10:inrealtime' C:/ruby/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support/core_ext/benchmark.rb:17:in ms' C:/ruby/lib/ruby/gems/1.8/gems/actionpack-2.3.5/lib/action_controller/benchmarking.rb:51:inrender' C:/ruby/lib/ruby/gems/1.8/gems/actionpack-2.3.5/lib/action_controller/base.rb:1326:in default_render' C:/ruby/lib/ruby/gems/1.8/gems/actionpack-2.3.5/lib/action_controller/base.rb:1332:inperform_action_without_filters' C:/ruby/lib/ruby/gems/1.8/gems/actionpack-2.3.5/lib/action_controller/filters.rb:617:in call_filters' C:/ruby/lib/ruby/gems/1.8/gems/actionpack-2.3.5/lib/action_controller/filters.rb:610:inperform_action_without_benchmark' C:/ruby/lib/ruby/gems/1.8/gems/actionpack-2.3.5/lib/action_controller/benchmarking.rb:68:in perform_action_without_rescue' C:/ruby/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support/core_ext/benchmark.rb:17:inms' C:/ruby/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support/core_ext/benchmark.rb:10:in realtime' C:/ruby/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support/core_ext/benchmark.rb:17:inms' C:/ruby/lib/ruby/gems/1.8/gems/actionpack-2.3.5/lib/action_controller/benchmarking.rb:68:in perform_action_without_rescue' C:/ruby/lib/ruby/gems/1.8/gems/actionpack-2.3.5/lib/action_controller/rescue.rb:160:inperform_action_without_flash' C:/ruby/lib/ruby/gems/1.8/gems/actionpack-2.3.5/lib/action_controller/flash.rb:146:in perform_action' C:/ruby/lib/ruby/gems/1.8/gems/actionpack-2.3.5/lib/action_controller/base.rb:532:insend' C:/ruby/lib/ruby/gems/1.8/gems/actionpack-2.3.5/lib/action_controller/base.rb:532:in process_without_filters' C:/ruby/lib/ruby/gems/1.8/gems/actionpack-2.3.5/lib/action_controller/filters.rb:606:inprocess' C:/ruby/lib/ruby/gems/1.8/gems/actionpack-2.3.5/lib/action_controller/base.rb:391:in process' C:/ruby/lib/ruby/gems/1.8/gems/actionpack-2.3.5/lib/action_controller/base.rb:386:incall' C:/ruby/lib/ruby/gems/1.8/gems/actionpack-2.3.5/lib/action_controller/routing/route_set.rb:437:in call' C:/ruby/lib/ruby/gems/1.8/gems/actionpack-2.3.5/lib/action_controller/dispatcher.rb:87:indispatch' C:/ruby/lib/ruby/gems/1.8/gems/actionpack-2.3.5/lib/action_controller/dispatcher.rb:121:in _call' C:/ruby/lib/ruby/gems/1.8/gems/actionpack-2.3.5/lib/action_controller/dispatcher.rb:130:inbuild_middleware_stack' C:/ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/query_cache.rb:29:in call' C:/ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/query_cache.rb:29:incall' C:/ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/connection_adapters/abstract/query_cache.rb:34:in cache' C:/ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/query_cache.rb:9:incache' C:/ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/query_cache.rb:28:in call' C:/ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/connection_adapters/abstract/connection_pool.rb:361:incall' C:/ruby/lib/ruby/gems/1.8/gems/actionpack-2.3.5/lib/action_controller/string_coercion.rb:25:in call' C:/ruby/lib/ruby/gems/1.8/gems/rack-1.0.1/lib/rack/head.rb:9:incall' C:/ruby/lib/ruby/gems/1.8/gems/rack-1.0.1/lib/rack/methodoverride.rb:24:in call' C:/ruby/lib/ruby/gems/1.8/gems/actionpack-2.3.5/lib/action_controller/params_parser.rb:15:incall' C:/ruby/lib/ruby/gems/1.8/gems/actionpack-2.3.5/lib/action_controller/session/cookie_store.rb:93:in call' C:/ruby/lib/ruby/gems/1.8/gems/actionpack-2.3.5/lib/action_controller/failsafe.rb:26:incall' C:/ruby/lib/ruby/gems/1.8/gems/rack-1.0.1/lib/rack/lock.rb:11:in call' C:/ruby/lib/ruby/gems/1.8/gems/rack-1.0.1/lib/rack/lock.rb:11:insynchronize' C:/ruby/lib/ruby/gems/1.8/gems/rack-1.0.1/lib/rack/lock.rb:11:in call' C:/ruby/lib/ruby/gems/1.8/gems/actionpack-2.3.5/lib/action_controller/dispatcher.rb:114:incall' C:/ruby/lib/ruby/gems/1.8/gems/actionpack-2.3.5/lib/action_controller/reloader.rb:34:in run' C:/ruby/lib/ruby/gems/1.8/gems/actionpack-2.3.5/lib/action_controller/dispatcher.rb:108:incall' C:/ruby/lib/ruby/gems/1.8/gems/rails-2.3.5/lib/rails/rack/static.rb:31:in call' C:/ruby/lib/ruby/gems/1.8/gems/rack-1.0.1/lib/rack/urlmap.rb:46:incall' C:/ruby/lib/ruby/gems/1.8/gems/rack-1.0.1/lib/rack/urlmap.rb:40:in each' C:/ruby/lib/ruby/gems/1.8/gems/rack-1.0.1/lib/rack/urlmap.rb:40:incall' C:/ruby/lib/ruby/gems/1.8/gems/rails-2.3.5/lib/rails/rack/log_tailer.rb:17:in call' C:/ruby/lib/ruby/gems/1.8/gems/rack-1.0.1/lib/rack/content_length.rb:13:incall' C:/ruby/lib/ruby/gems/1.8/gems/rack-1.0.1/lib/rack/chunked.rb:15:in call' C:/ruby/lib/ruby/gems/1.8/gems/rack-1.0.1/lib/rack/handler/mongrel.rb:64:inprocess' C:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/lib/mongrel.rb:159:in process_client' C:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/lib/mongrel.rb:158:ineach' C:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/lib/mongrel.rb:158:in process_client' C:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/lib/mongrel.rb:285:inrun' C:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/lib/mongrel.rb:285:in initialize' C:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/lib/mongrel.rb:285:innew' C:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/lib/mongrel.rb:285:in run' C:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/lib/mongrel.rb:268:ininitialize' C:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/lib/mongrel.rb:268:in new' C:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/lib/mongrel.rb:268:inrun' C:/ruby/lib/ruby/gems/1.8/gems/rack-1.0.1/lib/rack/handler/mongrel.rb:34:in run' C:/ruby/lib/ruby/gems/1.8/gems/rails-2.3.5/lib/commands/server.rb:111 C:/ruby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:ingem_original_require' C:/ruby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in require' script/server:3-e:2:inload'-e:2

A: it looks fine, just naming an attribute as "class" does not seem to be a good idea, it's usually pretty much reserved word...


text:
Q: Actionbar dropdown click event I have dropdown list in actionbar as navigation list. Using ActionBar.OnNavigationListener and onNavigationItemSelected to detect when user has clicked on item in actionbar dropdown navigation list and that works fine.
However, onNavigationItemSelected is not called if user has clicked on the same item as the one which is currently selected in dropdown list! (I need this exact functionality behavior for app to work properly)
So is there any way to detect click on any part of the dropdown list in actionbar?
Is there a way to somehow reference dropdown view in actionbar, and then set onclicklistner on that dropdown object in actionbar. Like when we use dropdown list in standard layout?

A: The problem here is the same as with any other Spinner. The workariund for this is clearly described here: Spinner : onItemSelected not called when selected item remains the same
However for the ActionBar the solution can be a bit tricky (except for when you are using the ActionBarSherlock and can explicitly mess with its code)


text:
Q: sonar custom rule check java collection type is unknownSymbol Collection type always return 'unknownSymbol' in a custom sonar check rule class.
//demo class
public class SaasConstantNameCheckCase {
    private static final long serialVersionUID;
    private final String title;
    public static final Integer maxSize = 1111;// Noncompliant
    private static List list = new ArrayList<>();
    private static HashMap<String, String> map = new HashMap<>();
}

// custom rule class
@Override
public void visitVariable(VariableTree tree) {
    VariableSymbol symbol = (VariableSymbol) tree.symbol();
    String type = symbol.type().name();
    System.out.println("type->"+type);
}

// test result
type->long
type->String
type->Integer
type->!unknownSymbol!
type->!unknownSymbol!

Why?

A: SonarJava will show this unknownSymbol! string when it fails to resolve the actual type symbols.
In this particular case, you should either use fully qualified types java.util.List and java.util.HashMap, or import them.


text:
Q: Convert Prolog sentence to query Is there any way to convert a simple sentence like:
Is Bob a man?

to a Prolog query like:
man(Bob).

My thought is to take Bob and man from the input then store them in variables. Then somehow build the query from those variables. Is that possible?


text:
Q: What is the else statement syntax? I am trying to make some code on swift that will allow me to type in a number, and it will print out it's square root without using the square root command. But when I'm using the else if and else statements, swift is throwing me an error. The code will only answer to inputs that are within the range 1 to 10000.
    import Swift

    var input = readLine()

    var intInput = Int(input!)!
    print(intInput)

    if intInput < 1 || intInput > 10000{
    print("out of bounds")
    }

    if else {

for i in 1...100{

if intInput / i == i{
    print(intInput / i)
}
}

}

else{
print("no root")
}

The error will say:
closure expression is unused
    else {
         ^

It will also say:
    Note: did you mean to use a 'do' statement?
    else {
         ^

A: I'm not very familiar with Swift but it looks the second else if statement is written in the wrong order ("if else") and also lacks a Boolean expression to test.
Also, I went ahead and improved the indentation for the sake of readability:
import Swift

var input = readLine()

var intInput = Int(input!)!
print(intInput)

if intInput < 1 || intInput > 10000
{
    print("out of bounds")
}
else if
{
    for i in 1...100
    {
        if intInput / i == i
        {
            print(intInput / i)
        }
    }
}
else
{
   print("no root")
}

Note that else if still lacks a condition, as it's up to you what you'd like to put there. This is likely just a simple case where a syntax error in one place gets identified in as an error in a completely different place, and can be pretty confusing.


text:
Q: Use of Unresolved Identifer in scheduledTimer I've been working on this for a day and can't figure out what is going wrong.  I've searched here and the documentation and still can't find the answer.
Here's the code:
`var counter = 60
 let timer = scheduledTimer(timeInterval:1.0, target: Any?, #selector(timerAction), userInfo: Any?, repeats: true)

 func timerAction() {
    for i in timer {
        counter -= 1
        print(counter)
  }

}
   timerAction()`
Any help would be greatly appreciated.


text:
Q: How to check if user has installed specific app on the WP8 device I'm developing an app for WP8.  Can I check (programmaticaly) if wp8 device has some specific app installed (i.e. WP8 Facebook app)?

A: You cannot get the list of applications that are installed on the Windows Phone that are published by someone other than the publisher of the calling application.
There is a way, however, to get the list of applications that are installed on the device and are originating from the publisher of the caller app. Here is what I am talking about:
IEnumerable<Package> apps = Windows.Phone.Management.Deployment.InstallationManager.FindPackagesForCurrentPublisher();
apps.First().Launch(string.Empty);

This required your app to run on a Windows Phone 8 device.


text:
Q: xcode 6.01+ swift: What is the minimal project structure I must have / How to remove unneeded file references? I'm trying to create a very lean iOS project structure with no unneeded files.  If one does new --> project and and selects single view project, you get a basic project file structure which includes  main.storyboard, LaunchScreen.xib and a folder projectTests.  If my code doesn't require the interface builder files and I don't want unit tests, besides removing the files, what other settings do I need to remove or change to clean things up?

A: From your described context, my best guess is you want a clean project to experiment on swift. I suggest you choose OSX -> Application -> Command Line Tool template. You'll have a clean project with only one main.swift.


text:
Q: Connecting two motors Basically i'm doing a small project where i'm using 2 dc motors on a bicycle as generators connected to a usb module to charge smart phones, is it possible to connect the motors together to generate the required voltage at a lower rpm.

A: It is possible to increase voltage by placing them in series.
The output generated can be seen as batteries. When batteries are placed in series the voltage stacks. When placed parallel the voltage stays the same but you can get a higher current from it.
Now if you want to charge a phone by USB you will need a steady 5 volt power. the easiest would be to use a simple 5V ldo so that you wont blow up the phone with a voltage that is too high.
Because some phones have a protection circuit to stop charging when an unstable charger is used, you will need Extra buffers.
An other option would be to use a booster circuit. this will boost the voltage to the required voltage. but you would still need the buffers. There are converters that can work with an input voltage of 1.8-15V and convert any of these to 5V. The output current is dependent on the input voltage/current

A: You can connect two motors but it's probably better to use a boost regulator on one motor like this one: -

Here is the site for it. This device operates from an input voltage as low as 0.8 volts and is rated for a maximum nominal input voltage of 5V so, if your motors-turned generators produce more than 5V you'd be looking for a different solution such as one that involves a low-drop-out buck regulator interfacing between generator and booster. Here is a possible option to consider - it works from a voltage as high as 42 volts to produce 5V.
Or go all out for the boost/buck device here - it works from 2.7 volts to over 11 volts - maybe this is enough. Plenty of choices really.
Is this better than using two motors - I think so but beware of reversing the generator - it will produce negative voltages and damage stuff.


text:
Q: I want to use Elasticserach and kibana alerts to detect line passing We would like to implement a system that draws a line on a map displayed by kibana in advance and detects when a moving object (such as a boat) passes through the line.
I believe a possible way to do this is to set up rules using Elasticsearch query from kibana's rule creation.
But I don't know how to realize it.
I drew a line by selecting create index in add layer from maps in kibana.
A json file containing location, speed, and time information was imported into elasticserch and displayed on a map.


text:
Q: Proximity range for Beacons changes back and forth even when the App is in the same place Beacon Proximity range changes the proximity response as Near - Immediate - Far, even while the ios Device remains in the same place.
As I open a view when the proximity response is Near. I get the proximity response back and forth, Near - immediate then Near. It shows up the view again and again
How can we solve this issue. Is there any event handler.
Thanks.

A: The proximity and accuracy values appear to be quite 'noisy'.  It can also depend on your environment.  Water (and therefore people) absorbs the frequencies used by Bluetooth so people moving can have an impact, but I observe variation in between 1.2m and 1.9m when both devices are sitting on my desk.
I think you are going to have to deal with the noise in your app.  Once a view has opened you should keep it open until the beacon is 'far' (or you get a region exit) for some period of time.  If the state transitions back to near or immediate then reset the timer.
You need to use some code similar to the following -
-(void)locationManager:(CLLocationManager *)manager
    didRangeBeacons:(NSArray *)beacons
           inRegion:(CLBeaconRegion *)region {

    CLBeacon *beacon=beacons[0];

    switch (beacon.proximity) {

    case CLProximityFar:
        if (self.farTimer==nil) {
            self.farTimer=[NSTimer scheduledTimerWithTimeInterval:30 target:self selector:@selector(farTimerFired:) userInfo:beacon repeats:NO];
        }
    break;

    case CLProximityNear:
    case CLProximityImmediate:
        if (self.farTimer!=nil) {
            [self.farTimer invalidate];
            self.farTimer=nil;
        }
    break;

    case CLProximityUnknown:
         NSLog(@"Beacon proximity is unknown");
    break;
   }
}

-(void) farTimerFired:(NSTimer *)timer {
 CLBeacon *beacon=(CLBeacon *)timer.userInfo;
 NSLog(@"Beacon %@ is really far",beacon.proximityUUID.UUIDString);
 self.farTimer=nil;
}

A: Understand that the proximity value is just an estimate based on radio signal strength, so this is expected behavior due to noise as @Paulw11 says in his answer.
Two things you can do to make the proximity (and accuracy) readings as solid as possible:

*

*Choose an iBeacon with as fast of a transmission rate as possible.  Different ibeacons transmit advertisements at different frequencies from 30 times per second to once per second or less.  Generally, faster transmission rates give you less noisy distance estimates because they give iOS more radio signal strength measurements to work with.  For your testing, Try an iOS-based iBeacon like Locate for iBeacon to see if it helps.  It is known to transmit 30x per second.

*Make sure your iBeacon is properly calibrated.  This will not reduce the noise, but it will make sure the readings you get are correct as possible on average.  If not properly calibrated you may see jumps between immediate and near more often when the device is solidly in the immediate zone, because it is calculating the distance as too far away.
Beyond this, A software filter on the proximity value might help as @Paulw11 suggests, but it still won't be perfect.  You simply have to decide if you can live with the noise for your use case.


text:
Q: Jetpack Compose can't import Text or setContent anymore I've been messing around with Jetpack Compose recently and I had gone through the basic tutorial here. Then I started looking at the Jetnewssample project they have. Now I'm ready to start working on my own project but now  when I create a new project in the same parent directory as the Jetnewssample project, (which is working fine) Android Studio can no longer import androidx.ui.core.Text or androidx.ui.core.setContent. I can import other classes from the same location but now I just get an unresolved reference error. This is a new project set to start with an Empty Compose Activity. Here is the code:

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.Composable
import androidx.ui.core.Text
import androidx.ui.core.setContent
import androidx.ui.material.MaterialTheme
import androidx.ui.tooling.preview.Preview

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MaterialTheme {
                Greeting("Android")
            }
        }
    }
}

@Composable
fun Greeting(name: String) {
    Text(text = "Hello $name!")
}

@Preview
@Composable
fun DefaultPreview() {
    MaterialTheme {
        Greeting("Android")
    }
}

Here's the module's gradle build file:
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"

    defaultConfig {
        applicationId "com.franklin.sanctified"
        minSdkVersion 21
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility = 1.8
        targetCompatibility = 1.8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
    buildFeatures {
        compose true
    }

}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.1.0'
    implementation 'androidx.ui:ui-layout:0.1.0-dev03'
    implementation 'androidx.ui:ui-material:0.1.0-dev03'
    implementation 'androidx.ui:ui-tooling:0.1.0-dev03'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}

A: Update on :May-2021
Add below dependencies in app level Gradle or kts file for set content{ .. }
implementation("androidx.activity:activity-compose:1.3.0-alpha07")

A: Those seem to be in ui-framework for dev03. Try adding that dependency to your lineup:
implementation "androidx.ui:ui-framework:0.1.0-dev03"

A: In my case the problem was that I was missing activities integration for compose. setContent is an extension function on ComponentActivity class, defined in package androidx.activity.compose
Just import:
implementation 'androidx.activity:activity-compose:1.4.0'


text:
Q: shadows are showing in unity editor but not on android device I am doing a game in unity game engine .
I started developing the game in 4.6 but later on unity 5 get released so i upgraded my project to unity 5 version now my game running on android devices but i have one problem with shadows of game-objects which are showed in unity editor but not on the device.I am not able sort out this problem. I am also using NGUI for game user interface.

A: just changed the quality settings to fastest
you can find that option in edit->project settings->quality->then in right side you will see levels for different platforms set it to fastest
this worked for me

A: Check your quality settings (Edit/Project Settings/Quality) and make sure the default quality level for Android has shadows enabled.

A: I had this problem too, and then discovered that it was a limitation of the device I was using.  On a slightly older Asus Nexus 7 tablet, shadows wouldn't appear, no matter what I did in the Quality Settings.  I switched to a Lenovo Yoga 2 tablet and everything worked fine.


text:
Q: How do I conditionally include arguments in a finder where clause? I'm using Rails 5 with PostGres 9.5.  How do I conditionally include arguments in a finder where clause?  I have the below
  def self.find_by_name_and_hometown_and_age(user)
    search_criteria = ["my_objects.user_id is null"]
    # Name criteria
    search_criteria.push("upper(my_object_times.name) = ?")

    # Hometown criteria
    search_criteria.push( "upper(my_object_times.city) = ?" )
    if user.address.state_id
      search_criteria.push( "my_object_times.state_id = ?" )
    end
    if user.address.country_id
      search_criteria.push( "my_object_times.country_id = ?" )
    end

    # Age
    search_criteria.push( "date ? + interval '1 year' * my_object_times.age between my_objects.day - interval '1 year' and my_objects.day + interval '1 year'" )

    results = MyObjectTime.joins(:my_object,
                              "LEFT JOIN user_my_object_time_matches on my_object_times.id = user_my_object_time_matches.my_object_time_id").where( search_criteria.join(' and '),
                                                                                "#{user.first_name.upcase} #{user.last_name.upcase}",
                                                                                "#{user.address.city}",
                                                                                "#{user.address.state_id}",
                                                                                "#{user.address.country_id}",
                                                                                user.dob )
  end

Note that if there is no "user.address.state_id" field or "user.address.country_id" field, I don't include the criteria in the search, but I'm unclear about how to tell the where clause to ignore those arguments.  I would prefer to only have a single where clause.

A: where clauses are chainable so you just need simple if statements
all_items = MyObjectTime.all

if some_condition
  all_items = all_items.where(...)
end

if some_other_condition
  all_items = all_items.where(...)
end

And in the end all_items will include what you want.


text:
Q: Initialize an associative array in PHP 7.* compared to PHP 5.* Maybe it's just a different PHP.INI setting (this is happening on a shared hosting after an automatic update) but the essential two lines of code:
$k = array();
// some code ...
$k["assoc"]++;

If you ask why I am doing it, it's just the fastest way I know to count which and how many "elements" I have when I can only read them one at a time from "somewhere".
No problem with PHP 5, but PHP 7 is telling me this:
Notice: Undefined index: assoc in *******
I do not know in advance what associative indexes I can have, so I cannot set them at zero beforehand.
So the question is: what is the proper way to initialize an associative array in PHP7, and maybe since I am asking, is there a way to force all the elements to be e.g. integers and be set at zero by default?


text:
Q: AWS Cognito Authentication via Facebook succeeds but getCurrentUser returns null In the browser, after Facebook Login, statusChangeCallback is called. Everything succeeds. Cognito even returns an Identity Id. However, userPool.getCurrentUser() returns null.  Cognito does not think there is an authenticated user.  How can I fix that?  Thanks.
function statusChangeCallback(response) {
    if(response.status == 'connected' && response.authResponse) {
        testAPI()

        console.log("FB statusChangeCallback", JSON.stringify(response))

        AWSCognito.config.credentials = new AWSCognito.CognitoIdentityCredentials({
            IdentityPoolId : '<%=process.env.AWS_USERPOOLGUID%>', // your identity pool id here
            Logins : {
                'graph.facebook.com': response.authResponse.accessToken
            }
        });
        console.log(JSON.stringify(AWSCognito.config.credentials))

        AWSCognito.config.region = '<%= process.env.AWS_REGION%>'

        AWSCognito.config.credentials.refresh(function(error) {
            if (error) {
                console.error("AWSCognito.config.credentials.get", error);
            } else {
                console.log("Cognito Identity Id", AWSCognito.config.credentials.identityId);
                console.log('Successfully logged!');
                var cognitoUser = userPool.getCurrentUser();
                console.log('cognitoUser', cognitoUser);

            }
        });
    }
}

A: userPool.getCurrentUser();

refers to the authenticated user with regards to the particular user pool. What you are doing, in the above code is obtaining AWS credentials using a Facebook identity. However, the current user refers to the last authenticated user of the user pool. That is saved in local storage after a successful authentication. So you would need to authenticate first, similar to the code below.
var authenticationData = {
    Username : 'username',
    Password : 'password',
};
var authenticationDetails = new AWSCognito.CognitoIdentityServiceProvider.AuthenticationDetails(authenticationData);
var poolData = {
    UserPoolId : '...', // Your user pool id here
    ClientId : '...' // Your client id here
};
var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(poolData);
var userData = {
    Username : 'username',
    Pool : userPool
};
var cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData);
cognitoUser.authenticateUser(authenticationDetails, {
    onSuccess: function (result) {
        console.log('access token + ' + result.getAccessToken().getJwtToken());

        AWS.config.credentials = new AWS.CognitoIdentityCredentials({
            IdentityPoolId : '...', // your identity pool id here
            Logins : {
                // Change the key below according to the specific region your user pool is in.
                'cognito-idp.<region>.amazonaws.com/<YOUR_USER_POOL_ID>' : result.getIdToken().getJwtToken()
            }
        });

        // Instantiate aws sdk service objects now that the credentials have been updated.
        // example: var s3 = new AWS.S3();

    },

    onFailure: function(err) {
        alert(err);
    },

});

A: Looks like you need to change your AWSCognito.config.credentials
From what you have to this:
// Add the Facebook access token to the Cognito credentials login map.
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
  IdentityPoolId: 'IDENTITY_POOL_ID',
  Logins: {
    'graph.facebook.com': response.authResponse.accessToken
  }
});

// Obtain AWS credentials
AWS.config.credentials.get(function(){
    // Access AWS resources here.
});

NOTICE : IdentityPoolId: 'IDENTITY_POOL_ID', and not IdentityPoolId : '<%=process.env.AWS_USERPOOLGUID%>', // your identity pool id here
Looks like you are trying to access your USER POOL and not your IDENTITY POOL.
Facebook users live in the Identity Pool because they are a federated user from the Facebook server.


text:
Q: jQuery manipulate DOM on click I want to change hidden inputs value to true or false when link is clicked.
Advanced search

advanced_search = $('.advanced-search-block .hidden-block')
advanced_search_field = $('#payment_search_advanced_search')

$('.open-advanced-search').on 'click', ->
  if '#help needed here'
    $(advanced_search).show()
    $(advanced_search_field).attr('value', 'true')
  else
    $(advanced_search).hide()
    $(advanced_search_field).attr('value', 'false')
  return
return

I know that there's a method toggle but that's enough for me, as i also want to update html element.

A: You don't need an if ... else, you can do both show/hide and true/false switches in one block, like this:
$(advanced_search).toggle()
$(advanced_search_field).attr('value', $(advanced_search).is(':visible'))

The first line toggles visibility on and off. The second line will then read out whether it is now visible, if so, the result is true else false.


text:
Q: COPY failed: stat /var/lib/docker/tmp/docker-builder/server/requirements.txt: no such file or directory Appears to be some kind of context issue. I'm trying to figure out why this would work fine when spinning up a local Kubernetes cluser with Skaffold, but is failing to build the image properly when pushing to Azure.
Basic structure is:
test-app/
  server/
    requirements.txt
    Dockerfile
azure-pipeline.yml
skaffold.yaml

I have the production server/Dockerfile as the following:
FROM python:3.7-slim
ENV PYTHONUNBUFFERED 1
WORKDIR '/app'
EXPOSE 5000
COPY ./server/requirements.txt .
RUN pip install -r requirements.txt
COPY ./server .
CMD ["python", "manage.py", "collectstatic"]
CMD ["gunicorn", "-b", ":5000", "--log-level", "info", "config.wsgi:application"]

I'm using the azure-pipelines.yml that was generated for me in the Pipelines section of Azure DevOps:
# Docker
# Build and push an image to Azure Container Registry
# https://learn.microsoft.com/azure/devops/pipelines/languages/docker

trigger:
- master

resources:
- repo: self

variables:
  # Container registry service connection established during pipeline creation
  dockerRegistryServiceConnection: '<connection-string>'
  imageRepository: 'testapp'
  containerRegistry: 'testappcontainers.azurecr.io'
  dockerfilePath: '$(Build.SourcesDirectory)/server/Dockerfile'
  tag: '$(Build.BuildId)'

  # Agent VM image name
  vmImageName: 'ubuntu-latest'

stages:
- stage: Build
  displayName: Build and push stage
  jobs:
  - job: Build
    displayName: Build
    pool:
      vmImage: $(vmImageName)
    steps:
    - task: Docker@2
      displayName: Build and push an image to container registry
      inputs:
        command: buildAndPush
        repository: $(imageRepository)
        dockerfile: $(dockerfilePath)
        containerRegistry: $(dockerRegistryServiceConnection)
        tags: |
          $(tag)

During the automated build it gets to COPY ./server/requirements.txt . and the throws the error in the title.
Reading this question, I've tried a number of the suggested solutions with no resolution, like:
COPY ./server/requirements.txt /app
COPY server/requirements.txt /app

In addition, I've also just tried:
COPY requirements.txt /app

Still get the error.
So, kind of stumped on:

*

*How to resolve this so it builds correctly in Pipelines and pushes to CRS...

*If it is a context issue, why isn't an issue in local dev when using Skaffold

Actually, the example project has a similar project structure:
pipelines-javascript-docker/
  app/
    Dockerfile

And it runs fine... some I'm probably overlooking something apparently.

A: When I encountered this obstacle I resolved by setting up the property buildContext in the yml file.
- task: Docker@2
  displayName: Build and push an image to container registry
  inputs:
    containerRegistry: '$(ACR.Connector)'
    repository: '$(imageName)'
    command: 'buildAndPush'
    Dockerfile: '$(Agent.BuildDirectory)/s/server/Dockerfile'
    buildContext: '$(Agent.BuildDirectory)/s'
    tags: '$(tag)'

A: After looking at the example project more closely, which has the same structure as what I'm trying to do, I ended up copying its Dockerfile formatting. I ended up with this which is working fine:
FROM python:3.7-slim
ENV PYTHONUNBUFFERED 1
WORKDIR /app
EXPOSE 5000
COPY requirements*.txt ./
RUN pip install -r requirements.txt
COPY . .
CMD ["python", "manage.py", "collectstatic"]
CMD ["gunicorn", "-b", ":5000", "--log-level", "info", "config.wsgi:application"]


text:
Q: Bootstrap templates auto-generated? I'm having trouble setting up Flask-bootstrap. From the official documentation, it seems like all I have to do is apply the Bootstrap constructor to my app, and the templates will be automatically created. So I tried this:
from flask import Flask
from flask.ext.bootstrap import Bootstrap

app = Flask(__name__)
Bootstrap(app)

@app.route('/')
def index():
    return '
Where is Bootstrap?
'

if __name__ == '__main__':
    app.run(debug=True)

When I run it, no new directories are created and I find no base templates anywhere. Am I missing a critical step? Is there some directory to be created first (I tried creating templates and static and setting the permissions to 777 but that didn't help)? Or perhaps the base templates are first to be generated from the command line?

A: The base templates are part of the Flask-Bootstrap package you installed.  You extend the boostrap base template and override the blocks in it to create a page with a standard layout.  You still need to write bootstrap related markup.  This is explained right in the docs you linked to.
my_project/templates/my_page.html:
{% extends "bootstrap/base.html" %}
{% block title %}This is an example page{% endblock %}

{% block navbar %}

{% endblock %}

{% block content %}

Hello, Bootstrap

{% endblock %}


text:
Q: How to find non duplicate set of integer from an array that equals to the target? This is an interview question.
Given an array of integers and an integer target, find all
combinations which sum up to target. Don't output duplicates. e.g.,
[2,3,4], target is 5. then output should be [2,3], or [3,2], but not
both.

A: If I understand correctly, this is the subset sum problem.
Quoting from wikipedia's subset sum problem:

An equivalent problem is this: given a set of integers and an integer
  s, does any non-empty subset sum to s?

A: In python
>>> L=[2,3,4]
>>> from itertools import combinations
>>> for i in range(len(L)):
...     for j in combinations(L,i):
...         if sum(j) == 5:
...             print j
...
(2, 3)

A: It looks like knapsack problem which is np-complete hence probably there doesn't exist an effective algorithm for solve this problem.


text:
Q: PHP PDO Calling public method in different class from other class i'm trying to figure it out, how i can use public method in a class from another class. i'm getting this error
Fatal error: Uncaught Error: Using $this when not in object context

I have main class user which contains insert method, basically this method inserts values into database.
<?php
  class User{
    protected $pdo;
    public function __construct($pdo){
      $this->pdo = $pdo;
    }

    public function insert($table, $fields){
      //here we insert the values into database
    }
  }
?>

here is my config.php file to instantiate the classes so i can use them
<?php
    session_start();
    include 'database/connection.php';
    include 'classes/user.php';
    include 'classes/follow.php';
    include 'classes/message.php';
    global $pdo;

    $userObj     = new User($pdo);
    $followObj   = new Follow($pdo);
    $messageObj  = new Message($pdo);
?>

And i have other classes message, and follow. in follow class i can access all methods from user class, and in message class i'm trying to use insert method which in user class
<?php
    class Message extends User{
        public function __construct($pdo){
            $this->pdo  = $pdo;
        }

        public static function sendNotification($user_id, $followerID, $type){
            //calling this method from user class
            $this->insert('notifications', array('By' => $user_id, 'To' => $followerID, 'type' => $type));
        }
    }
?>

In follow class i'm trying to use sendNotification method, remember this method is in message class, and it use method from user class
 <?php
    class Follow extends User{
        public function __construct($pdo){
            $this->pdo  = $pdo;
        }

        public function follow($user_id, $followerID){
            //here will be query to insert follow in database

            //now i need to sendNotification method from user
            Message::sendNotification($user_id, $followerID, 'follow');

        }
    }
?>

Getting Fatal error
Fatal error: Uncaught Error: Using $this when not in object context

What should i do?

A: Make sendNotification a non static function. Remove the static keyword
Use static methods when the method doesn't depend on the class been instantiated. Hence the reason why $this can't be used
In the follow function, do this instead
$message = new Message($this->pdo);//pass database connection
$message->sendNotification();//pass the variables

A: You are trying to access $this from a static method in this method:
public static function sendNotification($user_id, $followerID, $type){
            //calling this method from user class
            $this->insert('notifications', array('By' => $user_id, 'To' => $followerID, 'type' => $type));

You can make sendNotification non-static and create an instance of Message so you would be able to access public members of User


text:
Q: How can we show that a counting measure is purely atomic? Let $(\Omega,\mathcal A)$, $(E,\mathcal E)$ be measurable spaces, $I$ be a nonempty countable set, $(X_i)_{i\in I}$ be an $(E,\mathcal E)$-valued process on $(\Omega,\mathcal A)$ and $$\kappa_\omega(B):=\sum_{i\in I}\delta_{X_i(\omega)}(B)\;\;\;\text{for }(\omega,B)\in\Omega\times\mathcal E.$$ Assume $\{x\}\in\mathcal E$ for all $x\in E$. Fix $\omega\in\Omega$. Note that $$\kappa_\omega\{X_i(\omega)\}=\left|\left\{j\in I:X_i(\omega)=X_j(\omega)\right\}\right|\ge1>0\tag1$$ and hence $X_i(\omega)$ is an atom of $\kappa_\omega$ for all $i\in I$.

How can we show that $\kappa_\omega$ is purely atomic$^1$?

Can we maybe even show that $D_\omega=\{X_i(\omega):i\in I\}$?

$^1$ i.e. $$D_\omega:=\left\{x\in E:x\text{ is an atom of }\kappa_\omega\right\}$$ is countable and $$\kappa_\omega(D_\omega^c)=0.$$

A: You seem to be on the right path with your intuition. Indeed, all atoms for the measure $\kappa_\omega$ are on the form $X_i(\omega)$ for some $i\in I$. To show that $\kappa_\omega$ is purely atomic you must verify the implication:
$$
B\in\mathcal{E},\kappa_\omega(B)>0\Rightarrow B\text{ contains an atom.}
$$
You have already shown that $X_i(\omega)$ is an atom for any $i\in I$ so it seems reasonable to look for an $i_0\in I$ such that $X_{i_0}(\omega)\in B$. Try to write down $\kappa_\omega(B)$ and see if you can deduce the existence of such an index $i_0$.
With the above approach in mind you should be all set to also prove that $D_\omega=\{X_i(\omega):i\in I\}$.


text:
Q: error with jquery regular expression validation I'm new to programming. I'm trying to validate a form. I did it with php (I'm using Codeigniter) and had no problem with it, works fine.
When it comes to jquery I'm having trouble. For example, for username, it should appear an ok icon if the input validates. For that I've this:
var FormValidation = function () {

var handleValidation2 = function() {
    // for more info visit the official plugin documentation:
    // http://docs.jquery.com/Plugins/Validation

        var form2 = $('#form-val');
        var error2 = $('.alert-error', form2);
        var success2 = $('.alert-success', form2);

        //IMPORTANT: update CKEDITOR textarea with actual content before submit
        form2.on('submit', function() {
            for(var instanceName in CKEDITOR.instances) {
                CKEDITOR.instances[instanceName].updateElement();
            }
        })

        form2.validate({
            errorElement: 'span', //default input error message container
            errorClass: 'help-inline', // default input error message class
            focusInvalid: false, // do not focus the last invalid input
            ignore: "",
            rules: {

                username: {
                    minlength: 2,
                    maxlength: 15,
                    regex: "^[a-zA-Z0-9]*[a-zA-Z]+[a-zA-Z0-9]*$",
                    required: true
                },

                name: {
                    minlength: 2,
                    maxlength: 50,
                    // regex: ,
                    required: true
                },

                lastname: {
                    minlength: 2,
                    maxlength: 50,
                    required: true
                },

                gender: {
                    required: true
                },

                date_born: {
                    required: true
                },

                email: {
                    required: true,
                    email: true
                },

                status: {
                    required: true
                },

                member_id: {
                    minlength: 5,
                },

                documentType_id: {
                    required: true
                },

                documentn: {
                    required: true,
                    minlength: 2
                },
                address_street: {
                    required: true
                },

                address_number: {
                    required: true
                },

                address_floor: {
                    required: false
                },

                zipcode: {
                    required: true
                },

                city: {
                    required: true
                },

                state: {
                    required: true
                },

                country_id: {
                    required: true
                },

                phone: {
                    required: true
                },

                cellphoneNumber: {
                    required: true
                },

                cellCompany: {
                    required: true
                },

                cellbrand: {
                    required: true
                },

                marital_status: {
                    required: true
                },

                sons: {
                    required: true
                },
            },

            messages: { // custom messages for radio buttons and checkboxes
                username: {
                    required: "Este campo es requerido",
                    minlength: "El nombre de usuario debe tener como mínimo 2 caracteres",
                    maxlength: "El nombre de usuario debe tener como máximo 15 caracteres",
                },

                membership: {
                    required: "Please select a Membership type"
                },
                service: {
                    required: "Please select  at least 2 types of Service",
                    minlength: jQuery.format("Please select  at least {0} types of Service")
                }
            },

            errorPlacement: function (error, element) { // render error placement for each input type
                if (element.attr("name") == "education") { // for chosen elements, need to insert the error after the chosen container
                    error.insertAfter("#form_2_education_chzn");
                } else if (element.attr("name") == "membership") { // for uniform radio buttons, insert the after the given container
                    error.addClass("no-left-padding").insertAfter("#form_2_membership_error");
                } else if (element.attr("name") == "editor1" || element.attr("name") == "editor2") { // for wysiwyg editors
                    error.insertAfter($(element.attr('data-error-container')));
                } else if (element.attr("name") == "service") { // for uniform checkboxes, insert the after the given container
                    error.addClass("no-left-padding").insertAfter("#form_2_service_error");
                } else {
                    error.insertAfter(element); // for other inputs, just perform default behavior
                }
            },

            invalidHandler: function (event, validator) { //display error alert on form submit
                success2.hide();
                error2.show();
                App.scrollTo(error2, -200);
            },

            highlight: function (element) { // hightlight error inputs
                $(element)
                    .closest('.help-inline').removeClass('ok'); // display OK icon
                $(element)
                    .closest('.control-group').removeClass('success').addClass('error'); // set error class to the control group
            },

            unhighlight: function (element) { // revert the change done by hightlight
                $(element)
                    .closest('.control-group').removeClass('error'); // set error class to the control group
            },

            success: function (label) {
                if (label.attr("for") == "service" || label.attr("for") == "membership") { // for checkboxes and radio buttons, no need to show OK icon
                    label
                        .closest('.control-group').removeClass('error').addClass('success');
                    label.remove(); // remove error label here
                } else { // display success icon for other inputs
                    label
                        .addClass('valid').addClass('help-inline ok') // mark the current input as valid and display OK icon
                    .closest('.control-group').removeClass('error').addClass('success'); // set success class to the control group
                }
            },

            submitHandler: function (form) {
                success2.show();
                error2.hide();
            }

        });

        $('#form-val').select2({
            placeholder: "Select an Option",
            allowClear: true
        });

        //apply validation on chosen dropdown value change, this only needed for chosen dropdown integration.
        $('.chosen, .chosen-with-diselect', form2).change(function () {
            form2.validate().element($(this)); //revalidate the chosen dropdown value and show error or success message for the input
        });

         //apply validation on select2 dropdown value change, this only needed for chosen dropdown integration.
        $('.select2', form2).change(function () {
            form2.validate().element($(this)); //revalidate the chosen dropdown value and show error or success message for the input
        });
}

return {
    main function to initiate the module
    init: function () {
        handleValidation2();
    }
};
}();

That is full code, not yet finished making changes. The thing is that erros appears if input is less than 2 characters or bigger than 15, but when it's a correct input, icon ok doesn't appear and have the following error when inspecting it:
Uncaught TypeError: Cannot call method 'call' of undefined
If i erase the rule "regex" icon ok appears. But as you can see in the snippet, with that field it doesn't work fine.
What can the problem be? thnx in advance.

A: If you want to match a regular expression without writing a custom method (as in Hayzeus's) answer, load the jquery-validate additional methods:
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/additional-methods.min.js"></script>

Then you can use the pattern validation method:
            username: {
                minlength: 2,
                maxlength: 15,
                pattern: "[a-zA-Z0-9]*[a-zA-Z]+[a-zA-Z0-9]*",
                required: true
            },

The method automatically wraps the pattern with ^ and $, so you don't need them in your regexp.

A: You can't simply provide a regex string in your rules. You need to add a custom method to the validator.
Something like this:
$.validator.addMethod("regex", function(value, element) {
    var regex = /^[a-zA-Z0-9]*[a-zA-Z]+[a-zA-Z0-9]*$/
    return regex.test(value);
}, "Invalid Name");

Then in your rule:
username: {
    minlength: 2,
    maxlength: 15,
    regex: true,
    required: true
}


text:
Q: SQL - coalesce not working as expected (or as hoped!) I'm attempting to use a coalesce, but obviously am misunderstanding something. In the code below, the code after the first from (including the paren) - up to '= en.personID) st)' gives a listing of distinct stateIDs as expected. But when I run the entire code I get an error: Incorect syntax near the keyword 'where'. Can anyone see what I am doing wrong? Can you use a select/subquery in a coalesce?  Thank you!
select c.endYear
,coalesce(s.stateID, select st.stateID
                    from (select distinct st.stateID
                            from (select st.stateID
                                      ,st.personID
                                  from student st
                                  left join enrollment en on       st.personID = en.personID) st)
                    where s.personID =   st.personID)
, s.lastname
, s.firstname . . . .

A: Subqueries need to be surrounded by parentheses.  There might be other issues as well.  This version should parse:
select . . .
       coalesce(s.stateID,
                (select distinct st.stateID
                 from student st left join
                      enrollment en
                      on st.personID = en.personID
                  where s.personID = st.personID
                )),

This might still generate a run-time error, if the subquery returns more than one row.  Then you have to choose which state.  A general way is to use an aggregation function:
select . . .
       coalesce(s.stateID,
                (select max(st.stateID)
                 from student st left join
                      enrollment en
                      on st.personID = en.personID
                  where s.personID = st.personID
                )),

Alternatively, you can pull one row, using fetch first 1 row only, top, limit, or something similar.


text:
Q: How to formally describe this experimental design? Apologies if this is a little off-topic for a stats forum, but I don't know where else I could pose my question online and I'm positive that many contributors here would be able to easily answer my question.
Basically, I conducted an experiment but now I'm unsure of how to formally describe the experimental design I employed. I'll try to describe in fairly lay terms how the experiment was structured, and hopefully one of you knowledgeable sirs/madams will be able to set me on the right track!
So I conducted an online survey experiment. I'll outline the conditions and participant allocation procedures below:
Participants were initially randomly allocated to one of 4 conditions: a hierarchy-egalitarianism control condition, an individualism-communitarinaism control condition, a hierarchy-egalitarianism experimental condition and an individualism-communitarianism experimental condition.
In both the control and experimental hierarchy-egalitarianism conditions, participants completed a scale designed to measure their cultural values along this dimension. In the control and experimental individualism-communitarianism conditions, they completed a different scale designed to measure their cultural values along this dimension.
In both experimental conditions, scores on these scales were then calculated by the survey software in real time, immediately afterwhich participants were administered a particular experimental manipulation determined by whether they scored above or below the mid-point on the scale they completed.
So for instance, a participant in the experimental hierarchy-egalitarianism condition who scored above the mid-point on the hierarchy-egalitarianism scale was designated as a hierarchist, and exposed to a distinct experimental manipulation designed to make them even more hierarchical in outlook. In contrast, a participant scoring below the midpoint on the hierarchy-egalitarianism scale in this condition was designated an egalitarian, and as a result received a distinct manipulation designed to increase their egalitarianism yet further. The equivalent was true in the experimental individualism-communitarianism condition. Therefore, there were two experimental conditions to which participants were randomly assigned, each of which was then itself split into two conditions on the basis of participants cultural/ ideological outlook on the relevant dimension. This yielded four experiment conditions in total:

*

*experimental hierarchy

*experimental egalitarianism

*experimental individualism

*experimental communitarianism

No experimental manipulation was administered in the control conditions (obviously). However, there were two versions of the control condition, one in which participants completed the hierarchy-egalitarianism scale before seeing a control text, and one in which they completed the individualism-communitarianism scale. Allocation to control condition was completely random at this stage. Thus, in term of participant experience, control conditions were:

*

*Control hierarchy-egalitarianism

*Control individualism-communitarianism

However, for analytic purposes, participants in each control condition were further split into two "sub-conditions" to generate a control pairing for each experimental condition. Thus, according to the same criteria (i.e. scores above or below the midpoint on the relevant scale) which determined how participants were split in the experimental conditions, the control hierarchy-egalitarianism  was split into control hierarchy and control egalitarianism, and control individualism-communitarianism was split into control individualism and control hierarchy. Thus, from an analytic perspective, there were 8 conditions in total. control conditions were:

*

*control hierarchy

*control egalitarianism

*control individualism

*control communitarianism

*experimental hierarchy

*experimental egalitarianism

*experimental individualism

*experimental communitarianism

This left me with control and experimental condition pairs with which to perform between-subjects comparisons e.g. control hierarchy and experimental hierarchy.
Obviously, allocation to condition was part random and part based on participant characteristics.
So my question is, does anyone know how to describe this experimental design formally?
I'm thinking I have two IVs, one being the scale which participants completed and one being weather they received the control or experimental treatment.
Perhaps some hybrid between an experimental and quasi-experimental design?
I'm really not clear on the design, and I'm confusing myself reading about factorial nested designs, which may or may not be relevant!
I'm also not sure whether sample splitting for analytic purposes should be considered part of the design or not.
Any advice anyone might be able to give would be greatly, greatly appreciated!