text:
Q: Why didn't CSS adjacent combinator did not work here? Can someone help me understand why adjacent combinator (+) below isn't working as the commented part of css.
Adjacent combinator (+) should match second selector .btn if it immediately follows the first selector i.e. .btn-group according to https://developer.mozilla.org/en-US/docs/Web/CSS/Adjacent_sibling_selectors and so I was expecting my first btn's background to change to blue.

  <button class="btn">
    Save
  </button>

  <button class="btn">
    Revert
  </button>

/* .btn-group .btn:first-child {
  background-color: blue;
  color: white;
} */

.btn-group + .btn {
  background-color: blue;
  color: white;
}

A: Simply, .btn is a child of .btn-group not an adjacent sibling.
From the MDN document you linked to:

The adjacent sibling combinator (+) separates two selectors and matches the second element only if it immediately follows the first element, and both are children of the same parent element.

Emphasis mine,

A: The adjacent sibling combinator (+) only targets the immediately preceding sibling element, not child element. This can be seen in the following:

.btn-group + .btn {
  background-color: blue;
  color: white;
}

  <button class="btn">
    Save
  </button>

  <button class="btn">
    Revert
  </button>

<button class="btn">
  Target
</button>

If you want to target the very first child, then you do indeed need to use .btn-group .btn:first-child. You can add in the child combinator (>) to increase specificity if required, with .btn-group > .btn:first-child:

span {
  background-color: red;
}

/* Higher specificity with the child combinator */
.btn-group > .btn:first-child {
  background-color: blue;
  color: white;
}

  <button class="btn">
    Save
    Sub-class
  </button>

  <button class="btn">
    Revert
  </button>

Adding the child combinator avoids any descendants other than children also having the rule applied to them as well, which can be confusing in combination with the pseudo-selector :first-child, as demonstrated in the following example:

span {
  background-color: red;
}

/* Higher specificity without the child combinator */
.btn-group .btn:first-child {
  background-color: blue;
  color: white;
}

  <button class="btn">
    Save
    Sub-class
  </button>

  <button class="btn">
    Revert
  </button>

Hope this helps! :)


text:
Q: Set divs to fade in when a href is clicked (jQuery maybe?) So here is a project I'm working on for a friend - http://projects.beauaugust.co.uk/cheatulous/
What I need to happen is when one of the links in .menu are clicked, the divs inside .items fade in. I already have it so that the .sort div resizes to hold the content, I just need those divs to fade in afterward so it looks like the content is inside it, if that makes sense. If you click on one of the links inside the menu bar in the demo you'll see.
Cheers as ever, If I haven't given enough information I'm sorry!

A: $(function() {
    $(".item").hide();
    $(".menu a").click(function(event) {
        event.preventDefault(); //stops page from reloading on link click
        $(".item").fadeIn("slow");
    });
});

Something like that?
Alternative:
If you want the divs to fade in after the page has loaded (i.e. you want to actually switch to another html page and THEN have the divs fade in) the above won't work. Instead you could simply add:
$(function() {
    $(".item").hide().fadeIn("slow");
});

Which will make the .item divs flash (hide and then fade in, which is what you want afaik) on page reloads.
Alternative 2:
If you want the five divs currently displaying to be hidden when you first enter the page, and then be displayed as you click ANY link (i.e. they will be popped into view as the yellow background slides down), you could use display:none on .item in the CSS, and then use fade in on the links as above.

redpajama_set_name: RedPajamaStackExchange


text:
Q: stroke-dashoffset is not changing with jQuery in Chrome I am trying to change stroke-dashoffset with jQuery in a  element. Its working well in Mozilla but chrome is not changing its value..
Please let me know how can I change it with jQuery, and also if there is any other way please let me know.
here is my code ..
<!-- html -->
<div class="circleGraph" data-progress="86">
 <svg xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://www.w3.org/2000/svg">
     <circle style="fill:none; stroke:rgba(0,0,0,0.1);" stroke-width="9" r="60" cy="60" cx="65"/>
     <circle style="fill:none;" stroke-width="9" class="graphProgress" r="60" cy="60" cx="65"/>
  </svg>
 </div>

 <!-- CSS -->
     .circleGraph {width: 150px; height: 150px; position: relative;}
     .circleGraph .subjectIcon{width: 60px; height: 60px; z-index: 1;}
     .circleGraph .subjectIcon img {width:inherit; height:auto;}
     .circleGraph svg {width: inherit; height:inherit; transform: rotate(-90deg); -webkit-transform: rotate(-90deg); -moz-transform: rotate(-90deg); -ms-transform: rotate(-90deg); -o-transform: rotate(-90deg);}
    .circleGraph svg circle {transform: translate(10px,15px);}
    .graphProgress {stroke-dasharray: 380; stroke-dashoffset: 380;  transition: all 1s ease 0.5s;}

  <!-- jQuery -->
  $(".circleGraph").each(function () {
     var progressValue = $(this).data('progress');
     var progressBar = $(this).find('.graphProgress');
     var actualValue = parseInt(100 - progressValue);
     var circleMax = $(progressBar).css('stroke-dasharray');
     var absValue = (circleMax * actualValue) / 100;
    $(progressBar).css({strokeDashoffset: absValue});
  });

A: var absValue was showing me NaN, because circleMax was coming with 'px', but using parseInt with circleMax calculation, absValue is not showing NaN anymore and its working well..


text:
Q: Maximum density of water The maximum density of water in its liquid form occurs at around 4°C (under normal pressure p = 1013,25 hPa). If the pressure is increased (or decreased) would the point of maximum density still be at the exact same temperature?

A: As usual, the answer to such questions is on Martin Chaplin's water anomalies site:
"Increased pressure reduces the temperature of maximum density."
http://www1.lsbu.ac.uk/water/density_anomalies.html#Pdens


text:
Q: CakePHP 2.5.1 Number helper does not show currency symbol 'after' I tried to set up a number format for living space in Cakephp, it should look like this: "100,00 m²"
As I use this format often, I want to create a default format in my AppController beforeFilter():
CakeNumber::addFormat('AREA', array(
    'thousands' => ' ',
    'decimals' => ',',
    'places' => 2,
    'before' => false,
    'after' => ' m²'
));

In my view file I call:
echo $this->Number->currency($area, 'AREA');
The problem: 'after' does not apply, so it is missing "m²", only "100,00" shows up.
I know living space is not a currency, but it looks like the best option to define reusable number format.
Edit solution:
Thanks to Mantas:
CakeNumber::addFormat('AREA', array('thousands' => ' ',
  'decimals' => ',',
  'places' => 2,
  'wholeSymbol' => ' m²',
  'wholePosition' => 'after'
));

A: You should set

[
    'wholeSymbol' => ' m²',
    'wholePosition' => 'after',
]

to achieve desired format.


text:
Q: Unable to extract data from QR code in android After scan QR code, app will get Event title, start date, end date and location.

(html code: encodeURIComponent(txt1 + "\n" + txt2 + "\n" + txt3 + "\n" + txt4))
And how to put those value into this code:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
    if(result != null){
        if(result.getContents()==null){
            Toast.makeText(this, "You Cancelled the Scanning", Toast.LENGTH_LONG).show();
        }
        else {
            Calendar cal = Calendar.getInstance();
            Intent intent = new Intent(Intent.ACTION_EDIT);
            intent.setType("vnd.android.cursor.item/event");
            intent.putExtra("beginTime", ?);
            intent.putExtra("allDay", true);
            intent.putExtra("rrule", "FREQ=YEARLY");
            intent.putExtra("endTime", ?);
            intent.putExtra("title", ?);
            intent.putExtra("eventLocation", ?);
            startActivity(intent);
        }
    }
    else{
        super.onActivityResult(requestCode, resultCode, data);
    }
}

A: You can use String.split() to divide the string into substring. This will give you an array of strings that you can pass to the intent.
        String result = "Event title
 start date
 end date
 location"
        String[] info = result.split("
");
        Calendar cal = Calendar.getInstance();
        Intent intent = new Intent(Intent.ACTION_EDIT);
        intent.setType("vnd.android.cursor.item/event");
        intent.putExtra("beginTime", info[1].trim());
        intent.putExtra("allDay", true);
        intent.putExtra("rrule", "FREQ=YEARLY");
        intent.putExtra("endTime", info[2].trim());
        intent.putExtra("title", info[0].trim());
        intent.putExtra("eventLocation", info[3].trim());
        startActivity(intent);


text:
Q: UnderscoreJS template escapes JS operators I'm having an issue where JavaScript operators in my UnderscoreJS Template are escaped and therefore unusable.
Escaped characters that I found are &&, >, <.
I've looked for another similar issue but couldn't find any.
Where is the problem?
My template is:

    {{ _.each(collection, function(model) {

        if (model.id > 0)
        {
            // This can't be execute, the line above raised an error
        }
    }}

The error raised in Firebug is:
SyntaxError: missing ) after condition
    if (model.id > 0)                        {                            //

Here's my view:
Backbone.View.extend({
    el: '.list-container',

    events: {
        ...
    },

    /**
     *  Initiliaze the view variables and listeners of the view
     */
    initialize: function(){

        // Change delimiter from <% %> to {{ }}
            _.templateSettings = {
            interpolate: /\{\{\=(.+?)\}\}/g,
            evaluate: /\{\{(.+?)\}\}/g
        };

        this.collection = new myCollection();

        this.render();
    }
});

Thanks

A: Don't store your templates inside
s or anything else that is HTML. Anything that is considered to be HTML by the browser will be corrected to be valid HTML and templates are rarely going to be valid HTML. The result is a confusing mess.
Instead, store your templates inside a container whose contents will be left alone. Usually you use a

Then you can
var t = _.template($('#whatever').html());

to get your template functions without interference.

A: Your template should be inside a script as mu is too short mentioned. Additionally, your evaluate regular expression is incorrect, because . doesn't match newlines. You can try (?:.|\n) instead. Finally, you should close your function body with a bracket, and your function call list with a parentheses.
Working example:
HTML:

JavaScript+Underscore.js:
_.templateSettings = {
  interpolate: /\{\{\=(.+?)\}\}/g,
  evaluate: /\{\{((?:.|\n)+?)\}\}/g,
  //evaluate: /\{\{(.+?)\}\}/g, //<-your code
};

var a = document.getElementById('a');
var templateString = a.innerHTML;

var compiled = _.template(templateString);
var data = compiled({collection: [{id:1},{id:0}]});
console.log(data);

You will notice that this console logs the div with the filtered "model" {id:1} inside it.

A: try with this:
Javascript:
_.templateSettings = {
    evaluate:    /\{\{(.+?)\}\}/g,
    interpolate: /\{\{=(.+?)\}\}/g,
    escape:      /\{\{-(.+?)\}\}/g
};

var view = Backbone.View.extend({
    className: 'list-container',
    template: _.template($('#my-template').html()),
    render: function() {
      this.$el.html(this.template(this));
      return this;
    },
});

var collection = new Backbone.Collection();
collection.add([
    {id: 10, email: 'foobar10@demo.com'},
    {id: 11, email: 'foobar11@demo.com'}
]);

var myView = new view({collection: collection});
$('#container').html(myView.render().el);

Html:

You can check a small demo here: http://jsfiddle.net/levieraf/9h85q302/
Let me know if this work for you :)
Good luck man!


text:
Q: Products not appearing using Create New Items in Magmi first of all I couldn't find this specific problem anywhere on StackOverFlow.
I am trying to import products on my Magento website using Magmi. I have a product CSV with me which I exported using Magento DataFlow.
My problem is this, on Magmi, when I select "Create New Items & Update Existing Items" or "Create New Items & Skip Existing" the SKUs get imported succesfully but they are not visible on the backend. I get no error on Magmi ouput.
However, if I use "Update Existing Items" after I have done the above step, the items become visible in the backend. Hence, to make my items visible on backend I have to import twice, first using Create option and second using the Update option.
Could you help me on this problem as I believe this is not how magmi actually works.

A: I solved it! I had to explicitly mention "status" to enabled in the CSV file.


text:
Q: Computed property referencing wrong 'this' when trying to add a class depending on the character length in Vue I just need some help identifying why I get an error on my computed property. The error is:
Error in render: "TypeError: Cannot read property 'length' of undefined"

I assume as I am looping through activeConnect.nodes when I reference this.node it does't know which one I am referring too? How do I fix my computed to do this correctly?
   <v-col
      v-for="(node, index) in activeConnect.nodes"
      :key="index"
    >
      <v-card
        flex
        @click="edit(node)"
      >
        <v-card-text
          :class="nameClass"
          text-no-wrap
          v-text="node.content"
        />
      </v-card>
    </v-col>

Computed:
  computed: {
    nameClass () {
      if (this.node.content.length > 4) {
        return 'name-small'
      }
      return 'name'
    }
  }

SCSS:
.name-small {
  font-size: 12px !important;
}

.name {
  font-size: 20px !important;
}

A: There's no this.node, node is local name inside v-for. There are several options to address this.
nameClass can be a method that receives node as parameter.
A part of a template that depends on node value (v-card) can be moved to a separate component that receives node as a prop and can have nameClass computed.
A simple calculation like in nameClass can be moved to a template.


text:
Q: Is it possible to render an image stored in laravel storage while in development mode? I'm working on a web app using React and Laravel which are in separate projects, I'm trying to render an image fetched from Laravel storage in an img tag using the URL I'm getting for example /storage/file-name.png
this is my show method:
  public function show(Patient $patient)
    {
        $this->response = new stdClass();
        ...My code

        $this->response->image =  Storage::url($patient->user->image);

        ...My code
        return response()->json($this->response, $this->successStatus)->header('content-type', 'application/json');
    }

and in my react app I'm passing the URL to the component the contains the img tag as a props but nothing shows. I tried adding http://localhost:8000 to the /storage/file-name.png and result is the same.
P.S: i console logged the image prop and it's returning /storage/file-name.png which is correct.
here is my dropzone component render method:
render() {
    const { isHighLight } = this.state;
    const { isMultiple, isEnabled, title, image } = this.props;
    return (

        <input ref={this.fileInputRef} type='file' className='dropzone__input' multiple={isMultiple} onChange={this.handleFileUploaded} />
        {title}

    );
  }

Is there a way to show an image while in development mode? Or should I host my app somewhere in order to be able to show the images?

A: Your front-end application doesn't have permission to see the file in your storage path for default.
You can try to convert your file in base64:
public function getFile(string $name)
{
    if (file_exists("storage/{$name}")) {
        return base64_encode(file_get_contents("storage/{$name}"));
    }
}

front-end:


text:
Q: How to choose cut off for winsorization/ flooring- capping? What is the impact of variable distribution on the decision To perform logistic regression I wish to winsorize outliers in independent/ explanatory variables by flooring and capping independent variables.
Can you suggest how I should choose cut-off for winsorization, i.e 1 & 99th or something else.
Also is there any impact on decision if the distribution of variable is left/ right skewed and not normal.
Please assume we don't have common knowledge of the variable to choose cut off intuitively.


text:
Q: Generate a grid of random coordinates I want to generate a set of 16 (x,y) coordinates in a 4x4 square grid, such that for each (x,y) the nearest neighbour distance is 1.1m.
I have tried :
rad=1

ranx=(0,4)

rany=(0,4)

randPts=[]

for i in range(0,15):

    for j in range(i+1,16):

        x=random.randrange(*ranx)
        y=random.randrange(*rany)
        if (np.sqrt(((x[i]-x[j])**2)+((y[i]-y[j])**2)) != 1.1):
            randPts.append((x,y))

This is giving me the error : TypeError: 'int' object has no attribute '__getitem__'
Can anyone kindly suggest how I can generate the required (x,y) grid?
Thanks in advance.


text:
Q: Display mysql checkbox value in form A simple question but I can't seem to find the answer.
I have a simple form that inserts the value 'on' to a database when a checkbox is checked
How do I get the checkbox checked when the data is pulled from the database when the form is revisited and displaying with the database information?
I have tried this but it doesn't work
<input type="checkbox" name="positioning" class="input_margin" value="<? $row['positioning']; ?>">Positioning

(I only need help with this, I have the sql query etc set up fine)
Thanks

A: Use a conditional statement to check the database value and echo 'checked' if it should be checked
<input type="checkbox" name="positioning" class="input_margin" <? if($row['positioning']=='on'){echo 'checked';} ?>>

A: You need to use the checked property and not value.
The value field is what is provided if the box is checked (e.g positioning=on) for value="on"
<input type="checkbox" name="positioning" class="input_margin" <? if($row['positioning']) { ?> checked<? } ?>/>Positioning

A: Include the value attribute so the checkbox input will post "on" if checked.
Otherwise the form will initially retrieve a value but fail to post on any subsequent form submission. to the database
<input type="checkbox" name="positioning" class="input_margin" value="on" <? if($row['positioning'] =='on'){echo 'checked';} ?> />Positioning


text:
Q: Changing top margin for second page only? \vspace inserts extra whitespace I am trying to format a LaTex template for pandoc output from .md to pdf. The document is for lengthy university papers requiring very specific layout. The majority of the paper has 1 in margins all around, with the exception of the Title Page and Primary Headings (which require 2 in top margins).
\newgeometry works for the Title Page because it is a standalone page, but it creates a new page when used with \begingroup \newgeometry \section{Primary Heading} \endgroup which is unacceptable.
I thought I could solve the problem using \vspace*{}, but it appears to insert extra whitespace which causes too much top margin (see pictures). How can I create exactly two inches of top margin before a \section{Primary Heading} appearing at the top of a page that is not the first page of the document?
EDIT 1/17
I succeed in getting chapters to work as expected instead of sections. Using titlesec along with titlespacing, I am able to add 1in above the chapter headings (which should combine with the 1in margin to = 2 in), but the output is more than 1in. Could I use something like \vspace to subtract the extra whitespace that is added? How could I calculate how much extra whitespace is added?

Below is my MWE:
\documentclass[12pt, oneside]{book}

% Package Imports
    \usepackage{titlesec}
    \usepackage{setspace}
    \usepackage[showframe]{geometry}
    \usepackage{lipsum}

%% Section Formatting (Requires titlesec)
    %%% Primary Heading (H1)
        \titleformat{\chapter}
        {\center\normalfont\MakeUppercase}{}{0pt}{}
        \titlespacing*{\chapter}{0pt}{1in}{0pt}
    %%% First-Level Sub (H2)
        \titleformat{\section}
        {\center\normalfont\MakeUppercase}{}{0pt}{}
        \titlespacing*{\section}{0pt}{2em}{0pt}
    %%% Second-Level Sub (H3)
        \titleformat{\subsection}
        {\center\normalfont\bfseries}{}{0pt}{}
        \titlespacing*{\subsection}{0pt}{2em}{0pt}

% Page Formatting & Layout
    \raggedright %% Left Justify
    \doublespacing %% Line Spacing (Requires setspace)
    \geometry{margin=1in} %% Margins (Requires geometry)
    \setlength{\parindent}{0.5in} %% Fixes Paragraph Indentation
    %\setcounter{secnumdepth}{0} %% No counters for section headings

\begin{document}

% Title Page
    \begin{titlepage}
    \centering
    \newgeometry{left=1in,right=1in,top=2in,bottom=1in}
    \begin{singlespace}
    \uppercase{
    [Institution]\par
    \vspace{2in}
    [Paper Title]\par
    \vspace{2in}
    Submitted to [Professor]\par
    In partial fulfillment of\par
    [Course]\par
    \vspace{2in}
    by\par
    [Name]\par
    [Date]\par}
    \end{singlespace}
    \restoregeometry
    \end{titlepage}

% Body
    \chapter*{Primary Heading}\label{primary-heading}
    \lipsum[1]
    \section*{First-Level Sub}\label{first-level-sub}
    \lipsum[2]
    \subsection*{Second-Level Sub}\label{second-level-sub}
    \lipsum[3]
    \chapter*{References}\label{references}
    \addcontentsline{toc}{chapter}{References}

\end{document}


text:
Q: How Do I Prevent this Code from Randomly Being Called I'm developing a script in VBA for excel and currently I'm working on deleting every sheet but "Jan2016" and then copying "Jan2016" and renaming it several times.  Unfortunately, when I run my code, my DeleteAllButJanuary() function is randomly called deleting every sheet but January again and causing it to start over and eventually fail.  Here's my code:
Sub GenerateData()
    Dim WS_Count As Integer
    Dim I As Integer
    Dim Jan As Integer
    Dim Months() As String
    Months = Split("Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec", ",")

    ' Set WS_Count equal to the number of worksheets in the active
    ' workbook.
    WS_Count = ActiveWorkbook.Worksheets.Count

    Call DeleteAllButJanuary

    For I = 2 To WS_Count
        ActiveWorkbook.Worksheets("Jan2016").Copy _
        After:=ActiveWorkbook.Worksheets("Jan2016")
        ActiveWorkbook.Worksheets(I).Name = Months(I) + "2016"
    Next I
End Sub

'Delete all sheets except the January Sheet
Sub DeleteAllButJanuary()
    Application.DisplayAlerts = False
    For Each ThisSheet In ActiveWorkbook.Worksheets
        If ThisSheet.Name <> "Jan2016" Then
            ThisSheet.Delete
        End If
    Next
End Sub

Any insight would be appreciated.

A: Slightly edited code with some further error checking added
Sub GenerateData()
    If Not WorkSheetExists("Jan2016") Then Exit Sub

    Dim WS_Count As Integer, i As Integer, Jan As Integer
    Dim Months() As String
    Months = Split("Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec", ",")

    WS_Count = ActiveWorkbook.Worksheets.Count

    With ActiveWorkbook
        Application.DisplayAlerts = False
        For Each ThisSheet In .Worksheets
            If ThisSheet.Name <> "Jan2016" Then ThisSheet.Delete
        Next
        Application.DisplayAlerts = True

        For i = WS_Count To 2 Step -1
            .Worksheets("Jan2016").Copy After:=.Worksheets("Jan2016")
            .Worksheets(2).Name = Months(i - 1) + "2016"
        Next i
    End With
End Sub

Function WorkSheetExists(ByVal strName As String) As Boolean
   On Error Resume Next
   WorkSheetExists = Not ActiveWorkbook.Worksheets(strName) Is Nothing
End Function

A: Hope I've got this right.
You want to delete all worksheets, except January. Then you want to use this is a template to repopulate the rest of the months? Is that correct?...
If so, suggest that you delete in reverse order...
Option Explicit

Sub GenerateData()

    Dim I As Integer
    Dim Months() As String
    Months = Split("Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec", ",")

    Call DeleteAllButJanuary

    For I = UBound(Months) To LBound(Months) + 1 Step -1

        Call Worksheets("Jan2016").Copy(After:=Worksheets("Jan2016"))
        Worksheets(2).Name = Months(I) + "2016"

    Next I

End Sub

Public Sub DeleteAllButJanuary()

On Error Resume Next

Dim I As Integer
Application.DisplayAlerts = False

Call Sheets("Jan2016").Move(Sheets(1))
For I = Sheets.Count To 2 Step -1
    Sheets(I).Delete
Next
Application.DisplayAlerts = True

End Sub


text:
Q: Changing the size of the UISearchBar TextField? I have a UITableView with an Index on the side;  I want to add a UISearchBar to it, but the index overlaps with the "x" to clear the search.  I've noticed in the Contacts application, the textfield within the UISearchBar is resized to accommodate this, but I can't work out how to do this in my own app.
I have tried the following in my viewDidLoad, but it does not seem to work.
UITextField * textField = (UITextField *)[[self.search subviews] objectAtIndex:0];
CGRect r = textField.frame;

[textField setFrame:CGRectMake(r.origin.x, r.origin.y, r.size.height, r.size.width-30)];

Any ideas?

A: Ok, I've come up with a solution.

*

*Create a subclass of UISearchBar

*Include this code in the drawRect: method.
UITextView * textField = [self.subviews objectAtIndex:0];
textField.frame = CGRectMake(5, 6, (310 - kRightSideMargin), 31);

[super drawRect:rect];

Note: kRightSideMargin is a constant I set in my header file;  I have it set to 25.
Thanks for the suggestions from everyone else.

A: As Padraig pointed out all you have to do is subclass out the searchBar. Create your UISearchBar subclass, and add the following code into the layoutSubviews method:
- (void)layoutSubviews
{
    UITextField *searchField;

    for(int i = 0; i < [self.subviews count]; i++)
    {
        if([[self.subviews objectAtIndex:i] isKindOfClass:[UITextField class]])
        {
            searchField = [self.subviews objectAtIndex:i];
        }
    }

    if(!(searchField == nil))
    {
        searchField.frame = CGRectMake(4, 5, 285, 30);
    }
}

This loops through all the subviews and checks them against type UITextField. That way if it ever moves in its line up of subviews this will still grab it. I found 285 to just wide enough not to overlap with the index of my tableView.

A: As of iOS 6, the navigation bar solution didn't work well for me because of slightly different looks now between the UISearchBar and UINavigationBar.  So, I switched to something similar to Padraig's approach by subclassing the UISearchBar.
@interface SearchBarWithPad : UISearchBar
@end

@implementation SearchBarWithPad
- (void) layoutSubviews {

    [super layoutSubviews];
    NSInteger pad = 50;
    for (UIView *view in self.subviews) {
        if ([view isKindOfClass: [UITextField class]])
        view.frame = CGRectMake (view.frame.origin.x, view.frame.origin.y, view.frame.size.width - pad, view.frame.size.height);
    }
}
@end

Edit: Ah, I haven't tried it, but I think you might be able to set a navigation bar's clipToBounds = YES to turn off it's new shadow, thereby creating a consistent look again between the two controls.

A: I am using ViewDeck and want to show a UISearchbar inside the leftController.
Now the problem is if I open the left side which contains the navigation, the right bit overlaps my search field.
I got rid of this by over writing UISearchBar, the textfield will always have the same width, but in one case there is the ViewDeck overlapping and in the other case I hide the ViewDeck-bit and then the cancel button will take up the space:
Subclassing UISearchBar
#import "ViewDeckSearchBar.h"
#define kViewDeckPadding 55

@interface ViewDeckSearchBar()
@property (readonly) UITextField *textField;
@end

@implementation ViewDeckSearchBar

static CGRect initialTextFieldFrame;

- (void) layoutSubviews {

    [super layoutSubviews];

    // Store the initial frame for the the text field
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        initialTextFieldFrame = self.textField.frame;
    });

    [self updateTextFieldFrame];
}

-(void)updateTextFieldFrame{

    int width = initialTextFieldFrame.size.width - (kViewDeckPadding + 6);
    CGRect newFrame = CGRectMake (self.textField.frame.origin.x,
                                  self.textField.frame.origin.y,
                                  width,
                                  self.textField.frame.size.height);

    self.textField.frame = newFrame;
}

-(UITextField *)textField{
    for (UIView *view in self.subviews) {
        if ([view isKindOfClass: [UITextField class]]){
            return (UITextField *)view;
        }
    }

    return nil;
}

@end

ViewController class
In my Navigation class I need to overwrite these two UISearchbarDelegate methods in order to go to fullscreen with the search results:
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{

    [self.viewDeckController setLeftSize:0];

    // I am also using scopes, which works fine (they fade out when not searching)
    self.searchBar.scopeButtonTitles = @[@"Food",
                                         @"Beverages",
                                         @"Misc"];
}

-(void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
    self.viewDeckController.leftSize = 55;
}

Result
ViewDeck showing to the right:

(source: minus.com)
Search in Fullscreen (The button and the scope buttons are animated in).

(source: minus.com)

A: it's much easier than all these suggestions. In interface builder, instead of putting the Search Bar as the header of your Table View, you can put a View instead. Then, put a Navigation Bar inside this View. Grab the left resizing handle of the Navigation Bar and pull it to the right until the N B is only 25 pixels wide. Clear out the Title in the N B (double click to select it, then delete). Then, add a Search Bar into the same View. Move its right resizing handle to the left, adjust so that it abuts the N B. That's it.
You can enable a cancel button if you want too and it also won't overlap the index (remains within the search bar).
Apparently a Table View can only have 1 subview in its header, that's why you need to put the View first, then the N B and Search Bar inside it.
UPDATE: see Beginning iPhone Development from Apress, p. 241 of SDK 3 edition. You just disable the index while searching.
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    if (isSearching) {
        return nil;
    }
    return keys;
}

Also they talk about adding a magnifying glass to the top of the index.
Great book all around.

A: searchBar.layoutMargins = UIEdgeInsetsMake(0, 0, 0, rightPad);

My old solution of changing the UITextField frame stopped working in iOS 13.  Putting a UINavigationBar to the right of the UISearchBar never worked well for me as they had different looks at top and bottom.

A: Sorry to drag this all up again.
I wanted the UISearchBar to be shorter, and I'm using a UISearchBarController, but without actually wanting the index. This is because I have an overlay to the right:

To do this, I fake a sectionIndex with one blank item, then hide it. Here's how I do that:
 - (void)hideTableIndex {
    for (UIView *view in [tableView subviews]) {
        if ([view isKindOfClass:NSClassFromString(@"UITableViewIndex")]) {
            view.hidden = YES;
        }
    }
 }

 - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)aTableView {
    if (aTableView == self.searchDisplayController.searchResultsTableView) {
        return nil;
    } else {
        [self performSelector:@selector(hideTableIndex) withObject:nil afterDelay:0];
        return [NSArray arrayWithObjects:@"", nil];
    }
 }

 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
    return 0;
 }

This shortens the the UISearchBar and hides the index so it can't be tapped (a small section would otherwise hand to the left of the overlay that when tapped would scroll the UITableView to the top). Like this:

Best of all, when you use the search, you still get the full width bar:

A: Just put a UIView and put the search bar inside that UIView. UIView must be of same size as UISearchBar.
this worked for me.

A: Why not just make the actual UISearchBar smaller horizontally, and place an (empty) UINavigationBar to the right of it? They will render the exact same background.
Better than hacking the internals of Apple's objects that could change.
Also, when animating the UISearchBar's width, you'll notice that the inner text field is not animated along with it. You can fix this by calling UISearchBar's "layoutSubviews" within your animation block after changing its frame. (that's where it determines the size of the inner text field)

A: The text field used in UISearchBar is a subclass of UITextField called UISearchBarTextField.
AFAIK, there's no way to resize a UISearchBarTextField using the public API, and the private API doesn't reveal much either.
Maybe you can take a look at UISearchBarTextField's subviews, if it has any.
UPDATE: It doesn't.
UPDATE 2: I think you should take a look at UITextField's rightView property. The below code, although it doesn't work, seems like a good starting point:
UIView *emptyView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 25, 25)];
[textField setRightView:emptyView];
[textField setRightViewMode:UITextFieldViewModeAlways];
[emptyView release];

A: Sorry for Necroposting, but I found another way to make a little space on the right of the textfield.
I was having the problem, that I had an indexed tableview with a searchbar as the first row. Now the index and the searchbar (made in IB, btw.) were overlapping. It tried almost everything with no success. It seems that the width and height properties of the textifield don't respond... So I came up with this:
searchBar.showsCancelButton = YES;

UIView *cButton = [searchBar.subviews objectAtIndex:2];

cButton.hidden = YES;

I still can't adjust the size of the space, but this does it for now... although... pretty weird solution...

A: Everyone has provided ways to modify the UI.  I have discovered how to obtain identical results.  You must provide the following two implementations:

*

*Use UISearchDisplayController
More importantly, make sure you initialize it with:

- (id)initWithSearchBar:(UISearchBar *)searchBar contentsController:(UIViewController *)viewController

Failure to set a valid UISearchBar (or passing nil) will prevent the adjustment of the UITextField for the index.

*You must return a valid array of titles by implementing:

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView;

If you return nil, the index will not be displayed, and the UITextField will not be properly adjusted.
I've submitted a bug report to Apple, suggesting that it seems logical that only #2 should be required, not #1.  I have found nothing in the Human Interface Guideline (iPhone HIG) requiring use of the UISearchDisplayController.

A: The key is to use the "Search Bar and Search Display Controller" and not the "Search Bar" when using Interface Builder.

A: It kind of looks as though Apple resize the view (note that the index is animated to the right, off screen), making it bigger than the screen.
I would imagine that you'd need to implement the searchBarTextDidBeginEditing: method of the UISearchBarDelegate to trigger this at the appropriate point. This does, however, feel a bit hacky do maybe there's a better way of doing it.

A: Another appraoch (though tedious) would be to resize the search bar and fill the 'gap' with a navigation bar. Works for me.

A: What I've come up with isn't too much better. Basically, I make an empty view with the frame that I want to use for the search bar. Then I create a UIToolbar to go behind the search bar. Be sure to set its frame to the same frame as the UIView, except that the Y value has to be -1; otherwise, you'll get two borders drawn at the top. Next create your UISearchBar, but set the frame's width to 30 (or whatever makes sense for your app) less than the UIView. Add them as subviews and set your UIView as the tableHeaderView.

A: I followed Mike's advice by making a UIView, then putting a Navigation Bar and UISearch Bar inside it.  Only problem is first time the search bar is shown its background is the same as a Navigation Bar normally?
Interestingly, if I activate the search, then click cancel the background of this 'fixed'!?
I'm using SDK 3.0, so I removed the UISearchBar item made when I dragged a UISearchDisplayController in to my NIB, then made the view as described above and wired it up to the file owner and the searchBar outlet in the search display controller.

A: It work fine!!!

[searchBar setContentInset:UIEdgeInsetsMake(5, 0, 5, 35)];


text:
Q: Moving Borderless Forms I need your help with some code I found on the web a long time ago. Sadly I don't remember from where it is :( To move the borderless forms in my project I use this code snipped:
protected override void OnMouseDown(MouseEventArgs e)
{
     base.OnMouseDown(e);
     if (e.Button == System.Windows.Forms.MouseButtons.Left)
          {
               this.Capture = false;
               Message msg = Message.Create(this.Handle, 0XA1, new IntPtr(2), IntPtr.Zero);
               this.WndProc(ref msg);
          }
}

My problem is that I don't completely understand how the code works. As far as I understand the event gets activated when a mouse button is clicked on the forms. Then follows the query, if the mouse click is a left click. And from there I don't know what the following code does :(

A: The this.Capture=false tells the OS to stop capturing mouse events.  The Message.Create creates a new message to be send to the message loop of the current application.  0xA1 is WM_NCLBUTTONDOWN; which is a non-client left-button down message.  Meaning it simulated clicking the left mouse button on the missing border.
Windows then picks up the rest of the process.

A: At a basic level, you are sending a message to your window and having it handle it.
You are giving it a 0xA1 (WM_NCLBUTTONDOWN) and by sending a 0x02 as the parameter (HTCAPTION) you fool the process into thinking you are on the caption bar. Drags on a caption bar move the window around, hence you can drag the window by using your code.
Samples of doing this at:
C#: How to drag a from by the form and it's controls?
http://www.catch22.net/tuts/win32-tips-tricks

A: You're basically posting a message to the window.  A little MSDN research uncovers that the message you're posting is WM_NCLBUTTONDOWN.  Basically, you're telling the underlying window that the left mouse button is being held down and it needs to respond to that.  That response typically happens to be dragging the window about.


text:
Q: Compiler Issue with auto? Error: in a declarator-list 'auto' must always deduce to the same type std::vector<int> vec;
auto i = vec.begin(), j = std::next(i);

Error: in a declarator-list 'auto' must always deduce to the same type

A: This appears to be a compiler error.
See this link below.
http://connect.microsoft.com/VisualStudio/feedback/details/728741
May already have been fixed judging by the comments in the link.

A: Compiles fine in g++ on Linux, so it appears to be a compiler bug. Probably this one.

A: Yep, this was an issue on the VS2010 compiler toolchain. Swapped it to 2013 and it was fine.


text:
Q: Easy way to display a loading screen while downloading and upserting on ASP? I've only seen examples on how to display loading gifs while the page itself loads, and stopping once it's loaded, but I want it to display the loading gif while the code is downloading some XML files, reading them and upserting its content, it does this with button click event.
I'd like for it to display that circle loading gif, and hopefully like 'lock up' the screen, I got this idea it would look great if it somehow grayed out the page and displayed only a the gif on the center over the rest of the page until the process was finished, like the UAC popup window on Windows, but just the image will do for starters.
What's the best approach for this? Thanks!


text:
Q: Regarding SCSI Reservations I am trying to write a program to block a LUN using SCSI 2 reservations.
In SCSI 2 reservations, can the LUN be reserved by the same host with a different path or the I-T-L nexus is only a single path.
Eg : Lets say the host tries to reserve the already reserved LUN from the same target but with the different port of the target. Is this possible?
Basically the LUN reservation would still be the same host but would be from different paths.
[EDIT]
I have got the required response for the above mentioned problem but have another query.
Lets say the host has reservation on LUN X and a connection drops or the host issues logout. What happens to the reservation?
Whether it depends on the host driver to clear the reservation and clear its data or the reservation remains and other hosts would get a conflict if they try to reserve the same LUN.
I tried googling it but could not find the specs related to this issue.

A: Each I_T_L nexus is a single path.  When you use the RESERVE(6) or RESERVE(10) commands described in SPC-2, that's what you're reserving.  So, only one path can be active at a time.  If that's what you want, then you're good! (Edit: to be clear, the second I_T_L nexus to issue RESERVE gets a reservation conflict.)
If your initiator and target can handle it, the PERSISTENT RESERVE/RELEASE commands in SPC-3 offer much more flexibility.  You can register each nexus with the LU and then set an "exclusive-access registrants-only" reservation that blocks access to everyone else, but permits it to the registered nexuses.
An example of this can be seen in the description of a bug in the SCSI fence script used in the Redhat clustering software.  The existing solution didn't interoperate with multipath I/O, because the redundant paths kept hitting reservation conflicts.  The solution was to register all paths:  https://bugzilla.redhat.com/show_bug.cgi?id=661134
[EDIT] to respond to your additional question: if the connection drops, the reservation is still held.   From SPC-2:

This command shall request that the entire logical unit be reserved
  for the exclusive use of the initiator until the reservation is
  superseded by another valid RESERVE command from the same initiator or
  until released by a RELEASE command from the same initiator that made
  the reservation, by a TARGET RESET task management function performed
  by any initiator, by a hard reset condition, or by a power on cycle.


text:
Q: Selenium does not detect iframe [Python] im trying to make a small program to login into this site automatically  (es1.kingdoms.com/).
But the issue is that the iframe in which the login "popup" is, isn't detected by selenium.
As far as I know I have to use the switch_to function of the webdriver in order to acces the email and password fields inside it (since they aren't being detected either).
This is my code at the moment:
usernameStr= "example@example.com"
passwordStr= "12345"

browser = webdriver.Chrome()

nextButton = browser.find_element_by_xpath('//*[@id="loginButton"]/button')
nextButton.click()

iframe1 =  WebDriverWait(browser,10).until(EC.presence_of_element_located((By.ID, 'easyXDM_default7709_provider')))

browser.switch_to.frame(iframe1)

username = WebDriverWait(browser,10).until(EC.presence_of_element_located((By.XPATH, '//*[@id="login"]/div[1]/input')))
username.send_keys(usernameStr)

The line in which the error takes place is in the assignation of 'iframe1'. The 'WebDriverWait' times out before it detects the iframe. In the html the iframe looks like this.
<iframe name="easyXDM_default7709_provider" id="easyXDM_default7709_provider" class="mellon-iframe" src="https://mellon-t5.traviangames.com/easyXDM/proxy.html?timestamp=1494602441065&urn=%2Fauthentication%2Flogin%2FapplicationDomain%2Fwww.kingdoms.com%2FapplicationPath%2F%252Fes%252F%2FapplicationInGame%2F0%2FapplicationId%2Ftravian-ks%2FapplicationCountryId%2Fes%2FapplicationInstanceId%2Fportal-es%2FapplicationLanguageId%2Fes_ES%2FapplicationCookieEnabled%2F1%3Fmsname%3Dmsid%26msid%3D4qdpjbd8bdb72n7s5jede9uqa1&xdm_e=http%3A%2F%2Fwww.kingdoms.com&xdm_c=default7709&xdm_p=1" frameborder="0" style="position: static; top: auto; left: auto; outline: none; padding: 0px; width: 320px; height: 355px;" allowtransparency="1"></iframe>

I'have also checked that this iframe isn't inside another iframe.
Can anyone help?


text:
Q: How to integrate a remote VM server with all VMs to on-site LAN I have two sites: 1. the "local" site with client machines only and 2. the "remote" site with one VM server (ubuntu) hosting a number of VMs (ubuntu / windows).
Currently I'm connecting to those VMs using SSH tunnelling, but this is tedious (lots of fragile tunnels to maintain) and doesn't allow me to use standard ports for common services.
I'd like to connect to those hosted VMs like they were physical machines connected to the "local" LAN.
I've searched around, but I haven't found any questions dealing with connecting to hosted VM NAT network. All questions dealt with physical LANs and my networking knowledge really isn't sufficient to translate physical to VM NAT.
Is this possible? If so, what do I need to do to achieve this?

A: I would configure an IPSec site to site VPN for this using something like strongSwan. It should be fairly straightforward and the strongwan site has configuration examples to work with.


text:
Q: Join query with ElasticSearch I need to do a join query on firebase using elasticsearch,
can anyone help me?
In particular I have two nodes, in the child node I have a field that is the id of the father node and I would like to have as a result all the fields of the father node.
How do I build my index in the code?
In adding, in my client I use elasticsearchclient,
here is an extract of the code to index a node:
var db = admin.database();
var etest = db.ref(type);
etest.on('child_added',   createOrUpdateIndex);
etest.on('child_changed', createOrUpdateIndex);
etest.on('child_removed', removeIndex);

function createOrUpdateIndex(snap) {

 client.index(index, type, snap.val(), snap.key)
 .on('data', function(data) { console.log('indexed', snap.key + data ); })
 .on('error', function(err) { console.log('index error ', err); }).exec();
}

 function removeIndex(snap) {
  client.deleteDocument(index, type, snap.key, function(error, data) {
    if( error ) console.error('failed to delete', snap.key, error);
    else console.log('deleted', snap.key);
 });
}

And to take query results:
var queue = db.ref("search");
queue.child('request').on('child_added', processRequest);

function processRequest(snap) {
    console.log('process...... ');
   snap.ref.remove(); // clear the request after we receive it
   var data = snap.val();
   // Query ElasticSearch
    client.search(index, data.type, { "query": { 'query_string': {
            "query" : data.query
        }}})

   .on('data', function(results) {
       var res = JSON.parse(results);
       console.log(JSON.stringify(res.hits));
       console.log("TOTAL " + JSON.stringify(res.hits.total));
       queue.child('response/'+snap.key).set(results);
   })

   .on('error', function(error){ console.log("errore"); }).exec();

}

Thank you in advance

A: There are two ways to store your data.
First is creating a nested doc. This is helpful if you need to perform search on some of the values and need other info only for the display.
PUT /my_index {
"mappings": {
"yourIndex": {
  "properties": {
    "yourColumn": {
      "type": "nested",
      "properties": {
        "name":    { "type": "string"  },
        "parentNode": { "type": "string"  },
        "childNode":     { "type": "string"   }
      }
    }
  }
}}}

Eg.
'str1', 'parent1', 'child1'
'str2' 'parent1', 'child2'
If you need not maintain any hierarchy,
you can simply create 3 separate columns and store like a flat data.
You can specify parent1 id and search for all the docs in both the cases.


text:
Q: How to flush text to the right in CSS? I would like to have this
.--------------------------------------.
| Left                           Right |
'--------------------------------------'

One solution (with Bootstrap) is:

        Left

        Right

Is there a simpler way such as this?

Left Right

A: using bootstrap 4

Left

Right

without bootstrap

.someClass {
   display: flex;
   justify-content: space-between;
}

Left

Right


text:
Q: struct.error: unpack requires a buffer of 4 bytes I want to convert data from a device from bites to float
I use the code from this answer
bytes to float
import struct

byte_file = b'+001.80\r'
print(type(byte_file))

y = struct.unpack('f' , byte_file)
print(y)

I get this struct.error: unpack requires a buffer of 4 bytes
The correct outcome should be 1.80
do I need to implement a buffer argument ?

A: struct is used for binary packed data - data that is not human-readable. b'+001.80\r' is 8 bytes long: b'+', b'0', b'0', b'1', b'.', ....
You can just decode it and use float:
>>> b'+001.80\r'.decode()
'+001.80\r'
>>> float(_)
1.8
>>> import struct
>>> struct.pack('f', _)
b'ff\xe6?'  # doesn't look anything like your data!

However, because your data is 8 bytes long, you could treat it as a single double-precision floating-point value:
>>> struct.unpack('d', b'+001.80\r')
(3.711588247816385e-245,)

But that treats the data as binary-packed: +001.80\r, also known as 2b 30 30 31 2e 38 30 0d, is what 3.711588247816385e-245 looks like in memory.


text:
Q: How to Convert Number to always have 2 digits after the decimal? Quick question: I am trying to always get 2 digits after the money amount I previously had this code:
case 'tool_paid':
      echo get_post_meta ( $post_id, 'tool_paid', true );
      break;

But it only returns me 650 and I want it to return 650.00 I have tried the following with no success:
case 'tool_paid':
      $toolpaid = get_post_meta ( $post_id, 'tool_paid', true );
      echo $toolpaid number_format(2);
      break;

Thanks for any help on this, still a noob at php.

A: You need
case 'tool_paid':
      $toolpaid = get_post_meta ( $post_id, 'tool_paid', true );
      echo number_format($toolpaid,2);  // Corrected syntax & parameters here.
      break;

PHP will coerce the variable to float as required, unless declare(strict_types=1), in which case it will fail with a TypeError. You can coerce the number if need be with simple cast.
For example:
echo number_format((float)$toolpaid,2);
The PHP manual is a good place to look for function parameters and syntax.
Demo:https://3v4l.org/MpFMi


text:
Q: How to Share List ListBox items using ShareStatusTask in Windows Phone 8 I am new to Coding, But using tutorials I have so far created a little story app data blinded using class. I want to implement a Sharing ContextMenu on the XAML below.
Story.xaml
 <ListBox x:Name="ListParagraph"
         ItemsSource="{Binding Path=ListParas}"
         Loaded="ListParagraph_Loaded" >
        <ListBox.ItemTemplate>
            <DataTemplate>
                <ts:ParagraphTemplateSelector Content="{Binding}">
                    <ts:ParagraphTemplateSelector>
                        <DataTemplate>
                            <StackPanel Background="Transparent" Margin="10,0"  >

                                <toolkit:ContextMenuService.ContextMenu>
                                    <toolkit:ContextMenu x:Name="ContextMenu">
                                       <toolkit:MenuItem x:Name="Share"
                                           Header="Share" Click="Share_Click"/>
                                     </toolkit:ContextMenu>
                                </toolkit:ContextMenuService.ContextMenu>

                                <TextBlock  x:Name="Detail"
                                     Text="{Binding Path=Name, Mode=OneWay}"
                                      TextWrapping="Wrap">

                            </StackPanel>
                        </DataTemplate>
               </ts:ParagraphTemplateSelector>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

Here is the Story.xaml.cs
private void Share_Click(object sender, RoutedEventArgs e)
    {
        ShareStatusTask shareStatusTask = new ShareStatusTask();
        shareStatusTask.Status = "";
        shareStatusTask.Show();
    }

I searched the internet two days for this Share Status task/Share Linktask . But all I cound find was sample smales like the above .cs file. What should I add to shareStatusTask.Status = ""; to share the Data in the Above XAML file?


text:
Q: Passing arguments to the Class Constructor How can I pass a arbitrary number of arguments to the class constructor using the Object() function defined below?
<?php

/*
./index.php
*/

function Object($object)
{
    static $instance = array();

    if (is_file('./' . $object . '.php') === true)
    {
        $class = basename($object);

        if (array_key_exists($class, $instance) === false)
        {
            if (class_exists($class, false) === false)
            {
                require('./' . $object . '.php');
            }

            /*
            How can I pass custom arguments, using the
            func_get_args() function to the class constructor?

            $instance[$class] = new $class(func_get_arg(1), func_get_arg(2), ...);
            */

            $instance[$class] = new $class();
        }

        return $instance[$class];
    }

    return false;
}

/*
How do I make this work?
*/

Object('libraries/DB', 'DATABASE', 'USERNAME', 'PASSWORD')->Query(/* Some Query */);

/*
./libraries/DB.php
*/

class DB
{
    public function __construct($database, $username, $password, $host = 'localhost', $port = 3306)
    {
        // do stuff here
    }
}

?>

A: Instead of your class taking separated parameters I'd have it take an array.
class DB
{
    public function __construct(array $params)
    {
        // do stuff here
    }
}

That way you can pass the direct result of the func_get_args into your constructor. The only problem now is being able to figure out the array key / values.
If anyone else has any ideas I'd also be delighted to know :)

A: $klass = new ReflectionClass($classname);
$thing = $klass->newInstanceArgs($args);

Although the need to use reflection suggests that you are overcomplicating something in your design. Why do you want to write this function in the first place?

A: I haven't tried this, but call_user_func_array sounds like you want.
$thing = call_user_func_array(array($classname, '__construct'), $args);

Have a look in the PHP Documentation.

A: An alternative for the reflection method, would be evaluate your code.
eval('$instance = new className('.implode(', ', $args).');');


text:
Q: What is the consequence of re-using BSSID values? hostapd.conf:
# hostapd will generate BSSID mask based on the BSSIDs that are
# configured. hostapd will verify that dev_addr & MASK == dev_addr. If this is
# not the case, the MAC address of the radio must be changed before starting
# hostapd (ifconfig wlan0 hw ether <MAC addr>). If a BSSID is configured for
# every secondary BSS, this limitation is not applied at hostapd and other
# masks may be used if the driver supports them (e.g., swap the locally
# administered bit)
#
# BSSIDs are assigned in order to each BSS, unless an explicit BSSID is
# specified using the 'bssid' parameter.
# If an explicit BSSID is specified, it must be chosen such that it:
# - results in a valid MASK that covers it and the dev_addr
# - is not the same as the MAC address of the radio
# - is not the same as any other explicitly specified BSSID

The last point is violated by hostap generated by LEDE 17.01.2 :(.  The multiple interfaces were created using the LUCI web interface.  I don't believe this changed since OpenWrt 15.05 either.
interface=wlan0
ctrl_interface=/var/run/hostapd
disassoc_low_ack=1
preamble=1
wmm_enabled=1
ignore_broadcast_ssid=0
uapsd_advertisement_enabled=1
wpa_passphrase=hunter2
auth_algs=1
wpa=2
wpa_pairwise=CCMP
ssid=VOYAGER2091-90-jenkins
wpa_key_mgmt=WPA-PSK
okc=0
disable_pmksa_caching=1
bssid=74:44:01:86:42:d4

bss=wlan0-1
ctrl_interface=/var/run/hostapd
disassoc_low_ack=1
preamble=1
wmm_enabled=1
ignore_broadcast_ssid=0
uapsd_advertisement_enabled=1
wpa_passphrase=hunter2
auth_algs=1
wpa=2
wpa_pairwise=CCMP
ssid=VOYAGER2091-alan
wpa_key_mgmt=WPA-PSK
okc=0
disable_pmksa_caching=1
bssid=76:44:01:86:42:d4

Why does hostapd say it requires distinct BSSIDs?  What are the possible results of violating this?
In previous versions, I've had problems even creating multiple wifi networks like this.  After switching to this LEDE release, it seems able to create the networks OK.  However, moving away from the access point to room B, often one network shows up but not the other.  (Client is Fedora 26 with an Intel wireless card).  But this is within usable range, and if I had already connected to one of the networks, I think it is always able to remain connected when moving to room B.  So I'm slightly suspicious about this business with BSSIDs.

A:
Ummm they look distinct to me, one starts 74 the other 76? – user1998586

Ah.  What confused me is that you have to check the part which I expected to be the OUI.
The original Netgear OUI appears to be 74:44:01, as used on my WNDR3800.  This gets used on wlan0 (2.4Ghz), wlan1 (5Ghz), and eth1 (WAN).
103: wlan0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP qlen 1000
    link/ether 74:44:01:86:42:d4 brd ff:ff:ff:ff:ff:ff
107: wlan1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP qlen 1000
    link/ether 74:44:01:86:42:d6 brd ff:ff:ff:ff:ff:ff
3: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP qlen 1000
    link/ether 74:44:01:86:42:d5 brd ff:ff:ff:ff:ff:ff

The other interfaces appear to use different OUIs which do not show as being registered.  But this is because the Universal/Local bit, 0x02, has been set (meaning Locally assigned).  Each BSSID is distinct.
104: wlan0-1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP qlen 1000
    link/ether 76:44:01:86:42:d4 brd ff:ff:ff:ff:ff:ff
108: wlan1-1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP qlen 1000
    link/ether 76:44:01:86:42:d6 brd ff:ff:ff:ff:ff:ff
109: wlan1-2: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP qlen 1000
    link/ether 72:44:01:86:42:d6 brd ff:ff:ff:ff:ff:ff
113: wlan1-3: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP qlen 1000
    link/ether 7e:44:01:86:42:d6 brd ff:ff:ff:ff:ff:ff
121: wlan1-4: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP qlen 1000
    link/ether 7a:44:01:86:42:d6 brd ff:ff:ff:ff:ff:ff
161: wlan1-5: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP qlen 1000
    link/ether 66:44:01:86:42:d6 brd ff:ff:ff:ff:ff:ff

2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP qlen 1000
    link/ether 76:44:01:86:42:d4 brd ff:ff:ff:ff:ff:ff
65: br-lan: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP qlen 1000
    link/ether 76:44:01:86:42:d4 brd ff:ff:ff:ff:ff:ff
66: eth0.1@eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue master br-lan state UP qlen 1000
    link/ether 76:44:01:86:42:d4 brd ff:ff:ff:ff:ff:ff

The sequence of generated MAC addresses is not quite clear to me.  However it seems to reproduce if I delete the last network and then re-create it.
I'm not sure why eth0 / br-lan has been assigned the same MAC address as wlan0-1, or whether that could cause some other problem.  br-lan does not include wlan0-1; the only member of the bridge is eth0.1.


text:
Q: How to use encrypted password in apache BasicDataSource? At present i am keeping the password [ unencrypted ] in a property file. This password get placed as is in the configuration xml using ant.
 [ The configuration xml is for datasource, it is creating the object of dbcp.BasicDataSource ]
Now, is it possible that after the ant target the password is copied in encrypted form. Heard the Jasypt can do that! Till now i haven't tried this. But, the problem doesn't end here. BasicDataSource do not accept encrypted password. Is there any replacement for BasicDatasource.
FYI: I am using Spring, if that matters.

A: The following jasypt link explains how a properties file containing encrypted content can be read from within your application:
http://www.jasypt.org/encrypting-configuration.html
To create the properties file from within ANT my suggestion is to use the groovy task as follows:
<taskdef name="groovy" classname="org.codehaus.groovy.ant.Groovy"/>

<groovy>
import org.jasypt.encryption.pbe.StandardPBEStringEncryptor

def encryptor = new StandardPBEStringEncryptor();
encryptor.setPassword("secret");

def f = new File("config.properties")
f.println "datasource.driver=com.mysql.jdbc.Driver"
f.println "datasource.url=jdbc:mysql://localhost/reportsdb"
f.println "datasource.username=reportsUser"
f.println "datasource.password=ENC("+encryptor.encrypt("dbpassword")+")"

</groovy>

A: Not entirely true in the case of BasicDataSource.
If you read the javadocs for BasicDataSource, setPassword()  has no effect once the pool has been initialized.  The pool is initialized the first time one of the following methods is invoked: getConnection, setLogwriter, setLoginTimeout, getLoginTimeout, getLogWriter.
Ref: http://www.docjar.com/html/api/org/apache/commons/dbcp/BasicDataSource.java.html
All these methods call createDataSource() eventually.
So your new BasicDataSource class only needs to override the method createDataSource()
Something like this:
public class NewBasicDataSource extends BasicDataSource {

    protected synchronized DataSource createDataSource() throws SQLException {
        String decryptedPassword = decryptPassword( super.getPassword() );
        super.setPassword( decryptedPassword );
        return super.createDataSource();
    }

    private String decryptPassword( String password ) {
        return //logic to decrypt current password
    }
}

A: Extend BasicDataSource, override setPassword and setUserName methods. Decrypt the values in those methods and pass them to super class methods.

A: Create a new task by extending existing task Copy( responsible for file-copy ). Create a new type by extending FilterSet ( responsible for filtering of tokens ).
see the code here:-
How to create nested element for ant task?
build.xml
<target name="encrypted-copy" >
        <CopyEncrypted todir="dist/xyz/config" overwrite="true">
            <fileset dir="config"/>
            <encryptionAwareFilterSet>
                <filtersfile file="conf/properties/blah-blah.properties" />
            </encryptionAwareFilterSet>
        </CopyEncrypted>
    </target>

blah-blah.properties
property1=value1
property2=value2
PASSWORD=^&YUII%%&*(
USERNAME=rjuyal
CONNECTION_URL=...
someotherproperty=value

configuration xml
<bean id="dataSource"
        class="com.xyz.datasource.EncryptionAwareDataSource"
        destroy-method="close" autowire="byName">
        <property name="driverClassName">
            <value>com.ibm.db2.jcc.DB2Driver</value>
        </property>
        <property name="url">
            <value>@CONNECTION_URL@</value>
        </property>
        <property name="username">
            <value>@USERNAME@</value>
        </property>
        <property name="password">
            <value>@PASSWORD@</value>
        </property>
        <property name="poolPreparedStatements">
            <value>true</value>
        </property>
        <property name="maxActive">
            <value>10</value>
        </property>
        <property name="maxIdle">
            <value>10</value>
        </property>
    </bean>
...
...
...

After the execution of the target the xml is copied with values from properties file. Password will be encrypted.
This will handle the encrypted password.
EncryptionAwareDataSource
public class EncryptionAwareDataSource extends BasicDataSource{
    @Override
    public synchronized void setPassword(String password) {
        super.setPassword(Encryptor.getDecryptedValue( password ));
    }
}

That' all ;)

A: With Spring there is a better way: use the PropertyPlaceholderConfigurer class.
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <value>classpath:com/foo/jdbc.properties</value>
    </property>
    <property name="propertiesPersister">
        <bean class="com.mycompany.MyPropertyPersister" />
    </property>
</bean>

<bean id="dataSource" destroy-method="close"
      class="org.apache.commons.dbcp.BasicDataSource">
    <property name="driverClassName" value="${jdbc.driverClassName}"/>
    <property name="url" value="${jdbc.url}"/>
    <property name="username" value="${jdbc.username}"/>
    <property name="password" value="${jdbc.password}"/>
</bean>

When you specify a subclass of PropertiesPersister in the property placeholder, Spring load the jdbc.properties and decrypt the file using that class. Maybe something like:
public class MyPropertyPersister extends DefaultPropertiesPersister
{
    // ... initializing stuff...

    public void load(Properties props, InputStream is) throws IOException
    {
        Cipher decrypter = getCipher();
        InputStream cis = new CipherInputStream(is, decrypter);
        super.load(props, cis);
    }

    public void load(Properties props, Reader reader) throws IOException
    {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        IOUtils.copy(reader, baos);
        ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());

        Cipher decrypter = getCipher();
        InputStream cis = new CipherInputStream(bais, decrypter);

        InputStreamReader realReader = new InputStreamReader(cis);
        super.load(props, realReader);
    }

    public void loadFromXml(Properties props, InputStream is) throws IOException
    {
        Cipher decrypter = getCipher();
        InputStream cis = new CipherInputStream(is, decrypter);
        super.loadFromXml(props, cis);
    }

    private Cipher getCipher()
    {
         // return a Cipher to read the encrypted properties file
         ...
    }
    ...
}

Hope it helps.
EDIT
If you use Jasypt, you do not need to define any PropertiesPersister. From the Jasypt documentation:

Jasypt provides an implementation of these configuration-related Spring classes which can read .properties files with encrypted values (like the ones managed by the EncryptableProperties class) and handle them transparently to the rest of the Spring application beans.

With this, you can define jdbc.properties like this
 jdbc.driver=com.mysql.jdbc.Driver
 jdbc.url=jdbc:mysql://localhost/reportsdb
 jdbc.username=reportsUser
 jdbc.password=ENC(G6N718UuyPE5bHyWKyuLQSm02auQPUtm)

and the Spring config may be like this
<bean class="org.jasypt.spring.properties.EncryptablePropertyPlaceholderConfigurer">
   <constructor-arg>
     <bean class="org.jasypt.encryption.pbe.StandardPBEStringEncryptor">
       <property name="config">
         <bean class="org.jasypt.encryption.pbe.config.EnvironmentStringPBEConfig">
           <property name="algorithm" value="PBEWithMD5AndDES" />
           <property name="passwordEnvName" value="APP_ENCRYPTION_PASSWORD" />
         </bean>
       </property>
     </bean>
   </constructor-arg>
   <property name="locations">
     <list>
       <value>/WEB-INF/classes/jdbc.properties</value>
     </list>
   </property>
</bean>

<bean id="dataSource" destroy-method="close"
      class="org.apache.commons.dbcp.BasicDataSource">
    <property name="driverClassName" value="${jdbc.driverClassName}"/>
    <property name="url" value="${jdbc.url}"/>
    <property name="username" value="${jdbc.username}"/>
    <property name="password" value="${jdbc.password}"/>
</bean>

This way, you can put the password for decrypt the hidden property in an environment variable when you start the application and unset it later.


text:
Q: Repository pattern with EF Code First I am not grasping something when creating my repository pattern with EF Code First. If I want to abstract out EF I would have to make my repository be of type IObjectContextAdapter, no? That is what DbContext implements. If I later switch to use something like NHibernate or some other 3rd party ORM, it may not implement IObjectContextAdapter.
Is my only solution to create a wrapper that wraps the ORM and does return an implementation of IObjectContextAdapter? If so, what is the point?

A: I'm not sure you have to implement IObjectContextAdapter when creating a repository pattern with EF.  The main difference between using EF or something like NHibernate will be how to wrap either the DbContext or the ISession respectively.
Here is a sketch of how an EF code-first repository could be written:
public interface IRepository<TEntity>
{
    void Save();
}

public class Repository<TEntity> : IRepository<TEntity>
{
    private readonly IDbSet<TEntity> entitySet;

    public Repository(DbContext context)
    {
        this.entitySet = context.Set<TEntity>();
    }

    public void Save()
    {
        return this.entitySet.SaveChanges();
    }
}

This allows the actual DbContext to be injected.


text:
Q: android saving bitmap as jpeg properly but not display in image gallery Hello all i am saving my imageviews Bitmap as jpeg/png format but they are not listing in my image gallery( android default gallery)
THis is my method:
    public void save_Image() {

            String path = Environment.getExternalStorageDirectory().toString()
                    + "/ImageFrame";
            Log.d("Files", "Path: " + path);

            File f = new File(path);

            File file[] = f.listFiles();

            Log.d("Files", "Size: " + file.length);
            for (int i = 0; i < file.length; i++) {
                Log.d("Files", "FileName:" + file[i].getName());
            }

            // BitmapDrawable drawable = (BitmapDrawable) img_large.getDrawable();
            // Bitmap bitmap = drawable.getBitmap();

            RelativeLayout frm_l = (RelativeLayout) findViewById(R.id.frm_l);

            frm_l.setDrawingCacheEnabled(true);
            Bitmap bitmap = frm_l.getDrawingCache();

            File image = new File(sdCardDirectory + "/ImageFrame/", "HDWallpaper "
                    + file.length + ".png");

    //File image = new File(sdCardDirectory + "/ImageFrame/", "HDWallpaper "
            //  + file.length + ".jpeg");
            boolean success = false;
            FileOutputStream outStream;
            try {

                outStream = new FileOutputStream(image);
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
//          bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);

                /* 100 to keep full quality of the image */

                outStream.flush();
                outStream.close();
                success = true;
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (success) {
                System.out.println("this is path where stored.."
                        + Environment.getExternalStorageDirectory()
                                .getAbsolutePath());
                Toast.makeText(getApplicationContext(),

                "Saved Successfully", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(getApplicationContext(),
                        "Error during image sending", Toast.LENGTH_LONG).show();
            }

        }

This method works properly for me and saves bitmap But it does not list in my image gellery what should i do to overcome this problem?

A: You need to "tell" the gallery that you added an image. You can do this via MediaScannerConnection#scanFile:
MediaScannerConnection.scanFile(this,
    new String[] { "YourFilePathHere" }, null,
    new MediaScannerConnection.OnScanCompletedListener() {
        public void onScanCompleted(String path, Uri uri) {
            //now visible in gallery
        }
    }
);

taken from this answer. You may want to look at the other answers from that post, since they also solve your problem.

A: On which device u r testing right now ?
Use real device and test on it.
Or if you are using Genymotion then you must have to restart that device and then Open it again and check in gallary.(It's Genymotion problem).


text:
Q: Pandas DF referencing the same slice twice in the same computation I have a huge data set to process and I am trying to optimize the most costly line, processing wise.
I use a df with 3 columns, A, B and C.
I have 2 values, a and b, which are used to update the value of C in a subset of the df.
Before I continue, let me define a textual substitution to increase readability:
filter(_X) -> df.loc[df['A'] < a, _X]

Every time I type "filter", please substitute it with the text on the right (applying the correct argument in place of the parameter _X - think C/C++ macros).
The line of code in question is:
filter('C') += a * np.minimum(filter('B'), b)

What I'm not sure about is if python will process "filter" twice when evaluating the expression, or if it will use a "reference" (a-la C++) and only do it once.
In the former case, is there a way for me to rewrite the expression in a way to avoid the double execution of the code of "filter"?
Moreover, if you have suggestions on how to rewrite the "filter" itself, I'd be happy to test them.
EDIT:
Expanded version of the code:
df.loc[df['A'] < a, 'C'] += a * np.minimum(df.loc[df['A'] < a, 'B'], b)

A: If I understand correctly, you may not need to "filter twice" after the +=. see my example below:
np.random.seed(5)
df =  pd.DataFrame(np.random.randint(0,100,size=(4, 4)), columns=list('ABCD'))

    A   B   C   D
0   99  78  61  16
1   73  8   62  27
2   30  80  7   76
3   15  53  80  27

Now if you wanted to add the values of the minimum of columns C and D to the current value of B that would simply be: df.loc[df['A'] < 80, 'B'] += np.minimum(df['C'], df['D'])
    A    B      C   D
0   99  78.0    61  16
1   73  35.0    62  27 #<--- meets condition 8+27=35
2   30  87.0    7   76 #<--- meets condition 80+7=87
3   15  80.0    80  27 #<--- meets condition 53+27=80

Notice how when A < 80. the B value changes with whichever value in C or D is smaller. One thing to note is that B turns to a float. Not sure why.


text:
Q: H2 Database duplicates removal I wish to operate on duplicate rows in a H2 database table (DELETE would be a chance, SETting new value another).
Let's prepare some sample data:
create table receipt( id int primary key, receipt_number varchar(52), shop_id int);
insert into receipt(id, receipt_number, shop_id) values(1,'A',1);
insert into receipt(id, receipt_number, shop_id) values(2,'A',1);
insert into receipt(id, receipt_number, shop_id) values(3,'B',1);
insert into receipt(id, receipt_number, shop_id) values(4,'A',2);
select * from receipt;
select receipt_number, shop_id, count(*) count from receipt group by (receipt_number, shop_id);

which leads us to:

I thought that this statement would be enough:
merge into receipt as t1
using ( select receipt_number, shop_id, count(*) count from receipt group by (receipt_number, shop_id) ) as t2 on t1.receipt_number = t2.receipt_number
when matched and count > 1 then delete;

but an exception is raised:
Syntax error in SQL statement "MERGE INTO RECEIPT AS T1
    USING ( SELECT RECEIPT_NUMBER, SHOP_ID, COUNT(*) COUNT FROM RECEIPT GROUP BY (RECEIPT_NUMBER, SHOP_ID) ) AS T2 ON T1[*].RECEIPT_NUMBER = T2.RECEIPT_NUMBER
    WHEN MATCHED AND COUNT > 1 THEN DELETE "; expected "("; SQL statement:
merge into receipt as t1
    using ( select receipt_number, shop_id, count(*) count from receipt group by (receipt_number, shop_id) ) as t2 on t1.receipt_number = t2.receipt_number
    when matched and count > 1 then delete [42001-197] 42001/42001

You can easily test my code running
docker run -d -p 1521:1521 -p 8082:81  oscarfonts/h2

the browse to http://localhost:8082/ login and copy&paste code.

A: I think I solved it with
delete receipt
where id > (select min(id) from receipt t2 where receipt.receipt_number = t2.receipt_number and receipt.shop_id = t2.shop_id )

guess I can also use it for update.

A: Beware: The answer from Irkwz deletes all entries except the one with the lowest id (at least this happened in my trials.
Here is a better solution (tested on H2), but still not perfect as it removes only one duplicate per constraint per execution:
delete from receipt
where id in (
    select max(t2.id)
    from receipt t2
    group by t2.receipt_number, t2.shop_id
    having count(t2.id) > 1
);


text:
Q: Can jdk XPath search through custom document Is it possible to look through custom document and find custom object by using JDK's XPath?
If I am right class org.jaxen.DefaultNavigator is used for that purpose in Jaxen. Also C#'s XPathNavigator.
Does Java's XPath have something similar?
e.g.
javax.xml.xpath.XPath xp = XPathFactory.newInstance().newXPath();
MyOwnNodeList nodeList = (MyOwnNodeList) xpath.evaluate("//*[@Id='id']", myOwnDocumentTree, XPathConstants.NODESET);


text:
Q: TYPO3 8.4 and tx_indexedsearch_pi2 indexed search does not fully return results from header search box.
When I start a search there, it goes to the right page and takes the word searched into the search field of the search page, but does not search through it.
If I then click on the side where the plugin lies on search, it gives me the results.
Here is my TypoSrict: http://pastebin.com/yQ0UWdjn
my constants:
plugin.tx_indexedsearch {
view {
  templateRootPath = EXT:my_distribution/Resources/Private/Templates/
  partialRootPath = EXT:my_distribution/Resources/Private/Partials/
  layoutRootPath = EXT:my_distribution/Resources/Private/Layouts/
}
settings {
  targetPid = 11
  rootPidList = 1
  }
}

Templates, Partials, Layouts are copied from the Extension.

A: For extbase indexed search you should rename your search form field's name property with the following example code and put it in fluid template instead of TypoScript.
<f:form pageUid="{settings.searchPage}" extensionName="indexedsearch" id="headerSearchForm">

         <f:form.textfield class="form-control search" name="tx_indexedsearch[sword]" />

              <button class="btn btn-primary" type="button"></button>

</f:form>

A: For anybody else still having trouble, here was my solution for V8.7.19 (hopefully compatible with v6 - v9)
First, pass in the pageUId of the search field. I did this in my template setup:
page.10.settings.searchTargetPid = 119  //This is my pid number

Next, in my own private templates folder I created a search form using the following html:
<f:form method="post" pageUid="{settings.searchTargetPid}" name="tx_indexedsearch" extensionName="indexedsearch" pluginName="pi2" action="search" controller="Search">
    <f:form.textfield name="search[sword]" value="{sword}" />
    <f:form.submit name="search[submitButton]" value="Search" id="tx-indexedsearch-searchbox-button-submit" />
</f:form>

Note the use of the form parameters:

*

*extensionName="indexedsearch"  - without this your search text won't be used

*pluginName="pi2" - without this your search text won't be used

*action="search" - without this you will get an error regarding the denial of use of the "Standard" action

*controller="Search" - without this you will get an error regarding the denial of use of the "Standard" action

A: Thanks Manthan for your help.
Here is the final version:

            <f:form pageUid="{settings.indexedSearchResult}" action='search' extensionName="indexedsearch" controller='Search' pluginName='Pi2' id="headerSearchForm" style="width:100%;" class="navbar-form">

                <f:form.textfield class="form-control search" name="search[sword]" placeholder="Webseite durchsuchen..." />

              <button class="btn btn-default" type="submit" name="submitButton"></button>

            </f:form>


text:
Q: Differentiate between linear death process and pure death process I am having difficulty (and my textbook is of no help!) figuring out when to treat a problem as a linear death process with death parameters $\mu n$h vs. a pure death process with death parameter $\mu$h. Is there anything we need to look out for in questions to signify which one to use? Thanks for the help!

A: Think of it this way.  Given there are n individuals alive now, approximately how many do you expect to die in the next $\Delta t$ of time?  If different individuals' deaths are independent (which is the typical situation when the individuals are people or animals), this should be proportional to $n$ - there are more deaths per day in a big city than there are in a small village.  So then you want $\mu n \Delta t$.  On the other hand, you could have cases where the expected number of deaths does not depend on $n$.  For example, you might imagine a situation where deaths in an animal population occur only because at random times a hunter will come along and shoot one member of the population.  The hunter will not shoot more when there are more animals.  So in this case you would use $\mu \Delta t$.

A: But, i think a death process with death parameter $\mu_n$ is called pure death process and a death process with death parameter $\mu$ will poisson death process?
Where $\mu n$ is linear death process?


text:
Q: Multiple file upload & json object in a single POST Request on Play Framework I have a Windows Phone 8 client that makes the following post request:
public async Task<string> DoPostRequestAsync(String URI, JSonWriter jsonObject, ObservableCollection<byte[]> attachments)
    {
        var client = new RestClient(DefaultUri);

        var request = new RestRequest(URI, Method.POST);
        request.AddParameter("application/json; charset=utf-8", jsonObject.ToString(), ParameterType.RequestBody);

        // add files to upload
        foreach (var a in attachments)
            request.AddFile("picture", a, "file.jpg");

        var content = await client.GetResponseAsync(request);

        return content;
    }

From the RestSharp documentation i read that by adding files to a request it's automatically made as a "multipart/form-data" request.
The controller for the upload operation in Play 2.1 is as follows:
@BodyParser.Of(BodyParser.Json.class)
public static Result createMessage() {
    JsonNode json = request().body().asJson();
    ObjectNode result = Json.newObject();
    String userId = json.findPath("userId").getTextValue();
    String rayz = json.findPath("message").getTextValue();

    Http.MultipartFormData body = request().body().asMultipartFormData();
    Http.MultipartFormData.FilePart picture = body.getFile("picture");

    if (picture != null) {
        String fileName = picture.getFilename();
        String contentType = picture.getContentType();
        File file = picture.getFile();

        result.put("status", "success");
        result.put("message", "Created message!");
        return badRequest(result);
    } else {
        result.put("status", "error");
        result.put("message", "Message cannot be created!");
        return badRequest(result);
    }
}

Note that on the application.conf i have set the following in order to increase the size limit (seems not be working):
# Application settings
# ~~~~~
parsers.text.maxLength=102400K

Now, each time I am trying to make the POST request i noticed on the debugger that IsMaxSizeEsceeded variable is always true and that the multipart variable is null. When i tried to just upload one file nu using the following controller everything seemed to work normally. The size wasn't a problem and the multipart variable was set.
public static Result singleUpload() {
    ObjectNode result = Json.newObject();

    Http.MultipartFormData body = request().body().asMultipartFormData();
    Http.MultipartFormData.FilePart picture = body.getFile("picture");
    if (picture != null) {
        String fileName = picture.getFilename();
        String contentType = picture.getContentType();
        File file = picture.getFile();
        result.put("status", "success");
        result.put("message", "File uploaded!");
        return badRequest(result);
    } else {
        result.put("status", "error");
        result.put("message", "File cannot be uploaded!");
        return badRequest(result);
    }
}

The problem is that the attachments/files should be sent/uploaded along with the JSON object to the server in a single POST Request and NOT separately.
Has anyone faced similar problems before? Is it possible to achieve this - Send a json object and multiple files to be uploaded on the server in a single POST request with Play 2.1?

A: Found the way to do it..posting it in case someone else tries to do something similar in the future.
So first of all the request from RestSharp client must be done in the following way:
public async Task<string> DoPostRequestWithAttachmentsAsync(String ext, JSonWriter jsonObject, ObservableCollection<byte[]> attachments) {
    var client = new RestClient(DefaultUri);
    var request = new RestRequest(ext, Method.POST);

    request.RequestFormat = DataFormat.Json;
    request.AddParameter("json", jsonObject.ToString(), ParameterType.GetOrPost);

    // add files to upload
    foreach (var a in attachments)
        request.AddFile("attachment", a, "someFileName");

    var content = await client.GetResponseAsync(request);

    if (content.StatusCode != HttpStatusCode.OK)
            return <error>;

    return content.Content;
}

Now moving into Play the controller is as follows:
public static Result createMessage() {
    List<Http.MultipartFormData.FilePart> attachments;
    String json_str;

    Http.MultipartFormData body = request().body().asMultipartFormData();

    // If the body is multipart get the json object asMultipartFormData()
    if (body!=null) {
        json_str = request().body().asMultipartFormData().asFormUrlEncoded().get("json")[0];
        attachments= body.getFiles();
    }
    // Else, if the body is not multipart get the json object asFormUrlEncoded()
    else {
        json_str = request().body().asFormUrlEncoded().get("json")[0];
        attachments = Collections.emptyList();
    }

    // Parse the Json Object
    JsonNode json = Json.parse(json_str);

    // Iterate through the uploaded files and save them to the server
    for (Http.MultipartFormData.FilePart o : attachments)
        FileManager.SaveAttachmentToServer(o.getContentType(), o.getFile());

    return ok();
}

So the mistakes in the RestSharp side seemed to be the ParameterType.RequestBody on the json object; and in the controller the size doesn't really changes anything.. but the important part is not to use the @BodyParser.Of(BodyParser.Json.class) since that would convert the whole request body into a json object. That combined with the files that are being send to the server triggers the isMaxSizeExceeded flag.
Finally the multipart file handling in the controller is as shown above, only tricky part is that the attachments are optional meaning that this must be handled.


text:
Q: How to write captured input from a tkinter entry widget to a json file Thank you for your time. I reduced the structure of this problem to make it as simple to solve as possible. I am working in python with the GUI developer, tkinter. I want to capture the text input from an entry widget in tkinter and print/write it in a json file. What I have so far is this example, which capture the text from the entry widgets and prints the text in the shell terminal.
from tkinter import *

def show_entry_fields():
   print("First Name: %s\nLast Name: %s" % (e1.get(), e2.get()))
   e1.delete(0,END)
   e2.delete(0,END)

master = Tk()
Label(master, text="First Name").grid(row=0)
Label(master, text="Last Name").grid(row=1)

e1 = Entry(master)
e2 = Entry(master)

e1.grid(row=0, column=1)
e2.grid(row=1, column=1)

Button(master, text='Show', command=show_entry_fields).grid(row=3, column=1, sticky=W, pady=4)

mainloop( )

This code does exactly what I want to do, except that the text is printed in the shell terminal instead of a separate json file. To print the text in a json file, I have tried alternative function methods like:
def show_entry_fields():
   f = open('name.json', 'a', encoding = 'utf8')
   print("First Name: %s\nLast Name: %s" % (e1.get(), e2.get()))
   e1.delete(0,END)
   e2.delete(0,END)

Here, I hoped that the function would open the json file 'name.json' and print the text in that file in the same way that the first example printed the text in the shell terminal. This was not successful.
And:
def show_entry_fields():
   f = open('name.json', 'a', encoding = 'utf8')
   f.write("First Name: %s\nLast Name: %s" % (e1.get(), e2.get()))
   e1.delete(0,END)
   e2.delete(0,END)

Here, I hoped that the same goal would be accomplished, but again it was unsuccessful.
Ultimately, the goal is to print the text entered into the entry widget in the 'name.json' file. While I have been able to print the text from the entry widget in the terminal shell (see the first example), I have not been able to find a function to open a json file and print the text in that file. Thanks!
This is different than any other question because this question asks specifically how to export captured text to a json file. Previous questions deal specifically with capturing the text.

A: If you want to write json, the first step is to create a data structure that can be converted to json. Then, you can use the json.dump function to write the data to a file.
Example:
import json
...
data = {
    "first_name": e1.get(),
    "last_name": e2.get()
}
with open('name.json', 'w') as f:
    json.dump(data, f, indent=4)

When you execute that code, and enter "Foo" for the first name and "Bar" for the last name, the file will have this as its contents:
{
    "first_name": "Foo",
    "last_name": "Bar"
}

A: This code works! Using open("file name", "a") and then write, exports the input from the entry label to the file!
from tkinter import *

def show_entry_fields():
   f = open("name.json", "a")
   f.write("First Name: %s\nLast Name: %s" % (e1.get(), e2.get()))
   e1.delete(0,END)
   e2.delete(0,END)

master = Tk()
Label(master, text="First Name").grid(row=0)
Label(master, text="Last Name").grid(row=1)

e1 = Entry(master)
e2 = Entry(master)

e1.grid(row=0, column=1)
e2.grid(row=1, column=1)

e1.config(relief=SUNKEN)
e2.config(relief=SUNKEN)

Button(master, text='Show', command=show_entry_fields).grid(row=3, column=1, sticky=W, pady=4)

mainloop( )


text:
Q: UIDatePicker not updating UITextField I've been using a multitide of tutorials and stackoverflow answers to piece this together. I have a UITextField which when the user taps slides up a UIDatePicker (instead of keyboard). Once the datepicker is closed the TextField should update with the selected date.
However it just has the current date/time in there no matter what you change it to. What am I missing? I want it formatted as MM / dd / yyyy too.
- (void)viewDidLayoutSubviews {
[super viewDidLayoutSubviews];

//birthday view
UIDatePicker *datePicker = [[UIDatePicker alloc] init];
UIToolbar *doneBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.frame), 44)];

datePicker.datePickerMode = UIDatePickerModeDate;
[datePicker addTarget:self action:@selector(updateTextField:) forControlEvents:UIControlEventValueChanged];
_birthdayField.inputView = datePicker;
[_birthdayField setInputAccessoryView:doneBar];

[doneBar setBarStyle:UIBarStyleDefault];
UIBarButtonItem *spacer = [[UIBarButtonItem alloc]
                           initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
                           target:nil
                           action:nil];
[doneBar setItems: [NSArray arrayWithObjects:spacer, [[UIBarButtonItem alloc]
                                                      initWithTitle:@"Done"
                                                      style:UIBarButtonItemStyleDone
                                                      target:self
                                                      action:@selector(datePickerDone:)],nil ] animated:YES];
}

- (IBAction)datePickerDone:(id)sender {
    [_birthdayField resignFirstResponder];
}

-(void)updateTextField:(id)sender {
    if([_birthdayField isFirstResponder]) {
        UIDatePicker *picker = (UIDatePicker*)_birthdayField.inputView;
        _birthdayField.text = [NSString stringWithFormat:@"%@", picker.date];
    }
}

I assume it's something I'm missing in updateTextField.

A: Because you resign the _birthdayField when the done button is touched.
So the code in updateTextfield if block never gets called.

A: After playing around I figured out the issue. Bseh's answer didn't apply as when I placed a breakpoint in updateTextField it was definitely hitting it. I changed the following:
- (void)updateTextField:(UIDatePicker *)sender {
    NSDateFormatter *datePickerFormat = [[NSDateFormatter alloc] init];
    [datePickerFormat setDateFormat:@"MM  /  dd  /  yyyy"]; //here specify your format..
    NSString *dateString = [datePickerFormat stringFromDate:sender.date];
    self.birthdayField.text = dateString;
}

Changing that id to UIDatePicker made the difference for me! I've also added the formatting I wanted.


text:
Q: Python: creating a grid Is it possible to create a grid like below?
I didn't found anything in the forum.
#euler-project problem number 11
#In the 20 times 20 grid below,
#four numbers along a diagonal line have been marked in red.
#The product of these numbers is 26 times 63 times 78 times 14 = 1788696.
#What is the greatest product of four adjacent numbers in any direction
#(up, down, left, right, or diagonally) in the 20 times 20 grid?

import numpy

number = numpy.array([[08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08]
[49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00]
[81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65]
[52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91]
[22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80]
[24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50]
[32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70]
[67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21]
[24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72]
[21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95]
[78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92]
[16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57]
[86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58]
[19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40]
[04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66]
[88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69]
[04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36]
[20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16]
[20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54]
[01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48]])

EDIT no.1:
I found numpy-array now.
x = np.array([[1, 2, 3], [4, 5, 6]], np.int32)

Is there a way to do it without the commas?
EDIT no.2:
I also found a new problem.
Python: Invalid Token
Invalid token in number 08! :)

A: You can define the numbers in a string and split it easily in row/columns:
nums = """\
1 2 3
4 5 6
7 8 9 10
"""
rows = [map(int, row.split()) for row in nums.splitlines()]
print rows      ##> [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]

A: Check out NumPy - specifically, the N-dimensional array object.

A: Your code example won't compile unless you put commas between the list elements.
For example, this will compile:
value = [
         [ 1, 2, 3, 4],
         [ 5, 6, 7, 8],
         [ 9,10,11,12]
        ]

If you're interested in taking strings like you show, and parsing them into a list of lists (or numpy multi-dimensional array), or if you have a list of lists or numpy array and want to print them out like you describe, you can do that too with a clever couple of list comprehensions.

A: What you have above does not work, e.g if pasted into a file and then run as a script, or pasted into the interpreter. I get:
SyntaxError: invalid token

Again, I suspect that what you have done is paste text (a string) containing these characters. They are not integers, and you will get nowhere unless you realize that fact.
Edit:  I see...we only get "invalid syntax" if we avoid the "invalid token" error caused by the "08"
>>> import numpy
>>> number = numpy.array([[08 02 22 97]])
  File "<stdin>", line 1
    number = numpy.array([[08 02 22 97]])
                            ^
SyntaxError: invalid token
>>> number = numpy.array([[18 12 22 97]])
  File "<stdin>", line 1
    number = numpy.array([[18 12 22 97]])
                               ^
SyntaxError: invalid syntax

A: As for parsing the actual data, and you don't want to read it from a file or use sensible methods, there is always this:
s = """[[08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08]
...etc
"""

s = s.replace("]", "").replace("[", "").split()

numbers = [int(x) for x in s]

Then you got a 1d array of numbers, which you can have fun with.


text:
Q: Kafka streams with multiple application instances I have 2 instances of my application for kafka streams  consuming 2 partitions in a single topic.
will the single partitions data be only in one application or both applications? and Say if one applications instance is down will i have issues. how will interactive queries solve this ?
do i need to use globalktable?

A: Each kafka stream application instance will be mapped to one or more partition, based on how many partitions the input topics have.
If you run 2 instances for an input topic with 2 partitions, each partition will consume from one partition. If one instance goes down, kafka stream will rebalance the work load on the first instance and it will consumer from both partition.
You can refer the architecture here in detail : https://docs.confluent.io/current/streams/architecture.html