text:
Q: Improving performance on loading a long list of facebook friends
As part of my rails project, I have a feature that allows a user to issue invites to their FB friends. I'm using fb_graph for the API calls, and the below is a sampling of the code from the controller when the user hits the invite page.
This operation gets really expensive. I've seen it take longer than 30 seconds for users with upwards of 1000 friends. Also, this code re-executes each time a user hits the invite page. While a user's FB friends list isn't exactly static, it should be okay not recalculating this on every request.
So what I want to do is improve on this code and make it more efficient. I can think of a few  different potential ways to potentially do this, but what makes the most sense in this case? This is a bit more open-ended than I usually like to ask on SO, but as I'm still relatively new to programming, I'm curious just as much on what you would/wouldn't do as much as how to do it.
Here are some ideas on optimizations I could make:
1) Only optimize within a session. The code executes the first time the page is hit and will persist for the rest of the session. I'm actually not sure how to do this.
2) Persist to the database. Add a column to the user table that will hold the friends hash. I could refresh this data periodically using a background job (perhaps once a week?)
3) Persist with caching. I'm not even exactly sure what's involved with this or if this is an appropriate use-case. My feeling is that option 2 requires a lot of manual maintenance, and that perhaps there's a nice caching solution for this that handles expirations, etc., but not sure
Other ideas? Appreciate your thoughts on the options.
  # fetch full array of facebook friends
  @fb_friends = current_user.facebook.fetch.friends

  # strip out only id, name, and photo for each friend
  @fb_friends.map! { |f| { identifier: f.identifier, name: f.name, picture: f.picture }}

  # sort alphabetically by first name
  @fb_friends.sort! { |a,b| a[:name].downcase <=> b[:name].downcase }

  # split into two lists. those already on vs not on network
  @fb_friends_on_network =  Array.new

  @fb_friends.each do |friend|
    friend_find = Authorization.find_by_uid_and_provider(friend[:identifier], 'facebook')
    if friend_find
      @fb_friends_on_network << friend_find.user_id
      @fb_friends.delete(friend)
    end
  end

UPDATE # 1
Adding a bit more on an initial experiment I conducted. I added a column to my user table that holds the @fb_friends array (post-processing the transformations shown above). Basically the controller code above is replaced with simply @fb_friends = current_user.fbfriends. I thought this would cut the load significantly as there is no more call to Facebook, not to mention all the processing done above. This did save some time but not as much as expected. My own friends list took about 6 secs to load on my local machine, after these changes its down to 4 secs. I must be missing something bigger here on the load issue.
UPDATE #2
Upon further investigation, I learned that almost half of data transfer was attributed to the form I was using for the "Invite" buttons. The form would load once for each friend and looked like this:
<%= form_for([@group, @invitation], :remote => true, :html => { :'data-type' => 'html', :class => 'fbinvite_form', :id => friend[:identifier]}) do |f| %>
    <%= f.hidden_field :recipient_email, :value => "facebook@meetcody.com" %>

    <div class = "fbinvite btn_list_right" id = "<%= friend[:identifier] %>">
    <%= f.submit "Invite", :class => "btn btn-medium btn-primary", :name => "fb" %>

<% end %>

I decided to remove the form and inside place a simple button:
<div class = "fbinvite_form" id = "<%= friend[:identifier] %>" name = "fb">

        Invite

I then used ajax to detect a click and take the appropriate actions. This change literally cut the data transfer in half. Before loading about 500 friends took ~650kb, now its down to ~330kb.
I'm thinking I will go back and try what I tried in Update # 1, to do pre-processing. Combined I'm hoping I can get this down to a ~2 sec operation.
UPDATE #3
I ended up installing Miniprofiler to learn more what could be slowing this operation down and learned that my for loop above is terrible inefficient as it makes a trip to the DB on every friend. I posted in a separate question and got help to reduce the trips down to just one. I then went ahead and implemented the pre-processing I mentioned in Update #1. With all these changes, I have it down to ~700ms which is remarkable considering it was taking +20 secs plus before going down this path!

A: If you can run some query's in parallel I'll suggest you to take a look at: The futoroscope gem.
As you can see by the announcing blog post it tries to solve the same problem of making simultaneous API query's. It's seems to have pretty good support and good test coverage.


text:
Q: how get each single column data from php multidimensional array? how get each single column data from php multidimensional into single column array?
like $_test = = array(
    array(
        'id' => 1001,
        'first_name' => 'kalpesh',
        'last_name' => 'gamit',
    ),
    array(
        'id' => 1002,
        'first_name' => 'kartik',
        'last_name' => 'patel',
    ),
    array(
        'id' => 2002,
        'first_name' => 'smith',
        'last_name' => 'Jones',
    ),
    array(
        'id' => 4004,
        'first_name' => 'patel',
        'last_name' => 'Doe',
    )
);

want result like id OR first_name only without use loop like while, foreach, for etc
Array
(
    [0] => 1001
    [1] => 1002
    [2] => 2002
    [3] => 4004
)

A: update your script like below and check it please but it will work only in PHP 5.5 greater than version only...
 $_test = = array(
    array(
        'id' => 1001,
        'first_name' => 'kalpesh',
        'last_name' => 'gamit',
    ),
    array(
        'id' => 1002,
        'first_name' => 'kartik',
        'last_name' => 'patel',
    ),
    array(
        'id' => 2002,
        'first_name' => 'smith',
        'last_name' => 'Jones',
    ),
    array(
        'id' => 4004,
        'first_name' => 'patel',
        'last_name' => 'Doe',
    )
);

$ids_only = array_column($records, 'id');
print_r($ids_only);

Results for ID
Array
(
    [0] => 1001
    [1] => 1002
    [2] => 2002
    [3] => 4004
)

Results for first_name
$first_name = array_column($records, 'id');
print_r($first_name);
Array
(
    [0] => Kalpesh
    [1] => kartik
    [2] => smith
    [3] => patel
)

run above php script and please check....

A: You could use array_map:
$id_list = array_map(function($var) {
  return $var['id'];
}, $_test);

redpajama_set_name: RedPajamaStackExchange


text:
Q: First non-false value Is there a way to simplify the following?
CASE WHEN
    (a.is_future_release IS TRUE OR aa.is_future_release IS TRUE) THEN TRUE
    ELSE FALSE
END

In python I'd do:
a.is_future_release or aa.is_future_release or False

Can this be simplified in mysql/sql?

A: Doesn't this do what you want?
(a.is_future_release OR aa.is_future_release)

In MySQL, booleans are treated as integers, with a value of "1" for true and "0" for false.
The only difference between this and your original query is that this could return NULL if both values are NULL.

A: An IF statement is a bit cleaner:
IF(a.is_future_release IS TRUE OR aa.is_future_release IS TRUE, TRUE, FALSE)

Or using the boolean operators / shorthand:
IF(a.is_future_release|aa.is_future_release, TRUE, FALSE)


text:
Q: Android 12 Canvas drawPoint() - Paint contains alpha which can't be removed after setting targetSDK=31 and testing my app I stumbled over this weird behaviour, maybe you know the solution
my code looks like this:
    private val foregroundPaint: Paint by lazy {
        Paint().apply {
            isAntiAlias = true
            color = Color.BLACK
        }
    }
...
        val barcodeBitmap = Bitmap.createBitmap(
            width,
            height,
            Bitmap.Config.ARGB_8888
        )

        val canvas = Canvas(barcodeBitmap)
        canvas.drawColor(Color.WHITE)

        // Draw black pixels on bitmap
        for ((x, i) in (xLeft until xRight).withIndex()) {
            for ((y, j) in (yTop until yBottom).withIndex()) {
                if (bm[i, j]) {
                    canvas.drawPoint(
                        x.toFloat(),
                        y.toFloat(),
                        foregroundPaint
                    )
                }
            }
        }
        return barcodeBitmap

on Android 12 drawPoint contains some alpha Channel which can't be removed, I already tried with
   private val foregroundPaint: Paint by lazy {
        Paint().apply {
            alpha = 255
            color = Color.BLACK
        }
    }

but unfortunately it didn't work...
when i call drawPoint() 2 times, it's real black, but i think there must be a better solution to this problem.
here are the screenshots of my generated bitmaps

As you can see on Android 12 the Black Color is clearly brighter.
Every hint is welcome!
Short Update
instead of drawing the code onto the canvas I draw it directly onto the Bitmap
barcodeBitmap.setPixel(
   x,
   y,
   Color.BLACK,
)

now it's working as expected.
if you get here and know a better solution, please let me know :)


text:
Q: Rename file before unlocking PDF with ghostscript batch script Current behaviour
I have a batch script that unlocks pdfs with ghostscript. I just have to drop a pdf file via drag-and-drop on the script file to unlock it. It will create an unlocked file in the same folder.
example:
I drag-and-drop locked file "datasheet.pdf" onto the script file. It will generate an unlocked file called "datasheet_no.pdf" in the same folder where the "datasheet.pdf" file is.
I want to modify the NAMING of the files:
After dropping "datasheet.pdf" onto the script, I want to have a UNprotected "datasheet.pdf" file and the old protected file "datasheet_old.pdf"
I hope someone can help me. I tried out stuff like REN and DEL, but it never works. Or I end up with pdfs with blank pages and losing the old file. I have only little experience with batch. I found this Script via google.
Working Script which should be modified:
@echo off
echo.
echo.
set PATH="C:\Program Files\gs\gs9.20\bin"
echo **************************************
echo.
echo   Start processing, may take a while, please wait.
echo.
echo **************************************
echo.
echo.
set filein=%~1
set fileout=%filein:~0,-4%
set patch=%filein:~0,-4%

gswin64c -dSAFER -dBATCH -dNOPAUSE -sDEVICE=pdfwrite -sPDFPassword= -dPDFSETTINGS=/prepress -dPassThroughJPEGImages=true -sOutputFile="%fileout%_no.pdf" "%~1"

A: ren "%~1" "%~n1_old%~x1"
ren "%fileout%_no.pdf" "%~nx1"

should first rename the original file to originalname_oldoriginalextension and the createdoutputfile to originalnameandextension
Note that the target name of a ren command must not include the path to the file.


text:
Q: How to maintain same session Id for same client for particular session only? We used session Id as
const sessionId=uuid.v4();
But it resulted in giving different session ids for the questions for the same user.
How to maintain the same session Id throughout the session for a user in node.js?


text:
Q: How To print a long string into multiple pages in C# I'm trying to print a very long string using code below but it prints the whole text only in one page. Is there any easy way to print it correctly?
string text="the text has like 1000 words";

System.Drawing.Printing.PrintDocument p = new System.Drawing.Printing.PrintDocument();

p.PrintPage += delegate (object sender1, System.Drawing.Printing.PrintPageEventArgs e1)
{
    e1.Graphics.DrawString(text, new System.Drawing.Font("Times New Roman", 12), new System.Drawing.SolidBrush(System.Drawing.Color.Black), new System.Drawing.RectangleF(50, 50, p.DefaultPageSettings.PrintableArea.Width - 50, p.DefaultPageSettings.PrintableArea.Height - 50));

};
try
{
    p.Print();
}
catch (Exception ex)
{
    throw new Exception("Exception Occured While Printing", ex);
}

I tried to solve it with this article but the method stuck in some loop that I don't know how to fix.

A: You have to keep in mind that PrintDocument will raise the event PrintPage as long as you tell it there are more pages. It is your task to keep track of what is printed, what needs to printed next and if you need another page or not.
There are several ways to accomplish that. I have chosen in this case to take the content of your text, check how much of it fits on the current page, DrawString that bit and then update my processing string, called remainingtext to be able to repeat for the next Page. The decision if a next page is needed is controlled by setting HasMorepages of the PrintEvent arguments instance to true or false when we're done.
Here is the code:
PrintDocument p = new PrintDocument();

var font = new Font("Times New Roman", 12);
var margins = p.DefaultPageSettings.Margins;
var layoutArea = new RectangleF(
    margins.Left,
    margins.Top,
    p.DefaultPageSettings.PrintableArea.Width - (margins.Left + margins.Right ),
    p.DefaultPageSettings.PrintableArea.Height - (margins.Top + margins.Bottom));
var layoutSize = layoutArea.Size;
layoutSize.Height = layoutSize.Height - font.GetHeight(); // keep lastline visible
var brush = new SolidBrush(Color.Black);

// what still needs to be printed
var remainingText = text;

p.PrintPage += delegate (object sender1, PrintPageEventArgs e1)
{
    int charsFitted, linesFilled;

    // measure how many characters will fit of the remaining text
    var realsize = e1.Graphics.MeasureString(
        remainingText,
        font,
        layoutSize,
        StringFormat.GenericDefault,
        out charsFitted,  // this will return what we need
        out linesFilled);

    // take from the remainingText what we're going to print on this page
    var fitsOnPage = remainingText.Substring(0, charsFitted);
    // keep what is not printed on this page
    remainingText = remainingText.Substring(charsFitted).Trim();

    // print what fits on the page
    e1.Graphics.DrawString(
        fitsOnPage,
        font,
        brush,
        layoutArea);

    // if there is still text left, tell the PrintDocument it needs to call
    // PrintPage again.
    e1.HasMorePages = remainingText.Length > 0;
};
p.Print();

When I hookup an PrintPreviewControl this is the result:

A: So thanks to rene I figured it out how to print it correctly. I edit his code and the difference here is that the user chooses the paper size and rectangel drawing happens with choosen paper margin size. This is a ready printing method in case you want to use it...
private void Print(string thetext){

            try
            {

                System.Drawing.Printing.PrintDocument p = new System.Drawing.Printing.PrintDocument();

                var font = new Font("Times New Roman", 12);
                var brush = new System.Drawing.SolidBrush(System.Drawing.Color.Black);

                // what still needs to be printed
                var remainingText = theText;

                p.PrintPage += delegate (object sender1, System.Drawing.Printing.PrintPageEventArgs e1)
                {
                    int charsFitted, linesFilled;

                // measure how many characters will fit of the remaining text

                var realsize = e1.Graphics.MeasureString(
                        remainingText,
                        font,
                        e1.MarginBounds.Size,
                        System.Drawing.StringFormat.GenericDefault,
                        out charsFitted,  // this will return what we need
                        out linesFilled);

                // take from the remainingText what we're going to print on this page
                var fitsOnPage = remainingText.Substring(0, charsFitted);
                // keep what is not printed on this page
                remainingText = remainingText.Substring(charsFitted).Trim();

                // print what fits on the page
                e1.Graphics.DrawString(
                        fitsOnPage,
                        font,
                        brush,
                        e1.MarginBounds);

                    // if there is still text left, tell the PrintDocument it needs to call
                    // PrintPage again.
                    e1.HasMorePages = remainingText.Length > 0;
                };

                System.Windows.Forms.PrintDialog pd = new System.Windows.Forms.PrintDialog();
                pd.Document = p;
                DialogResult result = pd.ShowDialog();

                if (result == System.Windows.Forms.DialogResult.OK)
                {
                    p.Print();
                }

            }catch(Exception e2)
            {
                System.Windows.MessageBox.Show(e2.Message, "Unable to print",MessageBoxButton.OK);
            }

}

A: Code snippet for "when user clicked 'btnPrint' button, print 'rtbEditor' rich textbox's text.":
        private void btnPrint_Click(object sender, EventArgs e) {

            var d = new PrintDialog();
            d.Document = new PrintDocument();
            d.Document.PrintPage += Dd_PrintPage;
            remainingText = rtbEditor.Text;
            var res = d.ShowDialog();
            try { if (res == DialogResult.OK) d.Document.Print(); }
            catch { }
        }

        string remainingText;
        private void Dd_PrintPage(object sender, PrintPageEventArgs e){

            //this code was for 1 page
            //e.Graphics.DrawString(rtbEditor.Text,new Font("Comic Sans MS", 12f),Brushes.Black,new PointF(10,10));

            //this is for multiple pages
            PrintDocument p = ((PrintDocument)sender);
            var font = new Font("Times New Roman", 12);
            var margins = p.DefaultPageSettings.Margins;
            var layoutArea = new RectangleF(
                margins.Left,
                margins.Top,
                p.DefaultPageSettings.PrintableArea.Width - (margins.Left + margins.Right),
                p.DefaultPageSettings.PrintableArea.Height - (margins.Top + margins.Bottom));
            var layoutSize = layoutArea.Size;
            layoutSize.Height = layoutSize.Height - font.GetHeight(); // keep lastline visible
            var brush = new SolidBrush(Color.Black);
            int charsFitted, linesFilled;

            // measure how many characters will fit of the remaining text
            var realsize = e.Graphics.MeasureString(
                remainingText,
                font,
                layoutSize,
                StringFormat.GenericDefault,
                out charsFitted,  // this will return what we need
                out linesFilled);
            // take from the remainingText what we're going to print on this page
            var fitsOnPage = remainingText.Substring(0, charsFitted);
            // keep what is not printed on this page
            remainingText = remainingText.Substring(charsFitted).Trim();

            // print what fits on the page
            e.Graphics.DrawString(
                fitsOnPage,
                font,
                brush,
                layoutArea);

            // if there is still text left, tell the PrintDocument it needs to call
            // PrintPage again.
            e.HasMorePages = remainingText.Length > 0;
        }


text:
Q: SQLite3::SQLException: no such column:
Possible Duplicate:
undefined method `to_f' for #<ActiveRecord::Relation:0x472d0a0>

I'm trying to make a call tracking application to learn twilio and rails.
Right now, I would like to make a graph that shows a user how many phone calls a particular phone number gets per day.
The schema is user has_many phones has_many calls.
I try to make the graph by creating an instance method that counts the number of phones on a particular day, but when I try executing the code, I get the error :
SQLite3::SQLException: no such column: calls.placed_at: SELECT COUNT(*) FROM "calls"  WHERE "calls"."phone_id" = 44 AND ("calls"."placed_at" BETWEEN '2012-09-15 00:00:00.000000' AND '2012-09-15 23:59:59.999999')

I don't quite understand the code I'm using for the instance method, and it's probably calling the wrong column. Your help on this would be greatly appreciated.
Here's the important part of my call model:
def total_on(date)
  calls.where(placed_at: date.beginning_of_day..date.end_of_day).count
end

Here's how I'm counting the phone calls in my show view
<%= (1.month.ago.to_date..Date.today).map { |date| @phone.total_on(date).to_f}.inspect %>

Here's how I define the @phone variable
@phone = Phone.find_by_id(params[:id])

Here's my complete phone model (for schema reference)
# == Schema Information
#
# Table name: phones
#
#  id              :integer          not null, primary key
#  name            :string(255)
#  twilio_number   :integer
#  original_number :integer
#  user_id         :integer
#  created_at      :datetime         not null
#  updated_at      :datetime         not null
#

class Phone < ActiveRecord::Base

  attr_accessible :original_number, :user_id, :name, :twilio_number
  belongs_to :user
  has_many :calls, dependent: :destroy

  validates :name, presence: true
  validates :twilio_number, presence: true
  validates :original_number, presence: true
  validates :user_id, presence: true

  default_scope order: 'phones.created_at DESC'

  validate :check_phone_limit, :on => :create

  def check_phone_limit
    if User.find(self.user_id).at_max_phone_limit?
      self.errors[:base] << "Cannot add any more phones"
    end
  end

  def original_number=(value)
    num = value.to_s.gsub(/[^0-9+]/, "")
    write_attribute(:original_number, num.to_i)
  end

def total_on(date)
  calls.where(placed_at: date.beginning_of_day..date.end_of_day).count
end

end

Here's my complete call model
# == Schema Information
#
# Table name: calls
#
#  id               :integer          not null, primary key
#  AccountSid       :string(255)
#  From             :string(255)
#  To               :string(255)
#  CallStatus       :string(255)
#  ApiVersion       :string(255)
#  Direction        :string(255)
#  FromCity         :string(255)
#  FromState        :string(255)
#  FromZip          :string(255)
#  FromCountry      :string(255)
#  ToCity           :string(255)
#  ToState          :string(255)
#  ToZip            :string(255)
#  ToCountry        :string(255)
#  CallSid          :string(255)
#  DialCallSid      :string(255)
#  DialCallDuration :string(255)
#  DialCallStatus   :string(255)
#  RecordingUrl     :string(255)
#  phone_id         :integer
#  DialCallMinutes  :integer
#  created_at       :datetime
#  updated_at       :datetime
#

class Call < ActiveRecord::Base
  attr_accessible :AccountSid, :From, :To, :CallStatus, :ApiVersion, :Direction, :FromCity, :FromState, :FromZip, :FromCountry, :ToCity, :ToState, :ToZip, :ToCountry, :CallSid, :DialCallSid, :DialCallDuration, :DialCallStatus, :RecordingUrl, :DialCallMinutes
  belongs_to :phone

  def self.create_from_incoming_call(params)

   user_phone = Phone.find_by_twilio_number(params['To']) #Finds the phone number in the database based on what phone Twilio is calling

    twilio_request_params = {
      :CallSid => params['CallSid'],
      :AccountSid => params['AccountSid'],
      :From => params['From'],
      :To => params['To'],
      :CallStatus => params['CallStatus'],
      :ApiVersion => params['ApiVersion'],
      :Direction => params['Direction'],
        :FromCity => params['FromCity'],
        :FromState => params['FromState'],
      :FromZip => params['FromZip'],
      :FromCountry => params['FromCountry'],
      :ToCity => params['ToCity'],
      :ToState => params['ToState'],
      :ToZip => params['ToZip'],
      :ToCountry => params['ToCountry']
      :phone_id => user_phone.phone_id

    }

    call = Call.new(twilio_request_params)
    call.save
    return call

  end

  def Call.update_dial_call(params)

    twilio_request_params = {
        :DialCallSid => params['DialCallSid'],
        :DialCallDuration => params['DialCallDuration'],
        :DialCallStatus => params['DialCallStatus'],
        :RecordingUrl => params['RecordingUrl'],
      :DialCallMinutes => (params['DialCallDuration'].to_f/60.to_f).ceil
    }

    call = Call.where( :CallSid => params['CallSid'] ).first
    call.update_attributes twilio_request_params
    call.save

  end

end

I've been stuck on this for a while; any help would be greatly appreciated!

A: Your call model uses the standard rails created_at, yet your query was using placed_at, which doesn't exist.


text:
Q: Firebase firestore offline support, save data at the start of app React Js I am working on a book reading web app using React Js where the owner can make their own books and publish in the app . Since the data can be enormous so i wan't to ask is this possible or a good practice to load all the data at the start of web app, also i wan't to save it as a cache for offline support, what should i do for this.

A: Only load data you use
It's a simple principal, but only load data you use at that moment. You don't need book details on a book overview page (for example).
As for storing data and hydrating your state, this can be achieved quite easily with redux-localstorage if you're using the redux. I'm sure you can find another way to add data to local storage if not.
A tip, make sure you save only data you need in local storage and always check if its out of date before applying it to the app.

A: you can use like this
db.collection("cities").where("state", "==", "CA")
  .onSnapshot({ includeMetadataChanges: true }, (snapshot) => {
      snapshot.docChanges().forEach((change) => {
          if (change.type === "added") {
              console.log("New city: ", change.doc.data());
          }

          var source = snapshot.metadata.fromCache ? "local cache" : "server";
          console.log("Data came from " + source);
      });
  });

https://firebase.google.com/docs/firestore/manage-data/enable-offline


text:
Q: How to increase space width of text using css on condition of language used? I am using "Nafees Nastaliq" font on a wordpress website. This font provides English and Urdu characters to write in both languages. Urdu language doesn't need that width of space that english language needs. So, the font contains a narrow width of "space" character. On the website, I have to type English and Urdu both sometimes in the same div. So, is their anyway to increase the width of "space" character only when their is a space character between two characters which are both in English? Here is an example screenshot, how it look likes:

In the above example, system should check that if their is English words like "No Categories", so the space between "no" and "Categories" should be maximized in width just like it should be in English. But for the urdu side "اصنافِ سخن" it should not increase the width of space.
Here is CSS:
li {
    font-family: 'Nafees Nastaliq' !important;
    font-weight: normal !important;
}

Pseduo Code I have : But how to implement?

*

*Select a "space"

*check if left side character is in (A,B,C.. a,b,c...) AND check if right side character is in (A,B,C.. a,b,c...)

*If yes, then increase_space_width()

*else use_space_as_it_is() or do_nothing();

A: Put all your characters or words that you want to write in Urdu language, in a span with a specific class name. For example:
HTML CODE:

    This paragraph contains multiple languages such as Englsih and اردو at the same time.

CSS CODE:
p {
    font-familly: "English Font", "Urdu Font";
    font-weight: bBold;
}
p .urdu {
    font-weight: normal;
    /* Your custome style for Urdu language only */
}


text:
Q: Lowercase-only Input in Xamarin.Forms I am building a Xamarin.Forms app to be used with iOS and Android. The first Page of this app is a login form, with fields pictured below.

It's my intention to have the keyboard (when focused on the username field) expect all-lowercase characters.
I achieved this on a physical Android device by removing Keyboard="Text". However, the iOS emulator seems adamant that uppercase is the way to go on that first letter, also showing this behaviour when I have the software keyboard up on the emulator.
I've really struggled to find more information for this when browsing Google. Is anyone aware of:

*

*Expected behaviour of Xamarin.Forms here?

*A way to work around this?

A:
Expected behaviour of Xamarin.Forms here?

The Forms' Entry on iOS is via the native UITextField and autocapitalization is handled via iOS's keyboard and that default behavior for the default iOS keyboard for an English locale is to capital words.
You can override the behavior via the UITextField.AutocapitalizationType property.

The automatic capitalization style to apply to typed text. This attribute determines at what time the Shift key is automatically pressed. You can access the value of this attribute programmatically using the text field's autocapitalizationType property.

Example:
someTextField.AutocapitalizationType = UITextAutocapitalizationType.None;

A way to work around this?

You can define a Forms' behavior to handle that change:

*

*https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/behaviors/creating
Or a custom Entry iOs renderer:

*

*https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/custom-renderer/
UITextAutocapitalizationType:
public enum UITextAutocapitalizationType : long
{
    None,
    Words,
    Sentences,
    AllCharacters
}

A: I found a simple xaml solution from alexgavru on this question.
<Entry Keyboard="Plain" /> worked for me.

A: You can use TextTransform="Lowercase".
Better late than never. :)

A: I had a similar requirement except I wanted the keyboard to show all caps to enter a code value. So I used Effects provided by Xamarin to achieve this.
Here is the code for capitalizing it. But without any trouble you can change it to lower case.
Forms:
namespace VINEntryApp.CustomControls
{
    public class CapitalizeKeyboardEffect : RoutingEffect
    {
        public CapitalizeKeyboardEffect() : base("Company.CapitalizeKeyboardEffect")
        {
        }
    }
}

Droid:
[assembly: ResolutionGroupName("Company")]
[assembly: ExportEffect(typeof(CapitalizeKeyboardEffect), nameof(CapitalizeKeyboardEffect))]
namespace VINEntryApp.Droid.Custom
{
    [Preserve]
    public class CapitalizeKeyboardEffect : PlatformEffect
    {
        private InputTypes _old;
        private IInputFilter[] _oldFilters;

        protected override void OnAttached()
        {
            var editText = Control as EditText;
            if (editText != null)
            {
                _old = editText.InputType;
                _oldFilters = editText.GetFilters().ToArray();

                editText.SetRawInputType(InputTypes.ClassText | InputTypes.TextFlagCapCharacters);

                var newFilters = _oldFilters.ToList();
                newFilters.Add(new InputFilterAllCaps());
                editText.SetFilters(newFilters.ToArray());
            }
        }

        protected override void OnDetached()
        {
            var editText = Control as EditText;
            if (editText != null)
            {
                editText.SetRawInputType(_old);
                editText.SetFilters(_oldFilters);
            }
        }
    }
}

iOS:
[assembly: ResolutionGroupName("Company")]
[assembly: ExportEffect(typeof(CapitalizeKeyboardEffect), nameof(CapitalizeKeyboardEffect))]
namespace VINEntryApp.iOS.Custom
{
    [Preserve]
    public class CapitalizeKeyboardEffect : PlatformEffect
    {
        private UITextAutocapitalizationType _old;

        protected override void OnAttached()
        {
            var editText = Control as UITextField;
            if (editText != null)
            {
                _old = editText.AutocapitalizationType;
                editText.AutocapitalizationType = UITextAutocapitalizationType.AllCharacters;
            }
        }

        protected override void OnDetached()
        {
            var editText = Control as UITextField;
            if (editText != null)
                editText.AutocapitalizationType = _old;
        }
    }
}

Use:
<Entry>
     <Entry.Effects>
                    <custom:CapitalizeKeyboardEffect />
     </Entry.Effects>
<Entry>

A: Solution
In the end, programmatically setting the Keyboard property of the Entry as below worked a charm, without needing platform-specific code:
UsernameEntry.Keyboard = Keyboard.Create(KeyboardFlags.None);

Details
In Extensions.cs within the source code of Xamarin.Forms, the Xamarin keyboard type is checked to determine the behaviour of the platform-specific keyboards. An example of this is below:
if (keyboard == Keyboard.Default)
{
    textInput.AutocapitalizationType = UITextAutocapitalizationType.Sentences;


text:
Q: PHP gives T_STRING error when connecting to MySQL Code looks fine, but it throws up an error:
"Parse error: syntax error, unexpected T_STRING in /home/u924861036/public_html/press.php on line 7"
<?php
$ip = $_SERVER['REMOTE_ADDR'];
$type = $_POST['type'];
$data = $_POST['data'];

mysql_connect("localhost", "user_name", "pass") or
die("Could not connect: " . mysql_error());
mysql_select_db("db_name");

The second last line is line 7, but even if i delete it, the error is same, so there is some error in line 8 also.

A: I think you are using the wrong "  instead of " (notice they are 'italic')
please try this:
<?php
$ip = $_SERVER['REMOTE_ADDR'];
$type = $_POST['type'];
$data = $_POST['data'];

mysql_connect("localhost", "user_name", "pass") or
die("Could not connect: " . mysql_error());
mysql_select_db("db_name");
?>

edit:
Confirmed, this throws a invalid user/pass on my system :)

A: Use double or single quotes ( " / ' ) instead of a weird " symbol
<?php
$ip = $_SERVER['REMOTE_ADDR'];
$type = $_POST['type'];
$data = $_POST['data'];

mysql_connect("localhost", "user_name", "pass") or die("Could not connect: " . mysql_error());
mysql_select_db("db_name");

A: Your double quotes look weird.
Try this:
<?php
$ip = $_SERVER['REMOTE_ADDR'];
$type = $_POST['type'];
$data = $_POST['data'];

mysql_connect("localhost", "user_name", "pass") or
die("Could not connect: " . mysql_error());
mysql_select_db("db_name");

And please use mysqli or PDO instead of mysql_* functions.
Why shouldn't I use mysql_* functions in PHP?

A: <?php
$ip = $_SERVER['REMOTE_ADDR'];
$type = $_POST['type'];
$data = $_POST['data'];

mysqli_connect("localhost", "user_name", "pass") or die("Could not connect: " . mysqli_error());
mysqli_select_db("db_name");
?>

Just to make sure: You know that you are connecting with username 'user_name' and password 'pass' to the database 'db_name'? Fixed strange quotes.

A: Replace :-
mysql_connect("localhost", "user_name", "pass") or
die("Could not connect: " . mysql_error());
mysql_select_db("db_name");

with
mysql_connect("localhost", "user_name", "pass") or
die("Could not connect: " . mysql_error());
mysql_select_db("db_name");


text:
Q: overload == to compare two linked list recursively I have a homework problem, which asks me to overload == operator to compare two linked-list. And i need to do this in recursion.
Here is my .h file
class  LList {
   public:
      friend bool operator == (const LList& lfSide, const LList& rtSide);
   private:
      struct Node {
         int item;
         Node* next;
      };
      friend bool operator == (const LList& lfSide, Node* headlf, const LList& rtSide, Node* headrt);
      Node* head;
}

I tried to use a helper function to make the recursion happen, but it still gives error saying Node is not defined.
friend bool operator == (const LList& lfSide, Node* headlf, const LList& rtSide, Node* headrt);
Can anyone help me with this?

A: The structure Node is a private data member, It may not be used in the friend declaration
friend bool operator == (const LList& lfSide, Node* headlf, const LList& rtSide, Node* headrt);

You could define the structure like
#include <iostream>
class  LList {
   public:
      friend bool operator == (const LList& lfSide, const LList& rtSide);
   private:
      struct Node {
         int item;
         Node* next;
         bool operator ==( const Node &headrt);
      };
      Node* head;
};

And within the friend operator use the operator == of the structure Node.

A: One more approach could be to have only one argument passed to operator == as this is passed implicitly.Here is complete code
template <typename T>
struct Node
{
    T data;
    Node<T>* next;
};
template <class T>
class LinkedList
{
private:
    Node<T>* head;

    bool internalCompare(Node<T>* first, Node<T>* second)
    {
        if((first == nullptr) && (second == nullptr))
        {
            return true;
        }
        else if(((first == nullptr) && (second != nullptr)) || ((first != nullptr) && (second == nullptr)))
        {
            return false;
        }
        else if (first->data != second->data)
        {
            return false;
        }
        return internalCompare(first->next,second->next);
    }
public:
    LinkedList() :head(nullptr) {}
    bool operator ==(LinkedList<T> & second)
    {
        if(internalCompare(head,second.head))
        {
            return true;
        }
        return false;
    }
};

A: This might help you.
I kept the things simple by making some member variables as public.
class Node
{
public:
    int m_Value = -1;
    Node* m_Next = nullptr;
    Node()
    {
        m_Value = -1;
        m_Next = NULL;
    }
};

//Linked List class
class LinkedList
{
    //Head Node
    Node* m_Head;
    //Tail Node
    Node* m_Last;

public:
    //Constructor
    LinkedList()
    {
        m_Head = nullptr;
        m_Last = nullptr;
    }
    //Add value to list
    void AddValue(int value)
    {
        if (m_Head == nullptr)
        {
            m_Head = new Node();
            m_Head->m_Value = value;
            m_Last = m_Head;
        }
        else
        {
            Node* newNode = new Node();
            newNode->m_Value = value;
            m_Last->m_Next = newNode;
            m_Last = newNode;
        }
    }

    //Display the elements of the list
    void display()
    {
        Node* travelNode = m_Head;
        while (travelNode != nullptr)
        {
            cout << travelNode->m_Value << " ==> ";
            travelNode = travelNode->m_Next;
        }
    }

    //Compare function
    bool operator==(const LinkedList& List)
    {
        return CompareList(this->m_Head, List.m_Head);
    }

    bool CompareList( Node* LeftList,  Node* rightList)
    {
        //If both nodes reaches to end then it is equal
        if (LeftList == nullptr && rightList == nullptr) return true;

        //If one of the node has more nodes then list are not equal
        if (LeftList == nullptr || rightList == nullptr) return false;

        //Compare the values
        if (LeftList->m_Value != rightList->m_Value) return false;

        //Call recursion
        CompareList(LeftList->m_Next, rightList->m_Next);
    }
};

int main()
{
    //First List
    LinkedList list1;
    list1.AddValue(1);
    list1.AddValue(2);
    list1.AddValue(3);
    list1.AddValue(4);
    list1.AddValue(5);

    //list1.display();

    //Second List
    LinkedList list2;
    list2.AddValue(1);
    list2.AddValue(2);
    list2.AddValue(3);
    list2.AddValue(4);
    list2.AddValue(5);

    //list2.display();

    //Compare
    bool areEq = list1 == list2;
    cout << "Are Equal " << areEq << endl;
}


text:
Q: How to map data from one set to another set I have a set of numbers that has a non-injective, surjective correspondence to another set of numbers and I would like to quickly create a list of the output. For example, suppose I have

32  54  65  66  71
9   31  34  41  49
18  41  50  68  70
11  50  51  70  75
19  24  26  40  68
17  24  27  48  75
20  21  38  54  66
12  22  46  56  74
14  18  48  54  71
.
.
.

Each of these numbers has a correspondence to another set of numbers. For example each number on the left below corresponds to the number on the right

2   1
4   1
5   2
6   2
7   1
8   1
9   3
10  1
11  3
12  2
13  1
14  3
16  1
17  2
18  3
19  3
20  1
21  2
22  1
24  2
25  1
26  3
27  2
28  4
29  1
30  1
31  2
32  2
33  3
34  3
35  1
36  2
37  2
38  4
40  3
41  3
42  1
44  1
45  2
46  3
48  3
49  2
50  2
51  1
52  2
53  1
54  3
55  1
56  1
57  3
59  2
60  1
62  1
63  1
65  3
66  2
68  3
69  1
70  3
71  3
73  2
74  2
75  2
76  2
77  3

Using this correspondence I now have a list of the form
2 3 3 2 3
3 2 3 3 2
3 3 2 3 3
.
.
.

that is related to the first list.
How can I make this last calculation faster? I have a large number of rows so it isn't practical to look up each corresponding number and write the new set of numbers. I would call these matrices, but the order of numbers in each row does not matter to me. I'm not sure if that matters. So for the first row of the first matrix, 71 exchanged with 32 would not matter to me. Also, for the second list, the numbers on the second column could range from 1,..,n. I have just use n=3 How would I got about make a computation like this?
Any pointers, guidance, suggestions is greatly appreciated.

A: Try the following code~
asso=Association[Rule@@@list2]
Map[asso,list1,{2}]

will this help?


text:
Q: How to save many object (with the same class) to txt file and binding those object with listbox VB.NET I try to program a simple project to save data to txt file, read it and use binding data to show it. My project like this.

When I add ID Person to "Add ID" textbox (Textbox which near Button "Add ID"). It will add ID to Listbox and "ID Name" textbox. With this IDName, I insert FirstName and LastName for first person and Save Person's Name. Then, I Add new ID in "Add ID" textbox and fill First,last name and save it again

I refer this page http://vbnetsample.blogspot.de/2007/12/serialize-deserialize-class-to-file.html?m=1 to save and read data to txt file. It's run ok. But my problem is that when I save Person 2 with ID 2, Person 1 is overwrited. I think I can save Person to List Person. But it will make difficult when I want to update any Person's data. I don't know whether Is there any way to save and update each person. And by the way How can I show data by binding data in listbox.
Here is my code
Imports System.Runtime.Serialization.Formatters.Binary
Imports System.IO

Public Class Form1
    Public pPerson As New Person

    'Serialize and Save Data to txt file
    Private Sub SaveButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveButton.Click
        pPerson.IDName = IDNameTextBox.Text
        pPerson.FirstName = FirstNameTextBox.Text
        pPerson.LastName = LastNameTextBox.Text
        Dim fs As FileStream = New FileStream("C:\Users\Bruce\Desktop\test.txt", FileMode.OpenOrCreate)
        Dim bf As New BinaryFormatter()
        bf.Serialize(fs, pPerson)
        fs.Close()
    End Sub

    'Deserialize and Read Data from txt file
    Private Sub ReadButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ReadButton.Click
        If FileIO.FileSystem.FileExists("C:\Users\Bruce\Desktop\test.txt") Then
            Dim fsRead As New FileStream("C:\Users\Bruce\Desktop\test.txt", FileMode.Open)
            Dim bf As New BinaryFormatter()
            Dim objTest As Object = bf.Deserialize(fsRead)
            fsRead.Close()
            IDNameTextBox.Text = objTest.IDName
            FirstNameTextBox.Text = objTest.FirstName
            LastNameTextBox.Text = objTest.LastName
        End If
    End Sub

    Private Sub AddIDButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddIDButton.Click
        ListBox1.Items.Insert(0, AddIDTextBox.Text)
        IDNameTextBox.Text = AddIDTextBox.Text
    End Sub
End Class

'Create Class Person
<System.Serializable()>
Public Class Person
    Private m_sIDName As String
    Private m_sFirstName As String
    Private m_sLastName As String

    Public Sub New()
    End Sub
    Public Property IDName() As String
        Get
            Return Me.m_sIDName
        End Get
        Set(ByVal value As String)
            Me.m_sIDName = value
        End Set
    End Property

    Public Property FirstName() As String
        Get
            Return Me.m_sFirstName
        End Get
        Set(ByVal value As String)
            Me.m_sFirstName = value
        End Set
    End Property

    Public Property LastName() As String
        Get
            Return Me.m_sLastName
        End Get
        Set(ByVal value As String)
            Me.m_sLastName = value
        End Set
    End Property

End Class

A: To me it seems like the issue here is
Dim fs As FileStream = New FileStream("C:\Users\Bruce\Desktop\test.txt", FileMode.OpenOrCreate)

you have to change it to this:
If not File.Exists("C:\Users\Bruce\Desktop\test.txt") Then
File.create("C:\Users\Bruce\Desktop\test.txt")
End If
Dim fs As FileStream = New FileStream("C:\Users\Bruce\Desktop\test.txt", FileMode.Append)

The whole problem was that your file was simply open (or created if it was not there before) and being written from the first line.By using FileMode.Append your File will be opened and anything new will be tried to be written at the end of the file.
Let me know if this worked :)


text:
Q: get object on which a method was called in Python Is there a way in Python to get a reference to an object on which a method was called?
And in case it is, is it possible even in a nested way?
my_class.py:
from modules import math_ops

class A():
    def __init__(self):
        self.math_ops = math_ops.B()
        self.number = 1

modules/math_ops.py:
class B():
    def add_1():
        where_to_add = # Get instance of A() object
        where_to_add.number += 1

To execute this:
>>> a = A()
>>> a.math_ops.add_1()

And get this:
>>> a.number
2

I'm asking because I am interested in writing a static method which works with the object on which it was called, but would like to avoid using the object as an argument as it would be much nicer to call a method like my_object.prop.static_method() instead of my_object.prop.static_method(my_object).

A: If you never plan on reassigning math_ops outside A, this is fairly simple to do.
from modules import math_ops

class A():
    def __init__():
        self.math_ops = math_ops.B(self)
        self.number = 1

modules/math_ops.py:
class B():
    def __init__(self, creator):
        self.creator = creator

    def add_1():
        creator.number += 1

I will mention it again in case you skimmed the first line, the following will generate unexpected results since B is tracking the creator of the object rather than the caller.
a1 = A()
a2 = A()
a1.math_ops = a2.math_ops
a1.math_ops.add_1() # a2 is updated

If that looks like something you might wanna do, the answer is a tad more complicated. Here's my attempt:
from modules import math_ops
class A():
    def __init__(self):
        self._math_ops = math_ops.B(self)
        self.number = 1

    @property
    def math_ops(self):
        self._math_ops.set_caller(self)
        return self._math_ops

    @math_ops.setter
    def math_ops(self, new_math_ops):
        self._math_ops = new_math_ops

modules/math_ops.py:
class B():
    def __init__(self, caller):
        self.caller = caller

    def set_caller(self, caller):
        self.caller = caller

    def add_1(self):
        self.caller.number += 1

A: class A():
   number = 1

class B():
    def add_1():
        where_to_add = A
        where_to_add.number += 1

B.add_1()
print(A.number)
B.add_1()
print(A.number)
B.add_1()
print(A.number)


text:
Q: Get Query String Value in ASP.NET MVC I have this URL
var url = "/test/Create/" + $("#hdnFlag").val() +"?CmpT="+"Ilim";
window.location.href = url;

and in my Test controller I do this to get query string value
 tM_PMO.Type = Request.QueryString["CmpT"];

But always give me null values.

A: There is a difference between the GET and POST types.
Query string can be read with the URL of the GET request. However, you cannot read the Query string value in the URL when you make a POST request. For this you need to submit it to the server.
Below I give you a few examples of usage.
GET Request
You can read Query string with URL as below
public ActionResult Test(string CmpT)
{
    if (!string.IsNullOrWhiteSpace(CmpT))
    {
        //your codes...
    }else
    { }
    return View();
}

POST Request
If you are making a POST request and trying to read from the URL, it will return null. In order to read it, you need to send this value to the server as follows.
1st way : In your Html.BeginForm in your View Below, submit Query string as below and read this value as Action parameter
View Page
@using (Html.BeginForm("Test", "XController", new { returnUrl = Request.QueryString["CmpT"] }, FormMethod.Post, new { role = "form" }))
{
    <button type="submit">Send</button>
}

Controller
public ActionResult Test(string returnUrl)
{
    if (!string.IsNullOrWhiteSpace(returnUrl))
    {
        //your codes...
    }else
    { }
    return View();
}

2nd way : Create a hidden form element as part of the form between the Html.BeginForm tags in your view page and give its value as a query string. Then call it in Action method like below.
View Page
@using (Html.BeginForm("Test", "XController", FormMethod.Post, new { role = "form" }))
{
    @Html.Hidden("returnUrl", Request.QueryString["CmpT"])
    <button type="submit">Send</button>
}

Controller
public ActionResult Test(string returnUrl)
{
    if (!string.IsNullOrWhiteSpace(returnUrl))
    {
        //your codes...
    }else
    { }
    return View();
}

or for multiple form items (You can also access other form elements this way)
public ActionResult Test(FormCollection fc)
{
    string _returnUrl = fc["returnUrl"];
    if (!string.IsNullOrWhiteSpace(_returnUrl))
    {
        //your codes...
    }else
    { }
    return View();
}

A: I hope you are looking for below code sample where we just fetch the value in url which we says query string:
Request.QueryString["querystringparamname"].ToString();

You can assign this in any Var and use accordingly.


text:
Q: UnreachableBrowserException firefox driver selenium java I am having a problem with geckodriver (FF) in java-selenium.
I am running multiple test scenarios via TEST-NG parallel execution (6+ threads).
Sometimes happens that at the start (opening new browser) I get unreachableBrowserException. So i try-catch it, waited 100ms and try to create it again. it works, but it keeps the first failed browser opened, with a blank page.
Problem is that the first window got opened BEFORE it got initialized as a driver, so it cannot be closed by driver.close() or something (it is null). So I have to close them manually.
So, my question is, has anyone encountered such behaviour?
How can i close such browsers, without influencing the other threads?
while(true) {
            try {
                setDriver(DriverFactory.createInstance(getBrowserInstance()));
                break;
            } catch (UnreachableBrowserException e) {

            try {
                Thread.sleep(100);
                log.info("UnreachableBrowserException! Needed to wait for 100ms ");
                removeDriver();
                counter++;
            } catch (Exception e1) {
                log.info("Thread could not wait!");
                e1.printStackTrace();
            }
        }
        if(counter>100){
            log.info("Was not able to create a browser session!");
            break;
        }
    }

and the part of .createInstance :
final ProfilesIni profilesIni = new ProfilesIni();
                System.setProperty("webdriver.gecko.driver", "drivers/geckodriver.exe");
                System.setProperty(FirefoxDriver.SystemProperty.DRIVER_USE_MARIONETTE,"false");
                firefoxProfile = new FirefoxProfile();
                firefoxProfile.setAcceptUntrustedCertificates(true);
                firefoxProfile.setAssumeUntrustedCertificateIssuer(false);
                firefoxProfile.setPreference("app.update.auto", false);
                firefoxProfile.setPreference("app.update.enabled", false);
                firefoxProfile = profilesIni.getProfile("selenium_profile");
                capabilities = DesiredCapabilities.firefox();
                capabilities.setCapability(FirefoxDriver.PROFILE, firefoxProfile);

                return new FirefoxDriver(capabilities); //Here it throws the exception.

Selenium/Java/geckodriver versions are most recent. FF version is unfortunately 44.02 (cannot get newer).
I would be grateful for any tips/hints.
Kind regards,
Martin

A: As you are using Mozilla Firefox version 44.02 and cannot get newer you have to consider a lot of things.

*

*To use Selenium 3.x you have to mandatory use geckodriver. See why here.

*Firefox 44.02 is not marionette enabled, so you have to set marionette to false through DesiredCapabilities class. See why here

*There are couple of Selenium version dependencies and GeckoDriver version dependencies. See them here

*You cannot create a new Firefox Profile and then again try to use a existing Firefox Profile.

*Assuming you have a existing Firefox Profile by the name selenium_profile, the following code would open the Firefox Profile in a new browser session:
System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
ProfilesIni profile = new ProfilesIni();
FirefoxProfile firefoxProfile = profile.getProfile("selenium_profile");
firefoxProfile.setAcceptUntrustedCertificates(true);
firefoxProfile.setAssumeUntrustedCertificateIssuer(false);
firefoxProfile.setPreference("app.update.auto", false);
firefoxProfile.setPreference("app.update.enabled", false);
DesiredCapabilities dc = DesiredCapabilities.firefox();
dc.setCapability(FirefoxDriver.PROFILE, firefoxProfile);
dc.setCapability("marionette", false);
WebDriver driver = new FirefoxDriver(dc);
driver.get("http://www.google.com");

Now you can easily return the capabilities.


text:
Q: Can't merge dataframes because of index type mismatch I have loaded some data from CSV files into two dataframes, X and Y that I intend to perform some analysis on. After cleaning them up a bit I can see that the indexes of my dataframes appear to match (they're just sequential numbers), except one has index with type object and the other has index with type int64. Please see attached image for a clearer idea of what I'm talking about.
I have tried manually altering this using X.index.astype('int64') and also X.reindex(Y.index) but neither seem to do anything here. Could anyone suggest anything?
Edit: Adding some additional info in case it is helpful. X was imported as row data from the csv file and transposed whereas Y was imported directly with the index set from the first column of the csv file.

A: So I've realised what I've done and it was pretty dumb. I should have written
X.index = X.index.astype('int64')

instead of just
X.index.astype('int64')

Oh well, the more you know.


text:
Q: How do I get a folder name from a file path without VBA I have a long list of file paths and I include the containing folder of each file/folder. I need to go from
c:\Top\Middle\Bottom\file1.jpg
c:\Top\Middle\file2.jpg

to
c:\Top\Middle\Bottom
c:\Top\Middle

There can be folders that are deeply nested and file names vary in length.
How can it be done with a formula (MID, RIGHT, LEFT, SUBSTITUTE, FIND, etc.) without VBA code?

A: This is a beast of a nested formula, but it actually does work.
LEFT(A1,SEARCH("\@\",SUBSTITUTE(A1,"\","\@\",LEN(A1)-LEN(SUBSTITUTE(A1,"\","")))))

Based on a formula found at http://www.mrexcel.com/archive/VBA/5563.html

A: Try this array formula:
  =LEFT(A1,LEN(A1)-MATCH("\",MID(A1,LEN(A1)-ROW(1:255),1),0)-1)

It must be entered with the Control-Shift-Enter key combination.


text:
Q: How to listen to 'page loaded after a redirect' event in the WebEngine? I've been trying to automatize downloading a JDK distribution from oracle.com with WebEngine/WebView and experiencing issues with handling redirect at one of the pages. The problem is that it does not generate any kind of event I am aware of when the page is loaded.
I track down the occurring redirect by using webEngine.locationProperty(), so when this property changes I notice the redirect going on. But it is not being followed by a change of the webEngine.getLoadWorker().stateProperty() and the element I require is not loaded.
I resolved the issue by starting a thread which is watching my specific element to appear by running jQuery selector, i.e. webEngine.executeScript("$('#sso_username').length > 0").
Is there a better way to do this, may be to listen for some property to change when the page after a redirect will load?


text:
Q: Epoch vs Incremental Update over Entire Dataset In the context of neural networks, what is the difference between training like this:
foreach observation in dataset:
    compute_error(observation)
    update_weights()

and
foreach observation in dataset:
    compute_error(observation)
update_weights()

Both train over the entire dataset.

A: If I understand the difference correctly, if you're stuck in a local minimum the first method may not be able to get you out. The weight change at each increment would be too small.

A: The difference is huge. The first method is called "stochastic", "stochastic gradient descent" (SGD) or "online" training, while the other one is typically referred to as "batch". The most commonly used one is actually a hybrid, "mini batch training", which calculates the updates on a small set of samples--depending on your application, it ranges from 5 to 10 to 100 or 1000.
Let's take a step back. In neural networks, you are performing an optimization of a loss
$$\mathcal{L}(\theta, \{x_i\}_{i=1}^N)$$
over a set of $N$ training samples $\{x_i\}_{i=1}^N$ with respect to your parameters $\theta$. To do so, you require the gradient
$${\partial \mathcal{L(\theta, \{x_i\}_{i=1}^N)} \over \partial \theta}.$$
This is the correct way to do it, but if your data set is large, this quantity is costly to compute: it requires a complete pass over the data. Instead, one typically resorts to estimating the gradient, e.g.
$$g_i = {\partial \mathcal{L(\theta, \{x_i\})} \over \partial \theta}).$$
Note that we fixed $i$ here to a single instance.
It turns out, that following $g_i$ to lead us to the minimum, we only need $g_i$ to be correct in the expectation, i.e.
$$\mathbb{E}[g_i] = {\partial \mathcal{L(\theta, \{x_i\}_{i=1}^N)} \over \partial \theta}.$$
This is the case for iid samples.
There are many more intuitive but less formal arguments for SGD. For example, it is believed to be less prone to local minima. On the other hand, it also has regularizatory effects, e.g. overfits less than for example using LBFGS.


text:
Q: Adding KML layer in OpenLayers I'm struggling to add a KML layer to a simple test OpenLayers map - no errors are shown, but the KML layer does not display on the map.
I've tried multiple samples including the Sundials on a Spherical Mercator sample and the Layers help page. I can open this example in Firefox and see the KML points on the map without error.
I copied this sample's source code and adjusted the paths to the CSS, JS and KML files to use full paths.
However, when opening this map the KML points are not displayed. Firebug shows GET sundials.kml on the working example from OpenLayers, but OPTIONS sundials.kml on my version.
What am I doing wrong?
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <link rel="stylesheet" href="http://openlayers.org/dev/theme/default/style.css" type="text/css">
    <link rel="stylesheet" href="http://openlayers.org/dev/examples/style.css" type="text/css">

KML Layer Example

          kml, popup, feature

          Demonstrates loading and displaying a KML file on top of a basemap.

A: Firebug says that XMLHttpRequest cannot load http://openlayers.org/dev/examples/kml/sundials.kml. Origin null is not allowed by Access-Control-Allow-Origin. So you can move original kml file to the same host as your OpenLayers application or set up proxy.


text:
Q: Subset sum decision problem -- how to verify "false" case in polynomial time? I'm having a bit of trouble understanding how one would verify if there is no solution to a given instance of the subset sum problem in polynomial time.
Of course you could easily verify the positive case: simply provide the list of integers which add up to the target sum and check they are all in the original set. (O(N))
How do you verify that the answer "false" is the correct one in polynomial time?

A: It's actually not known how to do this - and indeed it's conjectured that it's not possible to do so!
The class NP consists of problems where "yes" instances can be verified in polynomial time. The subset sum problem is a canonical example of a problem in NP. Importantly, notice that the definition of NP says nothing about what happens if the answer is "no" - maybe it'll be easy to show this, or maybe there isn't an efficient algorithm for doing so.
A counterpart to NP is the class co-NP, which consists of problems where "no" instances can be verified in polynomial time. A canonical example of such a problem is the tautology problem - given a propositional logic formula, is it always true regardless of what values the variables are given? If the formula isn't a tautology, it's easy to verify this by having someone tell you how to assign the values to the variables such that the formula is false. But if the formula is always true, it's unclear how you'd show this efficiently.
Just as the P = NP problem hasn't been solved, the NP = co-NP problem is also open. We don't know whether problems where "yes" answers have fast verification are the same as problems where "no" answers have fast verification.
What we do know is that if any NP-complete problem is in co-NP, then NP = co-NP. And since subset sum is NP-complete, there's no known polynomial time algorithm to verify if the answer to a subset sum instance is "no."


text:
Q: Image of singular chain map, on $S^1$ First note that the question is very elemantary we need to find just a continuous function satisfying basic property.
Definitions:
$$\triangle^n=\{(x_0,x_1,\cdots,x_{n-1})\;|\; x_0+x_1+\cdots+x_{n-1}=1\}$$
For $S^1$ as a topological space we are defining chain complex as
$$C_n(S^1)=FA\left(\{f:\triangle^n\to S^1| f \quad\text{is continuous}\}\right)$$
where $FA$ means free abelian group generated by input.
Considering this particular chain complex of $S^1$
$$\cdots\xrightarrow{d_{n+2}} C_{n+1}(S^1)\xrightarrow{d_{n+1}} C_n(S^1)\xrightarrow{d_{n}} C_{n-1}(S^1)\xrightarrow{d_{n-1}}\cdots$$
Where $d_n:C_n(S^1)\to C_{n-1}(S^1)$ defined on generator as:
$\sigma\in C_n(S^1)$
$$d_n(\sigma)=\displaystyle\sum_{j=0}^n(-1)^j \sigma\circ \varphi_j$$
where $$\varphi_j:\triangle^{n-1}\to\triangle^n\\ (x_0,x_1,\cdots,x_{n-1})\mapsto (x_0,x_1,\cdots,\underbrace{0}_{\text{ith place}},\cdots,x_{n-1})$$
Question:
Let $$\sigma :\triangle^1 \to S^1\\ (x_0,x_1)\mapsto e^{2\pi i x_1}$$
and for fixed $n\in\mathbb Z$ $$f:S^1\to S^1\\ z\mapsto z^n$$
We can show easily that $\sigma\in C_1(S^1)$ and $f\circ\sigma\in C_1(S^1)$ are $1-$cycles meaning they are in $ker(d_1:C_1(S^1)\to C_0(S^1))$
Question: Are $f\circ \sigma$ and $n.\sigma$ same in $H_1(S^1)=\dfrac{ker(d_1)}{Im(d_{2})}$ equivalently is there some continuous function $\eta:\triangle^2\to S^1$( $\eta\in C_2(S^1)$), such that $d_2(\eta)=n.\sigma-f\circ\sigma$  (or we can separately show there are two functions that has images $f\circ \sigma$ and $n.\sigma$)
So let us try to construct desired functions:
$$\eta:\triangle^2\to S^1$$
It should satisfy the $d_2$ so given $(x_0,x_1)\in\triangle ^1$
$$d_2(\eta)(x_0,x_1)=\displaystyle\sum_{j=0}^2(-1)^j \eta\circ \varphi_j(x_0,x_1)\\=\eta\circ \varphi_0(x_0,x_1)-\eta\circ \varphi_1(x_0,x_1)+\eta\circ \varphi_2(x_0,x_1)\\ =\eta(0,x_0,x_1)-\eta(x_0,0,x_1)+ \eta(x_0,x_1,0)$$
I tried to use $(x_0,x_1,x_2)\mapsto e^{2\pi i x_0}\\ (x_0,x_1,x_2)\mapsto e^{2\pi i x_0(x_1+x_2)}$
but in each conditions I find $d_n(\eta)=1$
I feel  like constructing something like that a bit hard, maybe I cannot see it, can you please give me hint or how to show existence implicitly without finding $\eta$ explicitly.


text:
Q: How to get if User pressed Enter wxWidgets I want to get the Input from a field
wxTextCtrl* upperOnly = new wxTextCtrl(this, wxID_ANY, wxT("Test"),wxPoint(5,260), wxSize(630,30));

and this i want every Time the user Pressed Enter

A: Use wxTE_PROCESS_ENTER when creating the control, i.e.
wxTextCtrl* upperOnly = new wxTextCtrl(this, wxID_ANY, wxT("Test"),wxPoint(5,260), wxSize(630,30), wxTE_PROCESS_ENTER);

Then catch wxEVT_TEXT_ENTER and do your validation in its event handler, i.e.
upperOnly->Bind(wxEVT_TEXT_ENTER, [](wxCommandEvent&) {
        // Do something useful
     });


text:
Q: TypeError: string indices must be integers , I think I missed something I got an error with my code
This is my code :
def get_transactions(address):
    transactions_url = make_api_url("account", "txlist", address, startblock=0, endblock=99999999, page=1, offset=10000, sort="asc")
    response = get(transactions_url)
    data = [response.json()["result"]]

    internal_tx_url = make_api_url("account", "txlistinternal", address, startblock=0, endblock=99999999, page=1, offset=10000, sort="asc")
    response2 = get(internal_tx_url)
    data2 = (response2.json()["result"])

    data.extend(data2)
    data.sort(key=lambda x: int(x['timeStamp'])) # This is the error code >> TypeError: string indices must be integers

This is just a part of my code. And I got this error code because of this >> int(x['timeStamp']
I think this should not going wrong because I already change it to int before I run it.
I thought I missed something, but I can't find where it went wrong.
Thanks before.


text:
Q: any issues with using git in a CI environment? I work in a shop that lives by its CI process.  We have traditionally used SVN and are considering moving to git (want to leverage its ease of branching, stashing, etc).  Thinking in terms that a distributed source control system, by its very nature, seems to put the need for a central repository as a secondary concern, does git create any challenges for a CI process?  As long as the developer performs a "commit" then "push", does the concept of a central repo as I would have known it with SVN still exist, making CI builds just a different config (pull from git rather than svn)?
Any cultural issues (developers pushing to main repo less often and instead only committing locally perhaps)?
Would love to hear success/failure stories from a group that uses CI with git.

A: It doesn't add any more complexity that couldn't be considered opportunity. While you can use Git in a completely decoupled, decentralized fashion, many projects usually settle on one (or several) 'blessed' repositories, and these are the repositories that the CI server should be building.
You might have 'blessed' repositories for the main (as in the one you ship from) repository, as well as some for branches that eventually make their way to the end of the line. You can use your CI server to do what it does best, detect toxic revisions at any link in that chain.
So in many ways, it's better, because you catch stuff before it gets put into the central trunk and out in the wild to blow up gloriously. Still, the art really isn't the CI process, it's establishing a Git workflow that permits you to place CI builds at key places.
I use Hudson with both Git and Mercurial projects, sharing a similar workflow. Git is actually the easier of the two, as branches in Git are a bit easier to manage. Typically, we have a small team with one lead, the team lead gets requests to pull to a blessed branch repository. If CI checks look good there, the team lead sends a pull request to the project manager, who pulls in to a -next repository. If CI builds are fine there, it eventually goes into the single (combined) release repository. So you really can run tests at almost every step of the way, or less, depending on your need.


text:
Q: Give an example which proves/disproves the condition for convergence of the series. Firstly I have these 2 conditions for arbitrary sequences {$x_n$}:

Given any 1$\lt$q$\lt$p$\lt$ $\infty$, there is a real sequence
  {$x_n$} such that $\sum_{n=1}^{\infty}|{x_n}|^{p}$ is convergent but
  $\sum_{n=1}^{\infty}|{x_n}|^{q}$ is divergent.

I need an example to prove/disprove this. I tried to think of the auxiliary series $\sum {1\over n^p}$. But I ended up nowhere. A better example which I should consider here?
The second case is:

Given any 1$\lt$p$\lt$q$\lt$ $\infty$, there is a real sequence
  {$x_n$} such that $\sum_{n=1}^{\infty}|{x_n}|^{p}$ is convergent but
  $\sum_{n=1}^{\infty}|{x_n}|^{q}$ is divergent.
  I need an example to prove/disprove this as well.

A: I see that in the comments the first case has already been answered. So, I'll focus on the second one.
The most important part here is to know how the tail of your series behaves. For example, look at $p=1$ and $q=2$. The tail should converge quicker of the series where $q=2$ if the terms are below $1$. For example, $1/n^2$ converges slower than $1/n^4$ to $0$.
To make this idea precise, we know that in a convergent series the terms should converge to $0$. Hence, we can find an $N\in \mathbb{N}$ such that for all $n\geq N$: $|x_n|<1$. And thus, the tail after $N$ is dominated by the $|x_n|^p$ series, since for all these $n$, we have $|x_n|^q < |x_n|^p$. Moreover, note that the convergence does not depend on the fixed finite first elements of the series $\{x_1,...,x_{N}\}$.
I hope this helps!


text:
Q: Why does PATCH_SUPEE-6788 appear to have no effect on a 1.7.0.2 installation? Note:  This issue appears to apply to all versions of Magento which received the SUPEE-6788 patch.  You'll see in my answer that both .htaccess and .htaccess.sample need to be restored for the patch to succeed.

I'm working on applying the SUPEE-6788 patch to a CE 1.7.0.2 site using the shell script provided by magentocommerce.com/downloads.  The site has had all previous security patches applied.
The script's name is PATCH_SUPEE-6788_CE_1.7.0.2_v1-2015-10-27-12-00-16.sh and has an md5sum of cfc0cf533fe36a5f573414f0feeb1590 (this patch was unusual in that it was released uncompressed–although the file doesn't appear corrupt or truncated).
When running this script the console output appears to indicate that at least one of the included patches failed or was skipped, but that many parts of the patch were successful, however git is showing no changes.  The script has been tested on two different environments with the same codebase--one an Ubuntu GNOME 14.04 LTS workstation, the other a nexcess.com shared server (running CentOS).
Of interest is that the output on the two environments is slightly different.  Note the lines starting with "checking" vs "patching".
A sample of output from the Ubuntu environment:
bash PATCH_SUPEE-6788_CE_1.7.0.2_v1-2015-10-27-12-00-16.sh                                              [19:27:10]
Checking if patch can be applied/reverted successfully...
ERROR: Patch can't be applied/reverted successfully.

checking file .htaccess
Hunk #1 FAILED at 207.
1 out of 1 hunk FAILED
can't find file to patch at input line 38
Perhaps you used the wrong -p or --strip option?
The text leading up to this was:
--------------------------
|diff --git .htaccess.sample .htaccess.sample
|index 546f18e..3e79c77 100644
|--- .htaccess.sample
|+++ .htaccess.sample
--------------------------
File to patch:
Skip this patch? [y]
Skipping patch.
1 out of 1 hunk ignored
checking file app/code/core/Mage/Admin/Model/Block.php
checking file app/code/core/Mage/Admin/Model/Resource/Block.php
checking file app/code/core/Mage/Admin/Model/Resource/Block/Collection.php
checking file app/code/core/Mage/Admin/Model/Resource/Variable.php
checking file app/code/core/Mage/Admin/Model/Resource/Variable/Collection.php
checking file app/code/core/Mage/Admin/Model/Variable.php
...

A sample from the CentOS environment:
bash PATCH_SUPEE-6788_CE_1.7.0.2_v1-2015-10-27-12-00-16.sh
Checking if patch can be applied/reverted successfully...
ERROR: Patch can't be applied/reverted successfully.

patching file .htaccess
Hunk #1 FAILED at 207.
1 out of 1 hunk FAILED -- saving rejects to file .htaccess.rej
can't find file to patch at input line 38
Perhaps you used the wrong -p or --strip option?
The text leading up to this was:
--------------------------
|diff --git .htaccess.sample .htaccess.sample
|index 546f18e..3e79c77 100644
|--- .htaccess.sample
|+++ .htaccess.sample
--------------------------
File to patch:
Skip this patch? [y]
Skipping patch.
1 out of 1 hunk ignored
patching file app/code/core/Mage/Admin/Model/Block.php
patching file app/code/core/Mage/Admin/Model/Resource/Block.php
patching file app/code/core/Mage/Admin/Model/Resource/Block/Collection.php
patching file app/code/core/Mage/Admin/Model/Resource/Variable.php
...

I'll be digging into the error at the top of the output and possible manually applying the patches--but was hoping that someone might have insight into the cause or a relatively simple fix.

A: I tried downloading stock versions of .htaccess and .htaccess.sample and the patch still would not apply even after using the stock versions.
For anyone else experiencing this problem take a look at this article it explains how to remove the .htaccess and htaccess.sample parts from the patch itself then manually add them in after:
http://www.atwix.com/magento/security-patch-supee-6788-installation-issues/
FIX - edit the patch file by removing lines 163-195 starting with the line
diff --git .htaccess .htaccess

and ends with
+    </Files>

You may also need to remove the part relating to htaccess.sample this starts with
diff --git .htaccess.sample .htaccess.sample

and ends at
+    </Files>

After this has been done, try applying the patch again and it should apply successfully this time.
Next we need to add the following to the end of our .htaccess and .htaccess.sample files so they are up to date as per the patch
###########################################
## Deny access to cron.php
    <Files cron.php>

############################################
## uncomment next lines to enable cron access with base HTTP authorization
## http://httpd.apache.org/docs/2.2/howto/auth.html
##
## Warning: .htpasswd file should be placed somewhere not accessible from the web.
## This is so that folks cannot download the password file.
## For example, if your documents are served out of /usr/local/apache/htdocs
## you might want to put the password file(s) in /usr/local/apache/.

        #AuthName "Cron auth"
        #AuthUserFile ../.htpasswd
        #AuthType basic
        #Require valid-user

############################################

        Order allow,deny
        Deny from all

    </Files>

Following these steps I was able to apply the patch successfully, hope this helps!

A: This might help you, even though it's a different version - https://community.magento.com/t5/Security-Patches/1-9-1-0-applying-patch-6788-hunk-failed/td-p/20070

A: It appears that changes to my .htaccess as well as a missing .htaccess.sample are the culprit.  After restoring a stock copy of both files (both were required) the patch appears to apply successfully.
To solve this, without losing (needed) modifications, I followed these steps:

*

*Create a backup of .htaccess and .htaccess.sample–either with your version control system or by copying the files

*Copied a stock 1.7.0.2 version of .htaccess and .htaccess.sample into my codebase, replacing my customized .htaccess

*Applied the patch.  The output was much shorter than before (2-lines).

*Committed all changes, including .htaccess (for posterity)

*Checked out the previous version of .htaccess, without the patch, and manually applied the patch to that file.
Here's the git diff of the patch, showing the added lines:
diff --git a/.htaccess b/.htaccess
index 60e1795..aca7f55 100644
--- a/.htaccess
+++ b/.htaccess
@@ -207,3 +207,28 @@
 ## http://developer.yahoo.com/performance/rules.html#etags

     #FileETag none
+
+###########################################
+## Deny access to cron.php
+    <Files cron.php>
+
+############################################
+## uncomment next lines to enable cron access with base HTTP authorization
+## http://httpd.apache.org/docs/2.2/howto/auth.html
+##
+## Warning: .htpasswd file should be placed somewhere not accessible from the web.
+## This is so that folks cannot download the password file.
+## For example, if your documents are served out of /usr/local/apache/htdocs
+## you might want to put the password file(s) in /usr/local/apache/.
+
+        #AuthName "Cron auth"
+        #AuthUserFile ../.htpasswd
+        #AuthType basic
+        #Require valid-user
+
+############################################
+
+        Order allow,deny
+        Deny from all
+
+    </Files>

A: I had the same issue, it was because I downloaded the wrong patch. I am using Magento EE 1.13 and I had downloaded a CE patch... I downloaded patch for CE 1.8 while following a tutorial, thinking it would work for EE 1.13.
Make sure you download the patch for your version of Magento.

A: *

*Backup your .htaccess and .htaccess.sample

*Upload Original .htaccess and .htaccess.sample files as per your Magento version.

*Execute patch.


text:
Q: Spring Security LDAP authentication Multiple dn pattern We are using spring security & using LDAP to authenticate our web application. In our LDAP configuration, there are multiple userndn patterns available. I would like to know how to configure multiple userdn patterns in the applicationContext-security.xml file. I have the below configuration specified
<b:bean id="ldapProvider"
    class="org.springframework.security.ldap.authentication.LdapAuthenticationProvider">
    <b:constructor-arg>
        <b:bean
            class="com.intl.set.him.mait.security.CustomLdapAuthenticator">
            <b:constructor-arg ref="ldapContextSource" />
            <b:property name="userDnPatterns" value="cn={0},OU=GEN,OU=Users"/>
            <b:property name= "commonNameQuery" value = "select USER_CN from emt.sec_users1 where user_id=?"/>
            <b:property name="datasource" ref="dataSourceMSSQL"/>

</b:bean>

When I provide the above configuration in the xml file, users corresponding to Dn pattern for a particular location will only be able to login. I want to know how we can configure multiple userdn patterns in the xml file.
Any help on this is much appreciated. Thanks

A: The bean acts as a constructor (often with arguments and/or properties) for the specified class. If you simply extend that class in your own subclass, you can pass arguments to the supoerclass' constructor and set properties from the subclass:
CustomLdapAuthenticationProvider.java
public class CustomLdapAuthenticationProvider extends LdapAuthenticationProvider {
    //your constructor
    public CustomLdapAuthenticationProvider(unParsedArguments) {
        //some logic to parse the arguments as desired
        super(parsedArguments);
        //set super's properties as desired

    }

    //other methods as needed/required
}

This approach gives you considerable flexibility in your application design, and it's what motivates open-source -- it's easy to extend, override, etc. You're already doing it, too, for the most part.
Then, change your applicationContext-security.xml:
<bean id="ldapProvider"
        class="your.project.package.CustomLdapAuthenticationProvider">
    <constructor-arg value="firstArgument"/>
    <constructor-arg value="secondArgument"/>
    <!-- etc. //-->
    <property name="fieldName" value="valueToBeSet"/>
</bean>

Obviously, this is contrived, but you should see what you need to do: extend, override/overload, and call super's methods/constructors according to your logic as opposed to a static template.
I hope this helps.


text:
Q: Проблема с передачей значений между окнами JavaFx в Java новичок. Задача -
1) в главном окне вызывается модальное с заданным fxml.
2) в модальном в поле Label вводится значение
3) При закрытии модального окна введенное в label значение отображается в Label главного окна
4) У каждого окна свой контроллер и fxml
Проблема:
при передаче значения внутри одного контроллера все работает, при передаче из модального окна ошибка:
/usr/lib/jvm/java-8-oracle/bin/java -javaagent:/home/lezvie/intelijIDEA/idea/ideaIU-2018.3/idea-IU-183.4284.148/lib/idea_rt.jar=35797:/home/lezvie/intelijIDEA/idea/ideaIU-2018.3/idea-IU-183.4284.148/bin -Dfile.encoding=UTF-8 -classpath /usr/lib/jvm/java-8-oracle/jre/lib/charsets.jar:/usr/lib/jvm/java-8-oracle/jre/lib/deploy.jar:/usr/lib/jvm/java-8-oracle/jre/lib/ext/cldrdata.jar:/usr/lib/jvm/java-8-oracle/jre/lib/ext/dnsns.jar:/usr/lib/jvm/java-8-oracle/jre/lib/ext/jaccess.jar:/usr/lib/jvm/java-8-oracle/jre/lib/ext/jfxrt.jar:/usr/lib/jvm/java-8-oracle/jre/lib/ext/localedata.jar:/usr/lib/jvm/java-8-oracle/jre/lib/ext/nashorn.jar:/usr/lib/jvm/java-8-oracle/jre/lib/ext/sunec.jar:/usr/lib/jvm/java-8-oracle/jre/lib/ext/sunjce_provider.jar:/usr/lib/jvm/java-8-oracle/jre/lib/ext/sunpkcs11.jar:/usr/lib/jvm/java-8-oracle/jre/lib/ext/zipfs.jar:/usr/lib/jvm/java-8-oracle/jre/lib/javaws.jar:/usr/lib/jvm/java-8-oracle/jre/lib/jce.jar:/usr/lib/jvm/java-8-oracle/jre/lib/jfr.jar:/usr/lib/jvm/java-8-oracle/jre/lib/jfxswt.jar:/usr/lib/jvm/java-8-oracle/jre/lib/jsse.jar:/usr/lib/jvm/java-8-oracle/jre/lib/management-agent.jar:/usr/lib/jvm/java-8-oracle/jre/lib/plugin.jar:/usr/lib/jvm/java-8-oracle/jre/lib/resources.jar:/usr/lib/jvm/java-8-oracle/jre/lib/rt.jar:/home/lezvie/IdeaProjects/timer/out/production/timer sample.Main
Gtk-Message: 21:53:36.540: Failed to load module "canberra-gtk-module"
java.lang.NullPointerException
    at sample.SecondWindowController.setValue(SecondWindowController.java:45)
    at sample.SecondWindowController.lambda$initialize$0(SecondWindowController.java:29)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Node.fireEvent(Node.java:8411)
    at javafx.scene.control.Button.fire(Button.java:185)
    at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:182)
    at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:96)
    at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:89)
    at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Scene$MouseHandler.process(Scene.java:3757)
    at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
    at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
    at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:394)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$353(GlassViewEventHandler.java:432)
    at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:431)
    at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
    at com.sun.glass.ui.View.notifyMouse(View.java:937)
    at com.sun.glass.ui.gtk.GtkApplication._runLoop(Native Method)
    at com.sun.glass.ui.gtk.GtkApplication.lambda$null$48(GtkApplication.java:139)
    at java.lang.Thread.run(Thread.java:748)

Process finished with exit code 0

Я уже отчаялся(( подскажите пожалуйста в чём проблема.
Привожу весь код
код:
package sample;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        Parent root = FXMLLoader.load(getClass().getResource("fxml/gui.fxml"));
        primaryStage.setTitle("Таймер");
        primaryStage.setScene(new Scene(root, 235, 300));
        primaryStage.show();
    }

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

package sample;

import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;

import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.stage.Modality;
import javafx.stage.Stage;

public class Controller {

    protected Stage secondWindow;

    @FXML
    private ResourceBundle resources;

    @FXML
    private URL location;

    @FXML
    private Label LabelValue;

    @FXML
    private Button addTimer;

    @FXML
    void initialize() {
        addTimer.setOnAction(event -> {
            try {
                callPanel();
            } catch (IOException e) {

            }
        });
    }

    protected void setTextLabel(String text){
        LabelValue.setText(text);
    }

    private void callPanel() throws IOException{
        Parent root =  FXMLLoader.load(getClass().getResource("fxml/secondWindow.fxml"));
        Stage stage = new Stage();
        secondWindow = stage;
        secondWindow.initModality(Modality.WINDOW_MODAL);
        secondWindow.setScene(new Scene(root, 350, 200));
        secondWindow.show();
    }
}

package sample;

import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.stage.Stage;

import java.io.IOException;
import java.net.URL;

public class SecondWindowController extends Controller{

    //private String labelValue;

    @FXML
    private Button ok;

    @FXML
    private TextField date;

    @FXML
    void initialize() {
        ok.setOnAction(event -> {
            getDateValue();
           try {
            setValue();
            } catch (Exception e) {
                e.printStackTrace();
            }
            closeWindow();
        });
    }

    protected String getDateValue() {
        return date.getText();
    }

    private void setValue() {
        FXMLLoader loader = new FXMLLoader(getClass().getResource("gui.fxml"));
        Controller getController = loader.getController();
        String labelValue = getDateValue();
        getController.setTextLabel(labelValue);
    }

    private void closeWindow() {
        super.secondWindow = (Stage) ok.getScene().getWindow();
        secondWindow.close();
    }

}

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

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.ScrollPane?>
<?import javafx.scene.layout.AnchorPane?>

<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" style="-fx-background-color: #412227;" xmlns="http://javafx.com/javafx/8.0.171" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.Controller">
   <children>
      <Button fx:id="addTimer" layoutX="53.0" layoutY="228.0" mnemonicParsing="false" text="Добавить таймер" />
      <ScrollPane prefHeight="182.0" prefWidth="600.0">
         <content>
            <Label fx:id="LabelValue" prefHeight="32.0" prefWidth="178.0" style="-fx-background-color: gray;" />
         </content></ScrollPane>
   </children>
</AnchorPane>

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

<?import javafx.scene.control.Button?>
<?import javafx.scene.layout.AnchorPane?>

<?import javafx.scene.control.TextField?>
<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="124.0" prefWidth="375.0" style="-fx-background-color: #452d35;" xmlns="http://javafx.com/javafx/8.0.171" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.SecondWindowController">
   <children>
      <TextField fx:id="date" layoutX="56.0" layoutY="24.0" prefHeight="36.0" prefWidth="260.0" style="-fx-background-color: white;" text="Label" />
      <Button fx:id="ok" layoutX="177.0" layoutY="76.0" mnemonicParsing="false" text="ok" />
   </children>
</AnchorPane>

A: Можно использовать два варианта.

*

*Первый несколько топорный, но в целом рабочий вариант
в методе callPanel() потребуется выделить FXMLoader в отдельную переменную и после вызова load() из нее можно забрать secondController = fxmloader.getController (синтаксис по памяти) вашего второго окна. А далее перед вызовом show() выполнить secondController.setMainController(this). Теперь у второго контроллера появится связь с основным и можно дергать его методы.

*Второй способ использует немного магии.
Что бы связать несвязанные классы в приложении можно использовать паттерн Publisher/Subscruber.
Тут нужно будет почитать документацию. Одна из его реализация называется EventBus, вроде есть еще вторая популярная, но название не вспомнил. Суть в том, что оба контроллера в своих методах инициализации подписываются на события. Когда второй контроллер отправит событие, то eventBus вызовет у первого метод, который отвечает за обработку этого события.


text:
Q: How to fix problem with DeadObjectException? I have successfully finished an Android project's implementation and started to test the app for memory leaks.
Sometimes, I get DeadObjectExceptionafter a long trip in the app and all of the memory allocations are freed.
How can I detect this problem?
I have made some research about DDMS tools to detect memory leaks, Due to I have no idea about DeadObjectExeption, I don't know where to start.

A: This is not a memory leak problem. Definition of the memory leak (from Wikipedia):

A memory leak, in computer science (or leakage, in this context),
  occurs when a computer program acquires memory but fails to release it
  back to the operating system.

Here, you have an opposite case - memory is freed before it should (at least from your program's point of view).
From developer.android.com:

DeadObjectException extends RemoteException
The object you are calling has died, because its hosting process no longer exists.

For example:
You have the classes MyActivity and MyService. You use Handler/Messenger to communicate between them.
You create Handler and Messenger in MyActivity, and then send created instance of Messenger to MyService via an Intent. Then you do some stuff, time passes, and your MyActivity gets destroyed, together with it's Handler and Messenger. Now, if you don't handle that well, MyService won't know that Messenger that he has is not valid any more, so, he tries to send something through it, and get DeadObjectexception:

/*
  Send a Message to this Messenger's Handler.
Parameters:
message The Message to send. Usually retrieved through Message.obtain().
Throws:
RemoteException Throws DeadObjectException if the target Handler no longer exists.*/
public void send(Message message) throws RemoteException {...}

A: If You are calling any function from Native Library(.so file), Just check the package name used while creating JNI function is same as you are declaring native method in Java class.


text:
Q: magnetic field doing work on a wire I am a tutor and during a session today, a thought occurred to me. I've long been told (and been telling) that magnetic fields do no work, but it's pretty easy to imagine a situation in which a magnetic field DOES do work. If two wires have parallel currents traveling through them, with one wire situated above the other, the magnetic force would lift up the lower wire.
This would be basically the definition of work.
Why doesn't this negate the statement that magnetic forces do no work?

A: Magnetic fields do no work on unconstrained charged particles. This comes from the Lorentz force law:
$$F = q\vec{v} \times \vec{B}$$
\begin{align}
dW &= \vec{F}\cdot{}d\vec{x} \\
 &= (q\vec{v} \times \vec{B})\cdot{}d\vec{x} \\
 &= (q\vec{v} \times \vec{B})\cdot{}\vec{v}\,dt \\
 &= 0
\end{align}
(The last step is due to $(\vec{x} \times \vec{y})\cdot\vec{x} = 0$ for any vectors $\vec{x}$ and $\vec{y}$.)
It is certainly possible for magnetic fields to do work on other things:

*

*Current-carrying wires: where the charged particles are confined to the wire, so their velocity is not always parallel to the force. See railguns for a dramatic example of magnetic fields doing work.

*Other magnets (namely, dipoles), whether through attraction/repulsion (if the field has a gradient) or purely torque (if the field is uniform)

A: It is supprising how many people confuse work done   with energy. A static magnetic field contains no energy -and it is why  magnet only  based examples of  perpectual motion machines do not work . Magnetism is a force only, and work is done when a mass is moved a distance by that force. Clearly  the magnetic force is known to move  objects within its field of influence,and is capable of doing work as you  describe. Some might be convinced  that because work is done then energy  must be  available, however the only energy present is that which was first applied (eg  the power x time for which the parrallel conductors carrying  current) or  the energy required to place an object into the field of influence in the first place. The energy is either returned ( ideally) or converted into mechanical movement ( as per an electric motor). Static magnetic fields are not a source of energy.


text:
Q: Is $f(x)=\begin{cases}\frac{(-1)^n}{\sqrt{n}} \text{ ,if } x=\frac{1}{n} \\ 0 \quad \, \, \, \,\text{ ,if } x=0\end{cases}$ continuous? let Is $D:=\{1/n, n\in \mathbb{N}\}\cup \{0\}, f(x)=\begin{cases}\frac{(-1)^n}{\sqrt{n}} &\text{if } x=\frac{1}{n}, \\ 0 &\text{if } x=0.\end{cases}\quad$ Where is $f$ continuous?
My attempt:
Let $\varepsilon >0$ and $\delta >0$, then $\forall x,x_0\in D\backslash \{0\}$:
$|x-x_0|<\delta \implies \left| \frac{(-1)^x}{\sqrt{x}}-\frac{(-1)^{x_0}}{\sqrt{x_0}}\right |<\varepsilon$$\left| \frac{(-1)^x}{\sqrt{x}}-\frac{(-1)^{x_0}}{\sqrt{x_0}}\right |=\left |\frac{(-1)^x\cdot \sqrt{x_0}-(-1)^{x_0}\cdot \sqrt{x}}{\sqrt{x}\cdot \sqrt{x_0}}\right |\leq \left |\frac{(-1)^x\cdot \sqrt{x_0}-(-1)^{x_0}\cdot \sqrt{x}}{\sqrt{x_0}}\right  |=\left |(-1)^x-\frac{(-1)^{x_0}}{\sqrt{x_0}}\right |$ This does not seem to work out, what would be a good way show where $f$ is continious?

A: Continuity at $0$ follows from $|f(x)| \leq \sqrt x$ for all $x$. [Take $\delta =\epsilon^{2}$]. Continuity at any other point $x$ follows from the fact that $y=x$ whenever $|y-x|$ is sufficiently small.
To be explicit $x=\frac 1 n$ and $|y-x| <\frac 1 {n(n+1)}$ implies $y=x$. So choose $\delta = \frac 1 {n(n+1)}$ whatever your $\epsilon$ is.


text: Q: Getting Admin User in Formula I currently have a formula field in an object, but it is grabbing the Admin email when I put $User.email in the field, even when I am not logged in as the admin. I am completely unsure why the admin is grabbed as the current user.


text:
Q: Jenkins rebuild for job triggered by github pull requests builder Can the GitHub pull request builder work with the Rebuild plugin?
Correctly rebuild can see all the parameters of a github pr builder triggered build, but these parameters are not used for some reason. A rebuild of the rebuild will show no parameters.
I know I can trigger a build by commenting on a PR, but sometimes I find it's convenient to rebuild from Jenkins (e.g. build fails -> click the Jenkins link on the PR and get to the failed build -> it's a flaky spec -> rebuild).

A: Go to your Jenkins job and check the option "Rebuild Without Asking For Parameters". When you click "Rebuild" it'll trigger a new build with same parameters.
Job Rebuild Options


text: Q: Youtube branding I want to place YouTube video on my site with no branding . also I don't want any one to right click and grabbing the vid URL. JW player will support this but ppl still can click the YT watermark. is thire any way I could add allow networking internal only function to jw play. basically I don't want any onto go to YouTube and also to copy the url