text:
Q: How to allow two taps on a custom UIView to show and hide a popover? I have three custom UIViews which are small circles and are placed at different locations on the screen. If you click any circle, it shows a popover. There are 2 scenarios:
1. If I click a circle it shows a popover, if I click it again it hides the popover as well as the circle.
2. If I click a circle it will show a popover, but if I don't click it back again and instead click another circle, it should show me the popover of the second circle and should hide the first popover and circle.
In short at a time there should be only one popover visible. I managed to get implement the first scenario but struggling with the second. Here's the code:
   func showPopover(sender:UITapGestureRecognizer){
    if sender.view == hotSpotOne{

        let description = "Search \n" + "Search equities to view the order book and market prints for specific moments in time."
        let heading = "Search"
        let wordRange = (description as NSString).rangeOfString(heading)
        let attributedString = NSMutableAttributedString(string: description, attributes: [NSFontAttributeName: UIFont.systemFontOfSize(12)])
        attributedString.setAttributes([NSFontAttributeName: UIFont.boldSystemFontOfSize(12)], range: wordRange)
        self.helpTip!.showAttributedText(attributedString, direction: .Down, maxWidth: 200, inView: self.view, fromFrame: self.hotSpotOne.frame)

        if self.helpTip!.isVisible {
            self.helpTip!.hide()
            hotSpotOne.removeFromSuperview()
            return
        }
    }
    else if sender.view == hotSpotTwo{

        let description = "Market Events \n" + "Swipe to view recent market anomalies selected by Surveyor's analytics team."
        let heading = "Market Events"
        let wordRange = (description as NSString).rangeOfString(heading)
        let attributedString = NSMutableAttributedString(string: description, attributes: [NSFontAttributeName: UIFont.systemFontOfSize(12)])
        attributedString.setAttributes([NSFontAttributeName: UIFont.boldSystemFontOfSize(12)], range: wordRange)
        self.helpTip!.showAttributedText(attributedString, direction: .Down, maxWidth: 200, inView: self.view, fromFrame: self.hotSpotTwo.frame)

        if self.helpTip!.isVisible {
            self.helpTip!.hide()
            hotSpotTwo.removeFromSuperview()
            return
        }
    }
    else {

        let description = "Get More Data \n" + "Learn More about how Surveyor's professional products can benefit your financial institution."
        let heading = "Get More Data"
        let wordRange = (description as NSString).rangeOfString(heading)
        let attributedString = NSMutableAttributedString(string: description, attributes: [NSFontAttributeName: UIFont.systemFontOfSize(12)])
        attributedString.setAttributes([NSFontAttributeName: UIFont.boldSystemFontOfSize(12)], range: wordRange)
        self.helpTip!.showAttributedText(attributedString, direction: .Up, maxWidth: 200, inView: self.view, fromFrame: self.hotSpotThree.frame)

        if self.helpTip!.isVisible {
            self.helpTip!.hide()
            hotSpotThree.removeFromSuperview()
            return
        }

    }

}

I am using AMPopTip library to show the popovers. Any help is appreciated, thanks!


text:
Q: htaccess Rewrite Rule not working without index.php in url I am using apache2 in ubuntu m/c. I have enabled mod_rewrite and changed Allowoveride All in apache2.conf
Now I am trying to install Bug-Genie application in my server
But following .htaccess rules are not work as excepted.
I can access :
http://localhost/roxsoft/thebuggenie-3.2.6/thebuggenie/**index.php**/wiki

But I can't access :       --404 error
http://localhost/roxsoft/thebuggenie-3.2.6/thebuggenie/wiki

Here is my .htaccess file:
# .htaccess file for The Bug Genie

# make sure that magic_quotes and register_globals is always off
<IfModule mod_php5.c>
    php_flag magic_quotes_gpc   off
    php_flag register_globals   off
</IfModule>

# rewrite rules
<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
# Example:
# RewriteBase /
# or
# RewriteBase /dev/thebuggenie

  # skip all hidden files (starting with a .)
  RewriteCond %{REQUEST_URI} \..+$
  RewriteCond %{REQUEST_URI} !\.(html|wsdl|json|xml)$
  RewriteRule .* - [L]

  # redirect to front controller
  RewriteRule ^(.*)$ index.php?url=$1 [NC,QSA,L]

</IfModule>
# Stop people accessing directories they shouldn't have access to
RedirectMatch 403 ^/\.svn(/|$)

A: Try this:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond $1 !^(index\.php|assets|images|robots\.txt)
RewriteRule ^(.*)$ index.php/$1 [L]

Add the folder which contains the JavaScript and CSS to the rewrite condition

A: Here is the solution I just managed it with. This may help if anyone had a same problem...
I just removed
and added additional conditions in htaccess
here is it:
  RewriteCond %{REQUEST_URI} \..+$
  RewriteCond %{REQUEST_URI} !\.(html|wsdl|json|xml)$
  RewriteCond %{REQUEST_URI} !\.(jpg|png|css|js|php|gif|ttf|woff)$   ---- ADD FILTER CONDITION.
  #RewriteRule .* - [L]                                              ---- COMMENT THIS LINE************

  # redirect to front controller
  RewriteRule ^(.*)$ index.php?url=$1 [NC,QSA,L]

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is 'would stop its deployment' here? In a blog of the NYT, I can't understand the last part of this paragraph:

On Monday, the Chinese government-run English-language China Daily called THAAD a serious regional security threat, and said that "a sanctions package that is sufficient for Pyongyang to reevaluate its nuclear program," would stop its deployment.

Is it a continuation of the sentence written in an inverted comma? What is the exact meaning of the last phrase in this context?

A: The sentence in the quotes (not inverted commas as you've stated) is most likely a quote, and the bolded part of the sentence in this context would be referring to the deployment of the nuclear program referred to in the quote.


text:
Q: Trace output not getting logged in output file at times I'm using TextWriterTraceListener to log error messages to a text file.The TraceOutputFile has been mentioned in the web.config file as "trace.log.txt". The error messages are getting logged to the trace.log.txt. But at times I notice that some files are getting generated randomly under root folder with the exception details instead of logging to the trace.log.txt.
This is not happening in any particular page and hence I am unable to detect the reason as to why these files are getting generated.Ex:14dbc20a-9eb8-4fec-b6bd-54400db2ceatrace.log.txt .
Can u suggest me any circumstances when this might happen?

A: if you are familiar with ETW tracing, you could register EventProviderTraceListener instead of TextWriterTraceListener. You could details how to do that here.

A: I saw something similar when I had two threads trying to write to the log file at the same time whilst using the Enterprise Library logging classes.


text:
Q: Interaction term to deal with heteroscedasticity The variance in my dependent variable changes with a changing value in an important independent variable and is hence probably distorting the measured effect of the treatment. Can I combat this form of heteroscedasticity by introducing an interaction term?
I'm analyzing the influence of the scoring procedure in online challenges on the predictability of the challenges. I measure predictability as the absolute difference between the rank percentile of a participant in a challenge and the overall rating percentile of a participant at that time. If a challenge is predictable that means that highly rated participants also rank highly (i.e. low difference between these two values).
Each observation (n = 1425) in my dataset is the participation of an individual in a challenge. Hence, I have partially crossed data as not all participants contribute in all of the challenges. Further, the data is divided into strata of comparable challenges that only differ significantly in the treatment variable (i.e. scoring procedure). Therefore, I fit a mixed effects model with random effects for the individual and the strata as well as an interaction between the random effects.
Based on the answers in the following thread, I have used a linear model, a model with a log-transformed dv and a beta regression in comparison, all yielding similar results:
Regression with bounded non-normal dependent variable
I have observed that the variance of the dv changes with a change in the independent variable "rating" which I included as a control and which is a strong predictor of predictability. It seems that participants with a high rating are more consistent. See this plot:

Also, the precision model of the beta regression indicates that there is a lower variance in the dv with a rising value in rating.
So this is probably a cause of heteroscedasticity. To deal with this and to account for the fact that the effect of the treatment does not seem to be purely additive, but depending on the value of rating, I introduced an interaction term between rating and treatment. My question is: Is this a sensible approach or are there any arguments against introducing such an interaction term?

A: Note that in the case of the Beta model/distribution the mean and the variance are related. Hence, you expect to see a particular type of heteroscedasticity.
A better way to check the fit of the such a model to your data is to use the simulated residuals from the DHARMa package.


text:
Q: formatting DateTime as string in JSON using Gson I'm trying to format my DateTime attribute as a String using Gson. I now do this using
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssX").create();
but it doesn't work.
current output: "startTijd":{"date":{"year":2016,"month":10,"day":16},"time":{"hour":14,"minute":0,"second":0,"nano":0}}
required output (ISO 8061): 2016-10-16'T'14:0:0:0X


text:
Q: WHILE LOOP to prompt user to enter the correct number I am very new to Unix (BASH) and I need help with validating/checking user's number input to make sure they have entered:

*

*A number that starts with a 4, and

*The number is exactly three (3) digits in length

Currently, I am still trying to get #1 to work and I am already having trouble, any advice on how to proceed with this?
My Code:
echo "Please enter a three digit code that starts with '4':"
while read $input
do
    if $input = '^[4]*'; then
        echo "Your code started with 4"
    else
        echo "Invalid"
    fi
done


text:
Q: populating table or range to listbox in userform to get the values of the columns inside the table or range in closed workbook The problem is that the code is not working with me and gives "type mismatch error"
   Private Sub UserForm_Initialize()

   Dim cn As ADODB.Connection
   Dim rs As ADODB.Recordset

     Set cn = New ADODB.Connection

    cn.ConnectionString = _
                     "Provider=Microsoft.ACE.OLEDB.12.0;" & _
                     "Data Source=F:\Book1.xlsx;" & _
                     "Extended Properties='Excel 12.0 Xml;HDR=YES';"

    cn.Open
     Set rs = New ADODB.Recordset

    rs.ActiveConnection = cn

    rs.Source = "select [date] ,[factory] ,[records] from [sheet1$]"

    rs.Open
     With Me.ListBox1
     .ColumnCount = rs.RecordCount
     .List = Application.WorksheetFunction.Transpose(rs.GetRows)

     End With

    rs.Close
    cn.Close

A: (1) You get your type mismatch error because rs.RecordCount is of type LongLong which VBA cannot implicitly convert into a long. You could convert is explicitly with CLng(rs.RecordCount)
(2) When using Excel as data source, RecordCount will always be -1 as the Excel engine doesn't support RecordCount (see https://learn.microsoft.com/en-us/sql/ado/reference/ado-api/recordcount-property-ado?view=sql-server-ver16).
(3) You probably don't want to have RecordCount as number of columns for your listview anyhow - I assume you want to get the number of fields as column count:
With Me.ListBox1
    .Clear
    .ColumnCount = rs.Fields.Count
    .List = Application.WorksheetFunction.Transpose(rs.GetRows)
End With


text:
Q: Merge Comments on Data Explorer I'm trying to get StackOverflow posts along with comments. However it returns each post with the individual comments as a separate record. Something like this -

*

*ID Post Comment1

*ID Post Comment2

*ID Post Comment3

This leads to redundant records which quickly fill up the 50,000 records at a time that you're allowed to query. How do I combine all the comments into one single field ? Like this-

*

*ID Post Comment1 Comment2 Comment3

A: What you want to do is use the STRING_AGG() function to concatenate the comments together.
For example
Select posts.id, STRING_AGG(comments.text,' | ') from posts
join comments on postid =posts.id
where posts.id = 17406
group by posts.id

Run example
The second parameter of the  STRING_AGG() function is the separator between the comments.

A: You can create a pivot query. The first column will be the postid and then every next column will hold the comments. To make this work you'll need as much columns as the maximum number of comments under one post. This query
select max([commentcount]) [max comment count]
from posts

shows we need 157 columns to cover all those comments.
Here is the SEDE query that returns that result for you:
select postid, [1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21],[22],[23],[24],[25],[26],[27],[28],[29],[30],[31],[32],[33],[34],[35],[36],[37],[38],[39],[40],[41],[42],[43],[44],[45],[46],[47],[48],[49],[50],[51],[52],[53],[54],[55],[56],[57],[58],[59],[60],[61],[62],[63],[64],[65],[66],[67],[68],[69],[70],[71],[72],[73],[74],[75],[76],[77],[78],[79],[80],[81],[82],[83],[84],[85],[86],[87],[88],[89],[90],[91],[92],[93],[94],[95],[96],[97],[98],[99],[100],[101],[102],[103],[104],[105],[106],[107],[108],[109],[110],[111],[112],[113],[114],[115],[116],[117],[118],[119],[120],[121],[122],[123],[124],[125],[126],[127],[128],[129],[130],[131],[132],[133],[134],[135],[136],[137],[138],[139],[140],[141],[142],[143],[144],[145],[146],[147],[148],[149],[150],[151],[152],[153],[154],[155],[156],[157]
from
(
  select top 10000
         postid
       , row_number() over (partition by postid order by id) [num]
       , text
  from comments
) data
pivot
(
  min(text)
  for num in ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21],[22],[23],[24],[25],[26],[27],[28],[29],[30],[31],[32],[33],[34],[35],[36],[37],[38],[39],[40],[41],[42],[43],[44],[45],[46],[47],[48],[49],[50],[51],[52],[53],[54],[55],[56],[57],[58],[59],[60],[61],[62],[63],[64],[65],[66],[67],[68],[69],[70],[71],[72],[73],[74],[75],[76],[77],[78],[79],[80],[81],[82],[83],[84],[85],[86],[87],[88],[89],[90],[91],[92],[93],[94],[95],[96],[97],[98],[99],[100],[101],[102],[103],[104],[105],[106],[107],[108],[109],[110],[111],[112],[113],[114],[115],[116],[117],[118],[119],[120],[121],[122],[123],[124],[125],[126],[127],[128],[129],[130],[131],[132],[133],[134],[135],[136],[137],[138],[139],[140],[141],[142],[143],[144],[145],[146],[147],[148],[149],[150],[151],[152],[153],[154],[155],[156],[157])
) pvt
order by postid

This is an example of the output:

I think for performance reasons you best limit the inner query to decent number of rows. Trying to get all of them in one go is not going to fly anyway.


text:
Q: how can i add/ pass textbox value in url

    <title>Directives</title>

    <link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
    <link href="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.2.0/css/bootstrap-theme.css" rel="stylesheet">

      <input type="text" class="col-md-12" ng-model="search">
        <button ng-click="testGET()">Test GET</button>

          {{todo.prefLabel}}
          {{todo.definition}}

A: In the testGET method is where you would read the value of the search variable.
Initially you should just set it to an empty string.
$scope.search = ''; // not $scope.search = search

Then:
$scope.testGET = function () {
    var url = 'http://data.bioontology.org/search?q=' + $scope.search + '&ontologies=RADLEX&include_properties=false&include_views=false&includeObsolete=false&require_definition=false&exact_match=false&categories';
   // .. the http call.
};

Oh.. and in the success method by doing:
$scope.testGET = data.collection;

You're essentially overriding your method. That's probably not you meant.
Here's a plunkr with it:
http://plnkr.co/edit/wCEC5Z2eOpQ99ouVi5ts?p=preview


text:
Q: How to add missing value data in POWER BI / using SQL I have a table containing below data which might have missing information. But in that case , it should appear and shown as zero.I tried cross join but its performance is bad since it will create large number of records.

material location week value
123       p1      wk11  9
123       p1      wk13  13
456       p2      wk11  8
456       p2      wk12  7

desired o/p: (for material 123). in short, all possible combination of material and plant and week  will have value .

material location week value
123       p1      wk11  9
123       p1      wk12  0
123       p1      wk13  13
123       p2      wk11  0
123       p2      wk13  0
123       p2      wk12  0

A: This is an example of LEFT JOIN and COALESCE().
SELECT  123 AS material,
        y.location,
        z.week,
        COALESCE(y.value, 0) AS value
    FROM table_with_list_of_all_wks AS z
    LEFT JOIN your_table AS y  ON y.week = z.week
    WHERE y.location = 'p1'

This requires pre-building a table with all possible "wk" values.
y.value will be NULL when a row (week) is missing; COALESCE turns that into 0.


text:
Q: Strongly Typed ActionLink In Asp.Net MVC 2? I just downloaded VS.NET 2010 RC and created a new MVC project. It would seem that strongly typed ActionLinks are not in this release? Is this always going to be a "futures" thing? Or am I missing something?
<%=Html.ActionLink<HomeController>(x => x.Index(),"Home")%>

A: No there is no ActionLink<> see ScottGu blog ((
For performance reason.

re: ASP.NET MVC 2: Strongly Typed Html
  Helpers Tuesday, January 12, 2010 2:32
  AM by ScottGu
@Anthony,

but what about strongly typed ActionLinks?

We aren't adding built-in runtime
  helpers for this - but David Ebbo has
  created a nice VS tooling add-on that
  creates strongly-typed helpers you can
  use: aspnet.codeplex.com/wikipage
Hope this helps,
Scott

A: Strongly-typed ActionLink and route helpers are not scheduled to be moved from Futures to the main product any time soon.  In general it's not possible to run the MVC pipeline backward.  That is, given a MethodInfo and parameters, it's impossible to make a route which is guaranteed to hit that action.  For example, custom controller factories, action invokers, filters, existing files, or any number of other things can affect which action (if any) a particular route ends up hitting.
Because of this, the contract for strongly-typed ActionLink in Futures is essentially "given this information and assuming no extensibility hooks, guess which route will hit this action."  Such a contract is inappropriate for actual supported framework code.


text:
Q: unable to replace with jquery.extends with default values I'm playing around with apply, bind and call methods on objects. Below I'm unable to replace layout with the public data say if I didn't pass in from the object I'm calling.
var data = [{
      "option": "com_social",
      "userId": localStorage.getItem("ckuser"),
      "layout": "getSample",
      "view": "conversations",
      "format": "json",
      "limit": 1
    }];
var Data = 'default';
function ajaxCall(opt){
    var opt = jQuery.extend({}, data, opt);
    var layout = opt[0]['layout'];
    this.Data = layout;

}

/***global variable & functions end***/

var list = {
           data : [{
              "option": "com_social",
              "userId": localStorage.getItem("ckuser"),
              "layout": "getConversations",
              "view": "conversations",
              "format": "json",
              "limit": 2
            }]
        }

ajaxCall.call (list, list.data);
console.log(list.Data);

if I don't pass in "layout": "getConversations", for object list, it says undefined. I understood I asked to use data from list object. But now I want to be able to use jQuery.extend to replace with default data if list object doesn't pass in the property.

A: jQuery.extend which is similar to Object.assign will extend an object but, not array.
In the below code:
var opt = jQuery.extend({}, data, opt); data is an array with no key. So, it's not working as you expect..
Try this instead:
var opt = jQuery.extend({}, data[0], opt[0]); instead of var opt = jQuery.extend({}, data, opt);


text:
Q: (Python) Selenium Webdriver returns old elements after getting a new url I have a pretty simple process where within a loop, I get a url, wait for certain elements to load using WebDriverWait and then start processing the page source.
The issue I'm having is that it seems like if I don't add explicit wait times between the driver.get(url), webdriver can return elements from the old page rather than the most recent page. If I add explicit (for instance 3 seconds) or call on driver.get(url) twice, the issue gets resolved.
Has any one experienced this issue or know how to fix it?
Thanks.

A: Actually, I have encountered this on firefox with geckodriver and it is because you loaded another page by clicking on an old element. That driver object needs to be refreshed.
Reloading the page needed to traverse worked for me, waiting doesn't help.
driver.get(driver.current_url)

Edit: Chrome doesn't seem to have this problem and driver can access the elements from the clicked page directly.

A: It seems like a problem on a web browser. That is why after driver.get(url) I usually check, if driver.get() is successful:
driver.get(url)
sleep(n_seconds) #that is not necessary.
if driver.current_url == url:
    #do something
else:
    #try again to get the page or wait more.


text:
Q: JS events collision There is a collision while i run a html with inbuilt JS/jQuery. While this action onclick='window.location="location A" works for the whole  area and onclick='action 1'  should work only for 'Delete' link. The collision is when i press the 'Delete', JS works out the needed action1 first and also (that is not needed) redirects into 'location A'. Is it possible to leave the link inside the  area and make this div's JS not reacting on the click to this link?

Schedule

Delete

P.S. There should be jQuery script hanging on the 'delete' class. The preventDefault() method in jQuery on delete class does not work to prevent moving to location A.

A: If you intend to do it with jQuery:
$('div.scraper_item').click(window.location='location A');
$('a.delete').click(function(e){
    e.stopPropagation();
    action1();
});

e.stopPropogation() is what you're looking for, and it means the event we're dealing it will only trigger the current function and not all the events that it's parents are supposed to trigger.

A: Returning false from a jQuery event callback is the same as calling e.preventDefault() and e.stopPropogation()


text:
Q: Combinatorics problems 1) The sports club in the youth group consists of $12$ people, including $4$ girls. How many ways to choose a team of $5$ people, $3$ boys and $2$ girls?
2) How many different three-digit odd numbers can be formed from the digits $0, 1, 2, 3, 4$ provided that the numbers are not repeated?

A: $(1)$ How many ways can you choose $3$ boys from a group of $12-4=8$ boys? How many way can you choose $2$ girls from a group of $4$ girls? Multiply them by fundamental principle of counting and you get $\binom{8}{3} \times \binom{4}{2}=56 \times 6=336.$
$(2)$ The last digit can be $1$ or $3$. If it is $1$, we can choose any two from $0,2,3,4$ to fill up the first two places (since we cannot use $1$ again, as numbers can't be repeated). Note that here the order is important. So there are $4 \times 3=12$ ways to do it. Similarly if we have $3$ as the last digit, there are $12$ ways to do it. In total, you have $24$ odd numbers. But there's one more pitfall as noticed by @MeesdeVries. We cannot count the numbers starting with $0$. So we have to deduct $6$ numbers: $021, 031, 041, 013, 023, 043$ from the earlier set. So the total number of three-digited odd numbers obtained in the process is $24-6=18$. Thanks @MeesdeVries for the correction.


text:
Q: What's a good design to handle multiple global hotkeys? I'm struggling to think of a good design to handle multiple global hotkeys.
Say I have three different functions bound to three different global hotkeys...

*

*Play Song       | Ctrl + P

*Skip Song       | Ctrl + N

*Increase Volume | Ctrl + V

What's a good, effective way to check if the hotkey pressed conforms to a certain function? I'm using a class very similar to this: http://www.liensberger.it/web/blog/?p=207
Should I create a new instance of the hotkey class for each hotkey?
Hotkey hotkey = new Hotkey();
hotkey.RegisterHotkey(Shortcut.ModifierKeys.Control, Keys.F10);

hotkey.KeyPressed += ((s, args) =>
{
    //Do Something!
});

Or should I have an enum with different hotkey functions and manage it from within the hotkey class to prevent multiple instances (seems wasteful but easy). Thanks for any advice / help in advance.

A: I would opt for creating a separate instance of the class for each different function, as the Command Pattern seems like a good fit here. See this link for some more info.

A: Why not make the hotkey class static?
 Hotkey.Register(modifier, key, callback)

and keep them in a list within the class?
Also, I would recommend adding more modifiers to your hotkeys. All of yours are assigned to a common task: Control+P = Print, Control+N = New and Control+V = Paste


text:
Q: FORMATMESSAGE with a TAB character I have recently learned about the FORMATMESSAGE (link below) and I have started using it.
https://msdn.microsoft.com/en-us/library/ms186788.aspx
I have aware that I have print/select a TAB character (link below) but I would like to learn how to you it inside the FROMATMESSAGE function
https://msdn.microsoft.com/en-us/library/ms187323.aspx
I have tried using CHAR(9) and the escape character \t but it looks like it does not like it.
I know there are workarounds and it will not be hard for me to think of an alternative way outside of using FORMATMESSAGE but I was really curious about it.
Many thanks

A: Apologies but I have actaully found out my own answer.
Altough the escape character does not work but CHAR(9) works fine.
To see the results to have to change your results output to "Results To Text" (Ctrl + t).
You cannot see such non printable characters inside a Grid (Ctrl + D).


text:
Q: Using Parcel to clone an object? I have a class which has implemented Parcelable. Can I do something like the following to create a new instance of a class?:
Foo foo = new Foo("a", "b", "c");

Parcel parcel = Parcel.obtain();
foo.writeToParcel(parcel, 0);
Foo foo2 = Foo.CREATOR.createFromParcel(parcel);

I'd like foo2 to be a clone of foo.
---------------------- update -------------------------------
The above does not work (all Foo members are null in new instance). I'm passing Foos between activities just fine, so the Parcelable interface is implemented ok. Using the below which works:
Foo foo1 = new Foo("a", "b", "c");
Parcel p1 = Parcel.obtain();
Parcel p2 = Parcel.obtain();
byte[] bytes = null;

p1.writeValue(foo1);
bytes = p1.marshall();

p2.unmarshall(bytes, 0, bytes.length);
p2.setDataPosition(0);
Foo foo2 = (Foo)p2.readValue(Foo.class.getClassLoader());

p1.recycle();
p2.recycle();

// foo2 is the same as foo1.

found this from the following q: How to use Parcel in Android?
This is working ok, I can go with this but it is extra code, not sure if there's a shorter way to do it (other than properly implementing a copy constructor...).
Thanks

A: I had the same problem and here is my solution:
Parcel p = Parcel.obtain();
foo.writeToParcel(p, 0);
p.setDataPosition(0); // <-- this is the key
Foo foo2 = Foo.CREATOR.createFromParcel(p);
p.recycle();

A: There is a shorter way:
Foo foo1 = new Foo("a", "b", "c");
Parcel p = Parcel.obtain();
p.writeValue(foo1);
p.setDataPosition(0);
Foo foo2 = (Foo)p.readValue(Foo.class.getClassLoader());
p.recycle();

A: Yes, assuming that your parcel implementation correctly writes and reads all of the variables in Foo, that should create a clone.

A: I have done a Utility class with a static method that takes any parcelable and clone it.
import android.os.Parcel;
import android.os.Parcelable;

public class ParcelUtils {

    public static <T extends Parcelable> T clone(T object) {
        Parcel p = Parcel.obtain();
        p.writeValue(object);
        p.setDataPosition(0);
        Class<? extends Parcelable> c = object.getClass();
        @SuppressWarnings("unchecked")
        T newObject = (T) p.readValue(c.getClassLoader());
        p.recycle();
        return newObject;
    }
}


text:
Q: AJAX Auth required - what status code to use? The model and controllers in my MVC application throw LoginRequired exceptions whenever a public user attempts to access a secure resource.  I am listening for dispatch errors and when I detect one that is a LoginRequired exception, I then construct and return a custom response.
If the request was a normal HTTP request things are simple - I return a 302 redirect, and the 'location' is the login page.  But what about when the request is AJAX?
I have read here How to manage a redirect request after a jQuery Ajax call about setting a response header then looking for it in a global ajax success handler.  I can do that no problems, but surely there should be a HTTP status code to deal with this?
What would be a good choice of code?  I need one that is a reasonably good fit semantically, but is not going to automatically invoke any behaviour on the user agent.

A: You know I am not expert in such things but when I wanted to make a resume-able download I had added some headers and you can send costume request headers with ajax and Also you can send some response headers with PHP and get them with ajax (anything). But I think the headers are useful when they have some effects on both side or there is no different with a flag in header or a flag in body of ajax response.
And also some headers cause different behaviors on different browsers and also the browser will send different headers (just in especial little things) when you send a request (ajax or raw ,...)
ie. {'someFlallg':'ok','view':' --- content body --- '}
I hope that helps.


text:
Q: Is the Minecraft Java edition still available for Windows 10? I purchased the Java edition 6 years ago, but after some time I uninstalled it. A few weeks ago I wanted to play again. When I went to download it, I got a message that I have a free code for the Windows 10 edition, so I downloaded that edition, but I didn't like it (among other things, you couldn't press F3 to view your coordinates). Today I wanted to download the Java version again, but it seems I cannot; when I go to "Download", it says "You already own Minecraft" and I have an option to download it on Windows 10. Whatever I try, I always seem to end up with that message.
Is it still possible to play the Java edition on Windows 10?

A: Yes. You can download the Java edition on the Minecraft website.


text:
Q: Printing a Function After Calling (ocaml) I am very new to ocaml! I am using the code found here: https://rosettacode.org/wiki/Cartesian_product_of_two_or_more_lists#OCaml
I have been trying to figure out how to print the result after running the product function, Thank you very much!
open Printf

let rec product l1 l2 = (* Create a recursive function (rec) named product that has 2 parameters *)
    (*ignore (Printf.printf "Debug: %s\n" 1);*)
    match l1, l2 with
    | [], _ | _, [] -> []
    | h1::t1, h2::t2 -> (h1,h2)::(product [h1] t2)@(product t1 l2)
;;

let test =
    product [1;2] [3;4];;
    ignore (Printf.printf "test: %d*" 1);
(*- : (int * int) list = [(1, 3); (1, 4); (2, 3); (2, 4)]*)
product [3;4] [1;2];;
(*- : (int * int) list = [(3, 1); (3, 2); (4, 1); (4, 2)]*)
product [1;2] [];;
(*- : (int * 'a) list = []*)
product [] [1;2];;
(*- : ('a * int) list = []*)

A: Your fuction product has this type:
'a list -> 'b list -> ('a * 'b) list

There is no built-in way to print out the results of this function, because the results don't have a particular type. The type of the results depends on the types of the two input lists. Since OCaml is a strongly typed language, there's no way in general to examine a type at runtime and print it differently depending on the type.
If you run your code in the toplevel (OCaml's REPL), it will write out the results for you. It uses code that's not really available to an ordinary OCaml program:
# product [1;2] [3;4];;
- : (int * int) list = [(1, 3); (1, 4); (2, 3); (2, 4)]
# product [1.; 2.] ['a'; 'b'];;
- : (float * char) list = [(1., 'a'); (1., 'b'); (2., 'a'); (2., 'b')]

If you're willing to restrict yourself to lists of ints you can use this function to print a list of type (int * int) list:
let print_ints pair_list =
    let pair_str (i, j) = Printf.sprintf "(%d, %d)" i j in
    print_string
        ("[" ^ String.concat "; " (List.map pair_str pair_list) ^ "]\n")

If you run it in the toplevel it looks like this:
# print_ints (product [2;3] [4;5]);;
[(2, 4); (2, 5); (3, 4); (3, 5)]
- : unit = ()


text:
Q: How to take specific time interval on videos from Camera Roll on iOS? I need to take specific time interval of the video. For instance; last 40 seconds of it. I have searched for it. But could not find even a clue.
Could you please help or show me a way to do it.
BR,

A: This may help you out:
        AVURLAsset *videoAsset = [AVURLAsset URLAssetWithURL:videoURL options:nil];

        AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:videoAsset presetName:AVAssetExportPresetHighestQuality];
        exportSession.outputURL = [NSURL fileURLWithPath:outputURL];
        exportSession.outputFileType = AVFileTypeQuickTimeMovie;
        CMTimeRange timeRange = CMTimeRangeMake(CMTimeMake(startMilliseconds, 1000), CMTimeMake(endMilliseconds - startMilliseconds, 1000));
        exportSession.timeRange = timeRange;

        [exportSession exportAsynchronouslyWithCompletionHandler:^{
            switch (exportSession.status) {
                case AVAssetExportSessionStatusCompleted:
                    // Custom method to import the Exported Video
                    [self loadAssetFromFile:exportSession.outputURL];
                    break;
                case AVAssetExportSessionStatusFailed:
                    //
                    NSLog(@"Failed:%@",exportSession.error);
                    break;
                case AVAssetExportSessionStatusCancelled:
                    //
                    NSLog(@"Canceled:%@",exportSession.error);
                    break;
                default:
                    break;
            }
        }];


text:
Q: theano try except statements I wish to take the cholesky if possible in theano. For example:

try:
    L = T.slinalg.cholesky(self.cov)
except:
    return -np.inf

However, it seems that theano doesn't quite work with try catch statements since it chucks an error regardless. I'm using theano 0.9.0rc4 if it helps.


text:
Q: How to create the Surface for the SurfaceHolder? I'm trying to get an application to paint something on a canvas every half a second, but the SurfaceHolder.getSurface().isValid() returns false, and when I call SurfaceHolder.lockCanvas() this returns null.
As per this SO question, I should use a SurfaceHolder.Callback.surfaceCreated but the surface is never created.
The onCreate method from my main Activity
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
        WindowManager.LayoutParams.FLAG_FULLSCREEN);
    ChartPainter p = new ChartPainter(this);

    }

And part of my ChartPainter.java
public ChartPainter(Context context) {
    super(context);
    holder = getHolder();
    final boolean a[] = new boolean[1];
    a[0] = false;
    holder.addCallback(new Callback() {

        @Override
        public void surfaceCreated(SurfaceHolder holder) {
        // TODO Auto-generated method stub
        a[0] = true;
        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format,
            int width, int height) {
        // TODO Auto-generated method stub

        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
        // TODO Auto-generated method stub

        }

});

} [...]//more omitted code here

How do I create the surface for the SurfaceHolder?

A: Does ChartPainter extends SurfaceView?
Note: SurfaceHolder is usually used with SurfaceView. When the activity goes to the foreground and its SurfaceView is about to be rendered, WindowManager will ask SurfaceFlinger to create a new surface. Then SurfaceHolder's surfaceCreated() will be called.


text:
Q: Octave script no longer runs in Crontab I have some crontabs that run various Octave script files thus:
*/10 * * * 1-5 /usr/local/bin/octave "/path/to/octave/script.m" >/dev/null 2>&1

which, up until a few days ago, were working as they should but have, for some reason I cannot find, now stopped working. The script files download data via an API and then append to existing files. I don't believe it's a problem with the cronjob or cron daemon or such like as almost identical R script crontabs,
*/10 * * * 1-5 /usr/bin/Rscript "/path/to/R/script.R" >/dev/null 2>&1

which also download and append data, are still working as they should. The apparent failure is just for the call to run the Octave scripts.
I've done some obvious checks such as:

*

*check that the files are still executable (they are)

*check that symbolic links from /usr/local/bin/octave are still intact (they are)

*check that the script files can still be run manually from Octave (they can)

*grep CRON /var/log/syslog appears to show that everything is working, i.e. I get the following output
Oct  5 00:01:01 username CRON[12110]: (username) CMD (/usr/local/bin/octave "/path/to/octave/script.m" >/dev/null 2>&1)
What else can I do to track down the source of this problem?

A: Thanks to Cris's comment to direct output to a file I was able to find the source of this problem, which was a recent edit to the .octaverc start up file for Octave.
I had recently added a line to express a preference for a particular graphics toolkit and this was the first line in the .octaverc file. When Octave was being called by the crontab job this line was throwing an error. By moving this entry to be the last line of .octaverc, plus changing the crontab to use the command line version of Octave thus:
*/10 * * * 1-5 /usr/local/bin/octave-cli "/path/to/octave/script.m" >/dev/null 2>&1

the called "/path/to/octave/script.m" now runs as expected. I am still getting an error message thus:
error: graphics_toolkit: fltk toolkit is not available
error: called from
graphics_toolkit at line 88 column 5
/home/user/.octaverc at line 3 column 1

but since the command line interface doesn't require a GUI and the addpaths and such like in .octaverc are run before the error is thrown, the running of the script isn't interuptted.


text:
Q: Initializing A Variable With Its Default Constructor Question:
Is there a difference between the following initializations?
(A) What exactly is the second one doing?
(B) Is one more efficient than the other?
int variable = 0;
int variable = int();

This question also applies to other data types such as std::string:
std::string variable = "";
std::string variable = std::string();

Background:
I basically got the idea here (the second code sample for the accepted answer) when I was trying to empty out a stringstream.
I also had to start using it when I began learning classes and realized that member variable initializations had to be done in the constructor, not just following its definition in the header. For example, initializing a vector:
// Header.h
class myClass
{
 private:
      std::vector<std::string> myVector;
};

// Source.cpp
myClass::myClass()
{
    for (int i=0;i<5;i++)
    {
         myVector.push_back(std::string());
    }
}

Any clarity on this will be greatly appreciated!

A: Edit
After reading again, I realized that you explicitely asked about the default constructor while I provided a lot of examples with a 1 parameter constructor.
For Visual Studio C++ compiler, the following code only executes the default constructor, but if the copy constructor is defined explicit, it still complains because the never called copy constructor can't be called this way.
#include <iostream>
class MyInt {
public:
    MyInt() : _i(0) {
        std::cout << "default" << std::endl;
    }
    MyInt(const MyInt& other) : _i(other._i) {
        std::cout << "copy" << std::endl;
    }
    int _i;
};
int main() {
    MyInt i = MyInt();

    return i._i;
}

Original (typo fixed)
For int variables, there is no difference between the forms.
Custom classes with a 1 argument constructor also accept assignment initialization, unless the constructor is marked as explicit, then the constructor call Type varname(argument) is required and assignment produces a compiler error.
See below examples for the different variants
class MyInt1 {
public:
    MyInt1(int i) : _i(i) { }
    int _i;
};
class MyInt2 {
public:
    explicit MyInt2(int i) : _i(i) { }
    int _i;
};
class MyInt3 {
public:
    explicit MyInt3(int i) : _i(i) { }
    explicit MyInt3(const MyInt3& other) : _i(other._i) { }
    int _i;
};
int main() {
    MyInt1 i1_1(0); // int constructor called
    MyInt1 i1_2 = 0; // int constructor called

    MyInt2 i2_1(0); // int constructor called
    MyInt2 i2_2 = 0; // int constructor explicit - ERROR!
    MyInt2 i2_3 = MyInt2(0); // int constructor called

    MyInt3 i3_1(0); // int constructor called
    MyInt3 i3_2 = 0; // int constructor explicit - ERROR!
    MyInt3 i3_3 = MyInt3(0); // int constructor called, copy constructor explicit - ERROR!
}

A: The main difference between something like:
int i = int(); and int i = 0;
is that using a default constructor such as int() or string(), etc., unless overloaded/overridden, will set the variable equal to NULL, while just about all other forms of instantiation and declarations of variables will require some form of value assignment and therefore will not be NULL but a specific value.
As far as my knowledge on efficiency, neither one is "better".


text:
Q: Colors in ExclusionsStyle I have the following Plot:

Apparently MMA uses ColorData[1,1] for the edges in all graphs. I already tried adding
ExclusionsStyle -> {ColorData[1, 1], ColorData[1, 2], ColorData[1, 3]}

but that doesn't help; it only uses the first listed color. Adding `Directive' only uses the last listed color:
ExclusionsStyle -> Directive[{ColorData[1, 1], ColorData[1, 2], Red}]]

Any idea how I can Plot the edges in the same colors as the graphs?
edit
The code, upon request:
sqw[x_, f_] := SquareWave[x f]/3;
Plot[{sqw[x, 1] + 2.5, sqw[x, 0.95] + 1.5, -3 sqw[x, 1] sqw[x, 0.95] + 0.5}, {x, -1, 4},
Axes -> False, PlotStyle -> {AbsoluteThickness[2]},
ExclusionsStyle -> {ColorData[1, 1], ColorData[1, 2], ColorData[1, 3]}]

A: Perhaps
sqw[x_, f_] := SquareWave[x f]/3;
Plot[{sqw[x, 1] + 2.5, sqw[x, 0.95] + 1.5, -3 sqw[x, 1] sqw[x, 0.95] + 0.5}, {x, -1, 4},
         Axes -> False, PlotStyle -> {AbsoluteThickness[2]}, Exclusions -> False]

Edit
But you may find troubles if you need to specify a different Style for the exclusions in each function. For example, the following does not work as expected:
Plot[{2 + Floor[x], Floor[x]}, {x, 0, 4}, PlotStyle -> {Red, Blue},
 Exclusions -> True,  ExclusionsStyle -> {{Yellow, Green}, {White, Black}}]


text:
Q: Installing FreeBSD in VirtualBox aborts unexpectedly I have tried installing FreeBSD-10.0-RELEASE-i386-dvd1.iso into VirtualBox 3 times already today (each time starting from a fresh creation of a VM) and right when I'm about to Exit (Apply configuration and exit installer) the Final Configuration stage, I get this Abort error:

So then I either have to Restart or Exit...which is obviously not my end goal. I want to give FreeBSD a test drive in VirtualBox so I really want it to get installed. Hopefully someone can help.
Possibly relevant details:

*

*Host OS: 64-bit Arch Linux (Antergos)

*VirtualBox 4.3.14

*MD5 of ISO used checks out

Update 1
Opened another shell and checked /tmp/bsdinstall_log. Here are the last lines:

I assume umount failed?
Update 2
As suggested in the comments, I disabled Enable VT-x/AMD-V and it aborts after I set the root password.

The Abort dialog follows this screen

A: "Unstable" FreeBSD 10/i386 on VirtualBox, Xen, KVM
For FreeBSD installation
On FreeBSD boot menu, when booting from installation media, choose: 3. Escape to loader prompt to enter the following commands:

*

*set vfs.unmapped_buf_allowed=0 (enter)

*boot (enter)

Then proceed to FreeBSD installation as usual.
To run your new FreeBSD system
Two solutions:

*

*before leaving FreeBSD installation, at the end, when it asks for opening a shell (which is chrooted on / of your new system), answer yes, modify /boot/loader.conf (echo 'vfs.unmapped_buf_allowed=0' >> /boot/loader.conf) then exit when you have done to reboot on it

*or, the first time you boot it, repeat the steps you have done for installation then add this line to your loader.conf (echo 'vfs.unmapped_buf_allowed=0' >> /boot/loader.conf)

Source : FreeBSD 10.0 errata

A: this was happening to me i came googling for it.
I fixed it by just increasing the vm ram in virtualbox from 128MB to 384MB, by default virtaulbox gave it 128 MB as soon as i selected freeBSD, but it recommends 768 MB for a similar net install version of debian. i dont think debian non-gui needs ~7 times more ram then freeBSD non-gui :)


text:
Q: How to break an image into 9 small ones (sort of puzzle pieces) So, I tried creating a little puzzle game, which at the moment looks something like this

The top is the puzzle where you can put pieces that are chosen from a table with 1 row (scrollable) from the bottom of the page
Problem is those are 9 individual images cut from the original one.
I want to have only one image (the big one) and have them put into the bottom table in a similar manner to what's in the picture above in this post.
For simplicity sake, assume every table cell is 206px width 124px height, so the big picture is 618px width and 372px height (because that's the size of that random image I found online)
I've set an id to each td from the bottom table and tried using css sprite but to no avail.
I'm pretty sure I have to use sprite tho, I just can't seem to make it work. Plus, when I use background: url()... it automatically resizes the cells even tho they have a fixed size.
Thanks in advance

A: Based on the size of source image (as whole) you can use javascript to calculate top and left point of each piece. Then allocate fixed size piece divs and set same (source) background image to each of them with different offset like this:
.piece-1 {
   background-image: url("...");
   background-position: right <CALCULATED RIGHT>px top <CALCULATED TOP>px;
}

A: Use background-position
Updated: Thanks to @GCyrillus comment (and code sample), it is now scalable)

html, body {
  margin: 0;
}
.puzzle {
  width: 100vh;
  height: 100vh;
  display: flex;
  flex-wrap: wrap;
}
.puzzle > div {
  width: 33.333%;
  height: 33.333%;
  background: red;
  border: 1px solid white;
  box-sizing: border-box;
  background: url(http://lorempixel.com/600/600/nature/1/) no-repeat;
  background-size: 300%;
}
.puzzle > div[data-piece1] {
  background-position: 0 0;
}
.puzzle > div[data-piece2] {
  background-position: 50% 0;
}
.puzzle > div[data-piece3] {
  background-position: 100% 0;
}

.puzzle > div[data-piece4] {
  background-position: 0 50%;
}
.puzzle > div[data-piece5] {
  background-position: 50% 50%;
}
.puzzle > div[data-piece6] {
  background-position: 100% 50%;
}

.puzzle > div[data-piece7] {
  background-position: 0 100%;
}
.puzzle > div[data-piece8] {
  background-position: 50% 100%;
}
.puzzle > div[data-piece9] {
  background-position: 100% 100%;
}

Scrambled

html, body {
  margin: 0;
}
.puzzle {
  width: 100vh;
  height: 100vh;
  display: flex;
  flex-wrap: wrap;
}
.puzzle > div {
  width: 33.333%;
  height: 33.333%;
  background: red;
  border: 1px solid white;
  box-sizing: border-box;
  background: url(http://lorempixel.com/600/600/nature/1/) no-repeat;
  background-size: 300%;
}
.puzzle > div[data-piece1] {
  background-position: 0 0;
}
.puzzle > div[data-piece2] {
  background-position: 50% 0;
}
.puzzle > div[data-piece3] {
  background-position: 100% 0;
}

.puzzle > div[data-piece4] {
  background-position: 0 50%;
}
.puzzle > div[data-piece5] {
  background-position: 50% 50%;
}
.puzzle > div[data-piece6] {
  background-position: 100% 50%;
}

.puzzle > div[data-piece7] {
  background-position: 0 100%;
}
.puzzle > div[data-piece8] {
  background-position: 50% 100%;
}
.puzzle > div[data-piece9] {
  background-position: 100% 100%;
}


text:
Q: Angular 2 unit testing - getting error Failed to load 'ng:///DynamicTestModule/module.ngfactory.js' I have angular 2 webpack application, all webpack,karma configuration created as per angular.io webpack guide.
I am not using aot.
I am writing jasmine unit test spec to test my components.
First I tried without async block, in that case , unit test just get execute only till fixture.detectChanges() call, code after that doesn't get executed. Seems like fixture.detectChanges call getting blocked infinitely.
I tried by including code in async block.
Then I get following error.
Error:Failed to execute 'send' on 'XMLHttpRequest' : Failed to load 'ng:///DynamicTestModule/module.ngfactory.js'

Code without async
beforeeach(()=> {
TestBed.configureTestingModule({
imports:[],
declaration :[Mycomp],
providers:[{ provide:MyService, useclass:MyMockService}]
});
 fixture=TestBed.createComponent(Mycomp);
 console.log(' before detect changes'):
 fixture.detectChanges():
 console.log('after detect changes');// this is not getting
    logged .. karma shows 0 of 1 executed successfully

 });

With async
  beforeeach(async(()=> {
 TestBed.configureTestingModule({
  imports:[],
  declaration :[Mycomp],
  providers:[{ provide:MyService,       useclass:MyMockService}]
  });
   fixture=TestBed.createComponent(Mycomp);
    fixture.detectChanges():
  }));

getting error Failed to load dynamictestmodule/module.ngfactory.js

A: To find out what's really causing the error, disable source maps:
For angular-cli >= v6.x:
ng test --source-map=false

For angular-cli v1.x:
ng test -sm=false

You will then see a better error, e.g. "Cannot read property 'x' of undefined" in the actual source file that's causing the error.  For some reason, there's a bug with sourcemaps right now in testing, and you just get this cryptic error.

A: Adding on to Dan Field's answer
This is a problem with the Angular Cli version 1.2.2 or newer.  Run your test with --sourcemaps=false and you will get the right error messages.

ng test --sourcemaps=false

shorthand for this is:

ng test -sm=false

See details here: https://github.com/angular/angular-cli/issues/7296

A: I also had this issue and it was due to malformed mocked data.
In my component I had a service which made a http call.
something like: (service code)
getData() {
   return this.http.get(obj);
}

In the component I called this function and subscribed to it: (component code)
this.service.getData().subscribe((data) => {
  this.componentData = data.things; //**<=== part that broke everything**
}, (error) => {
  console.log(error);
});

Solution:
When I mocked out the service function I failed to return data that had the attribute things. This is what caused the XMLHttpRequest failure, I guess to angular it looked like the error happened as if it was the HTTP request. Making sure that I returned the correct attributes on any mocked HTTP requests fixed the issues.
Hope this clears things up. Below is the code for the implementation of the mock.
(component.specs)
function fakeSubscribe(returnValue,errorValue) {
  return {
    subscribe:function(callback,error){
      callback(returnValue);
      error(errorValue);
    }
  }
}

 class MockService {
      getData() {
        var fakeData = {
          things:[]
        }
        return fakeSubscribe(fakeData,0);
      }
   }

A: This is the most deceiving error message that I've ever encountered in Angular.
In my case it had nothing to do with sending, nothing to do with XmlHttpRequest - at least not on the level you'd guess when trying to follow the message.
It was too about mocking a class, namely ngrx/store. I introduced two Observable methods in a container that had not been included in my mock-up class before and I forgot to do so when I started using those. Once added to the mock-up, the error went away.
...leaving Karma happy to be able to execute 'send' from the XmlHttpRequest whatever it means.

A: I was bitten by the same error next day - this time the problem was buried in the HTML file. Using a simple array length test for *ngIf
<ng-container *ngIf="myArray.length > 0">

had to be refactored into
<ng-container *ngIf="myArrayNotEmpty">

with a getter as in:
get myArrayNotEmpty(){
  return this.myArray && this.myArray.length > 0;
}

I am a bit irritated though that such a variety of causes is covered by one very misleading and unhelpful message.

A: running tests with --sourcemaps=false will not fail Karma silently but give you some detail about the error instead.

A: I ran into this issue myself yesterday. The problem was that I had an Input() property on my component class that I wasn't setting in the test. So for example, in my-component.ts:
@Component({
  selector: 'my-component'
})
export class MyComponent {
  @Input() title: string;
}

and my-component.spec.ts:
beforeEach(() => {
  fixture = TestBed.createComponent(MyComponent);
  component = fixture.componentInstance;
  component.title = 'Hello there!' // <-- this is required!
  fixture.detectChanges();
});

Or you could provide a default value in the component somewhere. Either way, the test will crash if any inputs are not set and you'll get that unintuitive error.
Note: Running ng test -sm=false will give the actual error message causing the problem. Credit: https://stackoverflow.com/a/45802115/61311

A: In my case, my mock service was missing some public variables accessed by the component in the ngOnInit method.

A: I just had this issue as well. It turned out to be a simple null reference error in my component in one of my *ngIf checks.
I would suggest running ng serve and checking the component is working in the browser without any errors, or simply run ng test --source-map=false to get a more useful error message.

A: I had the same error when I accessed a variable of an undefined object.
Example:
Component:
soemthing = {}

Template:
<demo-something [someinput]="something.anotherthing.data"> ...

So something was defined, anotherthing was undefined and data could therefor not be accessed.
Very annoying error and as far as I could tell not in the list yet :)


text:
Q: Is jQl inconsistent or am I using it wrong? Im using jQl to asynchronously load my jQuery libraries and dependencies, but it appears to only work on every other page load (Im using Ctrl+F5 to ensure the scripts are loaded fresh each time)
I am using like this:
<script type="text/javascript">
    jQl.loadjQ("/Scripts/jquery-1.10.1.min.js");
    jQl.loadjQdep("/Scripts/jquery-ui-1.9.2.custom.min.js");
    jQl.loadjQdep("/Scripts/multiselect/jquery.multiselect.min.js");
    jQl.loadjQdep("/Scripts/autocomplete/jquery.autocomplete.min.js");
</script>

Is this not correct? Has anyone else had the same problems?

A: <script type="text/javascript">
    jQl.loadjQ("http://www.webiste.com/Scripts/jquery-1.10.1.min.js");
    jQl.loadjQdep("http://www.webiste.com/Scripts/jquery-ui-1.9.2.custom.min.js");
    jQl.loadjQdep("http://www.webiste.com/Scripts/multiselect/jquery.multiselect.min.js");
    jQl.loadjQdep("http://www.webiste.com/Scripts/autocomplete/jquery.autocomplete.min.js");
</script>


text:
Q: Terrraform list of objects syntax I'm using a module that references a central module used to build a Puppet server in terraform. There is one variable in the root module that allows additional tags to be used with the ASG however I can't seem to get the syntax right. This is the information in the core repository:
   variable "additional_asg_tags" {
  description = "A map of additional tags to add to the puppet server ASG."
  type        = list(object({ key = string, value = string, propagate_at_launch = bool }))
  default     = []
}

I've tried everything I can think of to call this but it always errors with messages like "incorrect list element type: string required." or "This default value is not compatible with the variable's type constraint: list of object required."
I'm trying to call the above with something like;
variable "additional_asg_tags" {
  description = "A map of additional tags to add to ASG."
  type        = list(object({ key = string, value = string, propagate_at_launch = bool }))
  default     = { key = "Name", value = "Puppet-nonprod", propagate_at_launch = "true"
 }
}

I've removed the square braces around this as that was causing errors also but I may need to add these back in.
Can someone help please in what is the correct way to reference a list of objects with these values

A: The correct default value for your additional_asg_tags is a list:
variable "additional_asg_tags" {

  description = "A map of additional tags to add to ASG."

  type = list(object({
               key = string,
               value = string,
               propagate_at_launch = bool
            }))

  default = [{
        key = "Name",
        value = "Puppet-nonprod",
        propagate_at_launch = "true"
   }]
}

You can reference individual elements as follows (some examples):
var.additional_asg_tags[0]["key"]

var.additional_asg_tags[0].value

# to get list
var.additional_asg_tags[*].propagate_at_launch


text:
Q: Is there a limit to the height to which a helium balloon can rise? My professor's answer to this is "It will rise until the weight of air displaced equals the mass of the balloon". I am a bit confused by this. Wouldn't it depend on densities rather than weights and masses? I thought it will keep rising till the density of air is the same as helium. Can anyone point out where I am wrong?

A: You are correct that the balloon will keep rising until the density of the air equals the density of the helium in the balloon. But since $W=\rho g V$ the weight $W$ of the volume $V$ of air displaced by the equal volume of helium will also be the same as the weight of the helium (neglecting the weight of the balloon material) when the densities $\rho$ are equal .
Hope this helps.

A: Per Archimedes' principle, a body immersed in a fluid has a buoyant force equal to the weight of the fluid it displaces. As air density changes for various reasons, its weight per volume also changes. The helium's density may also change for various reasons. The balloon's volume may expand or contract with changing conditions. All of these things may change at different altitudes, temperatures, or other reasons, but Archimedes' principle will hold true in any set of conditions. If the total weight of the balloon and its contents are less than the weight of the volume of air it displaces it will still rise. By the way it would be more accurate for your professor to say "weight" of the balloon, rather than "mass" of the balloon, as weight can change slightly with altitude in Earth's non uniform gravitational field but an object's mass does not change.


text:
Q: Change in state upon localization of particle into a region (x, x+a ) Suppose I momentarily, with hundred percent certainty, assure that a particle is in range $(x,x+a)$, by using some sort of detector.
If initial state was ket $\alpha$, what is the final state?
Is it some ket $\beta$ with $\psi_\beta(x) = 0$, for all $x \notin (x,x+a)$, with $\psi_\beta\neq\psi_\alpha$ for $x\in (x,x+a)$?
If yes, then can you explain the following, taken from Sakurai's textbook, where he talks of this experiment? Specifically in (1.6.5), he says that measurement reduces the state to RHS. He further suggests that such an action 'may' not affect the wavefunction..

A: The initial wavefunction is $\psi_\alpha(x)\equiv\langle x|\alpha\rangle$. The RHS in (1.6.5) corresponds to a wavefunction $\psi_\beta$ which is $0$ outside the interval and equals to the old one $\psi_\beta=\psi_\alpha$ within the interval. This is a usual projection measurement that simply cuts everything that doesn't correspond to the measured value. Of course for the following measurements you need to normalize wavefunction to $1$.
You may also read this answer of mine.

A: I would model the situation as follows.  Let
$$
\hat \Pi=
\int_{x-\Delta/2}^{x+\Delta/2}\,dx\,\vert x\rangle\langle x\vert
\tag{1}
$$
denote your "measuring apparatus".  Basically $\hat \Pi$ is a projection to the interval where your apparatus produces a click.  It generalizes to continuous spectrum the usual projection
$$
\hat \Pi=\sum_{\lambda=\lambda_0}^{\lambda_1} \vert \lambda\rangle\langle \lambda\vert \tag{2}
$$
where $\lambda$ is an eigenvalue of $\hat \Lambda$  and $\vert\lambda\rangle$ is and eigenvector of the
operator $\hat \Lambda$.
You would use (2)
to compute the total probability of getting $\lambda_0\le \lambda\le \lambda_1$ if you
measured the observable $\Lambda$.
Note that (1) assumes all positions in the interval have equal probability of detection, i.e. the detector has uniform sensitivity over the interval.  If not then (1) would be modified by multiplying the uniform probability $dx$ by $dx\, \phi(x)$, where $\phi(x)$ accounts for the sensitivity of the detector at detecting at location $x$ in the interval.
The probability you are looking for is then
$$
\langle \alpha\vert\hat \Pi\vert\alpha \rangle
=\int_{x-\Delta/2}^{x+\Delta/2}\,dx\,
\langle\alpha\vert x\rangle\langle x\vert\alpha\rangle
= \int_{x-\Delta/2}^{x+\Delta/2}\,dx\,
\vert\langle x\vert\alpha\rangle\vert^2\, .
$$
If you assume as suggested that $\vert\langle x\vert\alpha\rangle\vert^2$ is constant over the interval then you can pull it out of the integral and you obtain the probability as
$\vert\langle x\vert\alpha\rangle\vert^2 dx$ where $dx=\Delta$ is the width
over which your detector will click.


text:
Q: Facebook JS API: users_getInfo() inside ifUserConnected() deadlock I am trying to put Facebook connect button on the site and once connected display connected username. But for some reason following code goes into some infinite loop during first connection, and then works fine unless I delete this app from my facebook profile which causes freezing again.
Here is a code on FB connect button click:
FB.Connect.requireSession();

Here is code directly on the page:
<script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php/en_US" type="text/javascript"></script>
<script type="text/javascript">
    FB.init("123", "/xd_receiver.htm");
    FB.ensureInit(function() {
        FB.Connect.ifUserConnected(function() {
            FB.Facebook.apiClient.users_getInfo(new Array(FB.Connect.get_loggedInUser()),new Array("name"), function(user, exec) {
            console.log("logged in:"+user[0].name);
            });

        }, function(){
            console.log("guest");
        });
    });
</script>

If I remove FB.Facebook.apiClient.users_getInfo() it works fine, but I need to get username somehow. Any tips?
Thanks.

A: For that you need to pass username parameter as array like:
FB.Facebook.apiClient.users_getInfo(new Array(FB.Connect.get_loggedInUser()),new Array("name","username"), function(user, exec) {
            console.log("logged in:"+user[0].name);
            });

A: You can get like this;
FB.Facebook.apiClient.users_getInfo(loggedInUsersId, ['first_name','last_name','email','sex','birthday','username'], function(result,ex){
       alert(result[0]['username']);
    });


text:
Q: Uploadify 3.1 settings not working I am sending additional form data along with the file. Here is the form data:
         register_object['first_name']=$("#first_name").val();
         register_object['last_name']=$("#last_name").val();
         register_object['input_email']=$("#input_email").val();
         register_object['input_password']=$("#input_password").val();
         register_object['repeat_password']=$("#repeat_password").val();

And, following is the uploadify code that I use:
     $(document).ready(function(){
         $("#image_file").uploadify({
            'method'   : 'post',
            'queueSizeLimit' : 1,
            'formData' : JSON.stringify(register_object),
            'buttonText' : 'Profile Pic',
            'auto' : false,
            'multi' : false,
            'swf' : 'js/plugins/others/uploadify.swf',
            'uploader' : 'upload.ashx',
            'fileTypeDesc': 'Image Files',
            'fileTypeExts': '*.jpg;*.png;*.gif;*.bmp;*.jpeg',
            'onUploadStart' : function(file) {
                $('#file_upload').uploadify('settings', 'formData', JSON.stringify(register_object));
                alert(JSON.stringify(register_object));
            },
            'onUploadSuccess' : function(file,data) {
                alert('The file finished processing. ' + data);
            },
            'onUploadError' : function(file, errorCode, errorMsg, errorString) {
                alert('The file ' + file.name + ' could not be uploaded: ' + errorString + ' ' + errorMsg);
            }
         });
         $("#register").submit(function(){
            $('#input_password').val(CryptoJS.MD5($('#input_password').val()));
            $('#repeat_password').val(CryptoJS.MD5($('#repeat_password').val()));
         register_object['first_name']=$("#first_name").val();
         register_object['last_name']=$("#last_name").val();
         register_object['input_email']=$("#input_email").val();
         register_object['input_password']=$("#input_password").val();
         register_object['repeat_password']=$("#repeat_password").val();
            $("#image_file").uploadify('upload');
            return false;
        });
    });

When I access the post data on the server, I get nothing.
What am I doing wrong?

A: I was able to finally get the data to the server. Firstly, I had to use $("#image_file") instead of $("#file_upload") (sorry, my mistake) in onUploadStart. And secondly, I had to write complete JSON string within onUploadStart:
$('#image_file').uploadify("settings", "formData", {"first_name":register_object['first_name'],"last_name":register_object['last_name'],"input_email":register_object["input_email"],"input_password":register_object["input_password"],"repeat_password":register_object["repeat_password"]});

The code goes like this:
     $(document).ready(function(){
         $("#image_file").uploadify({
            'method'   : 'post',
            'queueSizeLimit' : 1,
            'formData' : JSON.stringify(register_object),
            'buttonText' : 'Profile Pic',
            'auto' : false,
            'multi' : false,
            'swf' : 'js/plugins/others/uploadify.swf',
            'uploader' : 'upload.ashx',
            'fileTypeDesc': 'Image Files',
            'fileTypeExts': '*.jpg;*.png;*.gif;*.bmp;*.jpeg',
            'onUploadStart' : function(file) {
                **$('#image_file').uploadify("settings", "formData", {"first_name":register_object['first_name'],"last_name":register_object['last_name'],"input_email":register_object["input_email"],"input_password":register_object["input_password"],"repeat_password":register_object["repeat_password"]});**
                alert(JSON.stringify(register_object));
            },
            'onUploadSuccess' : function(file,data) {
                alert('The file finished processing. ' + data);
            },
            'onUploadError' : function(file, errorCode, errorMsg, errorString) {
                alert('The file ' + file.name + ' could not be uploaded: ' + errorString + ' ' + errorMsg);
            }
         });
         ....
    });


text:
Q: Randomly pairing people to channels in discord rewrite I'm currently trying to make a command for a bot that allows me to take a list of users in Discord, randomly pair them up, then assign each pair to their own channel only they can access.
So far I have the code able to take the list of users, but whenever I run it, passing in the user IDs, it gives an error "Nonetype has no attribute 'add_roles'".
Here's the function in question:
async def startDraft(context, *users):
#Take a list of users of an even number, and assign them randomly in pairs
#Give each of these pairs a private #, then use that to assign them roles, and thereby rooms.
if not users or len(users)%2 is not 0:
    context.say("Malformed command. Please see the help for this command. (Type !help startDraft)")
    pass
userList = []
for user in users:
    userList.append(client.get_user(user))
random.shuffle(userList)
pairList = []
guild = context.guild
for i in range(int(len(users)/2)):
    pairList.append((userList[i*2], userList[i*2+1]))
for i in range(len(pairList)):
    pairRole = await guild.create_role(name="draft"+str(i))
    pairList[i][0].add_roles(pairRole)
    pairList[i][1].add_roles(pairRole)
    overwrites = {guild.default_role: discord.PermissionOverwrite(read_messages=False),
    pairRole: discord.PermissionOverwrite(read_messages=True)}
    await guild.create_text_channel(name="draft"+str(i),overwrites=overwrites)

A: We can use the zip clustering idiom (zip(*[iter(users)]*2)) to generate pairs. We can also use a converter to get the Member objects directly from the command
import discord
from dicord.ext import commands

bot = commands.Bot(command_prefix="!")

@bot.command()
async def startDraft(ctx, *users: discord.Member):
    if not users or len(users)%2:
        await ctx.send("Malformed command. Please see the help for this command. "
                       "(Type !help startDraft)")  # send not say
        return  # return to end execution
    guild = ctx.guild
    users = random.sample(users, k=len(users))  # users is a tuple so can't be shuffled
    pairs = zip(*[iter(users)]*2)  # Could also be it = iter(users); zip(it, it)
    for i, (user1, user2) in enumerate(pairs):
        name = "draft{}".format(i)
        pairRole = await guild.create_role(name=name)
        await user1.add_roles(pairRole)  # add_roles is a coroutine, so you must use await
        await user2.add_roles(pairRole)
        overwrites = {guild.default_role: discord.PermissionOverwrite(read_messages=False),
                      pairRole: discord.PermissionOverwrite(read_messages=True)}
        await guild.create_text_channel(name=name, overwrites=overwrites)

bot.run("Token")


text:
Q: How to stop a play and return right values in TPL? In my TPL application, I want to play a text to speech by a method PlayTTS(string text) to do it.
public static CancellationTokenSource cTokenSource = new CancellationTokenSource();
public static CancellationToken cToken = cTokenSource.Token;

Then in the consumer method.
async Task Consumer()
    {
        try
        {
            var executionDataflowBlockOptions = new ExecutionDataflowBlockOptions
            {
                MaxDegreeOfParallelism = 50,
                CancellationToken = cToken
            };
            var consumerBlock = new ActionBlock<AppointmentReminder>(
            remainder =>
            {
               if (cToken.IsCancellationRequested)
                  return;
                Dictionary<string, string> dict = new OutboundDial(ts).RunScript(remainder, cToken);
                // update UI by the returned dictionary
            },
            executionDataflowBlockOptions);

            m_bufferBlock.LinkTo(
            consumerBlock, new DataflowLinkOptions { PropagateCompletion = true });
            await consumerBlock.Completion;
        }

I have a button event to cancel the process(WPF).
private void Cancel_Click(object sender, RoutedEventArgs e)
{
    cTokenSource.Cancel();
}

You see there is cToken.IsCancellationRequested in the ActionBlock, however it did not help to stop the process in the method OutboundDial(ts).RunScript(remainder, cToken); although I passed into the cancellation token.
Now let's look at the method RunScript.
public Dictionary<string, string> RunScript(AppointmentReminder callData, CancellationToken cToken)
    {
        try
        {
             m_ChannelResource = m_TelephonyServer.GetChannel() as SipChannel;
             m_VoiceResource = m_ChannelResource.VoiceResource;
             // Many logging
             // Dial out

            MakeTest(callData, cToken);
        }
        catch
         {throw;}
        finally
        {
            // destroy m_ChannelResource and m_VoiceResource
         }
        return dict;
    }

The key point is the method MakeTest, inside it we have PlayTTS;
public void MakeTest(AppointmentReminder callData, CancellationToken cToken)
{
    try
    {
        if (!cToken.IsCancellationRequested)
        {
            m_VoiceResource.PlayTTS(callData.Text);
        }
        else
        {
            cToken.ThrowIfCancellationRequested();
            m_VoiceResource.Stop(); // Stops any current activity on m_VoiceResource.
            dict["ConnectedTime"] = " no connection";
            dict["DialingResult"] = " cancellation";
        }

My current code didn't reach m_VoiceResource.Stop() part when I click the cancel button.
So my question is when cTokenSource.Cancel();, how to let code run at:
m_VoiceResource.Stop(); // Stops any current activity on m_VoiceResource.
dict["ConnectedTime"] = " no connection";
dict["DialingResult"] = " cancellation";

EDIT: 1:10pm Oct 31 2014
Based on the comment by Servy, I used cToken.Register(() => m_VoiceResource.Stop());
I created a similar demo at OneDrive.

A: You're cancelling the token after you have already checked if the token is canceled and begun playing.  You are never going back and performing that condition again to stop.
What you need to do is simply register a callback to the token's cancellation that stops the player:
cToken.Register(() => m_VoiceResource.Stop());

Simply add that registration immediately after you start playing.

A: Finally I found the solution under the help from a Microsoft MVP.
Servy's solution was beautiful but with flaw.
cToken.Register(() => m_VoiceResource.Stop());

The registration should be placed before start playing rather than after it.
EDIT: Nov 10 2014 8:09 am
A better one:
 cToken.Register(() => m_VoiceResource.Stop());
 return;


text:
Q: Get large files from FTP with python lib I need to download some large files (>30GB per file) from a FTP server. I'm using ftplib from the python standardlib but there are some pitfalls: If i download a large file, i can not use the connection anymore if the file finishes. I get an EOF Error afterwards, so the connection is closed (due to timeout?) and for each succeeding file i will get an error 421.
From what i read, there are two connections. The data and control channel, where the data channel seems to work correctly (i can download the file completly) but the control channels times out in the meantime.
I also read that the ftplib (and other python ftp libraries) are not suited for large files and may only support files up to around 1GB.
There is a similar question to this topic here: How to download big file in python via ftp (with monitoring & reconnect)? which is not quite the same because my files are huge in comparison.
My current code looks like this:
import ftplib
import tempfile

ftp = ftplib.FTP_TLS()

ftp.connect(host=server, port=port)
ftp.login(user=user, passwd=password)
ftp.prot_p()
ftp.cwd(folder)

for file in ftp.nlst():
    fd, local_filename = tempfile.mkstemp()
    f = open(fd, "wb")
    ftp.retrbinary('RETR %s' % file, callback=f.write, blocksize=8192)
    f.close()

Is there any tweak to it or another library that i can use, which does support huge files?

A: If you experience issues with standard FTP, you can try using a different protocol that is specifically designed to handle such large files.
A number of suitable solutions exist. Rsync would probably be a good way to start.


text:
Q: Changing target compiler in VS 2013 to VS 2012 I have a VS 2012 project that worked fine till the template issues in c++ started causing problems in VS 2013.
Some one mentioned changing the compiler to VS 2012 in the settings will fix the issue by using the same compiler the VS 2012.
Steps to do this i was told was to first install VS 2012 then change the setting in the project properties.
How there does not seem to be a setting to change the compiler.
How do I change the compiler in VS 2013 to VS 2012?
=============== EDIT ===============
herohuyongtao below explained the compiler change Thx
However despite installing VS2012. VS2013 properties does not see VS2012 when i hard code the value 110 it says "Visual Studio 2012 (v110) (Not Installed)"
any thoughts on how to resolve that?
=============== EDIT ===============
The version of VS 2012 is express which is registered now. Will this work with VS 2013 pro?
=============== EDIT ===============
Also just installed Microsoft Visual Studio Tools for Applications 2012
http://www.microsoft.com/en-gb/download/details.aspx?id=38807
as recommend by the compiler error when tried to compile with v110 even though it was not there

A: Right-click the project in Solution Explorer and select Properties, and then:
Configuration Properties > General > Platform Toolset > v110.


text:
Q: Javascript convert object with array string keys to key/name value's I have an object with named keys like this
{
 'name[first]': 'john',
 'name[last]': 'doe'
 }

that I want to convert to:
{
 'name' : {
     'first' : 'john',
     'last' : 'doe'
   }
 }

Any idea on an elegent way to do this?

A: You can use reduce() to return obj and regular expression to split key.

var obj = {
  'name[first]': 'john',
  'name[last]': 'doe'
}

var result = Object.keys(obj).reduce(function(r, e) {
  var key = e.split(/\[(.*?)\]/)
  if (!r[key[0]]) r[key[0]] = {}
  r[key[0]][key[1]] = obj[e]
  return r;
}, {})

console.log(result)

For nested key structure you could again use reduce but with different approach to keys but then you face problem of deep merge of object and for that you can use lodash.

var obj = {
  'name[first[foo]]': 'john',
  'name[last]': 'doe',
  'name[last[foo[bar]]]': 'doe'
}

var result = Object.keys(obj).reduce(function(r, e) {
  var key = e.replace(/\[/g, '.').replace(/\]/g, '').split('.')
  var o = {}

  key.reduce(function(re, el, i) {
    return i != key.length - 1 ? re[el] = {} : re[el] = obj[e]
  }, o)

  r = _.merge(r, o)
  return r;
}, {})

console.log(JSON.stringify(result, 0, 4))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>

A: Using a for..in loop and constructing a new object:

var obj = {
    'name[first]': 'john',
    'name[last]': 'doe'
};

var newObj = {}
for (var key in obj) {
    var parts = key.split(/\[|\]/);
    if(!newObj.hasOwnProperty(parts[0]))
      newObj[parts[0]] = {};
    newObj[parts[0]][parts[1]] = obj[key];
}

console.log(newObj);

A: You can try the following:

var obj = {
  'name[first]': 'john',
  'name[last]': 'doe'
}

var result = Object.keys(obj).reduce(function(newObj, prop) {
  var key = prop.split(/\[|\]/)[1];
  newObj[key] = obj[prop];
  return newObj;
}, {})

console.log(result);

A: The solution using Object.keys, Array.prototytpe.reduce and String.prototype.match functions:

var obj = {'name[first]': 'john', 'name[last]': 'doe'};

var result = Object.keys(obj).reduce(function (o, key) {
  var parts = key.match(/^(\w+)\[(\w+)\]$/);
  if (!o[parts[1]]) {
    o[parts[1]] = {};
  }
  o[parts[1]][parts[2]] = obj[key];
  return o;
}, {});

console.log(result);

A:

var obj = {
  'name[first]': 'john',
  'name[last]': 'doe'
}
var newObj = {};
for (var property in obj) {
  if (obj.hasOwnProperty(property)) {
    var keys = property.match(/(\w+)/g);
    if (keys && keys.length == 2) {
      newObj[keys[0]] = newObj[keys[0]] || {};
      newObj[keys[0]][keys[1]] = obj[property];
    }

  }
}
console.log(newObj);


text:
Q: Atomic repository...in english please Simple question, hopefully a simple answer:
I am new to Linux servers, and my hosting company offered me a tip to:

You may want to add the Plesk
  repository provided by Atomic Turtle.

I know how to install it (they offered good insturctions), but i have no clue what it is...help?

A: Plesk is admin panel, something similar to DirectAdmin. Lets you (and your users) to administrate server via www, in browser.
http://en.wikipedia.org/wiki/Plesk
Repository is something like a database of various linux programs (in this case only, repository as a term is much broader). Your software, responsible for managing (downloading and installing) another soft uses repositories to download from. Said software can be apt, or Synaptic package manager, or whatever else.
So in plain English, its like this: add atomic repository address to your repositories list so that you would be able to easily download and install Plesk control panel :)

A: Plesk is a control panel for webhosting, as I'm sure you know. As with most things nowadays, it allows you to install various extra features or addins.
Atomic Turtle's repository is a set of such addins as well as a set of plesk-friedly Linux applications that help you administer your server. (though nowadays its more a site for his own Linux disto, ASL)

A: The most frequent reason of mine for using the Atomic repositories has been upgrading PHP from 5.1 to 5.2/5.3. You can't do this without crafting a repository script of yours or using a ready-made one like the Atomic.


text:
Q: Few doubts related to adjoints of matrices 1) If A is a symmetric matrix , then Adj(A) is symmetric.
A . Adj(A) = Adj(A) . A =|A| I (where 'I' is an indentity matrix).
What i did was take tranpose of the original equation giving me :-
A$^t$ . [Adj(A)]$^t$ = [Adj(a)]$^t$ . A$^t$ = |A| I. (Also A$^t$ = A as A is symmetric).
Therefore:- A . [Adj(A)]$^t$ = [Adj(a)]$^t$ . A = |A| I.We also know adjoint of a matrix is unique therefore Adj(A)=[Adj(A)]$^t$.
But in above case we have assumed |A| $\not=$ 0. So if we define Adjoint of a matrix such A . Adj (A) = Adj (A) A = |A| I , then adjoint of matrix A is not unique if |A|=0. And if we define adjoint as transpose of cofactor matrix then Adj (A) is unique.
So what is the correct defination of adjoint of a matrix? Is adjoint defined for  singular matrix? If 2nd defination is correct then is our statement valid for singular matrix ? If yes how to prove it?

2) If A is skew symmetric matrix of order n(where n is even) then Adj(A) is also skew symmetric . I used above method to prove it . Then again i have same doubts as in first question. How to prove it when |A|=0. And if Adj(A) is not defined for singular matrix then solve simply for transpose of cofactor matrix.(for the first question also)

3) transpose of cofactor matrix of a matrix of order n (odd) is symmetric if matrix is skew symmetric.
I did it for n=3 , but i don't how do it for general 'n'.Please provide a solution.
A = $$
\begin{bmatrix}
0 & a & b \\
-a & 0 & c \\
-b & -c & 0 \\
\end{bmatrix}
$$
Transpose of cofactor matrix:-
$$
\begin{bmatrix}
c^2 & -bc & ca \\
-bc & b^2 & -ab\\
ca & -ab & a^2 \\
\end{bmatrix}
$$

Please tell me if i made any mistake in my proof or if any of the given statement is wrong. thankyou for help!!

A: I was just making things complicated , it's actually very simple.
Adj(A$^t$)=[Adj(A)]$^t$
If A is symmetric [Adj(A)]$^t$ = Adj(A$^t$) =Adj(A)
If A is skew symmetric [Adj(A)]$^t$ = Adj(A$^t$) = Adj(-A)
(We know that Adj(kA)= k$^{n-1}$ A) = -Adj(A) if n is even and Adj(A) if n is odd.


text:
Q: How to deploy yii2 with a web root other than /web I am working on a yii2 project, and would like to deploy it to an apache server where the entire website is expected to exist in the /public_html directory, and /public_html is the web root for that host. The issue is that yii2 expects the web root to be /web, and it expects most of the site hierarchy to exist outside of the /web directory.
I would prefer not to have to change the webroot to /public_html/web, and for future projects, it may not be an option. So, is there a way to place the entire site hierarchy in /public_html , and still have the site work correctly?
I have tried creating a /public_html/.htaccess file with the following contents:
    RewriteEngine on
    RewriteCond %{REQUEST_URI} !web/
    RewriteRule (.*) /web/$1 [L]

And this seemed to work correctly, at first. Nothing outside of /public_html/web was accessible, and files within subdirectories of /web, such as /web/js/signup.js which could be accessed via the url http://localhost/js/signup.js, but this caused my routing rules (which were set up on a local system where I could have the web root pointing at /web) to no longer be recognized.
So, I would be happy with either an alternate to the .htaccess route, or a suggestion to how to fix the routing rules so that the .htaccess route would work.
Edit for Clarification
I have a hosting provider where the web root is ~/public_html . Yii has documentation explaining that you can rename www to public_html, and have everything that would normally be outside of /www located in ~, along with the various dotfiles and user-documents that Linux normally places in ~. I would prefer to have all site-related directories together (under the webroot).
As an alternative, a two-directory structure, such as the following would work:
~/
 |--- (Various dotfiles and subdirectories unrelated to the web site)
 |--- yii - Contains all subfolders that should be outside of the web root
      |--- commands
      |--- config
      |--- controllers
      |--- (etc...)
 |--- public_html - Contains everything that can be within the web root.
      |--- (etc...)

A: This has been asked so many times that they made a page for it in the Yii2 docs.
I personally answered this too many times to remember.

A: This can be done via the use of aliases.
Move your web directory to the new webroot (assuming ~/mysite.com is your existing site):
rm -rf ~/public_html
mv ~/mysite.com/web ~/public_html

Then, you move everything that was outside of your webroot to the new directory:
mv -prf ~/mysite.com ~/mysite.example-external

At this point, you should have a web root at ~/public_html , and you should have everything else in ~/mysite.example-external. You then edit your ~/public_html/index.php file. Please note that this is not considered part of yii core, so it's ok to modify it. The new index should have some variation on this:
<?php

// comment out the following two lines when deployed to production
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');

$thepath = __DIR__ . '/../mysite.example-external';

require( $thepath . '/vendor/autoload.php');
require( $thepath . '/vendor/yiisoft/yii2/Yii.php');

$config = require( $thepath . '/config/web.php');

(new yii\web\Application($config))->run();

From here, you also have to add aliases to your ~/mysite.example-external/config/web.php file, so yii can find its core files. In the web.php, at the point where $config is assigned a value, modify it to look something like the following:
$config = [
    'aliases'   => [
        'webroot/assets' => '/Users/XXXXXX/mysite.example-external/web/assets',
        'root' => '/Users/XXXXXX/mysite.example-external/web',
    ],


text:
Q: Log4cpp Naming Collision for 'DEBUG' detected. Issue
When compiling my project, I get an error with the log4cpp files. The error is the following :
/usr/include/log4cpp/Priority.hh:49:2: erreur: #error Naming collision for 'DEBUG' detected. Please read the FAQ for a workaround.
The file
The file referenced by this error is a header installed with Log4cpp. Here it is. The errors are on lines 49, 78 and 109
/*
 * Priority.hh
 *
 * Copyright 2000, LifeLine Networks BV (www.lifeline.nl). All rights reserved.
 * Copyright 2000, Bastiaan Bakker. All rights reserved.
 *
 * See the COPYING file for the terms of usage and distribution.
 */

#ifndef _LOG4CPP_PRIORITY_HH
#define _LOG4CPP_PRIORITY_HH

#include <log4cpp/Portability.hh>
#include <string>
#include <stdexcept>

/*
 * Optionally work around rudeness in windows.h on Win32.
 */
#ifdef ERROR
#ifdef LOG4CPP_FIX_ERROR_COLLISION

namespace log4cpp {
    static const int _tmpERRORValue = ERROR;
}

#undef ERROR
    static const int ERROR = log4cpp::_tmpERRORValue;
#define ERROR ERROR

#else  // LOG4CPP_FIX_ERROR_COLLISION
#error Naming collision for 'ERROR' detected. Please read the FAQ for a \
       workaround.
#endif // LOG4CPP_FIX_ERROR_COLLISION

#endif // ERROR

/*
 * Other Win32 rudeness in EDK.h
 */
#ifdef DEBUG

#ifdef LOG4CPP_FIX_ERROR_COLLISION

#undef DEBUG
#define DEBUG DEBUG

#else  // LOG4CPP_FIX_ERROR_COLLISION
#error Naming collision for 'DEBUG' detected. Please read the FAQ for a \
       workaround.
#endif // LOG4CPP_FIX_ERROR_COLLISION

#endif // DEBUG

namespace log4cpp {

    /**
     * The Priority class provides importance levels with which one
     * can categorize log messages.
     **/
    class LOG4CPP_EXPORT Priority {
        public:

        static const int MESSAGE_SIZE; // = 8;

        /**
         * Predefined Levels of Priorities. These correspond to the
         * priority levels used by syslog(3).
         **/
        typedef enum {EMERG  = 0,
              FATAL  = 0,
                      ALERT  = 100,
                      CRIT   = 200,
                      ERROR  = 300,
                      WARN   = 400,
                      NOTICE = 500,
                      INFO   = 600,
                      DEBUG  = 700,
                      NOTSET = 800
        } PriorityLevel;

        /**
         * The type of Priority Values
         **/
        typedef int Value;

        /**
         * Returns the name of the given priority value.
         * Currently, if the value is not one of the PriorityLevel values,
         * the method returns the name of the largest priority smaller
         * the given value.
         * @param priority the numeric value of the priority.
         * @returns a string representing the name of the priority.
         **/
        static const std::string& getPriorityName(int priority) throw();

    /**
     * Returns the value of the given priority name.
     * This can be either one of EMERG ... NOTSET or a
     * decimal string representation of the value, e.g. '700' for DEBUG.
     * @param priorityName the string containing the the of the priority
     * @return the value corresponding with the priority name
     * @throw std::invalid_argument if the priorityName does not
     * correspond with a known Priority name or a number
     **/
        static Value getPriorityValue(const std::string& priorityName)
    throw(std::invalid_argument);
    };
}

#endif // _LOG4CPP_PRIORITY_HH

Research
The only FAQ referencing this issue was I found was on log4cpp's Sourceforge. Here is what it says :

This is caused by the rudeness of some platforms, which mutilate the
  namespace with some blunt #defines. To be more precise, the Win32 API
  includes #defines of 'ERROR' and 'DEBUG'. Since the preprocessor is
  unaware of C++ naming scopes this results in reserving the words ERROR
  and DEBUG litterally everywhere. In particular this conflicts with
  log4cpp::Prioritiy::ERROR and log4cpp::Priority::DEBUG. These latter
  two names come from log4j, so they are not something we made up
  ourselves. They Win32 authors should not have rudelessly claimed these
  generic names through the preprocessor. There are much better
  alternatives:
If they use it as an integer constant, declare it using a language construct. Either 'enum {ERROR=1};' or 'static const int ERROR=1;'

would do fine.
      Use a less generic name like WIN32API_ERROR to make naming conflicts less likely
      In case they use it as a flag for conditional compilation, use '#define DEBUG DEBUG' and '#if defined(DEBUG)'. In that case the
  preprocessor would simply replace all occurrences of 'DEBUG' in the
  source code with 'DEBUG', in effect leaving everything intact.
Of course the proper solution would be if the offending party would
  use one of the above methods, but we could have to wait some time for
  this to actually happen. As an alternative log4cpp can workaround
  these #defines. The workaround code is enabled by doing #define
  LOG4CPP_FIX_ERROR_COLLISION 1 before #including any log4cpp header
  files and after #including all platform headers. For Win32 platforms
  this #define has already been included in log4cpp/config-win32.h.
Once log4cpp has been updated to the log4j 1.2 API we can get rid of
  this problem by adopting the new names for log levels.

Context
The thing is, I am not supposed to change the source code. I can only modify compilation configuration files (this project uses Apache Ant builder, build.xml files and bash scripts).
I'm quite new to this project and I can't ask the previous developper for help.
Question
Has anybody encountered this error before ? Is there any possible workaround other than changing the source codes and it's defines ? Are my environment variables the cause ?
I will continue my search, but any insight would be usefull. Thanks !

A: Like it says in the docs, you need to define LOG4CPP_FIX_ERROR_COLLISION. If you are not allowed to modify any source, you should be able to do it in your build.xml:
<define name="LOG4CPP_FIX_ERROR_COLLISION" value="1" />


text:
Q: Does including scripts in the head makes loading slower? Google says i have to put this files in the head of a document :
 <script src="https://www.gstatic.com/firebasejs/6.2.0/firebase-app.js"></script>
 <script src="https://www.gstatic.com/firebasejs/6.2.0/firebase-firestore.js"></script>

There are 6-8 scripts like this.
The point is that i do not need them before i load my html, only later.

*

*does my html body waits till it load all of these ?

*why Google explicitly advice to put them on the head and not after my html?

A: You can attach async tag to those scripts to prevent them from blocking the whole page.

A:
does my html body waits till it load all of these ?

If you detach the scripts using async your html body dont wait

why Google explicitly advice to put them on the head and not after my html?

I think firebase recommends to add it in the body  https://firebase.google.com/docs/web/setup
<body>
  <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->

  <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->
  <script async src="/__/firebase/6.3.1/firebase-app.js"></script>

  <!-- Add Firebase products that you want to use -->
  <script async src="/__/firebase/6.3.1/firebase-auth.js"></script>
  <script async src="/__/firebase/6.3.1/firebase-firestore.js"></script>
</body>

A: *

*There's option which you can attach script with async event, so it cannot interrupt with loading html body. Example :

*In my opinion, attach in near head because some people can forget to attach in the body. Not in after html tag, maybe before closing html tag. Some people code can be different.


text:
Q: equals() method? shouldn´t one pass an object to equal?
    String hej = pets.getBark();
    if(hej.equals("woff"))

why are you able to pass a string woff?

A: If I understand your question properly you are wondering why a literal string value can be passed to a method that accepts an argument of type String.  This is because a string literal is a shorthand for a String instance (either a new instance or a previously created instance that has been preserved by means of interning):

The String class represents character
  strings. All string literals in Java
  programs, such as "abc", are
  implemented as instances of this
  class.

A: A quoted string is an object.  It is an instance of the String class.

A: Under the hood, a string literal ( text inside quotes ) automatically is replaced by String instance. ( a string literal is shorthand for new String )
That is why this code works: String hello = "hello";
So,
 String hej = pets.getBark();
 if( hej.equals( new String("woff") ) ) {}

is identical to the code you provided.

A: You can pass java.lang.String, a subtype of java.lang.Object, because Liskov substitution principle says so.

A: A literal string is still of type String.