text:
Q: Having trouble with my XML: using layout_above in Relative Layout I have an EditText that I want to autosize until it hits the top of my button underneath. The button needs to stay at the bottom of the screen so I can't use android:layout_below. I want to use android:layout_above but VS spits the error

No resource found that matches the given name (at 'layout_above' with value '@id/_buttonSave1').

Here's my layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:minWidth="25px"
    android:minHeight="25px">
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/_editTextNoteTitle1"
        android:textSize="30dp"
        android:typeface="sans"
        android:text="Title" />
    <TextView
        android:text="Date"
        android:textSize="15dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_below="@id/_editTextNoteTitle1"
        android:id="@+id/_textViewNoteDate1" />
    <EditText
        android:inputType="textMultiLine"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/_editTextNoteBody1"
        android:text=""
        android:textSize="20dp"
        android:layout_below="@id/_textViewNoteDate1"
        android:layout_above="@id/_buttonSave1"
        android:layout_centerInParent="true"
        android:scrollbars="horizontal" />
    <Button
        android:id="@+id/_buttonSave1"
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:layout_marginRight="8dp"
        android:background="@drawable/update"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true" />
</RelativeLayout>

A: The id is defined in the Button after it is referenced in EditText.
Instead build your layout by first defining the button, and then defining the EditText to be above.


text:
Q: C++ std::list::iterator Does the iterator have acces to  member functions? This is my first time posting here at SO, but I've been utilizing the answers and help here for a while now.
I'm working on a simple card game right now that I've been planning on and off for a few years. Ultimately it's going to be my senior project for school(not asking anyone to do my homework for me!)
I'm experienceing an issue right now when trying to pint the contents of a list to the console through a couple classes.
for(std::list<Card>::iterator it = Hand.begin(); it != Hand.end(); it++)
    std::cout<< *it.GetName();

I'm trying to figure out if the line
std::cout<< *it.GetName();

is going to be valid or not. I'm troubleshooting from work and I don't have the ability to try anything right now. Before I had to drop the project this morning I was having some compile errors that lead me to believe I needed to overload the << operator which I tried and ended up getting a couple linking errors for some reason.
I've been researching most of the day, but haven't come across any situations that jumped out at me as the correct solution, but this little block is what I've found that seems the most correct for what I'm trying to do.
Will that block print the names of the Card Objects stored in the Hand list as is right now? Yes, the Card Class does have that GetName() function and it is declared correctly.

A: *it.getName();

is the same as
*(it.getName());

since . and function call have higher precedence than unary *.  So the compiler looks for a member getName in class std::list<Card>::iterator, but there isn't one: getName is (I assume) a member of Card, and iterators don't have any inheritance or forwarding relationship to their object.
You probably meant
(*it).getName();

or equivalently,
it->getName();

(The arrow -> operator is just a short cut for dereferencing and then naming a member.)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Error in Custom Blade Directives with array as parameter In my Laravel 5.7 app I want to use Custom Blade Directives and to pass an array in this directive
as there could be different access, like :
@loggedUserHasAccess([USER_ACCESS_ADMIN])

        Backend

@endLoggedUserHasAccess

And in app/Providers/AppServiceProvider.php :
class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {

        ...

        \Blade::directive('loggedUserHasAccess', function (array $accessArray) {
            $condition = false;

            if (Auth::check()) {
                $loggedUser  = Auth::user();
                $usersGroups = User::getUsersGroupsByUserId($loggedUser->id, false);
                foreach ($usersGroups as $next_key => $nextUsersGroup) {
                    if (in_array($nextUsersGroup->group_id, $accessArray)) {
                        $condition = true;
                    }
                }
            }
            return "<?php if ($condition) { ?>";
        });

        Blade::directive('endLoggedUserHasAccess', function () {
            return "<?php } ?>";
        });

But I got syntax error : https://imgur.com/a/I5s1TmQ
USER_ACCESS_ADMIN is defined in bootstrap/app.php.
looks like my syntax is invalid, but which is valid ?
Thanks!


text:
Q: How can i sort Jquery Datatable currency Column properly? I am  using  Datatables  Version 1.10.12  and  jquery-1.11.1
My  currency  column  doesn't sort properly,below is the code I am using to sort
$(document).ready( function () {
        $('#notSoCoolGrid').DataTable({
            "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
            columnDefs: [{ type: 'currency', targets: 1 }],
            "aaSorting": [[ 2, 'asc' ]]
        } );
    } );

And I am getting as shown below for my currency column.Please  note   brackets(  ) are considered negative number
($75.00) USD
($108.87) USD
($249.44) USD
($1,000.00) USD
£899.00 GBP
$905.00 AUD
£830.65 GBP
$825.00 USD
£59.67 GBP

A: Use brackets-negative sorting plug-in. Your code can stay the same, you just need to include extra JS file //cdn.datatables.net/plug-ins/1.10.13/sorting/brackets-negative.js.

A: Below is what  finally  works out for me,i have to consider the exchange rate as well.
<link href="datatables/1.10.13/css/jquery.dataTable.min.css" type="text/css" rel="stylesheet" />
    <script src="js/jQuery/1.11.1/jquery.js"></script>
    <script src="datatables/1.10.13/js/jquery.dataTables.js"></script>
    <script>
        $(document).ready( function () {
            var currencies = { GBP: 1.2403, AUD: 0.7364, USD: 1 };
            $.fn.dataTable.ext.type.order['currencies-pre'] = function(d) {
                var sign = /\([^)]*\)/.test(d)?-1:1;
                var currency = currencies[d.match(/USD|GBP|AUD/).pop()]; // /!\ all MUST have currency
                var n = d.replace(/[^\d.]/g,"");
                console.log(sign * n * currency);
                return sign * n * currency;
            };
            $('#notSoCoolGrid').DataTable({
                "aoColumns": [{ sWidth: "10%", bSearchable: false, bSortable: false }, { sWidth: "90%", bSearchable: false, bSortable: true }],
                "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
                "columnDefs": [{ type: 'currencies', targets: 1 }],
                "aaSorting": [[ 1, 'asc' ]]
            });
        });
    </script>


text:
Q: UIView parent window's frame and bound dimensions while rotating iPad I a have a following line of code invoked after a touch gesture has completed:
CGRect parentBounds = self.view.bounds;
CGRect parentFrame = self.view.frame;

when iPad is placed in a vertical way both parentFrame and parentBounds have similar dimensions of w:768 h:1004 (or something close to that), but when I rotate parentBounds is 1024x748 while parentFrame is 768x1024.
Is this behavior normal? I thought I understood the concepts beetwen frames and bounds (and how they relate to each other)... but now I am really confused.
Could anyone explain what is happening with frame and bounds of a window (superview) when rotation occurs?

A: The window does not change orientation; the root view does. It does this by applying a view transform (self.view.transform). You're not supposed to call frame if transform is not CGAffineTransformIdentity.

A: This is not a complete answer, but might help if you don't get something better: When the device is rotated, the top-level window's frame does not change.  Instead, a transform gets applied that rotates everything 90 degrees (or 180 degrees), and then the subviews will get resized to fit in the new coordinate system.

A: From Apple's PhotoScroller sample code:

We have to use our paging scroll view's bounds, not frame, to calculate the page placement. When the device is in landscape orientation, the frame will still be in portrait because the pagingScrollView is the root view controller's view, so its frame is in window coordinate space, which is never rotated. Its bounds, however, will be in landscape because it has a rotation transform applied.

In short, the view's frame is not affected by device rotations, but its bounds is.


text:
Q: MVC - filterContext.ExceptionHandled Does the filterContext.ExceptionHandled property ever get set to true by MVC or is it only set to true by user code? If so where does this happen?

A: filterContext.ExceptionHandled get set to true when an exception is thrown by an action method. By default HandleErrorAttribute has been added in FilterConfig class which is registered in Application_Start(). When an exception occurs, the OnException method is called in HandleErrorAttribute class.
In OnException method, before removing the current HTTP response body by using  Response.Clear(), the ExceptionHandled  property will set to true.
Below is the default OnException method:
public virtual void OnException(ExceptionContext filterContext)
{
    if (filterContext == null)
    {
        throw new ArgumentNullException("filterContext");
    }
    if (filterContext.IsChildAction)
    {
        return;
    }
    if (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled)
    {
        return;
    }
    Exception exception = filterContext.Exception;
    if (new HttpException(null, exception).GetHttpCode() != 500)
    {
        return;
    }
    if (!ExceptionType.IsInstanceOfType(exception))
    {
        return;
    }
    string controllerName = (string)filterContext.RouteData.Values["controller"];
    string actionName = (string)filterContext.RouteData.Values["action"];
    HandleErrorInfo model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);

    filterContext.Result = new ViewResult
    {
        ViewName = View,
        MasterName = Master,
        ViewData = new ViewDataDictionary<HandleErrorInfo>(model),
        TempData = filterContext.Controller.TempData
    };
    filterContext.ExceptionHandled = true;
    filterContext.HttpContext.Response.Clear();
    filterContext.HttpContext.Response.StatusCode = 500;
    filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
}


text:
Q: Get data from two collections - Firebase/Flutter I have got a question for my app. I have two collections which are called X and Y. I need to get data from specific field from those collections. "X" and "Y" collections have the same field like  "name". I have been trying to get the names from X and Y collections and list them on my page. My codes:
 getNames(myId) async{

    return await FirebaseFirestore.instance.collection("X").where('ID',isEqualTo: myId ).snapshots();
  }

I can get the name from X collection and list them on my page with this code. But I couldn't get the Y collections name at the same time with X and list them on my page.
Thanks for your interest and help in advance.

A:   getNames(myId) async{
    QuerySnapshot response1  = await FirebaseFirestore.instance.collection("X").where('ID',isEqualTo: myId ).get();
    QuerySnapshot response2 = await FirebaseFirestore.instance.collection("Y").where('ID',isEqualTo: myId ).get();
    List<DocumentSnapshot> list1 = response1.docs;
    list1.addAll(response2.docs);
    return list1;
}


text:
Q: Boost Python - debugging python code embedded in C++ I am using boost::python to embed python interpreter to my executable. I call python functions from C++ side. However, I cannot debug python side of the code. It seems that this is not a popular issue but I really need to debug the python code called from C++. It seems that visual studio has a support for this but I am using ubuntu. Is there a way that I can achieve debugging python code called from C++. I can use another library if boost::python does not support that.

A: Python has a native debugger called pdb. Use the lines:
import pdb
pdb.set_trace()

to start an interactive debugging session at any point in your python code.


text:
Q: ionic2 : content in slides not scrolling I have a couple of slides which have dynamic content that is added to them. The problem is the content inside of the slides doesn't scroll. So if I have a lot of items only some show and there is no ability to slide. How can I make it so the content in my lists slides inside of their slides?
<ion-content>
    <ion-slides (change)="onSlideChanged($event)">
        <ion-slide >
            <ion-list>
            <ion-item *ngFor="#item of items1; #i = index">

{{item}

            </ion-item>
            </ion-list>
        </ion-slide>
         <ion-slide>
                 <ion-list>
            <ion-item *ngFor="#item of items2; #i = index">

{{item}

            </ion-item>
            </ion-list>
        </ion-slide>
    </ion-slides>
</ion-content>

A: I have the same problem,and I solve it like this:
    <ion-slides style="height: auto">
       <ion-slide *ngFor="#item of items">

{{item.title}}

{{item.description}}

       </ion-slide>
    </ion-slides>

A: Looks like you need to wrap your long content in a <scroll-content> inside of each <ion-slide>, for example:
<ion-slides>
    <ion-slide *ngFor="#item of items">
      <scroll-content>

{{item.title}}

{{item.description}}

      </scroll-content>
    </ion-slide>
</ion-slides>

Note, you may need to do a text-align:left if you want the text to not be centered, since thats the default for content in <ion-slide>.

A: Setting style='height:auto' as stated in booyoungxu's answer disables sliding after you swipe on the first slide. style='overflow:scroll' works best.
<ion-slides style="height: auto">
...
</ion-slides>

A: In controller, put:
ngAfterViewInit() {
  this.slides.autoHeight = true;
}


text:
Q: identify sequence in a list I have a large list of real numbers, that vary between a maximum and a minimum.
For the sake of an example: megalist=RandomReal[{-5, 5}, 10^4].
Now, I have a much smaller list such as  minilist={0.3,1,-0.5} and I would like to see whether minilist is contained inside megalist, within a certain tolerance on each component of the list, let us say +-0.1.
In other words: whether megalist contains a sublist such as: {0.3+-0.1,1+-0.1,-0.5+-0.1}.
And, if it exists, I would like to get its position.
Any help is appreciated.

A: You can create a list of subsequences of length 3 using Partition and use Nearest with distance function ChessboardDistance (thanks: @CarlWoll ):
nF = Nearest[Partition[megalist, 3, 1] -> {"Element", "Index"},
  DistanceFunction -> (Norm[# - #2, Infinity] &)]

The function nF[x] returns the subsequences of megalist and their positions nearest x.
There are no subsequences within distance .1 of minilist:
nF[minilist, {All, .1}]

{}

There are 2 within distance .25:
nF[minilist, {All, .2}]

{{{0.473371, 1.18655, -0.703937}, 4590},
{{0.473238, 1.2483, -0.690072}, 6032}}


text:
Q: CSS - Setting buttons to 150% their recommended size I have a HTML button on a webpage in which the text turns bold upon hover. However, when this happens the button gets bigger, which I don't want to have to happen. I have therefore used some simple JavaScript to make the buttons 150% their size upon document.ready. However, I am trying to minimise use of JS, so is this possible in CSS alone?
Code sample:
<button id="b1">Test</button>

Thanks in advance,
-- Matthew

A:

  .btn1{
 background:#0095ff;
 border:0;
 outline:0;
 font-weight:400;
 color:#fff;
 font-size: 16px;
 padding: 6px 15px;
 transition: all .4s ease;
 cursor:pointer;
 text-transform:uppercase;
    }
    .btn1:hover{
 font-weight:600;
        background:#07c;
    }

    .btn2{
 background:#0095ff;
 border:0;
 outline:0;
 font-weight:400;
 color:#fff;
 font-size: 16px;
 padding: 6px 15px;
 transition: all .4s ease;
 cursor:pointer;
 text-transform:uppercase;
 min-width:150px;
    }
   .btn2:hover{
 font-weight:600;
 background:#07c;
    }
    This might be the Problem :
    <button class="btn1">Hello</button>

    Solution - need to add min-width or width in button
    <button class="btn2">Hello</button>


text:
Q: Manipulate in modal mode It is sometimes convenient to use Manipulate to set up global values which are to be used in the rest of the notebook. In such cases one can select and run the notebook up to the cell containing Manipulate, use the dynamic interface, and subsequently select and run the remainder of the notebook.
But it would be great to evaluate the whole notebook with the "Evaluate Notebook" menu item, and have the evaluation pause after the Manipulate, then continue when the user clicks a button indicating that they are done manipulating.
A simple example (each line represents a separate cell):
Manipulate[amazingGraphics[y], {y, 0, 1}, Button["Done", global = y^2]]

(* evaluation pauses here until the button is clicked *)

doSomeStuff[global]

doSomeMoreStuff[]

etc[]

How can this be achieved?

A: Taking inspiration from Kuba's answer I went digging in DialogInput and found the undocumented function WaitUntil which is used to pause evaluation until its argument is True. So this works:
a = 1;
Column[{
  Manipulate[Plot[Sin[x (1 + a x)], {x, 0, 6}], {a, 0, 2}, LocalizeVariables -> False],
  $done = False; DefaultButton[$done = True]
  }]

next cell...
WaitUntil[$done];
a

Here's a picture of the notebook before the button is clicked. I used "Evaluate Notebook" from the menu and the evaluation has paused at WaitUntil, allowing me to use the Manipulate controls to set a and then click the button to continue the evaluation:

A: I'd go with DialogInput or friends:
a = 1;

DialogInput@
 Column[{Manipulate[Plot[Sin[x (1 + a x)], {x, 0, 6}], {a, 0, 2},
    LocalizeVariables -> False], DefaultButton[]}]

a


text:
Q: Cake php upgrade showing error I am new in cake php development, I have done a cake php upgrade from 2.7.5 to latest version 3. but i have some issues, when i try to run bin/cake server it shows below errors.

PHP Warning:  include(Cake/Console/ShellDispatcher.php): failed to
  open stream: No such file or directory in
  /var/www/project_1/bin/cake.php on line 31 PHP Warning:  include():
  Failed opening 'Cake/Console/ShellDispatcher.php' for inclusion
  (include_path='/var/www/lib:.:/usr/share/php') in
  /var/www/project_1/bin/cake.php on line 31
PHP Fatal error:  Could not locate CakePHP core files. in
  /var/www/project_1/bin/cake.php on line 32

I can see the file cake.php which does not have any change but all other files moved from app to src folder, using cake php upgrade tool


text:
Q: Need to change container's colors temporarily I have a container that functions as a button. Upon clicking the container, a bottom modal sheet pops up from the bottom. How do I make it so that the container's background color and elements inside the color temporarily change color while the bottom modal sheet is up and displayed? Please note I do not wish to change the container of the bottom modal sheet itself.

A: you can do following

*

*Create a variable in your state class which is equals to the color of the container. Initially it will be the color you want to show the user when button is active.

*Once, button is clicked, just before calling showBottomModalSheet, change color value and call setState.

*You can await showBottomModalSheet and reverse back to original color and call setState afterwards.

You will have to make you onPressed/onTap async method.


text:
Q: Increase textarea's height with text Can a textarea adapt it's height while inserting text?
I want to hide the textarea's borders, so that users feel they'r typing in an unlimited space.
(The textarea's height should be increased by height of one line when a new line starts)
One way I guessed, is to; copy all texts into a div with same width on each keystroke, then measure the height of the div, then set the div's height for textarea.
One problem I noticed, is scroll bars width that should be subtracted from main width, and on different devices we have 0 to 16px variable scroll bar width..., any suggestions?

A: Here is What you want
First: html here is the text area with id : ta

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <textarea rows="10" cols="10" id="ta">
    </textarea>

And here is the jquery code which works as follows:
which increases the height (the rows number) of the text area each time you get into the last line

  $('#ta').keypress( function(){
                    var rows=$('#ta').attr('rows');
                    var text=$('#ta').val();
                    var lines=text.split('\n');
                    if(lines.length==rows){
                        rows++;
                        $('#ta').attr('rows',rows);
                    }
                });

And this css just for hide the border of the textarea so the user feels that he/she writes in the page

#ta{
      border: 0;
      }

A: You can easily achieve what you're trying to do using elastic.js, it's a simple one-line solution.

$('#note').elastic();
textarea#note {
 width:100%;
 display:block;
 resize: none;
 border: none;
}
textarea:focus {
 outline: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://jquery-elastic.googlecode.com/svn-history/r37/trunk/jquery.elastic.js"></script>
<textarea id="note">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.</textarea>


text:
Q: Excel perform specific validation on cells I'm looking to try and do two separate types of validation.

*

*Is it possible to configure validation on a cell to check the first character in that cell and it must be a letter ?

Eg. Anything starting with A-Z case insensitive is fine.

*Is is possible to set a cell so it can only contain a number ?

I've got the number check working using =ISNUMBER(J1) that seems to only allow numbers.
I'm trying to check the first character and have tried:
=ISTEXT(LEFT(B10,1)) but that doesn't seem to do what I was hoping..
Thanks

A: Checking if the whole cell is text is easy with just a simple formula, but if you want to check for only the first letter, then it's more involved.
To ensure that the first character is NOT a number, you can use the custom validation formula
=NOT(ISNUMBER(SUM(LEFT(A1,1),0)))

That will still allow special characters llike $ or & etc. as the first character. If you only want to allow a-z and A-Z as the first letter, then use
=AND(CODE(LEFT(A1,1))>=56,CODE(LEFT(A1,1))<=122)

To allow only numbers, use the built in validation options for Decimal or Whole Number.

A: *

*Select one or more cells to validate.

*Open the Data Validation dialog box.

*For this, click the Data Validation button on the Data tab, in the Data Tools group or press
the key sequence Alt > D > L (each key is to be pressed separately).

*On the Settings tab of the Data Validation dialog window, select Custom in the Allow box, and enter your data validation formula in
the Formula box.

*Click OK.

For text only in a cell build a custom rule with the ISTEXT function, for example:
=ISTEXT(D2)
Custom rule for numbers only in a cell using ISNUMBER.
=ISNUMBER(D2)
Reference: https://www.ablebits.com/office-addins-blog/2017/08/17/use-data-validation-excel-custom-rules-formulas/


text:
Q: Loadrunner WebServices Error socket connection aborted I'm hitting a nettcp based WCF Service using LR VuGen 12.02 and Web Services protocol by importing the WSDL of the Service.
After composing a request and trying to send it, I'm getting the following error. which actually works fine from the WPF Client but fails from the LR VuGen Script
    Action.c(16): Error:The socket connection was aborted. This could be caused by an error processing your message or a receive timeout being exceeded by the remote host, or an underlying network resource issue. Local socket timeout was '00:59:59.9949990'.
Error: An existing connection was forcibly closed by the remote host

Server stack trace:
   at System.ServiceModel.Channels.SocketConnection.ReadCore(Byte[] buffer, Int32 offset, Int32 size, TimeSpan timeout, Boolean closing)
   at System.ServiceModel.Channels.SocketConnection.Read(Byte[] buffer, Int32 offset, Int32 size, TimeSpan timeout)
   at System.ServiceModel.Channels.DelegatingConnection.Read(Byte[] buffer, Int32 offset, Int32 size, TimeSpan timeout)
   at System.ServiceModel.Channels.ClientFramingDuplexSessionChannel.SendPreamble(IConnection connection, ArraySegment`1 preamble, TimeoutHelper& timeoutHelper)
   at System.ServiceModel.Channels.ClientFramingDuplexSessionChannel.DuplexConnectionPoolHelper.AcceptPooledConnection(IConnection connection, TimeoutHelper& timeoutHelper)
   at System.ServiceModel.Channels.ConnectionPoolHelper.EstablishConnection(TimeSpan timeout)
   at System.ServiceModel.Channels.ClientFramingDuplexSessionChannel.OnOpen(TimeSpan timeout)
   at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
   at System.ServiceModel.Channels.ServiceChannel.OnOpen(TimeSpan timeout)
   at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
   at System.ServiceModel.Channels.ServiceChannel.CallOpenOnce.System.ServiceModel.Channels.ServiceChannel.ICallOnce.Call(ServiceChannel channel, TimeSpan timeout)
   at System.ServiceModel.Channels.ServiceChannel.CallOnceManager.CallOnce(TimeSpan timeout, CallOnceManager cascade)
   at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
   at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
   at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)

Exception rethrown at [0]:
   at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
   at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
   at HP.WcfRouter.IUniversalContract.Send(Message message)
   at HP.WcfRouter.WcfRouter.DoRequestInternal(Boolean isOneWay, Dictionary`2 context)
Action.c(16): Error:InvokeMethod failure: External component has thrown an exception..
Action.c(16): Error:ExtractResultArg failure: Object reference not set to an instance of an object..
Action.c(16): Error:Web service call "GetTopicsByUserID" execution failed

I have tried out many suggestions relevant but with no luck
For your reference:
Increasing Timeouts and maxItemsInObjectGraph and many more such posts on StackOverflow such as
Socket Connection Aborted-StackOverflow post
Any help is deeply appreciated.

A: Web Services will only work for HTTP binding, not NetTCP binding.   For NetTCP binding the way to go is with a virtual user in Visual Studio.  Use your client source to build a shell to pass your request.   You will still have access to the parameterization engine and run time settings from inside of Visual Studio


text:
Q: Change file names by Perl How to change file names from notation like this: SomeCodeFile.extension to C/C++ notation: some_code_file.extension. I'd like to use Perl + Find + Regex to print those names.

A: You can use a regular expression:
perl -e 'for $f (@ARGV) {
             ($n = $f) =~ s/(?<=.)([[:upper:]])/_\l$1/g;
             rename $f, lcfirst $n;
         }' SomeCodeFiles*

*

*[[:upper:]] matches upper case letters.

*(?<=.) is a look behind assertion, i.e. the letter is preceded by something (we don't want _some_code_file.ext)

*\l changes the following letter to lowercase (similarly to lcfirst)

Note that the result might be unpleasant in some situations (x_m_l2_j_s_o_n.c, u_r_l__validator.cpp).


text:
Q: keras pre-trained model feed a new input placeholder I have a model that has been trained. like this
model_inceptionv3_conv = InceptionV3(weights='imagenet', include_top=False)
for layer in model_inceptionv3_conv.layers:
    layer.trainable = False
x = model_inceptionv3_conv.output
x = GlobalAveragePooling2D()(x)
predictions = Dense(NB_CLASSES, activation='sigmoid', name='predictions')(x)
my_model = Model(inputs=model_inceptionv3_conv.input, outputs=predictions)
my_model.fit(...)

now I wan't feed a placeholder to this model, but it occured some value have uninitialized. Does this code preds = model(x) will generate a new graph?
x = tf.placeholder(tf.float32, shape=(None, 299, 299,
                                          3))
preds = model(x)
sess.run(preds, feed_dict={x: x_val})

error
FailedPreconditionError: Attempting to use uninitialized value batch_normalization_86/moving_mean......

A: your error is here:
preds = my_model(x)

it should be:
preds = my_model.predict(x)

here is a working example:
NB_CLASSES = 2
model_inceptionv3_conv = InceptionV3(weights='imagenet', include_top=False)
for layer in model_inceptionv3_conv.layers:
    layer.trainable = False
x = model_inceptionv3_conv.output
x = GlobalAveragePooling2D()(x)
predictions = Dense(NB_CLASSES, activation='softmax', name='predictions')(x)
my_model = Model(inputs=model_inceptionv3_conv.input, outputs=predictions)
test_img = np.random.rand(1,299,299,3)
preds = my_model.predict(test_img)

Have fun!

A: If you want to add a new placeholder to the graph then you have to follow these steps:-

*

*Save the weights of your model in one file using my_model.save() function

*construct graph again with addition of your placeholder and the load your model weights

Here is a working example -
input_layer = tf.placeholder(tf.float32, shape=(None, 299, 299,3))
model_inceptionv3_conv = InceptionV3(weights='imagenet', include_top=False, input_tensor=input_layer)
for layer in model_inceptionv3_conv.layers:
    layer.trainable = False
x = model_inceptionv3_conv.output
x = GlobalAveragePooling2D()(x)
predictions = Dense(NB_CLASSES, activation='sigmoid', name='predictions')(x)
my_model = Model(inputs=input_layer, outputs=predictions)

my_model.load_weights('model.h5')

now you can use my_model.predict() or sess.run() for prediction like -
sess.run(predictions, feed_dict={input_layer: x_val})

or
my_model.predict(x_val)

you can also refer to my GitHub jupyter notebook to see how to add preprocessing steps to your Keras model- https://github.com/CS-savvy/keras-preprocessing-inject/blob/master/keras%20inject.ipynb

A: If you want to get the gradient d(preds)/d(x), you can use K.gradients and wrap up into K.function.
from tensorflow.keras import backend as K

grad = K.gradients(my_model.output, my_model.input)
get_grad = K.function(my_model.input, grad)

test_data = np.random.rand(1,299,299,3)
res_grad = get_grad(test_img)

A: I find that there is a problem with my own code. I use a wrong sess. I use tensorflow.keras set sess before, but my original code is only based on keras, not tensorflow.keras.
Before
import tensorflow as tf
tf.keras.backend.set_session(sess)

After
import keras
keras.backend.set_session(sess)

And then, the code as follow can be run.  The uninitialized values are gone.
x = tf.placeholder(tf.float32, shape=(None, 299, 299,
                                          3))
preds = model(x)
sess.run(preds, feed_dict={x: x_val})


text:
Q: vi input mode in command line Matlab? I have these lines in my ~/.inputrc:
set editing-mode vi
set keymap vi

This allows me to use vi keybindings in every program that uses GNU readlines for text input.  Examples: python, irb, sftp, bash, sqlite3, and so on.  It makes working with a command line a breeze.  Matlab doesn't use readlines, but vi keybindings would be amazing to have when debugging or working interactively.  Is there an existing solution?
I tend to use matlab -nosplash -nodesktop from the command line and that got me thinking:  would it be possible to write a wrapper that does use readlines and pass the input to matlab?  (If I have to implement this, I'd probably prefer to do so in Ruby.)
Update:
Thanks for the help.  This almost works:
# See also: http://bogojoker.com/readline/
require 'readline'

puts 'Starting Matlab...'
io = IO.popen('matlab -nosplash -nodesktop 2>&1', 'w+')

while input_line = Readline.readline('>> ', true)
  io.puts input_line
  puts io.gets
end

But it only reads a single line from Matlab at a time (because I'm using gets).  Any ideas on how to get everything until the next time it's waiting for input?  Here's what's happening (I'm entering stuff at the >> prompt):
Starting Matlab...
>> 1

>> 2
                            < M A T L A B (R) >
>> 3
                  Copyright 1984-2009 The MathWorks, Inc.
>> 4
                 Version 7.8.0.347 (R2009a) 32-bit (glnx86)
>> 5
                             February 12, 2009
>> 6

>> 7

>> 8
  To get started, type one of these: helpwin, helpdesk, or demo.
>> 9
  For product information, visit www.mathworks.com.
>> 0

>> 1
>>
>> 2
ans =
>> 3

>> 4
     1
>> 5

>> 6
>>
>> 7
ans =
>> 8

>> 9
     2
>> 0

>> 1
>>
>> 2
ans =
>> 3

>> 4
     3

A: Yes, that should be easy enough.  It's just a special case of the general "open a process and bind to its stdin and stdout" problem, and that's not difficult.
A bit of Google searching finds that IO.popen() is the right piece of Ruby for that, and there's a little more detail in the replies here: http://groups.google.com/group/ruby-talk-google/browse_thread/thread/0bbf0a3f1668184c.  Hopefully, that's enough to get you started!
Update: Looks like you're almost there with your wrapper.  What you need to get finished is recognize when Matlab is asking for input, and only ask the user for input then.  I'd suggest trying this pseudocode:
while input_line = Readline.readline('>> ', true)
  io.puts input_line
  while ((output_line = io.gets) != '>> ')  // Loop until we get a prompt.
    puts io.gets
  end
end

That's not quite right, as you need to do the inner loop once before you ask for the first input line, but it should give you the idea.  You might need to adjust the prompt text that it's looking for, too.
Update 2: Okay, so we also need to account for the fact that there's no EOL after a prompt and so io.gets will hang.  Here's a revised version that uses the fact that you can give a blank line to a Matlab prompt and it will just give you another prompt without doing anything.  I've rearranged the loop to make things a little clearer, though this means you now have to add logic to figure out when you're done.
while [not done]   // figure this out somehow
  io.puts blank_line                        // This will answer the first
                                            // prompt we get.
  while ((output_line = io.gets) != '>> ')  // Loop until we get a prompt.
    puts io.gets                            // This won't hang, since the
  end                                       // prompt will get the blank
                                            // line we just sent.

  input_line = Readline.readline('>> ', true)  // Get something, feed it
  io.puts input_line                           // to the next prompt.

  output_line = io.gets   // This will eat the prompt that corresponds to
                          // the line we just fed in.
end

A: You could have used rlwrap in a straight-forward manner.
rlwrap is a wrapper that uses the GNU readline library to allow the editing
of keyboard input for any other command.

http://utopia.knoware.nl/~hlub/rlwrap/#rlwrap
Unfortunately it will block context-sensitive tab completion in MATLAB, which is useful on its own.

A: Actually, you might be better off writing this in C - then you can call the matlab engine directly. This basically allows you to write your own front-end to matlab, if you are so inclined, using the GNU Readline library.


text:
Q: Eliminating repeating code in python I'm trying to create a GUI in with PyQt4, I initially used QT designer to get my overall layout done and then modify the code afterwards. What I have noticed is that there is a lot of repeating code that would be replaced with wither a class or method but I'm not sure which would be better or how exactly to go about implementing either way properly. here is an example of the repeating code (its a very large program)
self.ch2_R = QtGui.QLineEdit(Form)
self.ch2_R.setSizePolicy(sizePolicy)
self.ch2_R.setText(_fromUtf8(""))
self.ch2_R.setFrame(True)
self.ch2_R.setAlignment(QtCore.Qt.AlignCenter)
self.ch2_R.setReadOnly(True)
self.ch2_R.setObjectName(_fromUtf8("ch2_R"))
print self.ch2_R

self.ch3_R = QtGui.QLineEdit(Form)
self.ch3_R.setSizePolicy(sizePolicy)
self.ch3_R.setText(_fromUtf8(""))
self.ch3_R.setFrame(True)
self.ch3_R.setAlignment(QtCore.Qt.AlignCenter)
self.ch3_R.setReadOnly(True)
self.ch3_R.setObjectName(_fromUtf8("ch3_R"))

self.ch4_R = QtGui.QLineEdit(Form)
self.ch4_R.setSizePolicy(sizePolicy)
self.ch4_R.setText(_fromUtf8(""))
self.ch4_R.setFrame(True)
self.ch4_R.setAlignment(QtCore.Qt.AlignCenter)
self.ch4_R.setReadOnly(True)
self.ch4_R.setObjectName(_fromUtf8("ch4_R"))

sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.ch2_R.sizePolicy().hasHeightForWidth())

sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.ch3_R.sizePolicy().hasHeightForWidth())

sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.ch4_R.sizePolicy().hasHeightForWidth())

self.gridLayout.addWidget(self.ch2_R, 4, 5, 1, 4)
self.gridLayout.addWidget(self.ch3_R, 5, 5, 1, 4)
self.gridLayout.addWidget(self.ch4_R, 6, 5, 1, 4)

this code is all within
from PyQt4 import QtCore, QtGui

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Ui_Form(object):
        def setupUi(self, Form):

My intial attempt was to creaet a method inside the Ui_Form class like this
def myQtlineEdit(self, name, form, sizePolicy):
        self.name = QtGui.QLineEdit(Form)
        self.name.setSizePolicy(sizePolicy)
        self.name.setText(_fromUtf8(""))
        self.name.setFrame(True)
        self.name.setAlignment(QtCore.Qt.AlignCenter)
        self.name.setReadOnly(True)
        self.name.setObjectName(_fromUtf8("%s" %name))

        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.name.sizePolicy().hasHeightForWidth())

self myQtlineEdit("ch2_R", form, sizePolicy)

It did create the text field I was looking for but the
self.gridLayout.addWidget(self.ch2_R, 4, 5, 1, 4)

would give me an error saying that ch2_R did no exsist
Thanks.

A: Instead of creating a attribute named ch2_R you are always assigning to attribute self.name, you should instead do this
def myQtlineEdit(self, name, form, sizePolicy):
    widget = QtGui.QLineEdit(Form)
    widget.setSizePolicy(sizePolicy)
    widget.setText(_fromUtf8(""))
    widget.setFrame(True)
    widget.setAlignment(QtCore.Qt.AlignCenter)
    widget.setReadOnly(True)
    widget.setObjectName(_fromUtf8("%s" %name))

    setattr(self, name, widget)

    sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed)
    sizePolicy.setHorizontalStretch(0)
    sizePolicy.setVerticalStretch(0)
    sizePolicy.setHeightForWidth(widget.sizePolicy().hasHeightForWidth())


text:
Q: cannot set headers after they are sent to the client - mongoose I want to write a small app that receives a welcome message via POST and returns it via GET. If I call only one method (GET or POST), there are no problems, but as soon as I call GET and POST, I get the following message:
events.js:174
      throw er; // Unhandled 'error' event
      ^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:470:11)
    at ServerResponse.header (C:\Users\aph\IdeaProjects\hello-world-node\ExpressApp\node_modules\express\lib\response.js:767:10)
    at ServerResponse.send (C:\Users\aph\IdeaProjects\hello-world-node\ExpressApp\node_modules\express\lib\response.js:170:12)
    at Greeting.find (C:\Users\aph\IdeaProjects\hello-world-node\ExpressApp\routes\hello.js:16:13)
    at C:\Users\aph\IdeaProjects\hello-world-node\node_modules\mongoose\lib\model.js:4568:16
    at C:\Users\aph\IdeaProjects\hello-world-node\node_modules\mongoose\lib\query.js:4315:12
    at process.nextTick (C:\Users\aph\IdeaProjects\hello-world-node\node_modules\mongoose\lib\helpers\query\completeMany.js:35:39)
    at process._tickCallback (internal/process/next_tick.js:61:11)
Emitted 'error' event at:
    at C:\Users\aph\IdeaProjects\hello-world-node\node_modules\mongoose\lib\model.js:4570:13
    at C:\Users\aph\IdeaProjects\hello-world-node\node_modules\mongoose\lib\query.js:4315:12
    at process.nextTick (C:\Users\aph\IdeaProjects\hello-world-node\node_modules\mongoose\lib\helpers\query\completeMany.js:35:39)
    at process._tickCallback (internal/process/next_tick.js:61:11)

This is my code:
const express = require("express");
const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const router = express.Router();

const Greeting = mongoose.model("Greeting", new Schema({message: String}));

router.get("/", (req, res) => {
    Greeting.find({message: "Hello World!"}, (err, greetings) => {
        if (err) {
            console.log(err);
            res.status(500).send(err);
            return;
        }
        res.send(JSON.stringify(greetings));
    });

    res.send("There are no greetings!");
});

router.post('/', (req, res) => {
    mongoose.connect("mongodb://localhost:27017/test", {useNewUrlParser: true});
    new Greeting(req.body).save()
        .then(() => {
            res.send('success');
        })
        .catch(err => {
            console.log(err);
            res.status(500).send("Error: " + err)
        });
});

module.exports = router;

I scanned this question but could not find a solution for my problem.

A: Greeting.find is an async function so the line res.send("There are no greetings!"); runs before the callback of Greeting.find runs which means the response 'There are no greetings!' is sent to the client before the callback ever runs.
Then in Greeting.find callback you're trying to send a response to the client again which causes the error.


text:
Q: How can I create a plot that shows number of successes that have happened in set amount of time? I have a group of crabs that I've measured their time to reach shelter.
I want to scatterplot this data with
x=Time To Shelter
The variable I am struggling with is showing the number of crabs that have reached shelter by the time on the x-axis. My data is imputed as each row being the crab and the amount of time it took to reach shelter.
How can I translate the y-variable to show this?


text:
Q: Fatal error when trying to write scons platform=windows generate_bindings=yes. Following gdnative cpp tutorial I was following this tutorial on youtube,
and on Github. When I run the command scons platform=windows generate_bindings=yes inside of gdtest/godot-cpp I get the following error. I have VS 2022.
C:\Users\Antonio>cd gdtest

C:\Users\Antonio\gdtest>cd godot-cpp

C:\Users\Antonio\gdtest\godot-cpp>scons platform=windows generate_bindings=yes
scons: Reading SConscript files ...

scons: *** Path for option target_path does not exist: demo/bin/
File "C:\Users\Antonio\gdtest\godot-cpp\SConstruct.py", line 26, in <module>

In my folder path I have:
C:\Users\Antonio\gdtest\demo\bin
C:\Users\Antonio\gdtest\godot-cpp
C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\bin
C:\Users\Antonio\gdtest
C:\msys64\mingw64\bin

This is my SConstruct file:
import os

opts = Variables([], ARGUMENTS)

# Gets the standard flags CC, CCX, etc.
env = DefaultEnvironment()

# Define our options
opts.Add(EnumVariable('target', "Compilation target", 'debug', ['d', 'debug', 'r', 'release']))
opts.Add(EnumVariable('platform', "Compilation platform", '', ['', 'windows', 'linuxbsd', 'linux', 'osx']))
opts.Add(EnumVariable('p', "Compilation target, alias for 'platform'", '', ['', 'windows', 'linuxbsd', 'linux', 'osx']))
opts.Add(BoolVariable('use_llvm', "Use the LLVM / Clang compiler", 'no'))
opts.Add(PathVariable('target_path', 'The path where the lib is installed.', 'demo/bin/'))
opts.Add(PathVariable('target_name', 'The library name.', 'libgdexample', PathVariable.PathAccept))

# Local dependency paths, adapt them to your setup
godot_headers_path = "godot-cpp/godot-headers/"
cpp_bindings_path = "godot-cpp/"
cpp_library = "libgodot-cpp"

# only support 64 at this time..
bits = 64

# Updates the environment with the option variables.
opts.Update(env)

# Process some arguments
if env['use_llvm']:
    env['CC'] = 'clang'
    env['CXX'] = 'clang++'

if env['p'] != '':
    env['platform'] = env['p']

if env['platform'] == '':
    print("No valid target platform selected.")
    quit()

# For the reference:
# - CCFLAGS are compilation flags shared between C and C++
# - CFLAGS are for C-specific compilation flags
# - CXXFLAGS are for C++-specific compilation flags
# - CPPFLAGS are for pre-processor flags
# - CPPDEFINES are for pre-processor defines
# - LINKFLAGS are for linking flags

# Check our platform specifics
if env['platform'] == "osx":
    env['target_path'] += 'osx/'
    cpp_library += '.osx'
    env.Append(CCFLAGS=['-arch', 'x86_64'])
    env.Append(CXXFLAGS=['-std=c++17'])
    env.Append(LINKFLAGS=['-arch', 'x86_64'])
    if env['target'] in ('debug', 'd'):
        env.Append(CCFLAGS=['-g', '-O2'])
    else:
        env.Append(CCFLAGS=['-g', '-O3'])

elif env['platform'] in ('linuxbsd', 'linux'):
    env['target_path'] += 'linuxbsd/'
    cpp_library += '.linux'
    env.Append(CCFLAGS=['-fPIC'])
    env.Append(CXXFLAGS=['-std=c++17'])
    if env['target'] in ('debug', 'd'):
        env.Append(CCFLAGS=['-g3', '-Og'])
    else:
        env.Append(CCFLAGS=['-g', '-O3'])

elif env['platform'] == "windows":
    env['target_path'] += 'win64/'
    cpp_library += '.windows'
    # This makes sure to keep the session environment variables on windows,
    # that way you can run scons in a vs 2017 prompt and it will find all the required tools
    env.Append(ENV=os.environ)

    env.Append(CPPDEFINES=['WIN32', '_WIN32', '_WINDOWS', '_CRT_SECURE_NO_WARNINGS'])
    env.Append(CCFLAGS=['-W3', '-GR'])
    env.Append(CXXFLAGS='/std:c++17')
    if env['target'] in ('debug', 'd'):
        env.Append(CPPDEFINES=['_DEBUG'])
        env.Append(CCFLAGS=['-EHsc', '-MDd', '-ZI'])
        env.Append(LINKFLAGS=['-DEBUG'])
    else:
        env.Append(CPPDEFINES=['NDEBUG'])
        env.Append(CCFLAGS=['-O2', '-EHsc', '-MD'])

if env['target'] in ('debug', 'd'):
    cpp_library += '.debug'
else:
    cpp_library += '.release'

cpp_library += '.' + str(bits)

# make sure our binding library is properly includes
env.Append(CPPPATH=['.', godot_headers_path, cpp_bindings_path + 'include/', cpp_bindings_path + 'include/core/', cpp_bindings_path + 'include/gen/'])
env.Append(LIBPATH=[cpp_bindings_path + 'bin/'])
env.Append(LIBS=[cpp_library])

# tweak this if you want to use different folders, or more folders, to store your source code in.
env.Append(CPPPATH=['src/'])
sources = Glob('src/*.cpp')

library = env.SharedLibrary(target=env['target_path'] + env['target_name'] , source=sources)

Default(library)

# Generates help for the -h scons option.
Help(opts.GenerateHelpText(env))

A: You need to specify the validator as:
PathVariable.PathAccept if it's ok that the target_path doesn't exist when you run SCons.
See:
https://scons.org/doc/production/HTML/scons-man.html#v-PathVariable

The default if not specified is:
PathVariable.PathExists
Verify that the specified path exists (this the default behavior if no validator is supplied).

A: Its resolved, I add to the SConstruct file on Godot-cpp : opts.Add(PathVariable('target_path', 'The path where the lib is installed.', 'demo/bin/', PathVariable.PathAccept))


text:
Q: Event distinction by key with Return and Intro in WPF Using Sap Business One I realised they make a distinction between intro key (numeric keyboard) and enter/return key. Events raised are differents depending on which one I press. That made me think I could control both events separately.
In C# I can set a keydown event using this method:
static void KeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Enter)
    {
        // my code here
        e.Handled = true;
    }
}

Only problem is that I have the very same result no matter which key I press. There are two values, Enter and Return, for Key enum, both with same value: 6. I tried to chek every property for KeyEventArgs but I cannot find any difference.
Is is possible know which key the user pressed?

A: There is an IsExtendedKey property that gets set to true for the Numpad Enter key.
It's internal though, so you'll have to use reflection to get its value:
static void KeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Enter)
    {
        PropertyInfo pi = typeof(KeyEventArgs)
            .GetProperty("IsExtendedKey", BindingFlags.NonPublic | BindingFlags.Instance);
        if (pi != null && (bool)pi.GetValue(e) == true)
        {
            MessageBox.Show("Into key was pressed!");
        }
        else
        {
            MessageBox.Show("Enter key was pressed!");
        }
    }
}


text:
Q: Core i3 vs Core i5 I'm in a dilemma to choose between Intel Core i3 and Core i5 CPUs. I'll be using Microsoft Office along with some browsing and some other general purpose activities.
Will I be seeing a big difference if I choose i5 instead i3?
The reason I am asking this because there is a great difference in costs of both and also I have used one laptop with Core i3(1st gen) 4GB RAM for same puposes but it hangs alot.
Asking this question again as none of the previous questions seems to be satisfactory. Please help!
PS: Planning to buy a new machine and will be running Windows 7 on it. Cost not a big issue but still why I should spend more if the need of hour doesn't demands that.
Also the new machine I am planning to buy will either sport a 4th Gen Core i3 (4010U) or 4th GenCore i5 (4210U).
Cant see much difference amongst i5 and i3 (Link). Only difference I could locate is i5 have functionality of turbo boost but that comes in picture only when I am supposedly doing any multi-tasking with some heavy operations like gaming or other graphics related.

A: Your question is going to solicit opinions
For me, I would check the CPU score, with websites similar to
https://www.cpubenchmark.net/cpu_list.php
You can see what the score is. Personally, if the score is 2k or above, IMO it will be fine for MS office use, regardless of whether it's an i3 or i5
You have mentioned 2 CPUs, the benchmark score is
i3 4010U - 2440 benchmark score
i5 4210U - 3398 benchmark score
Either will suffice.

A: If you're thinking about upgrading processor in a machine you currently own then this is very cost-ineffective way of improving speed. Also, there may be limitations on the system you may not be able to put in really good CPU.
You would be much better off swapping your HDD for SSD and I wholeheartedly recommend that instead. In fact, im not sure I can do that strongly enough.
If you're thinking on buying new machine then i5 is the way to go almost always. First: better computing power in office use, better power management and more RAM support. Also, be sure you go for the latest generation of i5, and if you think battery time is important then go for ones with letter U at the end. If more power, then letter M is way to go. Depending on your available funds you may decide on more powerful one (true quad core, not dual core with multi-threading.
4th gen Core i3 and i5 processors are somewhat similar (well, every generation they always are...), but at this point it all depends on your budget. i3 is low-end solution - yes, if you're on a budget. it's still pretty good CPU, but compared to i5 it simply lacks some features. What features? It all depends on version of the processor. At this point there are 37 models of Core i3:
http://ark.intel.com/pl/products/family/75025/4th-Generation-Intel-Core-i3-Processors#@All
and 55 models of i5:
http://ark.intel.com/pl/products/family/75024/4th-Generation-Intel-Core-i5-Processors#@All
So I hope you see the futility of any closer comparison...
Difference between the two processors you're looking at are negligible. i5 will be more powerful, but this will mostly be in the overall performance (that is including graphics). Also, it is capable of using 1600 MHz LPDDR3 RAM, while i3 only 1066 MHz DDR3L. This, incidentally, is the main reason i5 will be faster.
But in your case - intended use - i3 is perfectly acceptable. You would see improvement, but not that dramatic. Again, instead of i5 I'd suggest forking on SSD.
Hanging a lot in your current system is probably due to some mechanical failure (and most obvious one would be overheating).

A: In general, Core i3 is good for general-use type of computing. Core i5 is obviously a step above that, and will be better in more heavier, demanding workloads.
Keep in mind that a bigger number doesn't necessarily mean it's better. Each Core brand may be branded differently, but depending on what the system is going to be used, differences may only be minor.
Case in point - Intel® Core™ i5-5200U v Intel® Core™ i3-5020U (full comparison here). Apart from lack of Turbo Boost in Core i3 processors and a few virtualization features, they're pretty much the same.

The reason I am asking this because there is a great difference in costs of both and also I have used one laptop with Core i3(1st gen) 4GB RAM for same puposes but it hangs alot.

Laptops that come equip with Core i3 CPUs tend to have lower performing components to hit a certain price point. They often come with: 4 GB of RAM (while perfectly reasonable, nowadays, there's not a lot of headroom here), and HDD (here you'll notice a huge difference when you opt for an SSD). That's not to say that they're bad, it's just that manufacturers have certain expectations that these machines would only be used for general-use type of computing.


text:
Q: how do i create multiple txt files name from a column in a CSV file here is the code i am trying. it results in just the last line being created. so i guess the other files are being overwritten, although i tried to move them and that hasnt workeD?
for /f "usebackq tokens=1-8 delims=," %%a in ("chassisinfo.csv") do (
set hostname=%%a
set FQDN=%%b
set MGMT=%%c
set SUB=%%d
set gw=%%e
set dns=%%f
set vlan=%%g

echo # Seans scripted installation file > ks_%hostname%.cfg
echo # >> ks_%hostname%.cfg
echo # Accept the VMware End User License Agreement >> ks_%hostname%.cfg
echo vmaccepteula >> ks_%hostname%.cfg
echo # Set the root password for the DCUI and Tech Support Mode >> ks_%hostname%.cfg
echo rootpw >> ks_%hostname%.cfg
echo # The install media is in the CD-ROM drive >> ks_%hostname%.cfg
echo install --firstdisk --overwritevmfs >> ks_%hostname%.cfg
echo keyboard 'United Kingdom' >> ks_%hostname%.cfg

echo network --bootproto=static --device=vmnic0 --ip=%MGMT% --netmask=%SUB% --gateway=%gw% --nameserver=%dns% --vlanid=%vlan% --hostname=%hostname%%FQDN% >> ks_%hostname%.cfg
move ks_%hostname%.cfg d:\KSscripts\

)

A: You are recreating the file for every line because of the single > in the line.
echo # Seans scripted installation file > ks_%hostname%.cfg

change that to the line below.  Note that I also put quotes around the file name in case there are spaces in the filename.  It would be a good idea to do that in all cases.
echo # Seans scripted installation file >> "ks_%hostname%.cfg"

Then you should put a line like this on the line before you start first line of your code above to be sure that you don't append to an old file.
if exist "ks_%hostname%.cfg" del /f /q "ks_%hostname%.cfg"

Edit... To skip the first line, change your FOR statement to:
for /f "usebackq tokens=1-8 skip=1 delims=," %%a in ("chassisinfo.csv") do (

A: Your code does not create just the last file, but the file with the last value assigned to %hostname% variable, that is, the first time the program run it should create a file just named "ks_.cfg". If the Batch code does not have a SETLOCAL command, then the second and next times it runs it creates the file with the name of the last line.
The reason for this is that %hostname% variable value is expanded just once before the FOR command is executed, so all cycles are executed with the same value. You may solve this problem in two ways: using the original FOR replaceable parameter instead of the variable:
for /f "usebackq skip=1 tokens=1-8 delims=," %%a in ("chassisinfo.csv") do (

echo # Seans scripted installation file > ks_%%a.cfg
echo # >> ks_%%a.cfg

. . . .

move ks_%%a.cfg d:\KSscripts\

)

Or using delayed expansion: Insert setlocal EnableDelayedExpansion command at begining of your program and change all %hostname% expansions by !hostname!. For further details, look for "delayed expansion" in this site or read the explanation at set /?.


text:
Q: ADMOB interstitial ads not working in real-unit-id EVENthough it works on test-unit-id it has been a week to try to solve this problem...
I keep trying to put interstitial ad to my application.
And when testing with test-unit-id works fine on my application.
BUT! When changing to my real-unit-id, Ad don't be loaded in my application at all..
i don't know why this is happening.
so confused.
I used the same sample code in this tutorial, below link.
https://developers.google.com/admob/android/interstitial
and i uploaded the screenshots in my admob -id.
and i will give my codes in my apps. please let me know what is the problem. thanks in advance :)
[enter image description here][1]
[enter image description here][2]
below is my application codes.
1.mainactivity.java

    package admobtest.com.theaterwin.theateradmobtest;

import android.app.AlertDialog;
import android.app.Application;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;

import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.ads.MobileAds;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutionException;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.ads.MobileAds;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.ads.MobileAds;

public class MainActivity extends AppCompatActivity {
    private static final long GAME_LENGTH_MILLISECONDS = 3000;

    private InterstitialAd interstitialAd;
    private CountDownTimer countDownTimer;
    private Button retryButton;
    private boolean gameIsInProgress;
    private long timerMilliseconds;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Initialize the Mobile Ads SDK.
        MobileAds.initialize(this, "ca-app-pub-4942856506050335~1501960845");

        // Create the InterstitialAd and set the adUnitId.
        interstitialAd = new InterstitialAd(this);
        // Defined in res/values/strings.xml
        interstitialAd.setAdUnitId(getString(R.string.ad_unit_id));

        interstitialAd.setAdListener(new AdListener() {
            @Override
            public void onAdClosed() {
                startGame();
            }
        });

        // Create the "retry" button, which tries to show an interstitial between game plays.
        retryButton = findViewById(R.id.retry_button);
        retryButton.setVisibility(View.INVISIBLE);
        retryButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showInterstitial();
            }
        });

        startGame();
    }

    private void createTimer(final long milliseconds) {
        // Create the game timer, which counts down to the end of the level
        // and shows the "retry" button.
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }

        final TextView textView = findViewById(R.id.timer);

        countDownTimer = new CountDownTimer(milliseconds, 50) {
            @Override
            public void onTick(long millisUnitFinished) {
                timerMilliseconds = millisUnitFinished;
                textView.setText("seconds remaining: " + ((millisUnitFinished / 1000) + 1));
            }

            @Override
            public void onFinish() {
                gameIsInProgress = false;
                textView.setText("done!");
                retryButton.setVisibility(View.VISIBLE);
            }
        };
    }

    @Override
    public void onResume() {
        // Start or resume the game.
        super.onResume();

        if (gameIsInProgress) {
            resumeGame(timerMilliseconds);
        }
    }

    @Override
    public void onPause() {
        // Cancel the timer if the game is paused.
        countDownTimer.cancel();
        super.onPause();
    }

    private void showInterstitial() {
        // Show the ad if it's ready. Otherwise toast and restart the game.
        if (interstitialAd != null && interstitialAd.isLoaded()) {
            interstitialAd.show();
        } else {
            Toast.makeText(this, "Ad did not load", Toast.LENGTH_SHORT).show();
            startGame();
        }
    }

    private void startGame() {
        // Request a new ad if one isn't already loaded, hide the button, and kick off the timer.
        if (!interstitialAd.isLoading() && !interstitialAd.isLoaded()) {
            AdRequest adRequest = new AdRequest.Builder().build();
            interstitialAd.loadAd(adRequest);
        }

        retryButton.setVisibility(View.INVISIBLE);
        resumeGame(GAME_LENGTH_MILLISECONDS);
    }

    private void resumeGame(long milliseconds) {
        // Create a new timer for the correct length and start it.
        gameIsInProgress = true;
        timerMilliseconds = milliseconds;
        createTimer(milliseconds);
        countDownTimer.start();
    }

}

2. Androidmanifest.xml

    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="admobtest.com.theaterwin.theateradmobtest">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <meta-data
            android:name="com.google.android.gms.ads.APPLICATION_ID"
            android:value="ca-app-pub-4942856506050335~1501960845"/>

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.google.android.gms.ads.AdActivity"
            android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
            android:theme="@android:style/Theme.Translucent" />

    </application>

</manifest>

3. vales - strings.xml

    <resources>
    <string name="app_name">TheaterAdmobTest</string>
    <string name="action_settings">Settings</string>
    <string name="impossible_game">Impossible Game</string>
    <!--Replace with your own ad unit id. -->
    <!--<string name="ad_unit_id">ca-app-pub-3940256099942544/1033173712</string>-->
    <!--this is actual abunit_id 입니다 . -->.
    <string name="ad_unit_id">ca-app-pub-4942856506050335/8049265316</string>

</resources>

A: If you have not uploaded your app to google store, the real ads will not show. I've met this case.


text:
Q: Is it good choice to use Adobe Air (html & Javascript) to develop Point of Sale desktop application? Question: Is Adobe Air (HTML & JavaScript) a good technology choice for developing a restaurant PoS system?:
We tried out Adobe Air (HTML & JavaScript) and SQLite for desktop application to implement billing module for Restaurant Point of Sale system.
Billing module primarily does following things.

*

*Generate bills with having heavy usage.

*Have an interface with Printer, Barcode reader, Cash Drawers and other desktop peripherals for PoS system functionality.

*Have an offline support. Whenever system being online, application will sync data with web server.

Evaluating with thermal printer, we found difficulties of Air framework (html + javascript) to get quality print. With intense search, We did work around by zooming out and fix the area size with the data needed.
So is it a good choice to continue with Adobe Air as technology platform to develop restaurant PoS system considering upcoming future challenges?


text:
Q: How to access all "assigned" with google classroom API I'm new to the Google Classroom API, and would like to clarify if it is possible to access work from the "assigned" tab, or if possible, all the tabs in the image below. I'm using Javascript btw. Thanks!
https://imgur.com/a/zySH228
(I need 10 reputation to post pictures .-. so here's the link)

A: In Google Classroom courseWork is always in the context of some course. So to get courseWork from all courses you will have to iterate through all the courses that the student has access to and for each course use this API- developers.google.com/classroom/reference/rest/v1/…. This API will give all Published assignment for that class for the student.


text:
Q: jquery json not returning value I am using jquery to submit a form using serialize and all is well except if I input more than 1 box. If I input 1 box, the msg.box appears in #BA_addbox. If however I enter more than 1 box using , as delimiter, then no msg is shown and no json tab appears in firebug. just the html which is correct. Where have I gone wrong with code.
I have created an array and using foreach with explode to seperate the values but no multiple value being returned. Thanks
UPDATE: vars are being collected in the php script like thus:
php code
$dept = mysql_real_escape_string($_POST['customerdept']);
$company = mysql_real_escape_string($_POST['BA_customer']);
$address = mysql_real_escape_string($_POST['customeraddress']);
$service = mysql_real_escape_string($_POST['BA_service']);
$box = mysql_real_escape_string($_POST['BA_box']);
$date = DateTime::createFromFormat('d/m/Y', $_POST['BA_destdate']);
$destdate = $date - > format('Y-m-d');
$authorised = mysql_real_escape_string($_POST['BA_authorised']);
$submit = mysql_real_escape_string($_POST['submit']);

$array = explode(",", $_POST['BA_box']);

     if (isset($_POST['submit']))   {
        foreach ($array as $box) {

        //$sql = "INSERT INTO `act` (service, activity, company, address, department, user, destroydate, date, item, new) VALUES ('$service', '$activity', '$company', '$address', '$dept', '$authorised', '$destdate', NOW(), '$box', 1)";
        //$result = runSQL($sql) or die(mysql_error());

        $form=array('dept'=>$dept,
                 'company'=>$company,
                 'address'=>$address,
                 'service'=>$service,
                 'box'=>$box,
                 'destroydate'=>$destdate,
                 'authorised'=>$authorised,
                 'submit'=>$submit);
        $result=json_encode($form);

        echo $result;

   }
  }

jquery code
submitHandler: function()   {
                if ($("#BA_boxform").valid() === true)  {
                var data = $("#BA_boxform").serialize();
                $.post('/domain/admin/requests/boxes/boxesadd.php', data, function(msg) {
                $("#BA_addbox").html("You have entered box(es): " + "" + msg.box + "
 You may now close this window.");
                $("#BA_boxform").get(0).reset();
                }, 'json');

         } else

         {
           return;
         }
        },
        success:    function(msg)   {
                //$("#BA_addbox").html("You have entered a box");
                //$("#BA_boxform").get(0).reset();
        }

A: First fix the php to return a valid json array.
if (isset($_POST['submit']))   {
  foreach ($array as $box) {

    //$sql = "INSERT INTO `act` (service, activity, company, address, department, user, destroydate, date, item, new) VALUES ('$service', '$activity', '$company', '$address', '$dept', '$authorised', '$destdate', NOW(), '$box', 1)";
    //$result = runSQL($sql) or die(mysql_error());

    $form=array('dept'=>$dept,
             'company'=>$company,
             'address'=>$address,
             'service'=>$service,
             'box'=>$box,
             'destroydate'=>$destdate,
             'authorised'=>$authorised,
             'submit'=>$submit);
    $result[]=$form;

  }
  echo json_encode( $result );
}

Then the msg parameter in the post callback should be an array of results, so you can't just do msg.box to get the list of boxes. I would suggest something like this:
boxes = jQuery.map(msg,function(item){
  return item.box;
}).join(',');

That extracts the box property from each item in the array and joins them into a comma separated list. You can then display that list like this:
$("#BA_addbox").html("You have entered box(es): " + "" + boxes +
  "
 You may now close this window.");

Given these changes, your code works for me. If you're having other problems, I suggest you post more of your html - in particular your form structure. It's possible your form isn't submitted the correct values to get a valid response from the server.

A: Per @nnnnnn:
Your resulting json looks like the structure below if there is more than one box. This is invalid json, and therefore can not be reliably parsed.
{
  ...
}{
  ...
}

To fix this, you have to add the arrays to another array, then encode the parent array.
$box = mysql_real_escape_string($_POST['BA_box']);
$array = explode(",", $_POST['BA_box']);
$output = Array();

if (isset($_POST['submit']))   {
  foreach ($array as $box) {

    //$sql = "INSERT INTO `act` (service, activity, company, address, department, user, destroydate, date, item, new) VALUES ('$service', '$activity', '$company', '$address', '$dept', '$authorised', '$destdate', NOW(), '$box', 1)";
    //$result = runSQL($sql) or die(mysql_error());

    $form=array('dept'=>$dept,
                'company'=>$company,
                'address'=>$address,
                'service'=>$service,
                'box'=>$box,
                'destroydate'=>$destdate,
                'authorised'=>$authorised,
                'submit'=>$submit);

    //Add to a parent array instead
    $output[] = $form;

  }

  //encode the entire array
  $result = json_encode( $output );

  echo $result;
}

This will result in the following structure and for a variable data that contains the parsed json each box can be retrieved via data[0], data[1] etc.
[
  {
    ...
  },
  {
    ...
  }
]


text:
Q: What level to use when making inferences on the group mean in a hierarchical Bayesian analysis? (This question is a bit related to a previous question of mine, but that question was about between subject comparison while this question is specifically about making inferences the group mean.)
When analyzing data using a hierarchical Bayesian model you sometimes don't want to make inferences on the individual subjects but rather on the group level (e.g. for girls aged 10 the most credible test score is 100 with a 95% credible interval of [75, 125]). When building such a model using an MCMC framework, for example JAGS/BUGS, I see two ways of getting at the group level mean. Either I can use the mean of the prior ($\mu_\text{gr}$ in the diagram below.) on the mean of the sampling distribution or, for each iteration of the MCMC algorithm I can calculate the mean of all the subject means (that is the mean of all $\mu_\text{subj}$ in the diagram below). If I want to make inferences about the group mean which of these two alternatives should I use?
As a test to see what happens when using the the two different alternatives I ran a model with simulated data.
Here is a Kruschke style diagram of a hierarchical model where we estimate the mean $\mu_\text{subj}$ for a number of subjects with a normally distributed group prior on $\mu_\text{subj}$ with mean $\mu_\text{gr}$.

Here is JAGS and R code for specifying the model above and simulating data for 50 subjects where each subject gets a mean that is randomly normally distributed with $\mu=0$ and $\sigma=1$. The JAGS model is then run for 5000 iterations and each iteration the mean of the prior, group_mu, and the calculated mean of the subjects, mean_mu <- mean(mu[]), is saved.
library(rjags)
model_string <- "model {
  for(i in 1:length(y)) {
    y[i] ~ dnorm( mu[subject[i]], precision[subject[i]])
  }

  mean_mu <- mean(mu[])
  for(subject_i in 1:n_subject) {
    mu[subject_i] ~ dnorm(group_mu, group_precision)
    precision[subject_i] <- 1/pow(sigma[subject_i], 2)
    sigma[subject_i] ~ dunif(0, 10)
  }

  group_mu ~ dunif(-10, 10)
  group_precision <- 1/pow(group_sd, 2)
  group_sd ~ dunif(0, 10)
}"

# Creating fake data
n <- 10
n_subject <- 50
subject_mean <- rnorm(n_subject, mean=0, sd=1)
y <- rnorm(n * n_subject, mean=rep(subject_mean, each=n), sd=1)
subject <- rep(1:n_subject, each=n)

# Running the model with JAGS
jags_model <- jags.model(textConnection(model_string),
                         data=list(y=y, subject=subject, n_subject=n_subject),
                         n.chains= 3, n.adapt= 1000)
update(jags_model, 1000)
jags_samples <- jags.samples(jags_model,
                             variable.names=c("group_mu", "mean_mu"),
                             n.iter=5000)

Looking at quantiles and boxplots of mean_mu and group_mu show that they are both centered around the true group mean but they differ a lot in spread with the 95% credible interval being much wider for group_mu than for mean_mu.
quantile(jags_samples$mean_mu, c(0.025, 0.5, 0.975))
##       2.5%         50%       97.5%
##  -0.10804263 -0.00741235  0.09216414
quantile(jags_samples$group_mu, c(0.025, 0.5, 0.975))
##        2.5%          50%        97.5%
##  -0.262734656 -0.008996673  0.248624938
boxplot(jags_samples, outline=F, horizontal=T)

So if I want to make inferences about the group mean which distribution should I use, group_mu or mean_mu? For me this is not clear and any explanation why one is to be preferred over the other is highly appreciated!

A: What has happened is that the estimates of the individual subject means have been shrunk towards the group mean, causing the std. deviation of the subject means (and consequently that of the mean of the subject means) to be "too small".  This shrinkage is part and parcel of the hierarchical Bayesian approach.  The group_mu values are the ones that you want.
You can see in a more empirical manner that the group_mu values are correct by comparing the width of the observed 95% credible interval from your quantile summary to the width of the confidence interval you would expect in classical statistics if you had directly observed the 50 true subject means.  In this case, that's just $1.96/\sqrt{50}$, or +/- 0.28, which corresponds pretty well to the quantile results you displayed above for group_mu: (-0.26,+0.25).  Since you can't do better than you could if you'd actually observed the 50 subject means, it follows that the credible interval shouldn't be much smaller than the confidence interval (as you're not adding any substantial prior information to the likelihood.)  Clearly the (-0.1, 0.09) quantiles of the alternative mean are too close to 0, by this comparison.
In fact, you can use the ratio of the std. deviation of the mean of the estimated subject means to the std. deviation of group_mu as an index of how much shrinkage has taken place.  (It's not the only such metric; I'm just pointing it out since you're calculating them both anyway.)  If you have a very small ratio, that indicates, in a heuristic sense, that the hierarchical part of the model isn't adding much, and assuming all the subject means are the same may be a plausible alternative.  Conversely, if the ratio is near one, that also indicates that the hierarchical part of the model isn't adding much, and just having a "fixed effects" model for the subject means would likely be almost as good - questions of modeling approaches etc. aside.

A: If you wish to make inferences about the group level then your distribution of interest is $p(\mu_{gr}|Y)$. The simple reason is that $\mu_{gr}$ is actually a random variable in your generative model. Mean_mu is not a random variable in your generative model, it is a statistic that either your sampler happened to generate or you happened to compute. Furthermore, mean_mu is actually a point estimate of the posterior distribution of the true group mean, your distribution of interest. Point estimates provide less information than the full distribution, and you already have the full distribution itself (or at least a large number of samples that approximate it).


text:
Q: Getting on-prem Docker logs to Azure log analytics I'm working in a hybrid cloud environment where we have the majority of our infrastructure in Azure, but we have some on premises machines that we also want to monitor and aggregate their log data into the same log analytics workspace.
I've successfully installed the OMS Agent for Linux and I can see that at least performance metrics and heartbeat is being collected from our local machine after following this guide. However, I can't find any guidance on how to get logs from Docker containers from on-prem to cloud.
On the on-prem machines we are running Docker, no clusters. We have some IoT Edge modules that are being managed and deployed through the IoT Hub, although I guess it is the same procedure to collect these logs since it is still Docker.
How should I got about getting my Docker logs to log analytics using the OMS agent? Is the OMS agent what I need?

A: It was my own error. When I reinstalled the agent I could see in the logs that the Docker version was too old for the agent to handle, so it was skipped. Updated Docker and it works.


text:
Q: Socloz MonitoringBundle Profiler arguments After installing SoclozMonitoringBundle, I encountered this error:

ContextErrorException: Catchable Fatal Error: Argument 2 passed to
  Socloz\MonitoringBundle\Listener\Profiler::__construct() must be an
  instance of Socloz\MonitoringBundle\Notify\StatsD\StatsDInterface,
  null given, called in
  /project/app/cache/dev/appDevDebugProjectContainer.php on line 5127
  and defined in
  /project/vendor/socloz/monitoring-bundle/Listener/Profiler.php line 58

app/config/config/yml
socloz_monitoring:
    exceptions:
        enable: true
    profiler:
        enable: true
        request: true
    mailer:
        enable: true
        from: monitor@mail.com
        to: monitor@mail.com
    statsd:
        enable: false
        host: nowhere
        port: 42
        merge_packets: true

Did I forget something ?
I would like to know execution time of my rest api in production. And other stats of functions.
Thanks in advance.
Tanguy

A: Replace (https://github.com/SoCloz/SoclozMonitoringBundle/blob/master/Listener/Profiler.php#L58):
public function __construct(Xhprof $profiler, StatsDInterface $statsd, Logger $logger = null, $sampling = 100)

by:
public function __construct(Xhprof $profiler, StatsDInterface $statsd = null, Logger $logger = null, $sampling = 100)

See : https://github.com/SoCloz/SoclozMonitoringBundle/issues/19


text:
Q: Denied Exchange 2016's ECP access from internet I'm using Exchange 2016 in my production and I want to denied ECP access from external (internet). How can I do it and where should be configure?

A: I think you could try to use IIS.
First add "IP and Domain Restrictions" feature in IIS. "Install-WindowsFeature Web-IP-Security"
Then in the IIS management,  go to ECP directory, only allow the internal IP address rang.
You could refer to this article for more detailed information:
http://msexchangeguru.com/2016/09/10/e2016-deny-external-eac/


text:
Q: Bootstrap Navbar not collapsing on mobile View Working With Bootstrap Navbar Item not Collapsing on Mobile View
I just added navbar-fixed-top. i want to know whats wrong with mycode
and Want solution for it

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">

      </button>

About

Portfolio

Contact Info

A: You need to include jquery and bootstrap.min.js for collapsing navbar

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">

      </button>

About

Portfolio

Contact Info


text:
Q: npm ERR! path C:\Users\ruwan\Documents\projects\new project\Hair-4-U-hospital\Admin\Hair-4-U-Manufacture\node_modules\@firebase\util\dist I'm engaging with angular project. And now i'm referring a tutorial for make a file upload part with firebase. I have already installed this package "@angular/fire": "^5.1.2", for the project. but tutorial explains to install npm i firebase angularfire2 for the project. I tried for it and got an error like this.
npm ERR! path C:\Users\ruwan\Documents\projects\new project\Hair-4-U-hospital\Admin\Hair-4-U-Manufacture\node_modules\@firebase\util\dist
npm ERR! code EPERM
npm ERR! errno -4048
npm ERR! syscall unlink
npm ERR! Error: EPERM: operation not permitted, unlink 'C:\Users\ruwan\Documents\projects\new project\Hair-4-U-hospital\Admin\Hair-4-U-Manufacture\node_modules\@firebase\util\dist'
npm ERR!  { [Error: EPERM: operation not permitted, unlink 'C:\Users\ruwan\Documents\projects\new project\Hair-4-U-hospital\Admin\Hair-4-U-Manufacture\node_modules\@firebase\util\dist']
npm ERR!   cause:
npm ERR!    { Error: EPERM: operation not permitted, unlink 'C:\Users\ruwan\Documents\projects\new project\Hair-4-U-hospital\Admin\Hair-4-U-Manufacture\node_modules\@firebase\util\dist'
npm ERR!      errno: -4048,
npm ERR!      code: 'EPERM',
npm ERR!      syscall: 'unlink',
npm ERR!      path:
npm ERR!       'C:\\Users\\ruwan\\Documents\\projects\\new project\\Hair-4-U-hospital\\Admin\\Hair-4-U-Manufacture\\node_modules\\@firebase\\util\\dist' },
npm ERR!   stack:
npm ERR!    'Error: EPERM: operation not permitted, unlink \'C:\\Users\\ruwan\\Documents\\projects\\new project\\Hair-4-U-hospital\\Admin\\Hair-4-U-Manufacture\\node_modules\\@firebase\\util\\dist\'',
npm ERR!   errno: -4048,
npm ERR!   code: 'EPERM',
npm ERR!   syscall: 'unlink',
npm ERR!   path:
npm ERR!    'C:\\Users\\ruwan\\Documents\\projects\\new project\\Hair-4-U-hospital\\Admin\\Hair-4-U-Manufacture\\node_modules\\@firebase\\util\\dist',
npm ERR!   parent: 'ngx-admin' }
npm ERR!
npm ERR! The operation was rejected by your operating system.
npm ERR! It's possible that the file was already in use (by a text editor or antivirus),
npm ERR! or that you lack permissions to access it.
npm ERR!
npm ERR! If you believe this might be a permissions issue, please double-check the
npm ERR! permissions of the file and its containing directories, or try running
npm ERR! the command again as root/Administrator (though this is not recommended).

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\ruwan\AppData\Roaming\npm-cache\_logs\2019-05-06T02_06_24_456Z-debug.log
PS C:\Users\ruwan\Documents\projects\new project\Hair-4-U-hospital\Admin\Hair-4-U-Manufacture>

However I want to make a this sort of component according to tutorial.
import { Component } from '@angular/core';
import { AngularFireStorage } from 'angularfire2/storage';

@Component({
selector: 'app-root',
template: `
<label for="file">File:</label>
<input type="file" (change)="upload($event)" accept=".png,.jpg" />
`
})
export class AppComponent {
    constructor(private afStorage: AngularFireStorage) { }
    upload(event) {
        this.afStorage.upload('/upload/to/this-path', event.target.files[0]);
    }
}

Am I can't get AngularFireStorage from where currently exist packages inside the "@angular/fire": "^5.1.2"


text:
Q: How to convert pdf to doc file in java need to convert a pdf file to a doc file. I found different type of example to generate pdf file but not got pdf to doc.

A: What your asking is actually very difficult
I recommend you start here and look for a good parsing library. then you would have to write it out in .doc format. Inevitably a lot of the formatting and extra information would be lost. it would be a lot easier to output to docx format, but i assume thats not what your looking for.

A: I see few possible solutions:

*

*Davisor Publishor 6.2 probably can be used, but it is commercial, and seems that generates only txt from pdf... just have a look

*parse pdf with iText, and then
generate doc with Apache POI -
another way to try (free one ;)

*look for command line tools, like
Convert PDF To DOC and execute
them from java
Otherwise take a look at Con's answer, there is a link to the list with java pdf processing libraries, maybe some library can do it directly, or can be used to parse pdf (better than iText), and then just use Apache POI to generate doc. Hope it helps ;)


text:
Q: Trouble with generic methods I have an issue with the method idTag of Q class. I'm not sure what type should be put instead of XXXX.
I've tried < T extends Taggable< T >>  but there is an issue with the following call : Q.idTag (b) ;
It says :

The method idTag(List) in the type Q is not applicable for the
  arguments (ArrayList< RedElem>)

< T extends Taggable< T >>  Doesn't seem to be the correct answer but i'm running out of idea, I don't know what could be the right one
thank you
interface Taggable<T> {

  void tag(T t);

  T getTag();
}

class Elem implements Taggable<Elem> {}

class Obj implements Taggable<Obj> {}

class RedElem extends Elem {}

class Q {

  static <XXXX> void idTag(List<T> l) {
    for (T e : l) e.tag(e);
  }

  public static void main(String args[]) {
    ArrayList<Elem> a = new ArrayList<Elem>();
    ArrayList<RedElem> b = new ArrayList<RedElem>();
    ArrayList<Obj> c = new ArrayList<Obj>();

    idTag(a);
    idTag(b);
    idTag(c);
  }
}

A: What you are trying to say in your static method is that the list should contain Taggable items, that's not what you're declaring. You need
static <T, E extends Taggable<T>> void idTag(List<E> tList, T tagWith) {
    tList.forEach(e.tag(tagWith));
}

or if you really want to tag each item with itself (which doesn't make a lot of sense):
static <E extends Taggable<E>> void idTag(List<E> tList) {
    tList.forEach(e-> e.tag(e));
}


text:
Q: Docker multiple machine configurations I want to know if there is a suggested approach on how to configure Docker machines using configuration files. I have a service that I configure for several users, it is basically a Django app.
Until now I had a shared base image and a bunch of scripts. When I need to create a new machine for a new user, I create it in Google Cloud Engine using the base image. Then I :

*

*SSH into it

*Launch a script that download everything via git and launch all services

*Copy required credential files using scp

Is there a way to optimize some steps with Docker (using secrets or some external config management tool)?
Thanks!


text:
Q: On Windows XP - how do I use PowerShell background jobs which require windows authentication I'm trying to run some functions in the background of a PoSh script. The job never completes, but works fine when called normal. I've narrowed the problem down to the following line:
This line works fine:
$ws = New-WebServiceProxy  "http://host/Service?wsdl" -UseDefaultCredential

but this line blocks forever
start-job { New-WebServiceProxy "same url" -UseDefaultCredential } `
 | wait-job | Receive-Job

Some details: the service is local, and requires windows authentication. Client is XP & server 2003.
Why? How do I get it to work?

A: You can use ConvertFrom-SecureString and ConvertTo-SecureString cmdlets
Once run
$securestring = read-host -assecurestring
convertfrom-securestring $securestring | out-file c:\securestring

it will create a secured file on disk
after that you can use
$pass = Get-Content c:\securestring | convertto-securestring
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist "domain\administrator",$pass

and
start-job { New-WebServiceProxy "same url" -Credential $cred } | wait-job | Receive-Job

A: Got this to work. What OS are you running? XP or 2003 may be a problem.
start-job {
        $zip = New-WebServiceProxy "http://www.webservicex.net/uszip.asmx?WSDL"  -UseDefaultCredential
} | Wait-Job | Receive-Job

$zip | get-member -type method

A: I don't have any ASMX web services to test this against, but if you look at the help of Start-Job you'll see '-Authentication- and '-Credential'. The first specifies Default, Basic, Credssp, Digest, Kerberos, Negotiate, and NegotiateWithImplicitCredential. The second could be used to provide actual credentials to run the job.
Hope that helps.


text:
Q: In Flask application what is the difference between @app.teardown_request and @app.teardown_appcontext? I was going through a flask application and found the use of @app.teardown_request.
Can anyone please demystify the real reason of using @app.teardown_request rather than @app.teardown_appcontext?
In other words what exactly is the difference?

A: @app.teardown_appcontext - Bind a function after each request, even if an exception is encountered.
@app.teardown_request - Registers a function to be called at the end of each request whether it was successful or an exception was raised. It is a good place to cleanup request scope objects like a database session/transaction.
https://github.com/pallets/flask-sqlalchemy/issues/379


text:
Q: Why is my oauth2 config not using my custom UserService? I'm trying to use authentication by google. I am using springboot2, so most of the configuration is automatic. The authentication itself works good, but afterwards I would like to populate Principal with my own data (roles, username, and stuff).
I've created MyUserService that exteds DefaultOauth2UserService, and I am trying to use it as follows:
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    MyUserService myUserService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .anyRequest().authenticated()
                .and()
            .oauth2Login()
                .userInfoEndpoint()
                    .userService(myUserService);
    }
}

I've checked with debuger, that application never actually uses loadUser methods. And here is implementation of MyUserService:
@Component
public class MyUserService extends DefaultOAuth2UserService {
    @Autowired
    UserRepository userRepository;

    public MyUserService(){
        LoggerFactory.getLogger(MyUserService.class).info("initializing user service");
    }

    @Override
    public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
        OAuth2User oAuth2User = super.loadUser(userRequest);
        Map<String, Object> attributes = oAuth2User.getAttributes();

        String emailFromGoogle = (String) attributes.get("email");
        User user = userRepository.findByEmail(emailFromGoogle);
        attributes.put("given_name", user.getFirstName());
        attributes.put("family_name", user.getLastName());

        Set<GrantedAuthority> authoritySet = new HashSet<>(oAuth2User.getAuthorities());

        return new DefaultOAuth2User(authoritySet, attributes, "sub");
    }
}

A: I think you're missing the @EnableOAuth2Client annotation at the top of your SecurityConfig class.
Regardless, I made an examplewith a Custom user service for oauth2 here https://github.com/TwinProduction/spring-security-oauth2-client-example/ if it helps

A: Actually the solution was just to add another property for google authentication:
spring.security.oauth2.client.registration.google.scope=profile email

Not sure, what is the default scope, and why entrance to the service is dependent on scope, but without this line the code never reached my custom service.


text:
Q: How to pass typescript dynamic type as a parameter to react custom hooks? Is there any way to pass types as a parameter or something to another component? something like this, passing a dynamic type so I can type automatically third parties hooks outside my custom hook
const hook = useCustomHook<DynamicType>()

and in the custom hook do something like
 export const useCustomHook = () => {
     return useAnotherLibraryHook<DynamicType>()
 }

A: These are called generic type parameters. Simply put:
export const useCustomHook = <T extends any>() => {
  return useAnotherLibraryHook<T>()
}

However you will want to exchange any with something narrower that is relevant to the library, perhaps one of its internal types.