text:
Q: How to resize the text's width accordingly to the image responsive width I'm new to the html5/css3 and bootstrap world since I started to learn these things one week ago.
My problem is that I want the text width (the area's width in which the text is displayed) to be accordingly with the width of the responsive image.
When the page is in lg/md/sm responsive mode, the text is displayed correctly under the image accordingly to "its width" but when in xs responsive mode, the text is not displayed correctly.
Image of what I want:
http://imgur.com/F2Y4afD
Images (the link has to images, switch with keyboard's keys!) of your proposed solution (the problem is still there!):
http://imgur.com/tYKixk5,g9EkoM4#1
Here is the HTML code:

Latest News

Prova

The Pulpit Rock is a massive cliff 604 metres (1982 feet) above Lysefjorden, opposite the Kjerag plateau, in Forsand, Ryfylke, Norway. The top of the cliff is approximately 25 by 25 metres (82 by 82 feet) square and almost flat, and is a famous tourist attraction in Norway.

Prova

The Pulpit Rock is a massive cliff 604 metres (1982 feet) above Lysefjorden, opposite the Kjerag plateau, in Forsand, Ryfylke, Norway. The top of the cliff is approximately 25 by 25 metres (82 by 82 feet) square and almost flat, and is a famous tourist attraction in Norway.

Prova

The Pulpit Rock is a massive cliff 604 metres (1982 feet) above Lysefjorden, opposite the Kjerag plateau, in Forsand, Ryfylke, Norway. The top of the cliff is approximately 25 by 25 metres (82 by 82 feet) square and almost flat, and is a famous tourist attraction in Norway.

Any idea guys?
Sorry for my bad english, it's not my native language and sorry if my question has been answered over and over again but I don't know which keywords to search for...
I found this solution working for me (still I need to know the image size to add fixed width to the  element:

Latest News

Prova

The Pulpit Rock is a massive cliff 604 metres (1982 feet) above Lysefjorden, opposite the Kjerag plateau, in Forsand, Ryfylke, Norway. The top of the cliff is approximately 25 by 25 metres (82 by 82 feet) square and almost flat, and is a famous tourist attraction in Norway.

Prova

The Pulpit Rock is a massive cliff 604 metres (1982 feet) above Lysefjorden, opposite the Kjerag plateau, in Forsand, Ryfylke, Norway. The top of the cliff is approximately 25 by 25 metres (82 by 82 feet) square and almost flat, and is a famous tourist attraction in Norway.

Prova

The Pulpit Rock is a massive cliff 604 metres (1982 feet) above Lysefjorden, opposite the Kjerag plateau, in Forsand, Ryfylke, Norway. The top of the cliff is approximately 25 by 25 metres (82 by 82 feet) square and almost flat, and is a famous tourist attraction in Norway.

Here the css:
@media (max-width: 767px) {
  p {
    text-align: center;
    border: solid black 1px;
    display: block;
    margin-right: auto;
    margin-left: auto;
    /* Based on figure width */
    width: 430px;
  }
}

A: I think I saw an error in the management of the grid is written with col xm-12 that is not a class bootstrap3 instead of 'with-xs-as`
prova con queste classi

Latest News

Prova

The Pulpit Rock is a massive cliff 604 metres (1982 feet) above Lysefjorden, opposite the Kjerag plateau, in Forsand, Ryfylke, Norway. The top of the cliff is approximately 25 by 25 metres (82 by 82 feet) square and almost flat, and is a famous tourist attraction in Norway.

Prova

The Pulpit Rock is a massive cliff 604 metres (1982 feet) above Lysefjorden, opposite the Kjerag plateau, in Forsand, Ryfylke, Norway. The top of the cliff is approximately 25 by 25 metres (82 by 82 feet) square and almost flat, and is a famous tourist attraction in Norway.

Prova

The Pulpit Rock is a massive cliff 604 metres (1982 feet) above Lysefjorden, opposite the Kjerag plateau, in Forsand, Ryfylke, Norway. The top of the cliff is approximately 25 by 25 metres (82 by 82 feet) square and almost flat, and is a famous tourist attraction in Norway.

A: You can change the grid to col-xs-6 and apply offset with col-xs-offset-3
Output:

@media (max-width: 767px) {
  p {
    text-align: center;
  }
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />

Latest News

Prova

The Pulpit Rock is a massive cliff 604 metres (1982 feet) above Lysefjorden, opposite the Kjerag plateau, in Forsand, Ryfylke, Norway. The top of the cliff is approximately 25 by 25 metres (82 by 82 feet) square and almost flat, and is a famous
        tourist attraction in Norway.

Prova

The Pulpit Rock is a massive cliff 604 metres (1982 feet) above Lysefjorden, opposite the Kjerag plateau, in Forsand, Ryfylke, Norway. The top of the cliff is approximately 25 by 25 metres (82 by 82 feet) square and almost flat, and is a famous
        tourist attraction in Norway.

Prova

The Pulpit Rock is a massive cliff 604 metres (1982 feet) above Lysefjorden, opposite the Kjerag plateau, in Forsand, Ryfylke, Norway. The top of the cliff is approximately 25 by 25 metres (82 by 82 feet) square and almost flat, and is a famous
        tourist attraction in Norway.


text:
Q: c# datagridview does not refresh after passing parameters I am passing parameters from Form 1:Products into Form2:ProductEdit. After edit the parameters in ProductEdit, datagridview in Products does not refresh.
private void dataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        if (e.ColumnIndex == 0 && e.RowIndex >= 0)
        {
            ProductEdit pe = new ProductEdit(dataGridView.SelectedRows[0].Cells[1].Value.ToString(), dataGridView.SelectedRows[0].Cells[2].Value.ToString(), dataGridView.SelectedRows[0].Cells[3].Value.ToString());
            pe.Show(dataGridView);
        }
    }

public ProductEdit(string PId, string PName, string PPrice)
    {
        InitializeComponent();
        txtPId.Text = PId;
        txtPName.Text = PName;
        txtPPrice.Text = PPrice;
    }

A: There are 2 approaches to fixing this.

*

*Instead of passing in strings, pass in the cells. Bind the textboxes to the cells. Then the edits made will show up in the original form as you are directly modifiying it.

*When product edit is closing, write the values in the textboxes back to dataGridView.SelectedRows[0].Cells(xxxx)

An example of approach 1: ( untested)
ProductEdit pe = new ProductEdit(dataGridView.SelectedRows[0].Cells[1], dataGridView.SelectedRows[0].Cells[2], dataGridView.SelectedRows[0].Cells[3]);

public ProductEdit(DataGridViewCell PId, DataGridViewCell PName, DataGridViewCell PPrice)
{
    InitializeComponent();
    txtPId.DataBindings.Add("Text", PId, "Value");
    txtPName.DataBindings.Add("Text", PName, "Value");
    txtPPrice.DataBindings.Add("Text", PPrice, "Value");
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Any way to exclude source sudirectories with AWS DataSync? I have an S3 bucket with two directories in it:
/data
/app

I want to sync the contents under both directories into the same destination directory on an EFS. I've setup an AWS Datasync task to do this, however when I run the task, it creates /data and /app on the EFS, presumably it's just mirroring whatever is on S3. Is there a way to tell DataSync to dump both source directories into the same destination?


text:
Q: xib loaded but previous view controller not loaded? I have created an app using tab based application.By selecting a button in first view controller.xib image in second view controller.xib have to load.I have got the second view controller.xib but the problem is if i select first tab it not getting loaded.
Here is my code in firstview.controller.h
@property (unsafe_unretained, nonatomic) IBOutlet UIButton *aboutus;
- (IBAction)showabout:(id)sender;

firstviewcontroller.m
- (IBAction)showabout:(id)sender {
[[NSBundle mainBundle] loadNibNamed:@"SecondViewController" owner:self options:nil];}

A: Try this:
- (IBAction)showabout:(id)sender
{
 SecondViewController *scv = [[SecondViewController alloc]initWithNibName:@"SecondViewController" bundle:nil];
 [self.view addSubview:scv.view];
 [scv release];
}


text:
Q: How Do You Go From One Screen, Clear It Then Go To A New Screen In Python Turtle? So Basically, I am trying To Make A Screen, Make A Menu, Then Go Onto Another Screen Were The Actual Fun Happens. Help!

A: You mean this?
import turtle
#import time

screen1 = turtle.Screen()
#screen1.bgcolor('red')
#time.sleep(5)
screen1.clearscreen()
screen2 = turtle.Screen()
#screen2.bgcolor('blue')


text:
Q: HTTP Download very Big File I'm working at a web application in Python/Twisted.
I want the user to be able to download a very big file (> 100 Mb). I don't want to load all the file in memory (of the server), of course.
server side I have this idea:
...
request.setHeader('Content-Type', 'text/plain')
fp = open(fileName, 'rb')
try:
    r = None
    while r != '':
        r = fp.read(1024)
        request.write(r)
finally:
    fp.close()
    request.finish()

I expected this to work, but I have problems:
I'm testing with FF... It seems the browser make me wait until the file is completed downloaded, and then I have the open/save dialog box.
I expected the dialog box immediately, and then the progress bar in action...
Maybe I have to add something in the Http header... Something like the size of the file?

A: Two big problems with the sample code you posted are that it is non-cooperative and it loads the entire file into memory before sending it.
while r != '':
    r = fp.read(1024)
    request.write(r)

Remember that Twisted uses cooperative multitasking to achieve any sort of concurrency.  So the first problem with this snippet is that it is a while loop over the contents of an entire file (which you say is large).  This means the entire file will be read into memory and written to the response before anything else can happen in the process.  In this case, it happens that "anything" also includes pushing the bytes from the in-memory buffer onto the network, so your code will also hold the entire file in memory at once and only start to get rid of it when this loop completes.
So, as a general rule, you shouldn't write code for use in a Twisted-based application that uses a loop like this to do a big job.  Instead, you need to do each small piece of the big job in a way that will cooperate with the event loop.  For sending a file over the network, the best way to approach this is with producers and consumers.  These are two related APIs for moving large amounts of data around using buffer-empty events to do it efficiently and without wasting unreasonable amounts of memory.
You can find some documentation of these APIs here:
http://twistedmatrix.com/projects/core/documentation/howto/producers.html
Fortunately, for this very common case, there is also a producer written already that you can use, rather than implementing your own:
http://twistedmatrix.com/documents/current/api/twisted.protocols.basic.FileSender.html
You probably want to use it sort of like this:
from twisted.protocols.basic import FileSender
from twisted.python.log import err
from twisted.web.server import NOT_DONE_YET

class Something(Resource):
    ...

    def render_GET(self, request):
        request.setHeader('Content-Type', 'text/plain')
        fp = open(fileName, 'rb')
        d = FileSender().beginFileTransfer(fp, request)
        def cbFinished(ignored):
            fp.close()
            request.finish()
        d.addErrback(err).addCallback(cbFinished)
        return NOT_DONE_YET

You can read more about NOT_DONE_YET and other related ideas the "Twisted Web in 60 Seconds" series on my blog, http://jcalderone.livejournal.com/50562.html (see the "asynchronous responses" entries in particular).

A: Yes, the Content-Length header will give you the progress bar you desire!

A: If this really is text/plain content, you should seriously consider sending it with Content-Encoding: gzip whenever a client indicates they can handle it.  You ought to see huge bandwidth savings.  Additionally, if this is a static file, what you really want to do is use sendfile(2).  As for browsers not doing what you expect in terms of downloading things, you might want to look at the Content-Disposition header.  So anyhow, the logic goes like this:
If the client indicates they can handle gzip encoding via the Accept-Encoding header (e.g. Accept-Encoding: compress;q=0.5, gzip;q=1.0 or Accept-Encoding: gzip;q=1.0, identity; q=0.5, *;q=0 or similar) then compress the file, cache the compressed result somewhere, write the correct headers for the response (Content-Encoding: gzip, Content-Length: n, Content-Type: text/plain, etc), and then use sendfile(2) (however that may or may not have been made available in your environment) to copy the content from the open file descriptor into your response stream.
If they don't accept gzip, do the same thing, but without gzipping first.
Alternatively, if you have Apache, Lighttpd, or similar acting as a transparent proxy in front of your server, you could use the X-Sendfile header, which is exceedingly fast:
response.setHeader('Content-Type', 'text/plain')
response.setHeader(
  'Content-Disposition',
  'attachment; filename="' + os.path.basename(fileName) + '"'
)
response.setHeader('X-Sendfile', fileName)
response.setHeader('Content-Length', os.stat(fileName).st_size)

A: Here is an example of downloading files in chunks using urllib2, which you could use from inside of a twisted function call
import os
import urllib2
import math

def downloadChunks(url):
    """Helper to download large files
        the only arg is a url
       this file will go to a temp directory
       the file will also be downloaded
       in chunks and print out how much remains
    """

    baseFile = os.path.basename(url)

    #move the file to a more uniq path
    os.umask(0002)
    temp_path = "/tmp/"
    try:
        file = os.path.join(temp_path,baseFile)

        req = urllib2.urlopen(url)
        total_size = int(req.info().getheader('Content-Length').strip())
        downloaded = 0
        CHUNK = 256 * 10240
        with open(file, 'wb') as fp:
            while True:
                chunk = req.read(CHUNK)
                downloaded += len(chunk)
                print math.floor( (downloaded / total_size) * 100 )
                if not chunk: break
                fp.write(chunk)
    except urllib2.HTTPError, e:
        print "HTTP Error:",e.code , url
        return False
    except urllib2.URLError, e:
        print "URL Error:",e.reason , url
        return False

    return file


text:
Q: Can I use optimistic locking of an object to guard its associations? We're running into problems with a race condition in our rails app.  Here's a bit of (simplified) code before I explain:
class Message < ActiveRecord::Base
  belongs_to :question
end

class Question < ActiveRecord::Base
  has_many :messages

  def create_or_update_sending_message
    sending_message = messages.detect {|m| m.status == 'sending'}
    sending_message ||= messages.create :status => 'sending'
    sending_message
  end

  def validate
    errors.add_to_base('cannot have multiple sending messages') if messages.select {|m| m.status == 'sending'}.count > 1
  end
end

What's happening is that create_or_update_sending_message is being called from two processes.  Both see the messages collection as empty, so both create a new message.  Then a third process loads the question, modifies it, tries to save it, and we get an error thrown in a place that isn't where the actual problem occurred.
I can think of a few ways to avoid this if we were designing from scratch, but unfortunately create_or_update_sending_message is too deep in legacy code for this to be practical.
We have optimistic locking enabled for our Question model.  It doesn't help because the question isn't being saved - only its messages are.
Is there a way to use the optimistic locking on the question to guard against the saving of the creation of the message?  So it would look something like
def create_or_update_sending_message
  self.optimistically_lock do |lock|
    sending_message = messages.detect {|m| m.status == 'sending'}
    sending_message ||= messages.create_with_optimistic_lock lock, :status => 'sending'
    sending_message
  end
end

Does that even make sense from a database point of view?


text:
Q: Convert 2-level factor to TRUE / FALSE I have to convert this class to True and False
Class          : Factor w/ 2 levels "benign","malignant": 1 1 1 1 1 2 1 1 1 1

I already tried it to convert it to a numeric, by
as.numeric(BreastCancer$Class)
as.integer(BreastCancer$Class)

then I did
as.logical(BreastCancer$Class)

but I only get NA's.
I tried to use the install packages dplyr for recoding, but I can not figure out how that works.

A: It is important to keep track of what you are coding as TRUE or FALSE:
vec_factor <- factor(
  c(1, 1, 1, 1, 1, 2, 1, 1, 1, 1),
  labels = c("benign", "malignant")
)
str(vec_factor)
# Factor w/ 2 levels "benign","malignant": 1 1 1 1 1 2 1 1 1 1

vec_logical <- as.logical(as.integer(vec) == 1)
str(vec_logical)
# logi [1:10] TRUE TRUE TRUE TRUE TRUE FALSE ...

Update:
As @zx8754 commented, as.logical is redundant:
str(as.integer(vec) == 1)
# logi [1:10] TRUE TRUE TRUE TRUE TRUE FALSE ...

and @李哲源's answer is much more elegant.

A: Maybe simply:
BreastCancer$ClassLogical <- BreastCancer$Class == "benign"


text:
Q: How to deal with a dash in an Excel VBA input variable? I'm having some trouble with an Excel VBA macro and was hoping you could give me some advice on how to fix it. In the code below, when a user clicks a command button, an InputBox pops up and the user inputs a number in the form XXX-XXXXXX (e.g. 111-222222). Then, the macro takes the value from the column adjacent to button and uses the input variable to replace a certain part of the adjacent column's value. However, when I tried to run the macro and input a number such as 123-456789, nothing happens. I believe it has something to do with the dash that the user inputs, however I'm not sure how to fix it. Please help!
Sub CommandButtonTitleXXXdashXXXXXX_Click()
    Application.ScreenUpdating = False
    On Error Resume Next
    Dim n As Integer
    n = Worksheets("REVISIONS").Range("D3:D17").Cells.SpecialCells(xlCellTypeConstants).Count
    If n = 15 Then
        If MsgBox("Title revision box full. Add manually.", vbOKOnly, "Error") = vbOK Then
            Exit Sub
        End If
    End If
    Dim rs As Integer
    rs = ActiveSheet.Shapes(Application.Caller).TopLeftCell.Row
    Dim amount As String
    Application.ScreenUpdating = True
    amount = Application.InputBox("Enter case number:", "")
    Application.ScreenUpdating = False
    If amount = False Then
        Exit Sub
    Else
        Dim newCell As String
        newCell = Replace(Worksheets("TITLE").Range("A" & rs).Value, "XXX-XXXXXX", amount)
        Worksheets("REVISIONS").Range("D17").End(xlUp).Offset(1, 0) = newCell
    End If
End Sub

A: I would take your code to an extra step.
No need to declare amount as String. You can keep it as a Variant. Also like I mentioned in the comment above

Can your Case number be like @D1-1%#456? If not then you have an additional problem to handle ;)

See this example. I have commented the code so that you will not have a problem understanding it. Still if you do lemme know :) The other way would be to use REGEX to validate your Case ID. Let me know if you want that example as well.
Code
Sub Sample()
    Dim amount As Variant

    '    123-$456789 <~~ Invalid
    '    123-4567890 <~~ Valid
    '    ABC-&456789 <~~ Invalid
    '    456-3456789 <~~ Valid

    amount = Application.InputBox("Enter case number:", "")

    '~~> Check if user pressed cancel
    If amount = False Then Exit Sub

    '~~> Check if then Case ID is valid
    If IsValidCaseNo(amount) Then
        MsgBox amount
    Else
        MsgBox "Invalid case ID"
    End If
End Sub

Function IsValidCaseNo(sAmount) As Boolean
    Dim s As String
    Dim i As Long, j As Long

    s = sAmount

    '
    '~~> Initial basic checks
    '
    '~~> Check if the length is 11 characters
    If Len(Trim(s)) <> 11 Then GoTo Whoa
    '~~> Check if the string contains "-"
    If InStr(1, s, "-") = 0 Then GoTo Whoa
    '~~> Check if the 4th character is a "-"
    If Mid(s, 4, 1) <> "-" Then GoTo Whoa

    '~~> Loop through 1st 3 characters and check
    '~~> If they are numbers
    For i = 1 To 3
        Select Case Asc(Mid(s, i, 1))
        Case 48 To 57
        Case Else: GoTo Whoa
        End Select
    Next

    '~~> Loop through last 6 characters and check
    '~~> If they are numbers
    For i = 5 To 11
        Select Case Asc(Mid(s, i, 1))
        Case 48 To 57
        Case Else: GoTo Whoa
        End Select
        IsValidCaseNo = True
    Next
Whoa:
End Function

A: If you Dim amount as String, you can test it as a string:
Sub GetDash()
    Dim amount As String
    amount = Application.InputBox(Prompt:="Enter case number", Type:=2)
    If amount = "False" Then
        MsgBox "You cancelled"
    End If
End Sub


text:
Q: scipy.optimize.newton - tolerance argument tol does not refer to the results of the function but to the tolerance of the input? I wanted to solve a function being close to 0.
I tried using the newton function in the Scipy package, but the tolerance seems to apply to the input and not the function of the input:
from scipy.optimise import newton
fn = lambda x: x*x-60
res = newton(fn, 0, tol=0.1, maxiter=10000)
print(res)
print(fn(res))

res is close to 0, and fn(res) is about -60.
It looks like newton() stopped because it found two x values which are bounding the solution and within the tolerance.
Is that correct that the tolerance is on x and not fn(x)?
That seems very counterintuitive to me.

*

*SciPy reference on scipy.optimize.newton: https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.newton.html

A: Yes, the tolerance refers to the function argument x of the function f(x).
See here: zeros.py
The code checks if the step from p0 to p is small enough (they call the function argument p and not x in their code), and if yes, the algorithm stops.
You're in fact using the secant method and not Newton's method because you did not provide the derivative of your function.
Use newton(func=lambda x: x*x-60, fprime=lambda x:2*x, x0=0, tol=0.1, maxiter=10000) instead.
When you run the above code you get an error. That is because you're starting from a local minimum of your function where the tangent line is parallel to the x-axis.
In each iteration Newton's method jumps to the position where the tangent line and the x-axis intersect.
This is of course not possible if x-axis and tangent line are parallel. Try starting e.g. from x0=0.1 to get the correct output.
The plot below shows your quadratic function and the tangent lines at x=0 and x=2. It easy to see that starting from x0=2 works because x-axis and tangent will intersect at some point.


text:
Q: How to add search functionality to my listview? I'm trying without success to add search functionality to my images listview.
Can you help me?
What i have to add to adapter and fragment in order to do it?
My code below:
public class Fragment2 extends SherlockFragment {

DatabaseConnector dbConnector;
private Cursor cursor;
private ListView listView;
private EditText inputSearch;
ImageCursorAdapter adapter;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    final View view=inflater.inflate(R.layout.fragment2, container, false);

    dbConnector = new DatabaseConnector(view.getContext());
    dbConnector.open();
    cursor = dbConnector.getPlaces("");

    listView = (ListView)view.findViewById(R.id.lv);
    inputSearch = (EditText)view.findViewById(R.id.inputSearch);

    adapter = new ImageCursorAdapter(view.getContext(), R.layout.listview_each_item, cursor, new String [] { "title", "description", "picture"}, new int[] {  R.id.title, R.id.msg, R.id.pic });
    adapter.setFilterQueryProvider(new FilterQueryProvider() {

        @Override
        public Cursor runQuery(CharSequence arg0) {
            dbConnector = new DatabaseConnector(view.getContext());
            dbConnector.open();
            cursor = dbConnector.getPlaces(arg0.toString());
            dbConnector.close();
            return cursor;
        }
    });
    listView.setTextFilterEnabled(true);
    listView.setAdapter(adapter);
    dbConnector.close();

    inputSearch.addTextChangedListener(new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            adapter.getFilter().filter(s.toString());
        }
    });
    return view;
}

}
Asapter:
public class ImageCursorAdapter extends SimpleCursorAdapter {
private Cursor c;

private Context context;

String title;
String desc;
String pic;

@SuppressWarnings("deprecation")

public ImageCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
    super(context, layout, c, from, to);
    this.c = c;
    this.context = context;
}

public View getView(int pos, View inView, ViewGroup parent) {
    View v = inView;

    if (v == null) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = inflater.inflate(R.layout.listview_each_item, null);
    }
    this.c.moveToPosition(pos);
    title = this.c.getString(this.c.getColumnIndex("title"));
    desc = this.c.getString(this.c.getColumnIndex("description"));
    pic = this.c.getString(this.c.getColumnIndex("picture"));
    ImageView iv = (ImageView) v.findViewById(R.id.icon);
    if(pic != "")
    {
        try {

            String file_ = pic.replace("file:///", "");
            int size = 30;
            File f = new File(file_);
            Bitmap bitmap = decodeFile(f,60,80);
            iv.setImageBitmap(bitmap);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    else
    {
        iv.setImageResource(R.drawable.marker_green72);
    }
    TextView tv_title = (TextView) v.findViewById(R.id.title);
    tv_title.setText(title);
    TextView tv_desc = (TextView) v.findViewById(R.id.msg);
    tv_desc.setText(desc);
    return(v);
}

public static Bitmap decodeSampledBitmapFromPath(String path, int reqWidth,
        int reqHeight) {
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(path, options);
    options.inSampleSize = calculateInSampleSize(options, reqWidth,
            reqHeight);
    options.inJustDecodeBounds = false;
    Bitmap bmp = BitmapFactory.decodeFile(path, options);
    return bmp;
}

public static int calculateInSampleSize(BitmapFactory.Options options,
        int reqWidth, int reqHeight) {
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;
    if (height > reqHeight || width > reqWidth) {
        if (width > height) {
            inSampleSize = Math.round((float) height / (float) reqHeight);
        } else {
            inSampleSize = Math.round((float) width / (float) reqWidth);
        }
    }
    return inSampleSize;
}

public static Bitmap decodeFile(File f,int WIDTH,int HIGHT){
    try {
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(new FileInputStream(f),null,o);
        final int REQUIRED_WIDTH=WIDTH;
        final int REQUIRED_HIGHT=HIGHT;
        int scale=1;
        while(o.outWidth/scale/2>=REQUIRED_WIDTH && o.outHeight/scale/2>=REQUIRED_HIGHT)
            scale*=2;
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize=scale;
        return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
    } catch (FileNotFoundException e) {}
    return null;
}

}
I would appreciate an answer that includes repair to my code.
Thank you in advance.

A: Well if you have an edit text its a whole lot easier , forget the other answers , I've been through the same lot as your through right now .
Firstly , identify the edit text for ex edit text a;
Then add a text watcher to it and carry out the filtering in ontextchanged.
Well, I'm on mobile and its too tough to type so you can just contact me at avrsaditya@gmail.com , give me a chance ill  help you , if satisfied choose me as best answer , well I have a lot of sample code
And you might be interested of integrating to your action bar too


text:
Q: About the initialization of the UIView Support there are 2 views in the XIB file: UIView1, UIView2.
And the UIView1Owner is the owner of the UIView1. I guess when the XIB is loaded, it will automatically load the 2 views. However, the constructor (initWithFrame:) in the UIView1Owner will not be triggered.
It seems there is some magic behind the scene, and I am wondering how to add some stuff to the constructor of the UIView.

A: From the "initWithFrame:" section of http://developer.apple.com/library/ios/ipad/#documentation/uikit/reference/UIView_Class/UIView/UIView.html

If you use interface builder to design your interface, this method is not called when your view objects are subsequently loaded from the nib file. Objects in the nib are reconstituted and initialized using their initWithCoder: method...

Place any code you want in the initWithCoder: method.

A: initWithFrame will be called only for two created from xib objects (UIView1, UIView2). xib owner is assumed to exist before xib load.


text:
Q: Sylius - how to perform the checkout step programmatically? Today I faced a problem which I couldn't solve with the manual.
I have a case that if the customer selects the cash on delivery shipping method I'd like to skip the payment step.
So far I've created an event listener on sylius.order.post_select_shipping with onCashOnDeliveryShipmentSelect method.
public function onCashOnDeliveryShipmentSelect(ResourceControllerEvent $event)
{
    /** @var Order $order */
    $order = $event->getSubject();

    /** @var Shipment $shipment */
    foreach ($order->getShipments() as $shipment) {
        /** @var ShippingMethod $method */
        $method = $shipment->getMethod();
        if ($method->getCashOnDelivery()) {
            $order = $this->selectPayment($order);
            $this->getStateMachine($order)->apply(OrderCheckoutTransitions::TRANSITION_COMPLETE);

            $this->container->get('sylius.manager.order')->flush();
        }
    }
}

private function selectPayment(Order $order)
{

    $this->getStateMachine($order)->apply(OrderCheckoutTransitions::TRANSITION_SELECT_PAYMENT);

    $paymentMethod = $this->container
        ->get('sylius.repository.payment_method')
        ->findOneByCode('cash_on_delivery');

    foreach ($order->getPayments() as $payment) {
        $payment->setMethod($paymentMethod);
    }

    $this->flush();
    return $order;
}

private function getStateMachine(Order $order)
{
    $stateMachineFactory = $this->container->get('sm.factory');
    $stateMachine = $stateMachineFactory->get($order, OrderCheckoutTransitions::GRAPH);

    return $stateMachine;
}

private function flush()
{
    $this->container->get('sylius.manager.order')->flush();
}

Once I go through the checkout process and select the method with cashOnDelivey flag set to true I'm getting the redirect loop error even though the order is processed correctly.

A: Your business assumptions are just wrong.
Cash On Delivery - this is a Payment Method, not a Shipping Method.
Rethink what you are trying to do, and then come back. If you want to have a shipping method that can be paid only on delivery, then you will have to do sth similar to our skipping payment step when the order total is 0. :)


text:
Q: Discouraging zero-effort 'my code's broken, fix it for me' type questions I just came across a question on SO that was essentialy: 'my program stops here' and a short blob of code. Nothing else. He hand't even bothered to properly punctuate the four-word question. There wasn't a description of the problem, stack trace, error message, or any indication which line was producing the error.
Several people pointed out that if the user wanted a good answer, he'd have to invest more effort.
But somebody answered anyway. Sure it wasn't a good answer, but the point is that some people will do anything for rep, so regardless of how bad the question is, there'll always be an answer or two. I downvoted the question after leaving a comment, as did several other people.
And then I checked out the asker's profile: almost 20 questions, one upvote, 20% accept rate.
This user did not deserve to get any help. Is there anything that can be done besides downvoting to put a stop to this kind of behavior? Maybe some kind of warning when a user has a certain downvote/question ratio?

A: If things are really as bad as you describe: downvoting helps. This will eventually get the user a "Sorry, we are no longer accepting questions from this account":

Questions from IP addresses or accounts with a history of extremely poor questions will no longer be accepted. This is intended to weed out the worst quality questions.
(hint hint, question votes matter, so please continue to vote the best questions up and vote the worst questions down.)


text:
Q: Como fazer algo assíncrono com jQuery, busca no MySQL com PHP? Eu estou tendo muito problema com essa parte. Eu quero simplesmente fazer a uma busca no banco de dados e passar para o meu programa principal, isso sem dar um refresh. Eu sei fazer toda a parte do PHP e MySQL, entretanto a parte do jQuery já não é minha área, sei o básico de JS.
Seguinte: a pesquisa que quero é SELECT questoes_resolvidas FROM dados_usuario WHERE id = id_usuario;. Isso eu sei fazer. Mas o grande problema é pegar esse resultado e mandar para o meu index.php. Eu não quero mandar o resultado pra dentro de uma variável no index.php. Pode ser uma variável do próprio JavaScript mesmo.
Já tentei passar por $_SESSION mas não dá, pois tenho que atualizar a página para o $_SESSION pegar os valores atualizados. Eu não quero atualizar a página, mas a variável com a resposta do comando MySQL vai ser atualizada a todo momento que eu chamar a função try_it().
Me ajudem, por favor. Já tentei aprender esse jQuery mas acredito que preciso aprofundar em JS primeiro, e não tenho tempo pra isso no instante.

A: Você pode criar uma webservice para fornecer esses dados. Basicamente um arquivo que vai retornar apenas estes dados.
Primeiro crie um arquivo, ajax.php, por exemplo. Nele vc faz a consulta e escreve o resultado. Para facilitar para vc recomendo que imprima os dados parseados em JSON.
Dps disso, no jquery vc usa o método Ajax $.ajax(options, callback)
Assincronamente ele faz uma requisicao na URL q vc passar e quando terminado chama o callback. Quando cair no callback vc trata os dados que recebeu, ou uma eventual falha

A: Tu vai ter que ter uma página para receber essa requisição ajax.
Exemplifiquei abaixo, a conexão com o banco é fictícia, só para ilustrar.
ajax.php
// Apenas para exemplificar uma conexão com o DB
include("conexao_db.php");

$sql = <<<SQL
    SELECT *
    FROM minha_tabela
    WHERE minha_condicao = 1;
SQL;

$resultado = $db->query($sql);
$dados = $resultado->fetchAll();
// - - - - - - - - - - - - - -

// Parte importante
header("content-type: application/json");
echo json_encode($dados);

Aí no teu HTML tu vai fazer uma requisição AJAX para a página recém criada e inclui na página atual.
index.html

Meus dados

A: Depois de muito tempo (nem lembrava mais dessa pergunta) descobri com algumas buscas no Google. É bem simples:
$.ajax({
    type: "GET",//Tipo da requisicao, pode ser GET, POST, etc...
    data: {dado1: "Dado 1",dado2: "Dado 2"},
    url: "url_do_arquivo_que_faz_as_coisas.php",
    beforeSend: function(){
        console.log("Isso executara antes da requisicao");
    }
    success: function(responses){
        console.log(responses);//Aqui são os dados vindos do PHP
    }
});

Se la no PHP tivessemos algo assim
echo $_GET['dado1'].' - '.$_GET['dado2'];

Teriamos o seguinte no nosso console apos fazer a requisicao AJAX:
Dado 1 -Dado 2

Espero ter ajudado quem precisa como eu precisava na época. Alem do mais, você deve colocar o código do JS em um função pq dai você chama quando quiser e quantas vezes quiser, o resto e só modificar...


text:
Q: Google Chart callback function executed on page load After page is loaded I do not get google chart just red rectangle with words "Data Table is not defined".
After some investigations I think reason is that due to google load functions:
google.charts.load or google.charts.setOnLoadCallback
Callback function is called after page is loaded. Unfortunately at that time data set is not ready therefore error from google charts library. I can't define data set inside the callback function.
T.
code:
    google.charts.load('current', {'packages': ['corechart']});
    google.charts.setOnLoadCallback(drawChart);

    function drawChart(dataAir) {
      console.log("I'm in drawChart");
      var optionsAir = {
        title: 'air consumption - m3/h',
        legend: {position: 'right'},
        hAxis: {format: 'yy.MM.dd / HH:mm', gridlines: {count: 15}, textStyle: {fontSize: 10},},
        vAxis: {gridlines: {count: 15},title: 'Air consumption in m3/h',},
        height: 450,
        interpolateNulls: false,
      }
 var chartAir = new google.visualization.LineChart(document.getElementById('chart_Air'));
chartAir.draw(dataAir, optionsAir);
}

    $('input[name="daterange"]').daterangepicker({
        ranges: {
          'Last 1 day': [moment().subtract(1, 'days'), moment()],
          'Last 3 Days': [moment().subtract(3, 'days'), moment()],
          'Last 7 Days': [moment().subtract(6, 'days'), moment()],
          'Last 30 Days': [moment().subtract(29, 'days'), moment()],
        },
        alwaysShowCalendars: false,
        timePicker: true,
        timePickerIncrement: 30,
        showISOWeekNumbers: true,
        timePicker24Hour: true,
        minDate: "04/12/2016",
        maxDate: moment(),
        locale: {
          format: 'YYYY/MM/DD hh:mm'
        },
      },
      function(start, end, label) {
        var dateRange = {
          From: start.format('YYYY-MM-DD HH:mm:ss'),
          To: end.format('YYYY-MM-DD HH:mm:ss')
        };
        var jsonDataAir = google.visualization.arrayToDataTable([
          ['Year', 'Max score (100%)', 'MOL Group Total score', 'Best score', 'Industry average', 'Threshold'],
          ['2007',  100, 63, 77, 53, 68 ],
          ['2008',  100, 65, 80, 49, 68 ],
          ['2009',  100, 68, 82, 49, 69 ],
          ['2010',  100, 75, 77, 49, 70 ],
            ['2011', 100, 68, 86, 51, 68 ],
            ['2012', 100, 69, 85, 53, 72 ],
            ['2013', 100, 66, 83, 48, 69 ],
            ['2014', 100, 68, 87, 49, 68 ]
        ]);
        console.log("I'm in daterangepicker");
        drawChart(jsonDataAir);
      })

    $(document).ready(function() {
  block = 1;

      var dateRange = {
        From: moment().subtract(1, 'days').format('YYYY-MM-DD HH:mm:ss'),
        To: moment().format('YYYY-MM-DD HH:mm:ss')
      };
            var jsonDataAir = google.visualization.arrayToDataTable([
          ['Year', 'Max score (100%)', 'MOL Group Total score', 'Best score', 'Industry average', 'Threshold'],
          ['2007',  100, 63, 77, 53, 68 ],
          ['2008',  100, 65, 80, 49, 68 ],
          ['2009',  100, 68, 82, 49, 69 ],
          ['2010',  100, 75, 77, 49, 70 ],
            ['2011', 100, 68, 86, 51, 68 ],
            ['2012', 100, 69, 85, 53, 72 ],
            ['2013', 100, 66, 83, 48, 69 ],
            ['2014', 100, 68, 87, 49, 68 ]
        ]);
    console.log("I'm in document ready");
    drawChart(jsonDataAir);
    });

here you can find jsfiddle: https://jsfiddle.net/Loshka/xgra2x93/33/
ps. I've tried this Google Chart loads on Page Refresh without success and some other ideas but my JS knowledge is rather limited, so any help is appreciated.


text:
Q: Piping output of puppeteer page.pdf({ path: "output.pdf", format: 'A4'});

expects a file to dump to.  Is there a way to redirect the output to a pipe?

A: const content = await page.pdf({path: "output.pdf", format: 'A4'})
console.log(content.toString('hex'))

content will be a Buffer instance containing the pdf binary, then you can output

A: I don't know if it is a recent thing, but you can do
await page.createPDFStream();

and that will return a Readable that you can pipe.


text:
Q: I cant fix Lua value canceling out other value Okay well I have a piece of code which is a weed pot system for garrysmod Darkrp it allows you to create 4 pots and plant seeds with a timer counting down to complete.
However once another pot is on it cancels the others out and im not sure how i can fix this.
cheers dynamics
if hitEnt:GetClass() == "seed_weed" then

  if self.Entity:GetNWBool("Plantable") == true then

    self.Entity:SetNWBool("Plantable", false)

    hitEnt:Remove()

    self.Entity:SetModel("models/nater/weedplant_pot_planted.mdl")

    timer.Create("Stage2_", GrowTime/7, 1, function()

      self.Entity:SetModel("models/nater/weedplant_pot_growing1.mdl")

    end)

    timer.Create("Stage3_", GrowTime/6, 1, function()

      self.Entity:SetModel("models/nater/weedplant_pot_growing2.mdl")

    end)

    timer.Create("Stage4_", GrowTime/5, 1, function()

      self.Entity:SetModel("models/nater/weedplant_pot_growing3.mdl")

    end)

    timer.Create("Stage5_", GrowTime/4, 1, function()

      self.Entity:SetModel("models/nater/weedplant_pot_growing4.mdl")

    end)

    timer.Create("Stage6_", GrowTime/3, 1, function()

      self.Entity:SetModel("models/nater/weedplant_pot_growing5.mdl")

    end)

    timer.Create("Stage7_", GrowTime/2, 1, function()

      self.Entity:SetModel("models/nater/weedplant_pot_growing6.mdl")

    end)

    timer.Create("Stage8_", GrowTime/1, 1, function()

      self.Entity:SetModel("models/nater/weedplant_pot_growing7.mdl")

      self.Entity:SetNWBool("Usable", true)

    end)

  end

end

end

function ENT:OnRemove()

  timer.Destroy("Stage2_")

  timer.Destroy("Stage3_")

  timer.Destroy("Stage4_")

  timer.Destroy("Stage5_")

  timer.Destroy("Stage6_")

  timer.Destroy("Stage7_")

  timer.Destroy("Stage8_")

end

A: I'm guessing this is happening because the timers created are not unique. I.e. you spawn in one pot, which creates a timer called "Stage2_". You then create another pot, which creates another time with the same name "Stage2_", overriding the old one.
Consider adding some sort of unique identifier in the name for each pot that is spawned.
As an example, you could do this by adding a variable that increases by one each time a pot is spawned, then set the name of the timer to "Stage2_" + variable.
Make sure the variable is defined in a scope outside of the entity itself, or you will just end up re-declaring the variable each time an instance of the entity is spawned.


text:
Q: Bind Font Size in JavaFX? I'd like to make my application fluid. However, the fonts look small compared to the UI elements when I make the windows bigger. Ultimately, I want the size of my text to get bigger or smaller when I resize the window. I know I could theoretically do this with the style property, but I already have that property bound to something else in some instances.
I know there's the "fontProperty" method, but I have nothing to bind it to since I can't figure out how to create a dynamic ObjectProperty with a synced size. What should I do?
EDIT: To avoid confusion, I'm trying to make the Font size change based on other factors, not the other way around.

A: There is a simplest and proper method to bind font size with the container size, in order to make it in a responsive font scale effect.
The bind(Bindings.concat("-fx-font-size: " is a good alternative but when you resize the windows it seems to be very slow and I think is not the proper way to resolve the problem.
You can declare FontProperty and bind this FontProperty to the Component (Label, Text, etc.) and finally create an event to bind the size with the FontProperty size according with our design:
private Label textTracking = new Label();
private ObjectProperty<Font> fontTracking = new SimpleObjectProperty<Font>(Font.getDefault());

Then in constructor or some init method you can bind the font property of our object with our dynamic font:
textTracking.fontProperty().bind(fontTracking);

Finally, you need to bind the wrapper container change size with the dynamic font size:
    widthProperty().addListener(new ChangeListener<Number>()
    {
        @Override
        public void changed(ObservableValue<? extends Number> observableValue, Number oldWidth, Number newWidth)
        {
            fontTracking.set(Font.font(newWidth.doubleValue() / 4));
        }
    });

With this solution the dynamic font adjustment is very flow and fast, even more than bind(Bindings.concat("-fx-font-size: " method.

A: Just put everything where you want the fontsize to change in a container and set that style or use bindings if you want.
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class FontBind extends Application {

    private DoubleProperty fontSize = new SimpleDoubleProperty(10);
    private IntegerProperty blues = new SimpleIntegerProperty(50);

    @Override
    public void start(Stage primaryStage) {
        Button btn = new Button("click me, I change color");
        btn.setOnAction((evt)->{blues.set(blues.get()+20);});//max?
        Label lbl = new Label("I'm a label");
        TextArea ta = new TextArea("Lots of text can be typed\nand even number 1234567890");
        HBox hbox = new HBox(new Label("I never change"));
        VBox child = new VBox(btn, lbl, ta);
        VBox root = new VBox(child, hbox);
        Scene scene = new Scene(root, 300, 250);

        fontSize.bind(scene.widthProperty().add(scene.heightProperty()).divide(50));
        child.styleProperty().bind(Bindings.concat("-fx-font-size: ", fontSize.asString(), ";"
                                                  ,"-fx-base: rgb(100,100,",blues.asString(),");"));

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }

}

I'm not sure what your style is already bound to, but you're allowed to set multiple css values in the style string.

A: Set the .root -fx-font-size

*

*Create a custom stylesheet for your application.

*In sylesheet .root selector, set -fx-font-size to your desired value:
.root {
    -fx-font-size: 40px;
}
Why this works
This works because:

*

*All of the default controls are based on em units (which are based on the default font size).

*-fx-font-size is an inherited style.

*Everything inherits from the root.

Once you do this, all controls (and the text inside them) will automatically resize nicely to fit whatever font size you specified.
Related Sample

*

*javafx automatic resizing and button padding
Related Information
em is a generic unit that is not specific to JavaFX and em units are also used in HTML CSS.  If interested, you can read a broader discussion on em units versus other units.
Using em units in FXML via expression binding
Just setting a default font size gets you about 90% of the way to where you need to be, but is not necessarily a universal fix as some layout units might be specified not using em units.  Most of the time this isn't really an issue, but if it is in your case, you could also apply a mechanism described in an Oracle developer mailing list post, which appears to work, though is a little clunky.
How about using an expression binding.
For 35em x 25em you could write:
prefWidth="${35*u.em}" prefHeight="${25*u.em}"

It's not 100% concise, but perhaps passable.
These kind of sizing expressions work in scene builder 1.1, which is nice.

Here is an example using a Rectangle to store the width and height modifiers for the fxml file.
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.shape.*?>

<StackPane xmlns:fx="http://javafx.com/fxml">
<fx:define>
  <Rectangle fx:id="s" width="13" height="13"/>
</fx:define>
<AnchorPane id="AnchorPane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="${22 * s.width}" prefWidth="${14 * s.height}">
  <children>
    <Button layoutX="${4 * s.width}" layoutY="${ 5 * s.height}" prefWidth="${6 * s.width}" text="Top" />
    <Button layoutX="${4 * s.width}" layoutY="${10 * s.height}" prefWidth="${6 * s.width}" text="Middle" />
    <Button layoutX="${4 * s.width}" layoutY="${15 * s.height}" prefWidth="${6 * s.width}" text="Bottom" />
  </children>
</AnchorPane>
</StackPane>

Or instead, you can create your own unit class and use it in your sizing expressions, for example:
package org.jewelsea.measure;

public class Measurement {
  private double em;
  public  void   setEm(double em) { this.em = em; }
  public  double getEm()          { return em; }
}

. . .

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import org.jewelsea.measure.Measurement?>
<?scenebuilder-classpath-element .?>

<StackPane xmlns:fx="http://javafx.com/fxml">
  <fx:define>
    <Measurement fx:id="u" em="26.0" />
  </fx:define>
  <AnchorPane id="AnchorPane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="${22*u.em}" prefWidth="${14*u.em}">
    <children>
      <Button layoutX="${4*u.em}" layoutY="${ 5*u.em}" prefWidth="${6*u.em}" text="Top" />
      <Button layoutX="${4*u.em}" layoutY="${10*u.em}" prefWidth="${6*u.em}" text="Middle" />
      <Button layoutX="${4*u.em}" layoutY="${15*u.em}" prefWidth="${6*u.em}" text="Bottom" />
    </children>
  </AnchorPane>
</StackPane>

A: I had a similar problem and solved it this way:

*

*in the CSS and FXML files, I defined all font sizes in a relative way, using only "em" instead of "%" or "px"

*in the controller of the main window, I bound a double value within a style property of the main pane to some scene size property (e.g. a rough approximation of its diagonal length)

It works because the style that is set to the main pane will affect as a modifier all the nodes that are already defined in the FXML. The nodes that already have a style class are also impacted as the new style comes as an additional top layer of styling in the cascading style sheets.
The main advantage of this solution is to handle in a single place the font size zoom factor. Thus you don't have to find every node that has a Font property to make it working.
Sample files:
styles.css

.label {
    -fx-font-size: 1.1em;
}

.title {
    -fx-font-size: 1.5em;
    -fx-font-weight: bold;
}

main.fxml

<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.*?>
<?import javafx.scene.control.cell.*?>
<?import javafx.scene.layout.*?>
<BorderPane style="-fx-background-color: #fff;"
        xmlns="http://javafx.com/javafx/8"
        xmlns:fx="http://javafx.com/fxml/1"
        prefWidth="1280.0" prefHeight="720.0"
        fx:controller="controllers.MainController">
    <top>
        <Label text="Application title" styleClass="title"/>
    </top>
    <center>
        <Label text="Lorem ipsum"/>
    </center>
</BorderPane>

MainController.java

package controllers;

import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.layout.BorderPane;

public class MainController implements Initializable {
    @FXML private BorderPane mainPane;

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        initializeFontSizeManager();
    }

    private void initializeFontSizeManager() {
        // Cf. https://stackoverflow.com/questions/13246211/javafx-how-to-get-stage-from-controller-during-initialization
        mainPane.sceneProperty().addListener((observableScene, oldScene, newScene) -> {
            // We need a scene to work on
            if (oldScene == null && newScene != null) {
                DoubleProperty fontSize = new SimpleDoubleProperty(0);
                fontSize.bind(newScene.widthProperty().add(newScene.heightProperty())
                    .divide(1280 + 720) // I know, it's a very rough approximation :)
                    .multiply(100)); // get a suitable value to put before the '%' symbol in the style
                mainPane.styleProperty().bind(
                    Bindings.concat("-fx-font-size: ", fontSize.asString("%.0f")).concat("%;"));
            }
        });
    }
}

A: I know this is a very old question
but since 19-ea+9 you may use like
private DoubleProperty fontSize = new SimpleDoubleProperty(10);
node.styleProperty().bind(fontSize.map(size -> "-fx-font-size: "+size+";-fx-base: rgb(0,0,255);"));


text:
Q: Table with several one-to-many relationships I have an EF code-first model with a table having several one-to-many relationships with other tables:
public class Note
{
  [Key]
  public Guid Id { get; set; }
  public string NoteText { get; set; }
  public string Author { get; set; }
  public DateTime? CreationDate { get; set; }
}

public class Foo
{
  public Foo()
  {
    Notes = new HashSet<Note>();
  }

  [Key]
  public Guid Id { get; set; }
  public virtual ICollection<Note> Notes { get; set; }
  // other properties ommited...
}

public class Bar
{
  public Bar()
  {
    Notes = new HashSet<Note>();
  }

  [Key]
  public Guid Id { get; set; }
  public virtual ICollection<Note> Notes { get; set; }
  // other properties ommited...
}

As you can see, both Foo and Bar have their own list of Notes, but a Note belongs to either a Foo or a Bar.
When scaffolding the migration, EF creates a foreign key for Foo and Bar in the Notes table, which I think is not correct. I would like, instead, that a link table is created between Foo and Notes and another one between Bar and Notes.
Is there a way to automatically do this? Or do I have to manually create these classes in my code-first implementation?

A: This has already been answered in this other post!
But to save you a little googling, you are getting a one-to-many association, which is correct. you want a many-to-many relationship in your code, so what you will need to do is :
in your Notes class:
public class Note
{
  [Key]
  public Guid Id { get; set; }
  public string NoteText { get; set; }
  public string Author { get; set; }
  public DateTime? CreationDate { get; set; }
  public DateTime? CreationDate { get; set; }
  public virtual ICollection<Foo> Foos { get; set; }
  public virtual ICollection<Bar> Bars { get; set; }
}

Hope this helps


text:
Q: In tortoise and hare algorithm, Why we make the hare make 2 step forwards and check them In tortoise and hare algorithm why do we always make hare go two steps forward and hare 1 step forward and then compare them, we can also make the hare go 1 step forward and then check if its equal again then increment both the tortoise and hare again check them if they are equal! I think this will help in finding the loop faster?
For eg. this pseudocode
tortoise := firstNode
hare := firstNode

forever:

  if hare == end
    return 'No Loop Found'

  hare := hare.next

  if hare == end
    return 'No Loop Found'
   if hare==tortoise
return true

  hare = hare.next
  tortoise = tortoise.next

  if hare == tortoise
    return 'Loop Found'

A: The path consists of a tail and a loop; both the hare and the tortoise have to traverse the tail before they get to the loop. Since the hare moves two steps at a time, it gets to the loop first, and runs around the loop until the tortoise arrives. Up until the point at which the tortoise reaches the loop, it is not possible for the two of them to occupy the same cell.
Once the tortoise reaches the start of the loop, the hare is somewhere in the loop, effectively k steps behind the tortoise for some k, where k is certainly less than the loop size. For each step the tortoise makes, the hare makes two, which puts the hare one step closer to the tortoise. So after the tortoise moves one step, the distance between them is k-1 and then the next step it is k-2 and so on, until the hare catches up after k steps.
The hare never passes the tortoise in the loop, so there is no point checking for the hare being in the place the hare leaps over; it cannot be there. The extra check, therefore, will always fail, and including it will only slow the algorithm down.


text:
Q: Combining Exploratory Factor Analysis with Random Forest for Binary Logistic Regression Feature Selection For those of you familiar with Exploratory Factor Analysis (EFA) and Random Forest (RF), I have recently had an idea of combining these two methods to reduce the number of potential predictor variables for use in a parsimonious binary logistic regression model. For the purposes of this post, assume large n (200k or more) and 1000 potential predictor variables.
To employ this idea, the first step would be to perform an EFA with all potential predictor variables using proc varclus. Additionally, using randomForest to rank all potential predictor variables by IncNodePurity (Gini Index).
After these two methods are independently used, I propose retaining the variable with the largest IncNodePurity (from RF) within each factor (from EFA).
Does anyone have any thoughts/concerns with this methodology (or lack thereof) for feature selection? I am aware that this "picking and choosing" of methods may be complete garbage, but I had this random thought and wanted to share. Thanks!

A: Thanks to @Momo, I have came to the conclusion that making use of  L2 regularization to handle collinearity that likely exists among potential predictor variables and L1 regularization to allow me to select the desired number of variables to create my logistic regression models is a better approach than combining EFA and Random Forest. Thanks @Momo for the nudge over to elastic net and the documents you provided to start me on the right track!


text:
Q: Understanding logic tile LC_5 bits i m new to yosys and arachne-pnr. Here is the snippet from .asc and .icebox_explain. I could not understand how the bits of LC_5 are derived from .logic_tile 1 11.
example.v
module top (input a, b, output y);
  assign y = a & b;
endmodule

example.asc
.logic_tile 1 11
    000000000000000000000000000000000000000000000000000000
    000000000000000000000000000000000000000000000000000000
    000000000000001000000000000000000000000000000000000000
    000000000000000101000000000000000000000000000000000000
    000000000000000000000000000000000000000000000000000000
    000000000000000000000000000000000000000000000000000000
    000000000000000000000000000000000000000000000000000000
    000000000000000000000000000000000000000000000000000000
    000000000000000000000000000000000000000000000000000000
    000000000000000000000000000000000000000000000000000000
    000000000000000000000000000000011000110000000000000000
    000000000000000000000000000000001110110000000000000000
    000000000000000000000000000000000000000000000000000000
    000000000000001111000000000000000000000000000000000000
    000000000000000000000000000000000000000000000000000000
    000000000000000000000000000000000000000000000000000000

icebox_example.asc
   .logic_tile 1 11
LC_5 0000000000001111 0000
buffer local_g0_4 lutff_5/in_3
buffer local_g3_0 lutff_5/in_2
buffer neigh_op_lft_4 local_g0_4
buffer sp4_h_r_24 local_g3_0

How, LC_5 0000000000001111 0000 is generated from this stream?
Given in documentation:
LC_5 B10[36] B10[37] B10[38] B10[39] B10[40] B10[41] B10[42] B10[43] B10[44] B10[45] B11[36] B11[37] B11[38] B11[39] B11[40] B11[41] B11[42] B11[43] B11[44] B11[45]

I guess it should be:

B10-36:45=1100000000
B11-36:45=1100000000

which is not correct. Can you please help and guide?

A: LC_5 isn't the LC_ bits directly, but the 16 LUT init bits followed by 4 flipflop config bits.
The mapping from these to LC_ bit index is another step, also described in http://www.clifford.at/icestorm/logic_tile.html right at the bottom.


text:
Q: Input component > feeds Forms component - how to handle submit? I am missing how to bring the input value out of the child component.
I have an Input component that I want to re-use, there I can see what happens onChange, and I see every change on the input field.
Then on the parent component, Form, where I use <Input />, I have the rest of the form with the Submit button. At this level, I want to handle onSubmit, but I cannot see/console the value of the input here. I can only see it from the child.
Any ideas about what I am doing wrong?
Input.js - here I can see the input value onChange
function Input(props) {
    const { label, name, value } = props;
    const handleChange = (event) => {
        const updateForm = {...Form};
        console.log("change:", updateForm)
        updateForm[label] = event.target.value;
      }
    return (
        <label>
            {label}
            <input name={name} value={value} onChange={handleChange}></input>
        </label>
    )
}

export { Input }

Forms.js - here I cannot get access to the input value and submit/handle it
function Form(props) {

  const handleSubmit = (event) => {
    event.preventDefault();
    console.log(Input.value);
    console.log(props.label.value)
    alert(`form is: ${event.target.input}`);
  }
      return (
      <>
        <form onSubmit={handleSubmit}>
          <Input label={props.label} />
          <input type="submit" value="Submit"></input>
        </form>
      </>
    )
}

I have that structure because I am defining what I want in my Form on the main HomePage component:
  function Home() {
  return (
    <>
        .......
        <Section withForm label={["Name"]} {...homeObjFive}/>
        <Section withForm label={"Phone"} {...homeObjOne}/>
        .......

    </>
  )
}

A: Suppose you have a form with two inputs, name and email (these are the id props of the inputs). You can extract the form values like this:
  const handleSubmit = (event) =>
  {
    event.preventDefault()
    const data = new FormData(event.currentTarget)
    const name = data.get('name')
    const email = data.get('email')
    // do something with the data
  }

You can read more about FormData here.

A: This is the perfect case to use the useRef function from react.
In Form.js
import React, { useRef } from 'react'

create a reference constant and pass it as a prop into the input component. and change the input value that is handled in the onSubmit function to the reference
Also in Form.js (changes are made to the submit function)
function Form(props) {

  const { inputValue } = useRef(); // added

  const handleSubmit = (event) => {
    event.preventDefault();
    console.log(inputValue); // changed
    console.log(props.label.value)
    alert(`form is: ${event.target.input}`);
  }
      return (
      <>
        <form onSubmit={handleSubmit}>
          {/* added the inputValue prop to the input component */}
          <Input label={props.label} inputValue={inputValue} />
          <input type="submit" value="Submit"></input>
        </form>
      </>
    )
}

and now inside of the Input component set the input elements reference to the inputValue prop. you will no longer need a onChange function as reacts useRef function is updated automatically
In Input.js
function Input(props) {
    return (
        <label>
            {props.label}
            <input name={props.name} value={props.value} ref={props.inputValue}></input>
        </label>
    )
}

export { Input }


text:
Q: Python - switching positions: list[i], list[list.index(minimum)] = list[list.index(minimum)], list[i] could anyone explain me, why is it not possible to swap list positions in my function for selection sort?
This is what i wrote at first, but the function returns the same list as the input:
def selection_sort(list):
    for i in range(0, len(list)):
        minimum = list[i]
        for j in range(i + 1, len(list)):
            if list[j] < minimum:
                minimum = list[j]
        list[i], list[list.index(minimum)] = list[list.index(minimum)], list[i]
    return list

Then I tried to use a variable index = list.index(minimum) and suddenly it worked.
def selection_sort(list):
    for i in range(0, len(list)):
        minimum = list[i]
        for j in range(i + 1, len(list)):
            if list[j] < minimum:
                minimum = list[j]
        index = list.index(minimum)
        list[i], list[index] = list[index], list[i]
    return list

Could anyone explain me the difference and why is it not corect the first solution?
Thank you!

A: The right hand side of the assignment (list[list.index(minimum)], list[i]) is computed first, then assigned to the tuple on the left list[i], list[list.index(minimum)].
I'm guessing the next part, but I assume list[i] is assigned to, then list[list.index(minimum)]. However, since you've already assigned to list[i] you've already modified the list before finding list.index(minimum) a second time. Since you're not searching in identical lists, the indexes may be different.
Your second attempt calculates the index once and uses the same value in both places.
As a side note, it is good practice to not name variables the same as a python builtin name.  Your function takes a parameter called list so that "shadows" the builtin list function. You wouldn't be able to call that builtin inside your function because the name has been stolen.  Better to call it my_list, array, or list_to_sort etc.


text:
Q: Exchange crashed, backups failed, only mail is on my mobile (andriod) device, is it possible to move that data to Exchange Online? Bad weekend... I had a piece of hardware fail which spiked the power and took out my UPS which dropped my SAN and subsequently killed my Exchange 2010 server.  Then I found out that the Veeam backups I had been doing were not backing up exchange properly.  I was already planning on migrating to Exchange Online in another month but this kind of puts a little more priority on it.
During this process I discovered that my workstation's outlook was not caching my emails/contacts/calendar to a local PST.  However, my Android has at least the most recent 2 weeks of email and all of my calendar appointments.
I just got Exchange Online setup, is it possible to feed what is on my Android device back up to Exchange Online?

A:
I just got Exchange Online setup, is it possible to feed what is on my
Android device back up to Exchange Online?

That's doubtful unless you can somehow export the email from your phone.
What you can do if you have access to the Exchange mailbox database (EDB file) is use a third party utility to export the mailbox contents, which can then be imported into your Exchange Online mailbox.
https://www.nucleustechnologies.com/Exchange-Server-Data-Recovery.html
https://www.edbmails.com/
https://www.stellarinfo.com/edb-exchange-server-recovery.htm

A: I know this is an old question, but it just got bumped to home page and I saw it only now.
If you have undamaged database files, you can simply reinstall Exchange on a new server (with the same OS, hostname and Exchange install path) using "recover server" mode.
Documentation is only currently available from Exchange Server 2016 onwards, but the option definitely existed in Exchange Server 2010 and 2013 too.
https://docs.microsoft.com/en-us/exchange/high-availability/disaster-recovery/recover-exchange-servers


text:
Q: Wordpress custom post type image in RSS i have a theme (classipress) that uses a custom post type
the classified page doesn't use the wordpress featured image function
it uses its own image function
I was able to include the custom post types in RSS but i could not include the image of the classified item in the RSS feed
Any help ?

A: Better late than never I guess.
You have several options, first and easiest, you can install a plugin that searches for images in posts and the attach them as featured if no featured is found. This plugin can help you, but there are plenty more.
If you prefer not to rely in plugins, you can add a snippet in your functions.php file that searches for the first image in the post attachments and then features it. You have a tutorial here on how to accomplish this.
Lastly, you need to include the featured image in your RSS feed:
// display featured post thumbnails in WordPress feeds
function wcs_post_thumbnails_in_feeds( $content ) {
global $post;
if( has_post_thumbnail( $post->ID ) ) {
    $content = '<p>' . get_the_post_thumbnail( $post->ID ) . '</p>' .     $content;
}
return $content;
}
add_filter( 'the_excerpt_rss', 'wcs_post_thumbnails_in_feeds' );
add_filter( 'the_content_feed', 'wcs_post_thumbnails_in_feeds' );

Hope this helps.


text:
Q: Geopackage is not visible in QField offline editing mode I am using QGIS 3.4.9 Madeira and QField 1.4.4.
Having a gpkg and shp layer with the same information in a project and transferring them both to QField (both layers are set to offline editing), only the shapefile layer is visible. The gpkg file is not visible.

*

*Although gpkg file is not visible, it is editable! When I add a polygon, I see the new polygon in QField with the symbology as set in the QGIS project.

*I have the same issue with a line layer, but not with a point layer

*When using QFieldSync, the plugin asks me always: "do you want to save the changes in the layer Survey_V_Vlakken (offline)"? In other words, it seems that QFieldSync makes a new layer for mobile/offline use?

*Synchronizing back with QField, the changes in the gpkg and shp layers are added to the QGIS project

*First I was using a *.QGZ project (as the default in QGIS 3.4) but I also tried *.QGS and is does not make any difference.

*Both layers have the same CRS 31370 (Belgian Lambert)

Does anyone knows how I can make the gpkg file visible? In a similar question somebody added the same gpkg file as a copy for the QField project; in that way it was visible. But this is not a very handy solution...
Link so similar question

A: Problem resolved!
With a very big thank you @Matthias from OpenGis.ch who was spot on identifying the problem.

I run the Vector > Geometry > Multiple to single algorithm for both layers (polygon and line layer) that didn't show up.
1/ I found one polygon that was a multi-polygon > when it was fixed, the layer showed up in QField!
2/ Somehow the same problem in the line layer > also fixed!
And no longer a question about saving that offline file after running QFieldSync.


text:
Q: c++ variable initialization inside CASE after DEFAULT in SWITCH statement I have encountered an interesting peculiarity while playing with code. I am using Eclipse CDT 4.5.2 with Cygwin and C++14 turned on (-std=c++14). Variable initialization inside CASE's is normally prohibited, but the following code compiles:
switch( int switchStatement = 11)
{
    default:
        ++j;
        break; // break is optional, still compiles even if omitted
    case 11:
        int caseVariable = 0;
        ++j;
}

If another CASE is added, then exception "jump to case label" is raised.
switch( int switchStatement = 11)
{
    default:
        ++j;
    case 11:
        int caseVariable = 0;
        ++j;
    case 12: // exception
        ++j;
}

Could somebody explain me how it all works?

A: why you are getting error in second case but not getting error when you declare a variable in last case statement??
Because it's a rule of C++ that a jump cannot pass over a variable
declaration in the same scope. So when you jump to case 2, you pass over
the variable declaration in case 1. But the variable declaration in the
last case is OK, because it is never jumped over.
The reason for the rule is that if you allowed a jump over a variable
declaration it would be very hard for the compiler to work out whether
to call a destructor for that variable. If you had jumped over the
variable declaration you would not need to call the destructor, if you
had not jumped then you would.
The Variable declared and initialized in one case statement can still be visible in other case block but they will not be initialized because the initialization code belongs to another case.
In C++ Problem is of scope. Here, case statements are "labels". Hence, compiler will treat them for making jump from one statement to another. In this particular example, compiler won't understand how to proceed further. To solve this problem you can include the code inside the case into a {} block. The extra { and } mean that the compiler has no trouble working out when to call destructor. Therefore, providing scope or curly brackets to that particular case statement while declaring new variables is important.


text:
Q: dynamic parent class in python The django-file-resubmit module (file widgets.py) makes this import:
from django.forms import ClearableFileInput

and then it defines class based on ClearableFileInput:
class ResubmitBaseWidget(ClearableFileInput):
    # ...some code

I try to use the module with different base class and it works well. But I have to patch the import command in module code. (DBAdminClearableFileInput is inherited from django.forms.ClearableFileInput in an other 3rd party module):
from db_file_storage.form_widgets import DBAdminClearableFileInput as ClearableFileInput

My question is: Could the code of django-file-resubmit module be rewritten more clever, so it could be used with DBAdminClearableFileInput as parameter?
Note: I'm not sure if this is not duplicate question. However I think here are special problems of modules design and a question if some Pull Request  could be made or what is the best approach how to use both modules without changing them.

A: It sounds like what you might really want is co-operative multiple inheritance. E.g. You want to have
class MyFileInput(DBAdminClearableFileInput, ResubmitBaseWidget):
    pass

For that to work, both DBAdminClearableFileInput and ResubmitBaseWidget would need to be written with co-operative multiple inheritance in mind. It may not even be (theoretically) possible depending on how the end-state behaviour has to look. E.g. if DBAdminClearableFileInput wants to render the widget as <foo> and ResubmitBaseWidget wants to render the widget as <bar>, one of them has to 'win' (in the absence of additional code you might write yourself in MyFileInput.
It's possible (though probably unlikely) that multiple inheritance will 'just work', depending on what methods etc both those classes override and whether they make they already make the correct calls to super().
It's probably worth a try at least, in the worst case scenario you can add some 'glue' to your MyFileInput class to make it work.
Here's a trite example
class Elephant:  # Represents ClearableFileInput
    def colour(self):
        return "Grey"

class BrownElephant(Elephant):  # Represents ResubmitBaseWidget
    def colour(self):
        return "Brown"

class PinkElephant(Elephant):  # Represents DBAdminClearableFileInput
    def colour(self):
        return "Pink"

Now, at the moment, these classes do not cooperate, and so if you do multiple inheritance, you get:
class BrownAndPinkElephant(BrownElephant, PinkElephant):
    pass

nelly = BrownAndPinkElephant()
print(nelly.colour())

Will print "Brown", since the Method Resolution Order starts with BrownElephant, which returns "Brown" without ever calling super().colour(), and so Pink and 'default' Elephant's methods are never even called.
You could 'fix' this in a very limited (but might be enough for your purposes) with a hacky 'glue' method like this:
class BrownAndPinkElephant(BrownElephant, PinkElephant):
    def colour(self):
        colours = [
            BrownElephant.colour(self),
            PinkElephant.colour(self),
        ]
        return " and ".join(colours)

nelly = BrownAndPinkElephant()
print(nelly.colour())

Now the printed output is "Brown and Pink", which is more sensible (at least within the context of this example!). Hopefully you can see that you attempt to implement similar things for a subclass of DBAdminClearableFileInput, ResubmitBaseWidget to give you control over what aspects of each class end up being used in the final class.
It's worth saying, there are an awful lot of pitfalls with this approach and I wouldn't recommend it for anything 'serious'. However, when you have 2 classes with a common base class, that you want to combine, and you don't control the source code of either, then this may be a possible solution.


text:
Q: Why are some widget elements not showing up when embedded in iBook? I created a widget in Dashcode. It has some buttons, text fields and texts. It works fine when run from Dashcode or when installed into the Dashboard. When I install it into an iBook (via iBooks Author) and run it on the iPad then the buttons and texts all disappear (as well as a few other minor visual changes). Interestingly if I tap where some of buttons are, it invokes the button click event, but others don't work. Also, when a button click event updates the value of a text then that text becomes visible.
I tried both GlassButtons and regular Buttons, neither shows up. I inspected the properties of the buttons that work vs those that don't and they seem to be the same (beyond id and value).
Here is a screenshot of it running on the Mac:

Here is a screenshot of it running in iBooks on my iPad:

Notice the 8 where a text's value was updated. The connect and update buttons work when you tap in the right spot, but none of the others work.
As a side note, this widget is connecting to a web service over the network using RemObjects SDK for JavaScript, which is really cool. The web service works, if I can just get the buttons to show up.
Update: I replaced the <div> tag which Dashcode uses for a button with an actual HTML <input type="button"> and that shows up in the iBook. Text still doesn't show up. It is also a <div>.

A: I figured it out. When saving the widget it needs to be saved with a minimum Mac OS X version of 10.4.0 which is considered "Backwards-compatible". The default (at least on my install) was 10.4.3. The difference is that when it is saved backwards-compatible then the libraries are included that render the buttons and the text. Why it needs special libraries to render text is beyond me.
One note though is the text position gets messed up a bit when it runs in iBooks. I don't think Apple finished iBooks Author and iBooks 2 before they released it.


text:
Q: How to show all rows from database In the code below, I'm getting only the last row in my database, i.e. first name and last name of the last row in my DB. My question is: how do I change this code in order to get all the results printed?
package samples.directory;

import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.webkit.WebView;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class clanguage extends Activity {
protected Cursor c;
protected SQLiteDatabase db;

protected TextView employeeName;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.webdesign);
    WebView engine = (WebView) findViewById(R.id.web_engine);

    db = (new DatabaseHelper(this)).getWritableDatabase();

    Cursor c = db.rawQuery("SELECT firstName, lastName FROM employee", null);
    if (c != null ) {
        if  (c.moveToFirst()) {
            do {
                String firstName= c.getString(c.getColumnIndex("firstName"));
                String lastName = c.getString(c.getColumnIndex("lastName "));
                String data = "" +
                    "

 "+firstName+"	+
                    "+lastName+"
";

                engine.loadData(data, "text/html", "UTF-8");

            }while (c.moveToNext());
        }
    }
}

A: try this way
StringBuffer data = new StringBuffer("");
data.append("
");
do {

    String firstName= c.getString(c.getColumnIndex("firstName"));
    String lastName = c.getString(c.getColumnIndex("lastName "));

    data.append("
 "+firstName+"	"+lastName+"
");

}while (c.moveToNext());
data.append("
");
engine.loadData(data, "text/html", "UTF-8");

you everytime override content of data object and load it.

A: Hope this will work.
 String data = "" +
    "
 ";
if  (c.moveToFirst()) {

      do {

      String firstName= c.getString(c.getColumnIndex("firstName"));

      String lastName = c.getString(c.getColumnIndex("lastName "));

      data  += "
 "+firstName+"	+
     "+lastName+"
";

      }while (c.moveToNext());
 data  += "
";
 engine.loadData(data, "text/html", "UTF-8");
}


text:
Q: best options for a detailed azure invoice? I need to provide a detailed invoice for Azure usage to a client.  I'd like to be able to provide as granular of a breakdown as possible.  For example, if an Azure cost of $10 was accrued for an App Service on one day, then I'd like to be able to provide the info on why that was, if that info is available.  Was the cost due to a distributed allocation of a monthly cost?  Was the cost due to a specific measure of ingress/egress?  etc.  This is my first time trying to provide a detailed invoice like this, so I'm sure that there are others here who have had the need to do this before who can probably provide some valuable insight on this.

A: You can see the cost breakdown under Cost Management in Azure Portal
In the Azure portal, navigate to cost analysis for your scope. For example: Cost Management + Billing > Cost Management > Cost analysis.
Select Cost by resource.
Change the view to Table.


text:
Q: make project before run application android studio Normally when i execute Run > Run or Run > Debug in Android Studio, this make project and found errors and re compile application, but now, when i click on Run or Debug, directly launch application without compile changes and nothing, if i enter in Configuration of Run, i have "Before launch: Make"
If i execute Build > Make project works correctly, but i don't want execute all time Build > Make project and Run > Run.
I use Android Studio 0.3.4.

A: Open the Run/Debug Configurations dialog (choose Run -> Edit Configurations on the main menu).
Now select the run configuration you are using. On the right hand side you will see various options for the selected run configuration, look for the Before launch section (it should be near the bottom).
There should be a Make entry added to the list. If there is not a Make entry in the list add it using the green + symbol.

A: I have that issue as well and what helped was a complete reinstall of the android studio. So I just downloaded the latest version.

*

*Make sure Android Studio does not run!

*make a backup of the "sdk" folder (you find it in your Android Studio folder)

*Delete the Android Studio folder

*Unpack the downloaded zip to the same location

*copy your "sdk" backup back into the folder

*Start Android Studio

You will see that your settings are still there, your recent project will open normally and you should be able to just "run" your project again with "make" being executed correctly before.
Edit:
I suspect that the main reason for the issue was a failed update try frm 0.3.4 to 0.3.5 and restoring the backup I made will have create even more issues...
Edit 2:
As this is just a temporary fix (see my comment below) I made a ticket in the bugtracker.

A: In my case:

*

*Select "APP" (next to "Make Project" button).

*Select "Edit Configuration".

*In "Before launch".

*Add "Gradle-aware Make" then it will ask you about "Select Gradle Task", just select cancel. Then you will see "Gradle-aware Make" in "Before launch" tab.

*Select "OK".

Now Android will build "Make Project" first, apply all changes then run the app.


text:
Q: The PowerShell command for SPO365LinkSettings does not exist in the SharePoint farm I'm signing in to my Office 365 portal with my global administrator account from the development machine where I have a SharePoint Server 2013 Enterprise farm upgraded to October CU 2015. In the SharePoint admin center I try to configure hybrid > Hybrid SharePoint Sites.

Clicking Next

Clicking Configure

And then the error occurs:

SharePoint Hybrid Team Sites
An error has occurred.
One of the prerequisites is not met: the PowerShell command for
SPO365LinkSettings does not exist in the SharePoint farm. Current
SharePoint farm version is 15.0.4753.1000. As a prerequisite you
should first upgrade to SharePoint 2013 with September 2015 product
update and then re-run the wizard.
Klicken Sie hier, um mehr über die neuesten Informationen zu den
Voraussetzungen für SharePoint-Hybrid zu erfahren.

The link at the bottom is German, but I only got English, Swedish and Norwegian language packs installed (The second run gave an English result).
I already have the server patched to SharePoint 2015 CU, and I can't find any Product Update for September 2015. Is this a wrong error message? Or is it something else I miss?

Edit
All the following is in place (checked twice).

Prerequisites to using the Hybrid Picker:

*

*Be sure that an on-premises SharePoint Server 2013 farm has July PU or later properly installed (on-premises)

*Make sure that ports 80 and 443 are open in the firewall for outbound communications (on-premises)

*Log in to your SharePoint Server farm with an account that can access Central Administration as a Farm Administrator (on-premises)

*When you must log in to Office 365, use an account who is Global Administrator (Office 365)

*Accounts being synchronized must have at least one of the following properties: an e-mail address, a SIP address, or SMTP address.
(on-premises)

You need to run and configure these services:

*

*App Management Service

*Subscription Settings Service

*Search Service Application

*User Profile Service

on your on-premises SharePoint Server farm to avoid error messages
while using the Hybrid Picker. In Central Administration, click Manage
Services on server to check whether these services are in a started
state.

Reference: Hybrid picker in the SharePoint Online admin center
My guess is that this can't be done on SharePoint 2013 since the cmdlet Get-SPO365LinkSettings is only mentioned in combination with SharePoint 2016. See What's new in SharePoint 2016?

A: The product group released the delayed September 2015 Cumulative Update for the SharePoint 2013 product family. No other CU is required to fully patch SharePoint when using these "Uber packages".
As this is a common question: Yes, September 2015 CU includes all fixes from September 2015 PU.
ATTENTION:
Be aware that all Updates for SharePoint 2013 require SharePoint Server 2013 SP1 to be installed first.
Please also have a look at the article that discusses how to properly patch a SharePoint 2013 farm which has Search enabled (see below).
Previous releases of the SharePoint Server 2013 cumulative update included both the executable and the .CAB file in the same self-extracting executable download. Because of the file size, the SharePoint Server 2013 package has been divided into several separate downloads. One contains the executable file, while the others contain the CAB file. All are necessary and must be placed in the same folder to successfully install the update. All are available by clicking the same Hotfix Download Available link in the KB article for the release.
This CU includes all SharePoint 2013 fixes (including all SharePoint 2013 security fixes) released since SP1. The CU does not include SP1. You need to install SP1 before installing this CU.
The KB articles for September CU should be available at the following locations in a couple of hours:
KB 2975894 – SharePoint Foundation 2013 September 2015 CU
KB 2986213 – SharePoint Server 2013 September 2015 CU
KB 2986195 – SharePoint Server 2013 with Project Server September 2015 CU
KB 3085487 – Office Web Apps Server 2013 September 2015 CU – This is also a security fix!
The Full Server Packages for September 2015 CU are available through the following links:
Download SharePoint Foundation 2013 September 2015 CU
Download SharePoint Server 2013 September 2015 CU
Download Project Server 2013 September 2015 CU
Download Office Web Apps Server 2013 September 2015 CU
Important: If your farm has been on a patch level lower than July 2015 CU: Unlike other CUs – after installing the September 2015 CU you need to run the SharePoint 2013 Products Configuration Wizard on each machine in the farm.
If you don't run PSCONFIG after installing September 2015 CU (on a farm which had a lower patch level than July 2015 CU) crawl might no longer work – so ensure to schedule a maintenance window when installing this CU which includes PSCONFIG runs.
See here for detail: http://blogs.technet.com/b/stefan_gossner/archive/2015/07/15/important-psconfig-is-mandatory-for-July-2015-cu-for-sharepoint-2013.aspx
Be aware that the SharePoint Server 2013 CU contains the SharePoint Foundation CU. And the SharePoint Server 2013 with Project Server CU contains Project Server CU, SharePoint Server CU and SharePoint Foundation CU.

A: This command is part of SharePoint 2016 but also available for sharepoint 2013 after the September CU 2015. Could you please check the below link and make sure you met all the prerequisite.
Install and configure SharePoint Server 2013 hybrid

A: Coming back a year after trying this feature again, the result was the same in my SharePoint Server 2016 environment. The script halted at the exact same spot. Going forward I remembered that I have set up sites as Trusted Sites in internet explorer for getting SharePoint Designer to work properly. This was of course a long shot, but worth the try.
My trusted sites list now contains the following urls:
https://go.microsoft.com/
https://login.microsoftonline.com/
https://login.windows.net/
https://outlook.office.com/
https://outlook.office365.com/
https://portal.office.com/
https://tenantName.sharepoint.com/
https://tenantName-admin.sharepoint.com/
https://tenantName-my.sharepoint.com/
https://www.microsoft.com/

And this time, without knowing why, it actually works. I now also have implemented Hybrid Search with splendid result.


text:
Q: how to change color of href on hover I have the following code in my jsp:
<spring:message code="label.actual.expand" />

Basically i have to change the color to  orange when the mouse is over the label and blue
as default color. I know how to do it using an id attribute as indicated in this post(HTML / CSS - Hover Link Color since my id is  generated as shown below i can't use it:
id="${model.product.actualT[status.index].Id}"

Any idea how to do it please? I tried using the class tag but it is not working.
Thanks in advance

A: You can simply use additional class selector in css
a.highlight:link {color: #FFFFFF}
   a.highlight:active {color: #383838}
   a.highlight:visited {color: #FFFFFF}
   a.highlight:hover {color: #383838}

A: See this fiddle
.highlight:hover{
color:red;
}


text:
Q: TestMethod for verifying Web API calls in C# with Cache manager I need to write a test method for my AngularJS Web API calls which has application cache (Cache Manager) in the application start up. When I try to run the test method it calls the Controller and when the code reached the Business class, it is expecting the CacheManager to have the Cache in it, since the cache manager is empty as we have m=not started the application yet, it throws NULL Exception. Please help.

A: Good practice in unit testing is to separate tested logic from dependencies which should be tested separately. The easiest method to achieve this is mocking. You can use mocked Cache Manager and inject it into your application to handle all calls which will be made during test and return predefined values. Control over how mocked interface will behave is very fine grained. From my experience I would recommend Moq mocking package.

A: Before calling the API controller, need to set the config.Routes.MapHttpRoute and initialize the HTTPCONTEXT as below.
var Route = config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
            );
            HttpContext.Current = new HttpContext(
            new HttpRequest("", "http://localhost", ""),
            new HttpResponse(new StringWriter())
            );
            var RouteData = new HttpRouteData(Route, new HttpRouteValueDictionary { { "controller", "unittest" } });
            var Request = new HttpRequestMessage(HttpMethod.Get, "http://localhost");
            controller.ControllerContext = new System.Web.Http.Controllers.HttpControllerContext(config, RouteData, Request);
            controller.Request = Request;
            controller.Request.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;


text:
Q: How to use random.choice() in a list without a specific element? Im currently writing a very simplified version of the board game Clue. I have a question on how to present new clues to the user.
The code has a list called clew_list which has all of the characters and guns available. The new clue is chosen randomly using random.choice(clue_list). My doubt is how to implement that function without taking into consideration the actual crime, which is also an element of clue_list.
The Crime is also chosen randomly using classes and the same method mentioned earlier.
Thank you

A: You can create a new list and pick randomly in the new list
random.choice([element for clew_list in agents if !(isinstance(element, crime))])

A: You can have a while loop until you get what you were looking for. Might seem like a more rudimentary solution compared to the solution made by RCvaram, but if you agents list is big then the probability of picking the wrong thing goes down, and also creating a new list is pretty slow.
choice = random.choice(agents)
while !(isinstance(choice, crime):
   choice = random.choice(agents)


text:
Q: what is the use of total(currentMeausure within head set) in cognos I have a question regarding COGNOS inbuilt function.
I have a report of another developer in which he is using the inbuilt function total(currentMeausure within head set) in COGNOS. My task is to enhance the report. And the fields which have to be enhanced are using this function and I have no idea what this function is doing here.
Thanks,
Regards
Hajrah Naeem
I have searched a lot on google but didn't find accurate description about it. Can anyone explain me this function in easy way with some example so that I can continue my work?

A: Total is the aggregation to be done on the measure.
CurrentMeasure is either the defaultMeasure on the  Crosstab or the Measure projected on an edge
Within set(head(dimension/level/set,N)) means the first N members of the defined object.
So for total(currentMeasure within set(head([ProductLine],3)) would give you total of the first 3 members in the ProductLine level.