text:
Q: How to convert text into the fields of an object Okay, so I have a text file that is essentially a course description.
Physics Applied SPH4C  2014

Description:
    Physics  = course name
    Applied = course level
    SPH4C = course code
    2014 = academic year
So, I have already tokenized this info so that each field is on a separate line like:
Physics
Applied
SPH4C
2014

Now, I want to convert each line into a different type since my Course class accepts different types.
Like this:
public Course(String name, String code, char level, int academicYear)

How do I convert the string level that I get from the text file into a char
private void convertLevel(String courseLevel)
{
    level = DEFAULT_LEVEL;
    if(level == "IB") level = "7";
    if(level == "Academic")level = "1";
    if(level == "Applied") level = "1";
    if(level == "ELL") level = "9";
    if(level == "Special Education") level = "8";
} // end of method convertLevel(String courseLevel)

this is what I have, but it basically just changes the string, which wont allow me to enter it as a level since the course only accepts a char as a level, or am I wrong.
Also, I need help with the academic level as well
Also, how would I assign each line to a variable
Here is the hashtable
    //This allows you to define your list with string keys instead of
//using a bunch of ifs.
Hashtable<String, char> CourseLevels = new Hashtable<String, char>()
                                                        {
                                                            put("IB", '7'),
                                                            put("Academic", '1'),
                                                            put("Applied", '1'),
                                                            put("ELL", '9'),
                                                            put("Special Education",    '8')
                                                        };

but the compiler is telling me that a return type is required at the first put statement, any ways yo solve this
Here is the edited version
    private char convertLevel(String courseLevel)
{
    //This allows you to define your list with string keys instead of
    //using a bunch of ifs.
    Hashtable<String, Object> courseLevels = new Hashtable<String, Object>();
    {
        courseLevels.put("IB", '7');

        courseLevels.put("Academic", '1');

        courseLevels.put("Applied", '1');

        courseLevels.put("ELL", '9');

        courseLevels.put("Special Education", '8');
    };
    //Determine if the courseLevel exists in our list.
    if (courseLevels.containsKey(courseLevel))
    {
        //Assuming level is defined as a char and not a string
        //Yes it does, use it.
        level = (char)courseLevels.get(courseLevel); // gives me an error
    }
    else
    {
        //if not use the default.
        level = DEFAULT_LEVEL;
    }
    return level;
}

the error message is incompatible types
Here is the whole class
public class CourseUtility
{
// class constants
private static final String INPUT_FILE = "courses.text";
private static final String OUTPUT_FILE = "CoursesTokenized.text";

private static int counter = 0;
private static int courseNumber = 0;
private static int k = 0;
private static final String DELIMITER_SPACE = " ";
private static final String DELIMITER_TAB = "\t";
String delimiter = DELIMITER_TAB;
private static final String DEFAULT_LEVEL = "X";

String name = "";
String code = "";
String year = "";
String level = "";
String lineOfText;
private static String[] courseField = new String[5];

/**
 * Constructor for objects of class CourseUtility
 */
public CourseUtility() throws IOException
{

}

public void readFromFile() throws IOException
{
    int index = 0;
    int j = -1;
    int spaceCount = 0;
    courseNumber++;

    setCourseFieldDescription();

    BufferedReader inputFile = new BufferedReader(new FileReader(INPUT_FILE));
    PrintWriter outputFile = new PrintWriter(new FileWriter(OUTPUT_FILE));

    String lineOfText = inputFile.readLine();
    while (lineOfText != null)
    {
        for (char c : lineOfText.toCharArray())
        {
            if (c == ' ')
            {
                spaceCount++;
            }
        }

        if(spaceCount == 1)
        {
            delimiter = DELIMITER_SPACE;

        }
        else if(spaceCount == 2)
        {
            delimiter = DELIMITER_TAB;
        }

        System.out.println("Course" + courseNumber);

        // for each token in the string
        while ((j = lineOfText.indexOf(delimiter, (index = ++j))) != -1)
        {
            System.out.println(courseField[k] + ": " + lineOfText.substring(index, j));
            System.out.println("");
            outputFile.println(lineOfText.substring(index, j));
            counter++;
            k++;

        }

        // extract the last token
        if (index > 0)
        {
            System.out.println("Year: " + lineOfText.substring(index));
            outputFile.println(lineOfText.substring(index));
            ++courseNumber;
        }
        // for each token in the string
        //             Course c = new Course(hm.get("Name"), hm.get("Code"),
  hm.get("Level"), Integer.parseInt(hm.get("Year")) );
        //             System.out.println(c);

        if(k == 3)
        {
            k = k - k;
            index = 0;
        }

        delayDisplay();
        lineOfText = inputFile.readLine();

    } // while(lineOfText != null)

    inputFile.close();
    outputFile.close();
}

public CourseUtility(String name, String code, String level, String year)
{
    if(name == null)
    {
        this.name = Course.DEFAULT_NAME;
    }
    else
    {
        this.name = name;
    } // end of if(name == null)
    if(code == null)
    {
        this.code = Course.DEFAULT_CODE;
    }
    else
    {
        this.code = code;
    } // end of if(code == null)
    if(level == null)
    {
        this.level = DEFAULT_LEVEL;
    }
    else
    {
        this.level = level;
    } // end of if(level == null)
    if(year == null)
    {
        this.year = null;;
    }
    else
    {
        this.year = year;
    } // end of if(year == null)

}

private void delayDisplay()
{
    try
    {
        Thread.sleep(1000);
    } catch(InterruptedException ex)
    {
        Thread.currentThread().interrupt();
    } // end of try
} // end of method void delayDisplay()

//     private void convertLevel(String courseLevel)
//     {
//         level = DEFAULT_LEVEL;
//         if(level == "IB") level = "7";
//         if(level == "Academic")level = "1";
//         if(level == "Applied") level = "1";
//         if(level == "ELL") level = "9";
//         if(level == "Special Education") level = "8";
//     } // end of method convertLevel(String courseLevel)

private char convertLevel(String courseLevel)
{
    //This allows you to define your list with string keys instead of
    //using a bunch of ifs.
    Hashtable<String, Object> courseLevels = new Hashtable<String, Object>();
    {
        courseLevels.put("IB", '7');

        courseLevels.put("Academic", '1');

        courseLevels.put("Applied", '1');

        courseLevels.put("ELL", '9');

        courseLevels.put("Special Education", '8');
    };
    //Determine if the courseLevel exists in our list.
    if (courseLevels.containsKey(courseLevel))
    {
        //Assuming level is defined as a char and not a string
        //Yes it does, use it.
        level = courseLevels.get(courseLevel);
    }
    else
    {
        //if not use the default.
        level = DEFAULT_LEVEL;
    }

}

//
//         //Assuming level is defined as a char and not a string
//         if (CourseLevels.contains(courseLevel))
//         {
//             return CourseLevels.get(courseLevel);
//         }
//         else
//         {
//             return DEFAULT_LEVEL;
//         }

public void setCourseFieldDescription()
{
    courseField[0] = "Name";
    courseField[1] = "Level";
    courseField[2] = "Code";
    courseField[3] = "Year";
} // end of method setCourseFields()

A: Changing a 1-character to String to a char type can be done with:
myString.charAt(0);

A: to convert a String to a char you should use
"7".charAt(0); //first example;

you may have a look at this
In Java how does one turn a String into a char or a char into a String?
last but not least if you are comparing strings to each other you may not use the equality operator as i suppose you are checking the strings having the same values.
For that you should use the equals method. I recommend having a look at :
How do I compare strings in Java?
For further information try the official documentation of java.lang.String
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html
Hope this helps :)

A: Just pass level.charAt(0) while calling the function.

A: If your course level as indicated in the text file is SPH4C then you cant put it an a single char just change the char level in the paramater as String.
When you comparing two string then can use the equals method of the string
example:
if(level.equals("IB")) level = "7";


text:
Q: How to watch for changes to HAML files and save them I want to run a HAML command every time I save a particular file.  I know this can be done by compass but only for sass not HAML has anyone done this or guide me how to.

A: On MacOS (and I assume, on linux too) you can use the 'watch' command from the terminal.
First, you need to install it using, for example "homebrew"
brew install watch

and then you can run it like:
watch haml haml/mypage.html.haml html/mypage.html

A: Or if anyone stumbled in here like I did. There is a newer tool:  LiveReload that does all these automatically and more.

A: Sure, check out StaticMatic, nanoc, or Webby (search for these on gitHub). You can make them work with Compass too.

redpajama_set_name: RedPajamaStackExchange


text:
Q: use of if else in linux to find whether the folder exists or not I have the following bash script:
if [ -d "/$home/DB_handouts"] then
 echo "Directory DB_handouts found"
else
mkdir /$home/DB_handouts
 chmod 777 /$home/DB_handouts
fi

Running the above code produces an error:
./file.sh: line 12: syntax error near unexpected token `else'
./file.sh: line 12: `   else'

How can I fix this?

A: You need to add a semicolon (;) between if [ -d "/$home/DB_handouts"] and then (or put then in a new line):
if [ -d "/$home/DB_handouts" ]; then

Also in your case check if mkdir -p would do the job. Looking at the example i think the following should work:
mkdir -p /foo/bar
chmod 777 /foo/bar

A: There are multiple problems with your script:

*

*there has to be a ; between the ] and then (as @heemayl also indicated) or then should be put on a line of its own

*there has to be a space between handouts" and ]

*you should (but this doesn't generate an error) consistently indent, or use the -m option for mkdir (as @skwlisp indicated)

something like:
if [ -d "/$home/DB_handouts" ]
then
  echo "Directory DB_handouts found"
else
  mkdir -m 777 /$home/DB_handouts
fi

The above of course assumes that /$home exists, the whole thing can be much more easily achieved by using:
mkdir -p -m 777 /$home/DB_handouts

With -p there will be no complaints if the directory already exists.


text:
Q: Add rule lifecycle each object in bucket storage I'm a newbie with Google Cloud Platform Product, I would like to know. It's possible to assign a rule lifetime cycle. Which specific object in my bucket.
├── Bucket
    ├── object_a  (with rule)
    └── object_b  (without rule)

I have to read a document, Which a rule has been added to the bucket. Then effect to whole object in bucket. I can't avoid this one.
So is it possible to add rule for each object in the the bucket?

A: It's not possible.  As you've seen from the documentation, rules apply to entire buckets[1].  You can create different buckets with different rules, if you want[2].
[1] https://cloud.google.com/storage/docs/lifecycle#behavior
[2] https://cloud.google.com/storage/docs/creating-buckets


text:
Q: How to manage Android toolbar I'm working on an app where I've put an android widget.toolbar as supportActionBar, but I couldn't find anything on how to manage its properties. I would like, for example, to modify and add elements in the overflow menu (I don't know if the name is correct at all, however I mean the one that appears when you click the 3-points default icon on the right corner. I'll post an image.) and to set a listener for each one of them.

A: For the menu you have to follow the old implementation. You add an item inside the res/menu/your_menu.xml, you specify an action and you manage the action inside the onOptionsItemSelected() of your Activity or Fragment.

A: Look at this example:
In activity :
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);

        //Title and subtitle
        toolbar.setTitle("MY toolbar");
        toolbar.setSubtitle("Subtitle");

        //Menu
        toolbar.inflateMenu(R.menu.toolbar_menu);

        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem menuItem) {

                switch (menuItem.getItemId()){
                    case R.id.action_share:
                        Toast.makeText(ToolbarActivity.this,"Share",Toast.LENGTH_SHORT).show();
                        return true;
                }

                return false;
            }
        });

In XML file :
Create xml file like normal option menu :
toolbar_menu.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="example.gmariotti.it.test21.ToolbarActivity" >

    <item android:id="@+id/action_search"
          android:title="@string/action_search"
          android:icon="@drawable/ic_search"
          android:showAsAction="ifRoom" />

    <item android:id="@+id/action_share"
          android:title="@string/action_share"
          android:icon="@drawable/ic_share"
          android:showAsAction="ifRoom" />

    <item android:id="@+id/action_settings"
        android:title="@string/action_settings"
        android:orderInCategory="100"
        android:showAsAction="never" />
</menu>


text:
Q: How do I stop countdown timer using asp.net timer control? I had inserted a countdown timer in my project. When I run it , the timer start but when I stop debugging it and after some time when I again run it then what I notice is, the timer is still running. For example, I have given time of 3 minutes to the timer i.e. after 3 minutes it should redirect to the result page...now I run the page and the count down timer is started...when I stop debugging it suppose at 00:02:45(time left) and after 5 seconds when I again run it then the timer continues with 00:02:40(time left) .
I don't want like this to be happen . How do I stop the continuation of the timer?
Have a look at my code. Show me where I am making mistake and what is the solution.
On the TimerTest.aspx.cs page, I have the following lines of code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;

public partial class Student_TimerTest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

    if (Session["end_t"] == null)
    {
        DateTime start_time = DateTime.Now;
        DateTime end_time = start_time.AddMinutes(3);
        Session["end_t"] = end_time;
    }
}

protected void timer1_tick(object sender, EventArgs e)
{
    DateTime dt = (DateTime)Session["end_t"];
    DateTime dt_curr = DateTime.Now;
    TimeSpan ts = dt - dt_curr;
    lblTimer.Text = ts.Hours.ToString() + ":" + ts.Minutes.ToString() + ":" + ts.Seconds.ToString();
    if (ts.Minutes == 0)
    {
        timer1.Enabled = false;
        Response.Redirect("/Student/Result.aspx");
    }

}
}

On the TimerTest.aspx page, I have inserted the following lines of code:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="TimerTest.aspx.cs" Inherits="Student_TimerTest" %>

<!DOCTYPE html>

    <title></title>

    <form id="form1" runat="server">

        <asp:ScriptManager ID= "SM1" runat="server"></asp:ScriptManager>
        <asp:Timer ID="timer1" runat="server" Interval="1000" OnTick="timer1_tick"></asp:Timer>

       <asp:UpdatePanel id="updPnl" runat="server" UpdateMode="Conditional">
       <ContentTemplate>
       <asp:Label ID="lblTimer" runat="server"></asp:Label>
       </ContentTemplate>
       <Triggers>
       <asp:AsyncPostBackTrigger ControlID="timer1" EventName ="tick" />
       </Triggers>
       </asp:UpdatePanel>

</form>

A: To say that the timer is still running is a little misleading. There isn't actually any code running after you quit debugging. However, you store the start time in session state which, by default, is stored in the browser. If you stop debugging and then start again, the application instance for your web app is restarted, but your browser preserves the session state. So your browser still has the old start time. Therefore, on page load, the line if (Session["end_t"] == null) results in false. There is a value there.
There are many options here, but one would be to always clear the value on page load if it's not a post back. If it is a post back, just check if there's a value in session already.
Sample code:
protected void Page_Load(object sender, EventArgs e)
{
    // If this is the initial page load (not a post back),
    // or if there's not already an end time in Session,
    // then set the end time
    if (!Page.IsPostBack || Session["end_t"] == null)
    {
        DateTime start_time = DateTime.Now;
        DateTime end_time = start_time.AddMinutes(3);
        Session["end_t"] = end_time;
    }
}


text:
Q: Swift: Pull to refresh is too sensitive am not too sure if anyone has encountered this issue, but it seems that my refreshControl is too sensitive. In my implementation, I attempt to do a pull to refresh and the code executes even before I see the refreshControl spinning.
Is there something wrong I'm doing?
My implementation so far.
//At initiation
lazy var refreshControl: UIRefreshControl = {
    let rc = UIRefreshControl()
    rc.tintColor = .white
    rc.addTarget(self, action: #selector(refreshControlDidRefresh), for: .valueChanged)
    return rc
}()

//At viewDidLoad(), I call a function setupViews()
func setupViews() {
    view.backgroundColor = .white
    view.addSubview(tableView)

    tableView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
    tableView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor).isActive = true
    tableView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor).isActive = true
    tableView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true

    tableView.register(GossipsTableViewCell.self, forCellReuseIdentifier: "gossipCell")
    tableView.tableHeaderView = emptyTableViewHeader()
    tableView.refreshControl = refreshControl
}

@objc func refreshControlDidRefresh() {
    DispatchQueue.main.async {
        self.gossips.removeAll()
        self.tableView.reloadData()
    }

    getData()
}

func getData() {
    FirebaseClient.shared.fetchAllGossips { (results, error) in
        if let error = error {
            print(error.localizedDescription)
        } else if let results = results {
            self.gossips = results.sorted(by: { (gossip1, gossip2) -> Bool in
                guard
                    let gossip1Timestamp = gossip1.timestamp,
                    let gossip2Timestamp = gossip2.timestamp else {
                        return false
                }

                return gossip1Timestamp > gossip2Timestamp
            })

            self.filterGossips()

            DispatchQueue.main.async {
                if self.refreshControl.isRefreshing {
                    self.refreshControl.endRefreshing()
                }

                if JustHUD.shared.isActive {
                    JustHUD.shared.hide()
                }

                var indexPaths = [IndexPath]()
                for (index, _) in self.gossips.enumerated() {
                    let indexPath = IndexPath(row: index, section: 0)
                    indexPaths.append(indexPath)
                }

                self.tableView.insertRows(at: indexPaths, with: .automatic)
                self.segmentedControl.isUserInteractionEnabled = true
            }
        }
    }
}

You may see the results here. As I attempt to pull down, the refresh gets executed even before I start to see the refreshControl being drawn. Is there anything I'm missing out?

A: You are doing everything correctly, this is the default behaviour of pull to refresh control. If you want it to act differently, try a 3rd-part solution or remove the control and implement your own logic in scrollViewDidScroll.


text:
Q: returning a boost ublas matrix by value working only in release config for vs2012 I'm using visual studio 2012 and I isolated a problem in my code to this, but I can't solve it. When running it in release mode it works perfect, but I get an error if I run it in debug.
The code is:
#include "stdafx.h"

#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/io.hpp>

typedef boost::numeric::ublas::matrix<double> BMT;

BMT fun()
  {
  BMT mym;
  mym.resize(3,3);
  for(int i = 0; i<9;++i) mym(i/3,i%3)=i;
  std::cout << mym << std::endl;
  return mym;
  }

int main(int argc, char* argv[])
  {
  fun();
  //closing message
  std::cout<<std::endl<<"press enter to exit."<<std::endl;
  std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
  }

and the error in debug is the following:
1>------ Build started: Project: myproject, Configuration: Debug x64 ------
1>  myapp.cpp
1>C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\include\xmemory(348): error C4996: 'std::_Uninitialized_copy0': Function call with parameters that may be unsafe - this call relies on the caller to check that the passed values are correct. To disable this warning, use -D_SCL_SECURE_NO_WARNINGS. See documentation on how to use Visual C++ 'Checked Iterators'
1>          C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\include\xmemory(333) : see declaration of 'std::_Uninitialized_copy0'
1>          C:\thirdparty\vs2012\x64\boost_1_53_0\boost/numeric/ublas/storage.hpp(94) : see reference to function template instantiation '_FwdIt std::uninitialized_copy<const double*,double*>(_InIt,_InIt,_FwdIt)' being compiled
1>          with
1>          [
1>              _FwdIt=double *,
1>              _InIt=const double *
1>          ]
1>          C:\thirdparty\vs2012\x64\boost_1_53_0\boost/numeric/ublas/storage.hpp(89) : while compiling class template member function 'boost::numeric::ublas::unbounded_array<T>::unbounded_array(const boost::numeric::ublas::unbounded_array<T> &)'
1>          with
1>          [
1>              T=double
1>          ]
1>          C:\thirdparty\vs2012\x64\boost_1_53_0\boost/numeric/ublas/matrix.hpp(160) : see reference to function template instantiation 'boost::numeric::ublas::unbounded_array<T>::unbounded_array(const boost::numeric::ublas::unbounded_array<T> &)' being compiled
1>          with
1>          [
1>              T=double
1>          ]
1>          C:\thirdparty\vs2012\x64\boost_1_53_0\boost/numeric/ublas/matrix.hpp(100) : see reference to class template instantiation 'boost::numeric::ublas::unbounded_array<T>' being compiled
1>          with
1>          [
1>              T=double
1>          ]
1>          junkApp1.cpp(10) : see reference to class template instantiation 'boost::numeric::ublas::matrix<T>' being compiled
1>          with
1>          [
1>              T=double
1>          ]
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

Do you know what can the problem be?

A: I was having a similar issue using ublas.
I am not sure what the cause might be but I suppose it's got to do with ublas' copy on write / copy on demand optimizations. Would it be an option to just use the define -D_SCL_SECURE_NO_WARNINGS and be done with it? I have that set globally as I consider 90% of those warnings OS specifc BS anyway.

A: The problem is that you are compiling with warnings treated as errors.
EDIT: Microsoft has decided that certain parts of C++ (and C) are deprecated, and the compiler reports use of those parts as errors unless _SCL_SECURE_NO_WARNINGS (respectively _CRT_SECURE_NO_WARNINGS) is defined.


text:
Q: LESS - USING [ ] statements I would like to use the following code in a LESS file -
.chevron_btn.[aria-expanded="true"]{

but it produces an error when compiled - is it possible to implement?

A: Remove the extra .:
.chevron_btn[aria-expanded="true"]{


text:
Q: Rails 3/delayed_job - Wanted: Basic example of delayed mail I've been trying to figure out how to send delayed mail using delayed_job with rails 3. I've tried pretty much every combination of feasible possibilities I can think of - I can get the mail to run in the background, I just can't get it to delay the sending to a future time. The delayed_jobs table in the db clears the tasks, the log says 'sent', the delayed_job task processor picks up the task & says sent without failure...but the mail is either:

*

*sent immediately, or

*simply doesn't arrive

if I try to send in the future.
If anyone could offer a bare-bones example of a rails 3 delayed_job that sends mail in the future, I'd be really appreciative. I'm sure lotsa folks do this so I suspect I'm missing something obvious. One (of countless) combinations I've tried below:
delayed_job: 2.1.2
rails: 3.0.3
actionmailer: 3.0.3
Controller:
class TestmailerController < ApplicationController
  def index
    Testmailer.delay.test_mail
  end

end

Mailer:
class Testmailer < ActionMailer::Base
  def test_mail
    mail(:to => '(myemailaddress@removedforprivacy.com', :from => '(removedforprivacy)@gmail.com', :subject => 'Testing Delayed Job', :content_type => 'text/plain').deliver
  end
  handle_asynchronously :test_mail, :run_at => Proc.new { 2.minutes.from_now }

end

relevant mail part of config/environments/development.rb:
  # Don't care if the mailer can't send
  config.action_mailer.raise_delivery_errors = true

  # Print deprecation notices to the Rails logger
  config.active_support.deprecation = :log

  config.action_mailer.default_url_options = { :host => 'localhost:3000' }

  ActionMailer::Base.smtp_settings = {
    :address => "smtp.gmail.com",
    :port => 587,
    :domain => "gmail.com",
    :user_name => "(removedforprivacy)",
    :password => "(removedforprivacy)",
    :authentication => "plain",
    :enable_starttls_auto => true
  }

Job command:
rake jobs:work

A: I agree with andrea - I was having this exact problem, and after switching my local development database from sqlite to mysql, I can run code like
Emailer.delay({:run_at => 5.minutes.from_now}).welcome(@user)

and it sends the email 5 minutes later.  Note that you might need a bigger delay than five minutes (in case of time zone weirdness) to be sure it is working.

A: Both using the .delay method and setting handle_asynchronously :test_mail is redundant. Try removing the .delay method from your code. use simply
Testmailer.test_mail   # without .deliver due to a delayed_job issue

However, I ran some test on your configuration and when using sqlite, run_at is simply ignored (do not know why), but when using mysql2 everything works fine.

A: I found in Rails 3 with mongoid that removing the handle_asynchronously line gets it to work. I was having all kinds of problems, and it appeared that delayed_job wasn't recognizing any objects within my Emailer class. Removing handle_asynchronously fixed it.


text:
Q: How to mount a samba share on non-standard port? The firewall on my network drops all packets on TCP port 139 and 445. So all samba shares don't work outside the LAN.
I tried letting the samba daemon listen on a non-standard port. This method works well for linux, because both smbclient and smbmount has an option to set server port. But on windows I cannot find a similar option.
Does Windows support mounting smb shares on non-standard ports? Third-party softwares are also acceptable.

Edit:
\\hostname:port\share in Windows explorer doesn't work. Strangely, I can see the connection is established on the server. But Windows keeps telling me that the server couldn't be reached. It doesn't work even in LAN with standard port 445, in which case a path without port number will get through.

A: Unfortunately, it is not possible as windows does only support ports 445 and 139
You might be able to use ssh tunneling. Here is a reference using windows and linux: https://www.ocf.berkeley.edu/~xuanluo/sshproxywin.html

A: For those who are still looking for a way to mount SMB resources on a non-standard port, here is a great article on how to do this. I personally set up stunnel to wrap SMB traffic with SSL, since I access my SMB shares remotely over the Internet. Works like a charm.

A: This is possible! It's been a good few years, but combining a loopback interface tutorial I found with portions out of @Mike's [..link-only] answer (multihost version) I've created a script that can do this for you.
You can use this after running Install-Module -Name LoopbackAdapter -MinimumVersion 1.2.0.0 in an admin terminal (dont forget to dot-source the script so you can call this).
Create-Host -Name bob -Ip 10.254.0.1 -Dest ipOfHostname -Port port

which [upon reboot] will allow you to go to \\bob (fake IP 10.254.0.1) which attaches to your "hostname:port" from your question.
This will persist across boots and you don't need to re-run it if the source server goes up or down; teardown is as simple as Retire-Host -Name bob.
That easy, one command, programmatic, no gui/windows settings dialogs; but feel free to follow along below manually.

Explanation:
Use netsh portproxy to link a fake IP with your SMB server, this will make the nonstandard port accessible on one Explorer accepts.
#it's important IP's are used here, not hostnames
netsh `
    interface portproxy `
    add       v4tov4 `
    listenaddress=<#fakeIP#> `
    listenport=445 `
    connectaddress=<#serverIP#> `
    connectport=<#serverPort#>

Optionally add the IP to your %windir%\System32\drivers\etc\hosts file so you don't need to remember this IP (Eg interact with \\bob instead of \\10.254.0.1).
Use DevCon to create a loopback network adapter, this "network" is what will host the IP.
$interface = New-LoopbackAdapter -Name <#NAME#>

Disable conflicting/unused services that break various things.
$interface `
| Disable-NetAdapterBinding `
    -ComponentID ms_msclient,ms_pacer,ms_server,ms_lltdio,ms_rspndr

$interface `
| Set-DnsClient `
    -RegisterThisConnectionsAddress $False `
    -PassThru `
| Set-NetIPInterface `
    -InterfaceMetric '254' `
    -WeakHostSend    Enabled `
    -WeakHostReceive Enabled `
    -Dhcp Disabled

Set the IP your machine will be reachable at on this "network".
$interface `
| New-NetIPAddress `
    -IPAddress     <#fakeIP#> `
    -PrefixLength  32 `
    -AddressFamily IPv4

Done! Upon reboot the forwarding will have hooked up, and you can access it as long as your pc can access the remote port. The setup will not disappear until you manually tear it down.

It's worth noting I only forward to 445 (and actually from 445 using ssh -L tunnelling to a machine on a network my pc cannot directly see), but it will simply be a change/additional netsh portproxy to swap/add the 139 equivalent if wanted.
To troubleshoot you can check windows is attempting to forward using
netsh interface portproxy show v4tov4

whether that is successfully listening on the loopback device
netstat -an | sls ':445'

and if your remote machine's server is accepting connections
Test-NetConnection -ComputerName <#serverIP#> -Port <#serverPort#>

finally that the whole thing has come together (and maybe it's some credential issue)
Test-NetConnection -ComputerName <#fakeIP#> -Port 445

A: If third-party tools are OK and you only need to access a SMB share and not really mount it to an drive letter, the tool Owlfiles does the job. Here you can enter a different port number for accessing SMB shares.
I started to use it when tunneling SMB through SSH so I do not need to setup a loopback adapter.
The tool is available through MS store and the feature is available in the free version of this tool.


text:
Q: jQuery transform animate translation to pure JavaScript I am trying to use the following marquee code that I found on Stack-Overflow:
Javascript Marquee to replace <marquee> tags
The full source code example here:
https://www.sanwebcorner.com/2016/07/marquee-text-without-marquee-tag-using.html
I would like to convert the jQuery animate to pure JavaScript (I'm thinking JavaScript animate).
The jQuery code is as follows:

 Flash message without marquee tag using javascript!

The marquee works quite well, but I am trying to avoid the overhead of jQuery and use pure JavaScript.

A: I struggled with this problem before I posted the question, and I continued to work on it after I posted.  I in fact tried the eventual solution before, but incorrectly.
My CSS is a little more general then the M. Lak (sanwebcorner.com) example.  I want to be able to define multiple marquees with different widths.

For rendering the marquee I wanted the duration/speed to be encoded, so I used a data attribute.  The text can be any number of HTML tags.

Short marquee text!

Finally, the real problem is the JavaScript.  I was confused by pure CSS marquees.  I eventually understood the problem and got beyond the syntax.

The marquee works quite well, and now I can avoid the overhead of jQuery and use pure JavaScript.


text:
Q: OSRM API provides various results for route, is this server issue? We started to try the potential for OSRM
but I have a question related to how is set the server.
Those 2 queries:
http://router.project-osrm.org/route/v1/foot/2.770657539367676,42.48209897188378;2.7791547775268555,42.463359622467586?overview=false&alternatives=false&continue_straight=false&steps=true&geometries=geojson
http://router.project-osrm.org/route/v1/foot/2.770657539367676,42.48209897188378;2.7791547775268555,42.463359622467586?overview=false&alternatives=false&continue_straight=false&steps=true&geometries=geojson
got the exact same parameters, however answer provided is different
The second one provides the awaited result. Any idea?


text:
Q: SELECT with many LEFT JOINs runs very slowly I would like some advice on how I could optimize the performance of a query that is stored in a procedure.
Previously, it took 20 minutes and now we can get it in 13 minutes. But it's still a long time.
I've checked the indexes several times, updated the statistics too and got the 13 minutes running.
I also tried to replace the logic of LEFT JOIN with OUTER APPLY but performance deteriorated.
Strangely, when I removed the [ShowToUser] = 1 filter in the WHERE clause, in SSMS the query was very fast (all records have a value of 1), so I commented this line of code and I removed the indexes with this column, as I thought it unnecessary. But when processing via application, the performance was even worse!
SELECT COUNT([Id]) AS [Events],
    [ClientId],
    [PersonId],
    [FullName],
    [SuperiorId],
    [Manager],
    [ClientPhoneNumberId],
    [PhoneNumber],
    [Departament],
    [CostCenter],
    [CostCenterCode],
    [TelecomUserInitialDate],
    [TelecomUserEndDate],
    [TelecomUserId],
    [PhoneCompanyId],
    [PhoneCompanyName],
    (SUM([UserCost]) / COUNT(DISTINCT [ReferenceMonth])) AS [AverageCostMonth],
    MAX([ReferenceMonth]) AS [ReferenceMonth],
    CAST(SUM(CASE
                WHEN [ReferenceMonth] = @referenceMonthEnd
                    THEN [UserCost]
                ELSE 0
                END) AS DECIMAL(18, 4)) AS [CostSumLastReference],
    Meta,
    ServicesValue,
    RegisteredArea,
    CASE
        WHEN ServicesValue > 0
            THEN (
                    ServicesValue - CAST(SUM(CASE
                                WHEN [ReferenceMonth] = @referenceMonthEnd
                                    THEN [UserCost]
                                ELSE 0
                                END) AS DECIMAL(18, 4))
                    ) * 100 / ServicesValue
        ELSE 0
        END AS ServicesPercent,
    CASE
        WHEN Meta > 0
            THEN (
                    Meta - CAST(SUM(CASE
                                WHEN [ReferenceMonth] = @referenceMonthEnd
                                    THEN [UserCost]
                                ELSE 0
                                END) AS DECIMAL(18, 4))
                    ) * 100 / Meta
        ELSE 0
        END AS MetaPercent
FROM (
    SELECT DISTINCT [t].[Id],
        [c].[Id] AS [ClientId],
        [p2].[Id] AS [PersonId],
        [p2].[FullName],
        [p2].[SuperiorId],
        [mg].[Fullname] AS [Manager],
        [cn].[Id] AS [ClientPhoneNumberId],
        [n].[Number] AS [PhoneNumber],
        [dp].[Name] AS [Departament],
        [tcc].[Name] AS [CostCenter],
        [tcc].[Code] AS [CostCenterCode],
        [tu].[InitialDate] AS [TelecomUserInitialDate],
        [tu].[EndDate] AS [TelecomUserEndDate],
        [a].[ReferenceMonth] AS [ReferenceMonth],
        [tu].[Id] AS [TelecomUserId],
        tu.goal AS Meta,
        tu.ServicesValue,
        tu.RegisteredArea,
        CASE
            WHEN @phoneCompanyId IS NOT NULL
                THEN [cn].[PhoneCompanyId]
            ELSE NULL
            END AS [PhoneCompanyId],
        [cp].[TradingName] [PhoneCompanyName],
        CAST([t].[UserCost] AS DECIMAL(18, 4)) AS [UserCost]
    FROM [telecom].[CallDetailRecord] AS [t]
    LEFT JOIN [telecom].[TelecomBill] AS [a]
        ON [a].[Id] = [t].[TelecomBillId]
    LEFT JOIN [telecom].[TelecomBillAccount] AS [tba]
        ON [tba].[Id] = [a].[TelecomBillAccountId]
    LEFT JOIN [telecom].[TelecomBillAccountContract] AS [tbacon]
        ON [tbacon].[TelecomBillAccountId] = [tba].[Id]
    LEFT JOIN [doc].[PersonContract] AS [pcontr]
        ON [pcontr].[Id] = [tbacon].[ContractId]
    LEFT JOIN [people].[Person] AS [p]
        ON [p].[Id] = [pcontr].[ContractorId]
    LEFT JOIN [customer].[Client] AS [c]
        ON [c].[PersonId] = [p].[Id]
    LEFT JOIN [telecom].[PhoneNumber] AS [n]
        ON [n].[Id] = [t].[PhoneNumberId]
    LEFT JOIN [telecom].[ClientPhoneNumber] AS [cn]
        ON [cn].[PhoneNumberId] = [n].[Id]
            AND [cn].[ClientId] = [c].[Id]
    LEFT JOIN [telecom].[TelecomUser] AS [tu]
        ON [tu].[ClientPhoneNumberId] = [cn].[Id]
    LEFT JOIN [people].[Person] AS [cp]
        ON [cp].Id = [cn].[PhoneCompanyId]
    LEFT JOIN [people].[Person] AS [p2]
        ON [p2].[Id] = [tu].[PersonId]
    LEFT JOIN [people].[Person] AS [mg]
        ON [mg].[Id] = [p2].[SuperiorId]
    LEFT JOIN [people].[Departament] AS [dp]
        ON [dp].[Id] = [cn].[DepartamentId]
    LEFT JOIN [accounting].[CostCenter] AS [cc]
        ON [cc].[Id] = [dp].[CostCenterId]
    LEFT JOIN [telecom].[TelecomUserCostCenter] AS [tuc]
        ON [tuc].[TelecomUserId] = [tu].[Id]
    LEFT JOIN [accounting].[CostCenter] AS [tcc]
        ON [tcc].[Id] = [tuc].[CostCenterId]
    LEFT JOIN [telecom].[PhoneNumber] AS [n1]
        ON [n1].[Id] = [t].[CalledPhoneNumberId]
    WHERE (
            [t].[CallDate] BETWEEN [tu].[InitialDate]
                AND (
                        CASE
                            WHEN [tu].[EndDate] IS NULL
                                THEN getdate()
                            ELSE [tu].[EndDate]
                            END
                        )
            OR [t].[CallDate] IS NULL
            )
        AND [ShowToUser] = 1
        AND [c].[Id] = @clientId
        AND [p2].[SuperiorId] = @superiorId
        AND [cn].[PhoneCompanyId] = ISNULL(@phoneCompanyId, [cn].[PhoneCompanyId])
        AND (
            ISNULL([cn].[DepartamentId], 0) = ISNULL(@departamentId, 0)
            OR [cn].[DepartamentId] = ISNULL(@departamentId, [cn].[DepartamentId])
            )
        AND [a].[ReferenceMonth] BETWEEN @referenceMonthInitial
            AND @referenceMonthEnd
    ) AS tb
GROUP BY [ClientId],
    [PersonId],
    [FullName],
    [Manager],
    [ClientPhoneNumberId],
    [PhoneNumber],
    [Departament],
    [CostCenter],
    [CostCenterCode],
    [TelecomUserInitialDate],
    [TelecomUserEndDate],
    [SuperiorId],
    [TelecomUserId],
    [PhoneCompanyId],
    [PhoneCompanyName],
    Meta,
    ServicesValue,
    RegisteredArea

A: Good work updating statistics as well as checking indexes.
With that monster, you need to simplify and reduce the load and complexity as early as possible.

*

*Anything in your WHERE clause that can be put into a JOIN safely should be, unless you measure a performance degradation.

*

*such as an equality to a parameter!

*this lets SQL eliminate rows as early as possible

*Create #temp tables for subsets of those tables - a few joined together at a time

*

*And put useful unique clustered indexes on those #temp tables!

*Apply your filtering as early as possible, getting only the rows you need

*Get ONLY the columns you need, plus enough for uniqueness (to prevent bad data)

*As an example, CREATE TABLE #cnAndSubset (cols you need), and then INSERT into it every row you need from cn and every table that joins ONLY on cn. Index that #temp table and then replace the existing many joins in the query with one join to the #temp table.  Repeat with reasonable sets until performance levels off.

*Figure out WHY you have the DISTINCT and that massive GROUP BY

*

*Most common cause: joins that fail to isolate only the rows required correctly

*on that GROUP BY - if Manager is ALWAYS the same for a given PersonId, and you're already grouping on PersonID, take the MAX(Manager) or MIN(Manager), don't group by it!

A: I'd do all the already-mentioned tricks in the other answers, but also clean up that inner query to the following. (there was some crazy filter logic overcomplications)
    ...
    FROM [telecom].[CallDetailRecord] AS [t]
    JOIN [telecom].[TelecomBill] AS [a] ON [a].[Id] = [t].[TelecomBillId]
        AND [a].[ReferenceMonth] BETWEEN @referenceMonthInitial
            AND @referenceMonthEnd
    JOIN [telecom].[TelecomBillAccount] AS [tba] ON [tba].[Id] = [a].[TelecomBillAccountId]
    JOIN [telecom].[TelecomBillAccountContract] AS [tbacon] ON [tbacon].[TelecomBillAccountId] = [tba].[Id]
    JOIN [doc].[PersonContract] AS [pcontr] ON [pcontr].[Id] = [tbacon].[ContractId]
    JOIN [people].[Person] AS [p] ON [p].[Id] = [pcontr].[ContractorId]
    JOIN [customer].[Client] AS [c] ON [c].[PersonId] = [p].[Id]
        AND [c].[Id] = @clientId
    JOIN [telecom].[PhoneNumber] AS [n] ON [n].[Id] = [t].[PhoneNumberId]
    JOIN [telecom].[ClientPhoneNumber] AS [cn] ON [cn].[PhoneNumberId] = [n].[Id]
        AND [cn].[ClientId] = [c].[Id]
    JOIN [telecom].[TelecomUser] AS [tu] ON [tu].[ClientPhoneNumberId] = [cn].[Id]
    JOIN [people].[Person] AS [p2] ON [p2].[Id] = [tu].[PersonId]
        AND [p2].[SuperiorId] = @superiorId
    LEFT JOIN [people].[Person] AS [cp]
        ON [cp].Id = [cn].[PhoneCompanyId]
    LEFT JOIN [people].[Person] AS [mg]
        ON [mg].[Id] = [p2].[SuperiorId]
    LEFT JOIN [people].[Departament] AS [dp]
        ON [dp].[Id] = [cn].[DepartamentId]
    LEFT JOIN [accounting].[CostCenter] AS [cc]
        ON [cc].[Id] = [dp].[CostCenterId]
    LEFT JOIN [telecom].[TelecomUserCostCenter] AS [tuc]
        ON [tuc].[TelecomUserId] = [tu].[Id]
    LEFT JOIN [accounting].[CostCenter] AS [tcc]
        ON [tcc].[Id] = [tuc].[CostCenterId]
    LEFT JOIN [telecom].[PhoneNumber] AS [n1]
        ON [n1].[Id] = [t].[CalledPhoneNumberId]
    WHERE (
            [t].[CallDate] BETWEEN [tu].[InitialDate]
                AND ISNULL([tu].[EndDate], getdate())
            OR [t].[CallDate] IS NULL
            )
        AND [ShowToUser] = 1
        AND (@phoneCompanyId IS NULL OR [cn].[PhoneCompanyId] = @phoneCompanyId)
        AND (@departamentId IS NULL OR [cn].[DepartamentId] = @departamentId)
    ) AS tb
...


text:
Q: Append SVG element to an existing SVG element using JS I am trying to append SVG element circle to an existing SVG element , i want to circle to sit on top of map i.e overlay but i am unable to do it properly , i  have created JSfiddle for it .Please let me know how to achieve this.
MY code is here
How to append at exact co ordinate i am using below code
document.getElementById('us').appendChild(c1);

A: You should remove onmouseover attribute from html and bind mouseover event in javascript code, something like this pseudocode:
var item = document.getElementById('id');
item.addEventListener('mouseover', function() {
    var x = getXPosition();
    var y = getYPosition();
    circleElement.setAttribute('cx', x);
    circleElement.setAttribute('cy', y);
}, false);

You should also show/hide element when needed with css classes, inline style or any other method.


text:
Q: Render an Element with React Honestly I don't think that this is the best Title, but I've no idea how explain it.
So sorry for it.
I'm trying to write a Component that parse all links(thar are not into a anchor tag) and emoji and render it like links or image.
For emoji I'm using this amazing component: https://github.com/banyan/react-emoji
It works well, but the problem is with the simple links...I don't have found a way for render it like links, instead of text of the link tag.
This is my code:
# @cjsx React.DOM

@Linkify = React.createClass
  displayName: 'Linkify'

  mixins: [ReactEmoji]

  componentDidMount: ->

  componentWillUnmount: ->

  render: ->

      {@parseLinks(@props.text)}

  parseLinks: (text) ->
    pattern = /(ht|f)tps?:\/\/[^\"<]*?(?=\s|$|<\/[^a]>)/gi
    results = text.match(pattern)
    new_text = text
    if results and results.length > 0
      for result in results
        link_html = React.createElement('a', {href: result}, result)
        new_text = new_text.replace(result, link_html)
    return @emojify(new_text)

and if I wrote:
Hello search here google.com :)
I get:
Hello search here [object Object] :) (instead of :) I've the correct emoji image)
The problem is: why it don't show correctly the Object Link ? where I done wrong ?
Thanks for any help.

A: link_html = React.createElement('a', {href: result}, result)
new_text = new_text.replace(result, link_html)

You can't use String#replace to put an object (returned by React.createElement) into a string. It's like saying

var text = "one two three";
var el = {testing: true};
alert(text.replace("two", el));

Instead, you should return a ReactElement (created with JSX or React.createElement) that contains the associated text, but with the link in the correct place in the children.
Consider the output of
Test google.com link

which is
React.createElement("span", null,
  "Test ",
  React.createElement("a", {href: "google.com"},
    "google.com"
  ),
  " link"
)


text:
Q: Have nginx serve up all files in a certain directory I want to have nginx serve up all images in /public/system/articles/images in my Rails app. I've tried
    location /system {
      allow all;
    }
which when I put in my_site.com/public/system/picture.png returns the Rails 404 page (as opposed to the nginx 404 page, or the image which is what I'm really after).
This is my current conf file:
upstream varnish {
    server localhost:6081;
}

server {
    listen 80;
    server_name my_site.com;

    location ~* \.(ico|css|js|gif|jpe?g|png)\?[0-9]+?$ {
      expires max;
      break;
    }

  root /home/my_site/my_site/current/public;

  location /system {
    allow all;
  }

  location @app {
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off;
    proxy_set_header X-AI-App "my_site";
    proxy_pass http://varnish;
  }

  #root /home/my_site/my_site/current/public;

  location / {
    # all IP addresses are listed here:
      allow all;

    try_files $uri @app;
  }

}

A: Seems I didn't need to do anything to the nginx conf files.
When trying to access things under the /public directory you don't put /public in the URL you're calling.
So instead of my_site.com/public/system/picture.png I should have been putting in my_site.com/system/picture.png


text:
Q: Proper way of saying: "The one who listens to others is the one who is listened by others" I'm doing a presentation and one of my key point (as the one developed in Forbes.com here) is that to be relevant to others you have to listen them first.
I would like to say it in a compact and catchy way using twice the same verb ("listen" here but I am open to any suggestion) in order to insist on both the passive and active part of the action.
Thank you

A: How about:

He who listens will be he to whom others will listen.

That would seem to satisfy your request.
Or alternatively,

To be heard, one must first hear.

A: "One who listens to others is the one who is heard by others," or more simply: "To be heard, you must first listen."
– Mick, in comments section.
Posting this answer so this question can be "answered".


text:
Q: Setting time out for NSMutableURLRequest to custom time
Possible Duplicate:
NSMutableURLRequest timeout doesn't trigger if data starts to load but not webViewDidFinishLoad

I am using a Async HTTP request and setting timeout for my NSMutableURLRequest to 30 seconds and I want to timeout the request within this time.
Problem: Request is not getting timed out withing 30 seconds. It is always taking 90 seconds to timeout. Any solution for this.
Here is my code for connection:
NSMutableURLRequest *myRequest = [[NSMutableURLRequest alloc] initWithURL:myURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
[myRequest setHTTPMethod:@"POST"];
[myRequest setHTTPBody:myData];

NSURLConnection *myConnection = [[NSURLConnection alloc] initWithRequest:myRequest delegate:self];

And I am implementing following delgates:
- (void)connection:(NSURLConnection *)iConnection didReceiveResponse:(NSURLResponse *)iResponse;
- (void)connection:(NSURLConnection *)iConnection didReceiveData:(NSData *)iElementContructionContextData;
- (void)connection:(NSURLConnection *)iConnection didFailWithError:(NSError *)iError;

A: You can set your time for timeOutSeconds  like this:-
[myRequest setTimeOutSeconds:1000];

Set timeOutSecond according to yourself.


text:
Q: javascript function .change() not run on cloned element i designed a dynamic table which user can add more row.
and there is a function .change() on an input
for the first row its run, but for next (cloned) elements the function doesn't run
my fiddle is here
the code as follow
$(document).ready(function(){
$("#btnAddItemAssignee").click(function(e){
    e.preventDefault();
    $(".oAssignee:last").clone().insertAfter(".oAssignee:last");
    $(".oAssignee:last").find("#txtAssigneeType").val("");
    $(".oAssignee:last").find("#txtAssigneeId").val("");
});
});

$("body #txtAssigneeType").change(function(){
if ($(this).val()=="Individu")
{
    console.log($("body #txtAssigneeType").length);
    alert("call me");
}
});

A: Replace $(".oAssignee:last").clone().insertAfter(".oAssignee:last");
with
$(".oAssignee:last").clone("true").insertAfter(".oAssignee:last");

Demo

A: It is because you are using same Id for all drop-down.. #txtAssigneeType.. Change it when you are adding new group..
eg: add random id
     #txtAssigneeType1,
     #txtAssigneeType2,
     #txtAssigneeType3

A: .clone() accepts two arguments. First one is for "withDataAndEvents" and second one is for "deepWithDataAndEvents".
Both the values are false by default.
Change your statement to this and it will clone the data as well as events.
$(".oAssignee:last").clone(true).insertAfter(".oAssignee:last");

https://api.jquery.com/clone/

A: I found the solution, it must be add true inside .clone(true).


text:
Q: Finding the derivative of an equation I am currently doing an investigation in which I am required to design the dimensions of a juice box (can be cube/cuboid) which has the least possible surface area that can hold 200 ml of juice.
I have combined these surface area and volume formulas:
$$V = lwh$$
$$A = 2(lw + lh + wh)$$
(V = volume. A = surface area. l = length. w = width. h = height.)
...
To make this:
$$A = 2(lw + \frac{200}{w} + \frac{200}{l})$$
(the V was substituted with the volume, 200 ml)
...
So, now that I have an equation (which I don't know if it is correct), I would like to find the least possible value for A, the surface area. If I am not mistaken, I will need to find the derivative of the equation using differential calculus. But, what then? Is that already the least possible surface area?
Apologies, I am new to the concept of calculus, so please inform me if I have done anything wrong in my calculations.

A: Let us admit that we do not know the answer (that is to say that the smallest surface area of a cuboid for a given volume is a cube as calculus commented).
You properly arrived to $$A = 2\big(lw + \frac{200}{w} + \frac{200}{l}\big)$$ Since you want $A$ to be minimum, you need to set its derivatives with respect to the variables $l,w$ equal to $0$ (think about the bottom of a valley).
So, $$A'_l=2 \left(w-\frac{200}{l^2}\right)=0\tag 1$$ $$A'_w=2 \left(l-\frac{200}{w^2}\right)=0\tag 2$$ From $(1)$, $w=\frac{200}{l^2}$. Plug this in $(2)$ to get $$l-\frac{l^4}{200}=l\big(1-\frac{l^3}{200}\big)=0$$ I suppose that you will accept to forget the case $l=0$. So, what remains is $l^3=200$ which corresponds to $l= \sqrt[3]{200}$. Back to $w$, you will get the same value as well as for $h$.
So, we face a cube of side equal to $ \sqrt[3]{200}\approx 5.84804$.
You could change the specific $200$ to any $V$ and get a cube of side dimension $ \sqrt[3]V$.


text:
Q: Example that :$u\in C^\infty(U)$ not $u \in C^\infty(\overline{U})$ for elliptic equation Let $U$ be arbitrary open subset in $\Bbb{R}^n$,Let $u \in H^1(U)$ be the solution for the following equation with $f\in C^\infty(U)$:
$$\int_U \nabla u \cdot\nabla \varphi = \int_U f\varphi$$
for all $\varphi \in C^\infty_c(U)$ .
By interior regularility result for elliptic equation we know $u \in C^\infty(U)$.But It needs not to be a solution that $u\in C(\overline{U})$.
Is there some good example  ?

A: Let $U$ be the circle segment (in polar coordinates)
$$
U = \{ (r,\theta): \ r\in(0,1), \ \theta \in (0,\omega)\}
$$
with $\omega \in (\pi,2\pi)$. Then $U$ is non-convex. Define
$$
u(r,\theta) = r^{\pi/\omega} \sin(\pi\frac \theta\omega).
$$
Then $u\in H^1(U)$, $-\Delta u=0$, so it satisfies the requirements with $f=0$. But $u\not\in C^1(\bar u)$, as $|\nabla u(r,\theta)|\to\infty$ for $r\searrow0$.


text:
Q: How to do the following query in Firebase? (more than one where condition) Consider following firebase structure :
{
  "users" : {
    "00:03:aa:dc:1c:2b" : {
      "firstName" : " Ofek",
      "groupName" : "thailand",
      "lastName" : "Ron",
      "registration" : {
        "type" : "regular",
        "time" : 1418288589636
      },
      "phoneNumber" : "345345345"
    },
    "04:46:65:8D:60:C6" : {
      "firstName" : " Ofek",
      "groupName" : "thailand",
      "lastName" : "Ron",
       "registration" : {
        "type" : "regular",
        "time" : 1418288589630
      },
      "phoneNumber" : "345345345"
    },
  }
}

how do you implement the following query :
SELECT * FROM USERS WHERE groupName="thailand" and registration.time>=1418288589631

I was trying to do it like this :
fireBase.orderByChild("groupName").startAt("thailand").endAt("thailand").orderByChild("time").startAt("1418288589631")

but that threw an exception since firebase doesnt allow multiple orderbys...
Any ideas?

A: Firebase currently only supports a single orderBy per query.
So if you want to filter (or order) on more than one property, you'll either have to do the additional filtering (or ordering) client-side in your JavaScript code or you'll have to come up with your own indexing scheme that combines the properties.


text:
Q: checking to see if product is downloadable in Woo commerce I need to display a note on single product pages of a WooCommerce store whenever the product is downloadable. I've created a function that works except for the part that checks for whether the product is downloadable. Right now the page seems to just quit rendering content when it reaches to point where this note would go. I've googled nine ways to Sunday on this and cannot seem to make it work. Any help would be appreciated--thanks. My function is below:
//add text note to product description page for all downloadable products
add_action( 'woocommerce_before_add_to_cart_button' , 'append_download_note'
);
function append_download_note() {
    global $product;
    if ( $product->is_downloadable() ) {
        echo '
Please note: a link to your downloadable product will be
        available on the purchase confirmation page.
';
    }
}


text:
Q: Limit of Product description and short description character in magento 2 Is there any limit to number of characters for product description and short description in magento 2?

A:
Use Custom Code Try

    $sdesc = $_product->getShortDescription();<br ?--> $sdesc = trim($sdesc);
    $limit = 40;
    if (strlen($sdesc) > $limit) {
    $sdesc = substr($sdesc, 0, strrpos(substr($sdesc, 0, $limit), ' '));
    }
    echo $sdesc."...";


text:
Q: bundle exec rake secret cannot load such file -- phusion_passenger/rack_handler When I run this command to generate secret on production server. I followed the installation documentation from the official website of Passenger, since I'm using Passenger with NGINX.
The URL to the documentation can be found here: https://www.phusionpassenger.com/library/walkthroughs/deploy/ruby/aws/nginx/oss/rubygems_rvm/deploy_app.html:
bundle exec rake secret
[ec2-user@ip-172-31-20-167 feutradmin]$ bundle exec rake secret
rake aborted!
LoadError: cannot load such file -- phusion_passenger/rack_handler
/usr/local/rvm/gems/ruby-2.3.0/gems/bundler-1.12.4/lib/bundler/runtime.rb:86:in `require'
/usr/local/rvm/gems/ruby-2.3.0/gems/bundler-1.12.4/lib/bundler/runtime.rb:86:in `block (2 levels) in require'
/usr/local/rvm/gems/ruby-2.3.0/gems/bundler-1.12.4/lib/bundler/runtime.rb:81:in `each'
/usr/local/rvm/gems/ruby-2.3.0/gems/bundler-1.12.4/lib/bundler/runtime.rb:81:in `block in require'
/usr/local/rvm/gems/ruby-2.3.0/gems/bundler-1.12.4/lib/bundler/runtime.rb:70:in `each'
/usr/local/rvm/gems/ruby-2.3.0/gems/bundler-1.12.4/lib/bundler/runtime.rb:70:in `require'
/usr/local/rvm/gems/ruby-2.3.0/gems/bundler-1.12.4/lib/bundler.rb:102:in `require'
/var/www/html/feutradmin/config/application.rb:7:in `<top (required)>'
/var/www/html/feutradmin/Rakefile:4:in `require'
/var/www/html/feutradmin/Rakefile:4:in `<top (required)>'
/usr/local/rvm/gems/ruby-2.3.0/gems/bundler-1.12.4/lib/bundler/cli/exec.rb:63:in `load'
/usr/local/rvm/gems/ruby-2.3.0/gems/bundler-1.12.4/lib/bundler/cli/exec.rb:63:in `kernel_load'
/usr/local/rvm/gems/ruby-2.3.0/gems/bundler-1.12.4/lib/bundler/cli/exec.rb:24:in `run'
/usr/local/rvm/gems/ruby-2.3.0/gems/bundler-1.12.4/lib/bundler/cli.rb:304:in `exec'
/usr/local/rvm/gems/ruby-2.3.0/gems/bundler-1.12.4/lib/bundler/vendor/thor/lib/thor/command.rb:27:in `run'
/usr/local/rvm/gems/ruby-2.3.0/gems/bundler-1.12.4/lib/bundler/vendor/thor/lib/thor/invocation.rb:126:in `invoke_command'
/usr/local/rvm/gems/ruby-2.3.0/gems/bundler-1.12.4/lib/bundler/vendor/thor/lib/thor.rb:359:in `dispatch'
/usr/local/rvm/gems/ruby-2.3.0/gems/bundler-1.12.4/lib/bundler/vendor/thor/lib/thor/base.rb:440:in `start'
/usr/local/rvm/gems/ruby-2.3.0/gems/bundler-1.12.4/lib/bundler/cli.rb:11:in `start'
/usr/local/rvm/gems/ruby-2.3.0/gems/bundler-1.12.4/exe/bundle:27:in `block in <top (required)>'
/usr/local/rvm/gems/ruby-2.3.0/gems/bundler-1.12.4/lib/bundler/friendly_errors.rb:98:in `with_friendly_errors'
/usr/local/rvm/gems/ruby-2.3.0/gems/bundler-1.12.4/exe/bundle:19:in `<top (required)>'
/usr/local/rvm/gems/ruby-2.3.0/bin/bundle:23:in `load'
/usr/local/rvm/gems/ruby-2.3.0/bin/bundle:23:in `<main>'
/usr/local/rvm/gems/ruby-2.3.0/bin/ruby_executable_hooks:15:in `eval'
/usr/local/rvm/gems/ruby-2.3.0/bin/ruby_executable_hooks:15:in `<main>'
(See full trace by running task with --trace)

A: I added
gem "passenger", ">=5.0.25", require: "phusion_passenger/rack_handler"

followed by bundle install to get rid of the error.


text:
Q: Null pointer Exception in JList when is ListSelectionListener is running I wrote some code that sets the Image on the JLabel. The path of Image is obtained from getSelectedValue() method for selected item on the JList.
The Jlist was populated when user clicked search button by typing the item to be searched in JTextField(i.e searchTextField) after choosing any option out of three items in JComboBox(i.e typeChooserBox). Then my program reads saved records from a file "Records.txt" and breaks into tokens to compare proper token(based on index of typeChooserBox) with the user input value(in searchTextField). Then it populates JList.
Below is the event handler for search Button that populates JList.
    public class searchButtonListener implements ActionListener{
public void actionPerformed(ActionEvent ev){
       model.clear();//This empties the JList creating nullpoint Ex
        int index=typeChooserBox.getSelectedIndex();
        String toCompare=searchTextField.getText();

        try {
                        File file = new File("Records.txt");
        BufferedReader reader = new BufferedReader(new FileReader(file));

            String line=null;
                while((line=reader.readLine())!=null){
                    String[] tokens = line.split("/");

                    if( index==0){
                        if(tokens[0].equals(toCompare))
                            model.addElement(tokens[2]);}

                    if(index==1){
                        if(tokens[1].equalsIgnoreCase(toCompare))
                            model.addElement(tokens[2]);}
                    if(index==2){
                        if(tokens[3].contains(toCompare))
                            model.addElement(tokens[2]);}
                                    }
        }
        catch(FileNotFoundException e2){
    JOptionPane.showMessageDialog(null,"File not found", "Error",JOptionPane.ERROR_MESSAGE);
    }
        catch(IOException ex){
            JOptionPane.showMessageDialog(null,"File not found", "Error",JOptionPane.ERROR_MESSAGE);
        }

}

}
When I search for a record. For the First time -my JList gets populated with results of search .Then when I select an item from JList, it works(sets the correct image on JLabel) until I perform a new search. As soon as I click the search button(second time). My program throws nullPointExecption and stops working. Sorry I have not included SSCCE. But if these little information is not sufficient please let me know. :)
WELL I FIGURE OUT MY PROBLEM...
the code model.clear() clears all the item in the list when a search button is clicked. Due to this reason, there will be no selected item at the list resulting null pointer exception. But How do I solve this. Can I clear all the field but avoid null value when getSelctedValue() is called for the JList.
I tried doing this but it still didn't work.
    public class searchListListener implements ListSelectionListener {
        String s;
        String imagePath;

        public void valueChanged(ListSelectionEvent evt){ try{

         imagePath= (String) searchResult.getSelectedValue();

        ImageIcon image = new ImageIcon(imagePath);
        imageLabel.setIcon(image);
        searchResult.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

    }
        catch(NullPointerException ne){
             JOptionPane.showMessageDialog(null, "NullPointerException");
             model.addElement(s);
             searchResult.setSelectedValue(s, true);

            }
        finally{
            s=imagePath;
        }
}
    }

public class typeChooserBoxListener implements ItemListener{
    public void itemStateChanged(ItemEvent ev){

    }
}

I am new on this java world, Sorry if I have not been able to help you to help me.:(

A: It is hard to tell without the stack trace of your exception or what happens in searchResult.getSelectedValue().
Perhaps try this:
public void valueChanged(ListSelectionEvent evt){
    if( evt.getValueIsAdjusting() ) return;

    // your code here

}


text:
Q: Javascript regex to find expression in a line then append to the end of that line I am busy parsing a text log to HTML and I am replacing tabs with HTML bullet tags
I need a regular expression to identify the beginning of a line and then append something to the end of it. eg:
config system accprofile
    edit "Number 1"
        set mntgrp read-write
    edit "read-only"
        set mntgrp read

config system 2
    edit "Number 2"
        set mntgrp read-write
    edit "read-only"
        set mntgrp read

Needs to be changed to:

config system accprofile

edit "Number 1"

set mntgrp read-write

edit "read-only"

set mntgrp read

config system 2

edit "Number 2"

set mntgrp read-write

edit "read-only"

set mntgrp read

I can identify the front of each row by searching for 'config' but I then need to append \n\t
 to the end of the line.
How can I do this?

A: You can do this way:

function myReplaceMethod (text) {
    console.clear();
    text = text.replace(/^(?:\t| {4}){2}(?!\s)(.*)/gm, '\t\t\t
$1
');
    text = text.replace(/^(?:\t| {4}){1}(?!\s)(.*)/gm, '\t\t
$1
\n\t\t\t
');
    text = text.replace(/^(?!\s)(.*)/gm, '\t
$1
\n\t\t
');
    text = text.replace(/(\n(\s*)
.*)(?:\n(?!\2\s)|(?![\s\S]))/gm, '$1\n$2
\n');
    text = text.replace(/^/, '
\n');
    text = text.replace(/$/, '\n
');
    text = text.replace(/(\n(\s*)(?:\t| {4})<\/ul>\n)(?=\n)/gm, '$1$2
');
    return text;
};

// ---

var string =
    'config system accprofile\n' +
    '    edit "Number 1"\n' +
    '        set mntgrp read-write\n' +
    '    edit "read-only"\n' +
    '        set mntgrp read\n' +
    '\n' +
    'config system 2\n' +
    '    edit "Number 2"\n' +
    '        set mntgrp read-write\n' +
    '    edit "read-only"\n' +
    '        set mntgrp read';

var output = myReplaceMethod(string);

console.log(output);


text:
Q: Updated a MySQL table with PHP This seems so easy.  My code checks out, and even if I run the resetting fuction in phpMyAdmin it works, but for some reason the table never updates when I run the php.
<?php
$servername="localhost" ;
$username="***" ;
$password="***" ;
$dbname="***" ;
$conn=new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT `Alert` FROM `poonpad_daveAlert` WHERE 1";
$result = $conn->query($sql);
if ($result == 1) {
    echo "wow, stuff is happening. resetting."; resetting();
} else {
    echo "this place is dead";
}

function resetting() {
    $sql = "UPDATE `poonpad_daveAlert` SET `Alert`=2 WHERE 1";
}

$conn->close();
?>

A: First, I'd use the below to execute the query.
$result = mysqli_query($conn,$sql);

Second, instead of (result==1) which I'm not sure is intended for what purpose, you should use (mysqli_num_rows($result)>0).
Third, for the resetting function, I think you need to mention the column name for the WHERE condition which you set to 1 as well as the main $sql query, and you don't need the WHERE if you have to select all rows.
"UPDATE `poonpad_daveAlert` SET `Alert`=2 WHERE [column-name]=1";


text:
Q: Why is the state not being updated? im trying to load images based on search query and able to drag them. For example when i type the word "Cat" i can see pictures of cats.
This is the code to type the search term:
<input type="text" value={this.state.searchedValue} onChange={(e)=>{this.setState({searchedValue: e.target.value})}}/>
<button onClick={() => this.handlePress()}>Search</button>

This is the function to load image and put it in the array based on search query
 handlePress = async () => {
        console.log("function is called");
        fetch('http://localhost:5000/testData?title_picture=' + this.state.searchedValue, {
            "method": "GET"
        })
         .then((response) => response.json())
         .then((responseData) => {
             this.setState({newData: responseData,
                            loaded:true})
             console.log(this.state.newData);
         })
    }

this is to load the images
{this.state.newData.map((data) => (

                                         ))}

When i do the console log inside of handlePress function I can see there is a picture inside the array.
But when I do it in ComponentDidMount() it shows me an empty array. How can I solve this? It cannot be an empty array, otherwise I can't drag the picture to the canvas.

A:
setState() does not always immediately update the component. It may
batch or defer the update until later. This makes reading this.state
right after calling setState() a potential pitfall.

https://reactjs.org/docs/react-component.html#setstate
In your case, I do not see any reason to operate on the state instead on the response value in the "handlePress" method.
If you really need it, then you can use setState callback
this.setState({
  newData: responseData,
  loaded:true
}, () => {
  console.log(this.state.newData)
})


text:
Q: pattern match for for date with symbol and end symbol I am getting an id in request with date in a specific format and no of hits they have tried on my API and if its last hit of that day then in form of string as an end.
my variable is
@Pattern(regexp = "^\\d{8}_.*", message = "Field 'batchId' invalid.please provide in format yyyyMMdd_<digit/end>")
    private String batch Id;

for example 20200509_001 for the first try or 20200509_9999999 for 9999999 hits ie format yyyyMMdd_no_of_tries
or 20200509_end ie yyyyMMdd_end for the last hit of the day (this end can be case insensitive.)
but 1 of them must be there, either no_of_tries or end 20200509_ this is invalid.
I need to prepare a pattern for this., so far I have come up "^\\d{8}_.*" it matches up to 8 digits, but I am not able to match digits or string after the _.

A: You could use this pattern:
^\d{8}_(\d+|end)$

This forces having digits or end at the end.
RegEx Demo
In your code:
@Pattern(regexp = "^\\d{8}_(\\d+|end)$", message = "Field 'batchId' invalid.please provide in format yyyyMMdd_<digits/end>")
    private String batch Id;

In case you want the end case insensitive:
@Pattern(regexp = "^\\d{8}_(\\d+|[Ee][Nn][Dd])$", message = "Field 'batchId' invalid.please provide in format yyyyMMdd_<digits/end>")
    private String batch Id;


text:
Q: joi validation for passing key value pair to other schema I have a object like
{
"a": {
    "name": "name of a",
    "year": "1"
},
"b": {
    "name": "name of b",
    "year": "2"
},
"c": {
    "name": "name of c",
    "year": "123456"
}
}

I'm using the below validation
var mainobject=Joi.object().pattern(/^/,subObject),
var suboject=joi.object({
name:joi.string(),
year:joi.string()
})

With this code, can I be able to iterate through objects?Is there anything wrong with my first code? Here in the main object, I used pattern for unknown keys. If I want to include one more data like details,
{
"a": {
"name": "name of a",
"year": "1"
"details":(should include name and year in "name":'name of a',"year":'1')
},
"b": {
"name": "name of b",
"year": "2"
},
"c": {
"name": "name of c",
"year": "123456"
}
}

How can I achieve the above solution? Please, help me out.

A: Use .unknown() API to allow unknown key.
var subobject = Joi.object({
  name:Joi.string(),
  year:Joi.string()
}).unknown();


text:
Q: Law of conservation of energy using work done vs maxwell theory of electromagnetic radiation Consider the motion of a charged particle in a uniform magnetic field. $\vec{B} = B_0(-\hat{k})$. Let the initial velocity with which it enters the field be $\vec{v_i} = v_0(-\hat{i})$. It is well known that it follows a circular path of radius $R = \frac{m v_0}{qB_0}$.

*

*Using Work Energy Theorem
$$∆K = W_B = \int \vec{F_B}.\vec{v}dt = \int q(\vec{v}×\vec{B}).\vec{v}dt = 0$$
$$ K_f = K_i $$ Therefore speed of the charged particle and radius of the path remains constant.

*Using Theory of Electromagnetic Radiation
Direction of velocity changes continuously. Therefore, the charged particle is in accelerated motion. Therefore, it continuously loses energy in the form of electromagnetic radiation. Therefore it must follow a spiral path.
Which of the following is correct?
N.B. I am high school student. So, please limit the answer within high school mathematics.

A: Yes, your second reasoning is correct. Accelerating charges do emit electromagnetic radiation, and what you described is known as synchrotron radiation. This energy loss increases sharply as the particle approaches the speed of light. In fact, this is a limiting factor of the maximum speed that particle accelerators can produce. If no additional energy is provided, then the particle will indeed spiral. The first one is just a simplification, since radiation from accelerating charges are not typically considered at the high-school level.
The power radiated by a point charge is given by the Larmor formula and a derivation of the angular distribution of the radiation (which is slightly more complicated) can be found here.

A: There is a formula for the Power of the emitted radiation due to an accelerating charge, the Larmor formula
$$P=\frac{q^2a^2}{6\pi\epsilon_0c^3}$$
where $a$ is the acceleration of the charge also $\frac{Bqv}{m}$.
In calculations the energy lost by radiation can often be ignored, you can put in various numbers to see the size of the effect, but technically you are right, the particle would follow a spiral path.


text:
Q: Projection of rational normal scroll I am looking at the classification of degree $d$ nondegenerate projective surface in $\mathbb{P}^d$. (See Theorem 8 in https://projecteuclid.org/download/pdf_1/euclid.kjm/1250776405).
One kind of such surfaces consists of projections of minimal surfaces in $\mathbb{P}^{d+1}$ from a point out side of the surface. (Minimal surfaces are also classified in the same paper, they are cones over rational normal curve, rational normal scrolls or the Veronese surface).
Let $S$ be a surface of minimal surface(degree $d$) in $\mathbb{P}^{d+1}$(assume it is not the Veronese surface), let $\pi$ be the projection from a point outside of $S$, so that $\pi(S)$ is of degree $d$.
My question is: what does $\pi(S)$ look like?
All I know $\pi(S)$ is a projective surface which can be singular. In fact it was proved in the above paper that $\pi(S)$ can be not normal and in that case the singular locus is a line.
I hope to obtain more info on $\pi(S)$ what we know on $S$ itself. In particular, I am interested in the following things:
1. when $S$ is a cone, it $\pi(S)$ is a cone (of some sort)?

*When $S$ is a scroll, what is the image of a line?

Thanks!


text:
Q: Coffeescript/jQuery Pattern: Caching Data Across Events I have a list of items that are abstracts, and can be made to expand via Ajax on click. I'v written the following code in Coffeescript:
current_open_row = null

$('li.faq-item').live 'click', (event) ->
  $.post("/faqs/update_rows", {old_row_id: current_open_row, new_row_id: $(this).attr('id')}, (data) ->
    replace_items data
  , 'json')
  current_open_row = $(this).attr('id')

This doesn't read like smooth Coffeescript and I find myself thinking, "what could I have done better," but in particular, instantiating the current_open_row variable outside the scope of the click handler feels strange. Not doing this, of course, causes a new instantiation upon entry to the handler, which is always undefined.
Other than refactoring $(this).attr('id') into a variable, is there anything that jumps out as ugly, suboptimal, unreadable, etc., or is this pretty much the way of it?
Thanks!

A: Well, first off, I think you'll find yourself switching to camelCase eventually... I know that many people strongly prefer the readability_of_underscores, but every library you interact with (including jQuery) uses camelCase. Just something to keep in mind.
Setting that aside, the issue of having to scope variables with = null is a good one. I've tried to persuade Jeremy that there should be a nicer scoping syntax, but he's firmly against it. So I'd suggest moving the variable to an object property. Fortunately, this is jQuery, so there are plenty of places to stick data. How about using the list's .data method? This has an additional advantage: If you want to do this on multiple lists in the future (with one current_open_row in each list), you won't have to change your code one bit. Just add more lists with .faq-item children to the markup.
One more minor point: You give the post call a callback
(data) -> replace_items data

If that's all you're doing, why not just pass replace_items directly? :)
I'd also put each argument to the post function on its own line for readability. Key-value pairs are automatically combined into a single object, even without curly braces. Here's how it all looks:
$('li.faq-item').live 'click', (event) ->
  $row = $(this)
  $list = $row.parent()
  row_id = $row.attr 'id'

  $.post(
    "/faqs/update_rows",
    old_row_id: $list.data('current_open_row'),
    new_row_id: row_id,
    replace_items,
    'json'
  )

  $list.data 'current_open_row', row_id


text:
Q: I have a gridview in my main activity but the app crashes when i tap an image of the grid after device orientation is changed The app crashes only if the device orientation is changed.
Here is the main activity:
public class MainActivity extends AppCompatActivity implements Listener {

    boolean mTwoPane;

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

        if (findViewById(R.id.fragment_two) != null) {
            mTwoPane = true;

        } else {
            mTwoPane = false;
        }

        if (null == savedInstanceState) {
            MoviesFragment moviesFragment = new MoviesFragment();
            moviesFragment.setListener(this);
            getSupportFragmentManager().beginTransaction().add(R.id.fragment_movies, moviesFragment).commit();
        }
    }

    @Override
    public void setSelectedMovie(MoviesData.ResultsBean movie) {

        if (mTwoPane == true) {
            DetailFragment detailsFragment = new DetailFragment();
            Bundle extras = new Bundle();
            extras.putSerializable("MoviesData", movie);
            detailsFragment.setArguments(extras);

            getSupportFragmentManager().beginTransaction().replace(R.id.fragment_two, detailsFragment).commit();

        } else {

            Intent intent = new Intent(this, DetailActivity.class);
            intent.putExtra("MoviesData", movie);
            startActivity(intent);

        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.sort_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();

        if (id == R.id.action_settings) {
            startActivity(new Intent(this, SettingsActivity.class));
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

}

The main Fragment code:
public class MoviesFragment extends Fragment {

    ArrayList<MoviesData.ResultsBean> moviesList;
    private ImagesAdapter moviesAdapter;
    private ArrayList<String> mImageUrlList;
    Listener mListener;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_movies, container, false);

        mImageUrlList = new ArrayList<String>();

        moviesAdapter = new ImagesAdapter(getActivity(), mImageUrlList);
        GridView list = (GridView) rootView.findViewById(R.id.gridview_movies);
        list.setAdapter(moviesAdapter);
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                Toast.makeText(getActivity(), "title: " + moviesList.get(position).getOriginal_title(), Toast.LENGTH_SHORT).show();

                mListener.setSelectedMovie(moviesList.get(position));
            }
        });

        return rootView;

    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);

    }

    public void updateMoviesDisplay() {
        FetchMoviesTask fetchMoviesTask = new FetchMoviesTask();
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
        String type = prefs.getString(getString(R.string.pref_display_type_key),
                getString(R.string.pref_display_categeory_defualt));
        String pop = "popular";

        //String displayType="popular?";
        Log.i("type00", type);
        System.out.println("type= " + type);
        if (type.equals("favourite")) {
            System.out.println("type= " + type);
            mImageUrlList.clear();
            MovieDb db = new MovieDb(getActivity());
            moviesList = db.getAllMovie();
            List<MoviesData.ResultsBean> mResultsBean;
            mResultsBean = db.getAllMovie();
            for (int i = 0; i < mResultsBean.size(); i++) {
                mImageUrlList.add(mResultsBean.get(i).getPoster_path());

            }

            moviesAdapter.notifyDataSetChanged();
        } else if (type.equals("popular")) {
            fetchMoviesTask.execute("popular");
        } else if (type.equals("top_rated")) {
            fetchMoviesTask.execute("top_rated");
        }
        Log.i("kkkk", String.valueOf(type.equals(pop)));

    }

    public boolean onOptionsItemSelected(MenuItem item) {

        /* FetchMoviesTask task = new FetchMoviesTask();
        if (id == R.id.popular) {
            task.execute("popular");
            return true;
        } else if (id == R.id.top_rated) {
            task.execute("top_rated");
            return true;
        } else if (id == R.id.favourite_sort) {
            mImageUrlList.clear();
            MovieDb db = new MovieDb(getActivity());
            moviesList = db.getAllMovie();
            List<MoviesData.ResultsBean> mResultsBean;
            mResultsBean = db.getAllMovie();
            for (int i = 0; i < mResultsBean.size(); i++) {
                mImageUrlList.add(mResultsBean.get(i).getPoster_path());

            }
            moviesAdapter.notifyDataSetChanged();
        }
        moviesAdapter.notifyDataSetChanged();*/
        return true;
    }

    public void setListener(Listener listener) {
        this.mListener = listener;
    }

    public static String BuildImageUrl(String imagePath) {
        Uri uri = Uri.parse("http://image.tmdb.org/t/p/").buildUpon().appendEncodedPath("w342").appendEncodedPath(imagePath).build();
        return uri.toString();
    }

    public class FetchMoviesTask extends AsyncTask<String, Void, MoviesData> {

        @Override
        protected MoviesData doInBackground(String... params) {

            try {
                return new FetchMovies().fetchMovieData(params[0], 1 + "");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(MoviesData movie) {
            super.onPostExecute(movie);
            if (movie == null) {
                Toast toast = Toast.makeText(getActivity(), "No internet connection", Toast.LENGTH_LONG);
                toast.show();
                return;
            }

            moviesList = movie.getResults();

            mImageUrlList.clear();
            for (ResultsBean bean : movie.getResults()) {

                mImageUrlList.add(BuildImageUrl(bean.getPoster_path()));

            }

            moviesAdapter.notifyDataSetChanged();

        }
    }

    @Override
    public void onStart() {
        super.onStart();

        updateMoviesDisplay();
    }

}

I get a nullpointerexception:

Attempt to invoke interface method 'void
  com.example.mohamed.movieapp.Listener.setSelectedMovie(com.example.mohamed.movieapp.Data.MoviesData$ResultsBean)'
  on a null object reference
                                                                                at com.example.mohamed.movieapp.MoviesFragment$1.onItemClick in this
  line in "MoviesFragment"
  mListener.setSelectedMovie(moviesList.get(position)); in the
  setOnItemClickListener method

A: When you rotate the device the savedInstanceState is NOT null. In your activity you ONLY set listener if the savedInstanceState is null. Therefore in the case of device rotation the mListener object in your fragment is NULL. Therefore invoking anything on it will produce NPI.
You need to find fragment by tag or id using SupportFragmentManager in case the savedInstanceState is NOT null, like in case of any configuration change, like, say, device rotation, and in that case set the Listener to a fragment object you find.


text:
Q: How do I add an additional IP address to an interface in Ubuntu 14 I want to have the wired interface simultaneously obtain a DHCP address, and also alias a fixed address so I can communicate with a device with a fixed IP address on a different subnet over the same link.
When searching for IP address aliasing in Ubuntu, I found this article How do I add interface aliases using Network Manager GUI?. Unfortunately, the Edit Connections GUI in Ubuntu 14 does not have the "additional addresses" button.
Where has this functionality moved?

A: In order to add an address temporarily use ip:
ip a add 192.168.178.2/24 dev enx0050b60c19af

For example to install OpenWRT on some old devices:
https://openwrt.org/toh/avm/avm_fritz_wlan_repeater_450e

A: Skip the gui and do it via command line.
The following link provides detailed information on how to create the alias on a temporary basis, as well as how to edit the interfaces file to make the change permanent.
http://www.cyberciti.biz/faq/linux-creating-or-adding-new-network-alias-to-a-network-card-nic/
Information from site in case of site death:
ifconfig command line
You can use ifconfig command to configure a network interface and alias. For example:

*

*eth0 NIC IP 192.168.1.5

*eth0:0 first NIC alias: 192.168.1.6

To setup eth0:0 alias type the following command as the root user:
# ifconfig eth0:0 192.168.1.6 up

Verify alias is up and running using following command:
# ifconfig -a

# ping 192.168.1.6

However, if you reboot the system you will lost all your alias. To make it permanent you need to add it network configuration file.
# vi /etc/network/interfaces

Append the following to the file (This is in addition to existing information, not a replacement for it)
auto eth0:1
iface eth0:1 inet static
name Ethernet alias LAN card
address 192.168.1.7
netmask 255.255.255.0
broadcast 192.168.1.255
network 192.168.1.0

Save and close the file. Restart the network:
# /etc/init.d/networking restart

A: You can use the below steps to add IP Address in a ubuntu network interface.

*

*Login to Ubuntu server via ssh.

*Hit the Following Command.
nano /etc/network/interfaces

*Enter the interface alias eth0:0 as mentioned in below.
(Note: If you already have interface alias eth0:0, you can add eth0:1 or eth0:2 for additional IP Address)
#secondary ip address
auto eth0:0
iface eth0:0 inet static
address 1*3.2*8.149.***
netmask 255.255.255.***

*Below Command will up the added interface alias within the network.

ifconfig eth0:0 1*3.2*8.149.*** up

*Restart the network service.

/etc/init.d/networking restart

*check the newly added ip address with the below command.

ifconfig
It is Done.

A: I just learned a trick from my colleague which involve the following:
If say eth_lan0 is set as the name of your wired network and has first been configured with the IP 192.168.1.2, say with something like netplan, you can then add an alias to connect to another internal network say with an IP with the pattern 10.42.0.x with the following:
sudo ifconfig eth_lan0:1 10.42.0.2

This assumes that the IP 10.42.0.2 has not yet been assigned to your LAN and that your host is connected to both networks, one with IP 192.168.1.x and the other with 10.42.0.x. Check if you have been successful by running ifconfig to see if the alias has been set. Then, it would be recommended to ping the hosts you are trying to connect on the two local networks to make sure everything runs as expected.


text:
Q: How to only allow A-Z, 0-9 in Perl CGI form + How to hide the database name/user/password #!/usr/bin/perlml
use CGI;
print "Content-type:text/html\n\n";

# read the CGI params
my $cgi = CGI->new;
my $username = $cgi->param("username");
my $password = $cgi->param("password");
$username =~ s/(\/|\.\.)//g;
$password =~ s/(\/|\.\.)//g;

use DBI;
$dbh = DBI->connect('DBI:mysql:Database', 'username', 'password'
               ) || die "Could not connect to database: $DBI::errstr";
$dbh->do('CREATE TABLE new_test (username VARCHAR(40), password VARCHAR(40))');
my $s = "insert into new_test(username,password) values (?, ?)";
$dbh->do( $s, undef, $username, $password) or die $dbh->errstr;

$dbh->disconnect();

The Html form I'm using, uses UTF-8 encoding. The above is a test perl script I'm using, so far, I can disallow the special characters if they are input alone, but cannot do so, if they are with some text.
"{}" is disallowed
"rf{}" is still working

about the second part:
I read somewhere, that its possible to import the connection settings from other perl script. But not sure how to do that.
+++++++++++++++++++++++
EDIT
++++++++++++++++++++++++
#!/usr/bin/perlml
use cPanelUserConfig;
use CGI;

print "Content-type:text/html\n\n";

# read the CGI params
my $cgi = CGI->new;
my $username = $cgi->param("username");
my $password = $cgi->param("password");
if ($username =~ /[^a-zA-Z0-9]/) { die "Illegal characters" }
if ($password =~ /[^a-zA-Z0-9]/) { die "Illegal characters" }

my $filexyz = './file.cnf';

use DBI;
my $dsn =
  "DBI:mysql:Python;" .
  "mysql_read_default_file=$filexyz";

$dbh = DBI->connect($dsn, undef, undef
               ) || die "Could not connect to database: $DBI::errstr";

$dbh->do('CREATE TABLE new_test (username VARCHAR(40), password VARCHAR(40))');
my $s = "insert into new_test(username,password) values (?, ?)";
$dbh->do( $s, undef, $username, $password) or die $dbh->errstr;

$dbh->disconnect();


text:
Q: Including a Trend Component in a Rolling Regression I am new to rolling regressions, but am currently trying it for my current research. As the post title suggests, I'm trying to assess my specification. What I have now is:
ŷ = β0 + β1*x + ε

But I'm wondering if I should include a time trend as a right hand side variable. My data structure is time series, 5 years of daily observations. The data exhibit a unit root, I should add. I have looked in the literature, I haven't seen anyone include a time trend. But since my data have a unit root, it almost seems like I should. Perhaps there are many different conventions for denoting time trend and I misunderstood. My statistical package uses the following, which is directly included with the other right hand side variables.
@trend

I'm unclear because if I am adding a time trend, it almost seems to defeat the purpose of a rolling regression (90 day window, 10 period step) of examining the changes in the coefficients over time. Or on the other hand, if I'm not, I wonder if the trend will behave the same way in a static OLS regression, and account for trending in the time series, making it clearer how x may affect y, and ameliorate inflated r-squared values due to trending, among other things.
Which specification is the best way to go?

A: I will take a crack at this now that I've had about 1 week or so to grapple with this situation. I think I can now demystify some of the underlying concepts, but if someone can outdo me in this regard then I would invite such answers as well.
The short answer is: Probably a deterministic time trend is not needed. If ∆e = 0:
∆y = yt1-yt0 = ∝

A trend component is justified if there are changes in y as a result of ∝ (trend coef) only.  Unless your window size at each iteration is very large then odds are you won't have a trend for that sub-section. In other words the series at each iteration will likely be a stationary process. A Dicky-Fuller test can come in handy if you don't feel eye-balling the graph is the right way to go.
Seasonal trends are a different story. One tool available is to make sure the sample at each iteration has equal exposure to seasonal trends. The window size will depend on the frequency of your data.


text:
Q: Can't turn on MySQL log for slow queries I'm trying to log MySQL slow queries, but I can't turn it on, I will explain all my steps:

*

*I Edit my.cnf and add the following lines

long_query_time = 1
slow_query_log_file = /home/mysql/slow_queries.log
slow_query_log = 1

*

*Give mysql user permitions to write on the file

chown -R mysql:mysql /home/mysql

*

*Restart the service

/etc/init.d/mysqld restart
I check the MySQL logs and don't find any error during the restart!

A: This depend of you MySQL version. If you're running MySQL 5.0, you need to use :
log_slow_queries = 1

http://dev.mysql.com/doc/refman/5.0/en/server-options.html#option_mysqld_log-slow-queries
And only with new version (MySQL 5.1), you can use this :
slow_query_log = 1

http://dev.mysql.com/doc/refman/5.1/en/server-system-variables.html#sysvar_log_slow_queries


text:
Q: Extending an existing web2py database I have an existing web2py application.  Now I need to create a new registration form using a db Table that includes a Field that requires a Row from a different Table.
This should be similar to what you commonly see with Country Fields in registration forms, except I want people to be able to add values to the 'Country' Table if the value doesn't already exist.

A: Making a small improvement to the previous response:
# create auth
auth = Auth(db)
# create the country table
db.define_table('country',
                Field('name'),
                Field('desc'),
                format = '%(name)s')
# say you want to add it to auth_user table (not yet created)
auth.settings.extra_fields['auth_user']=[Field('country','reference country')]
# ask auth to make the auth tables, including auth_user
auth.define_tables()

JMax is right. We are more responsive on the web2py mailing list.

A: You can use a one to many relation (cf. the book):
db.define_table('country',
                Field('name'),
                Field('desc'))

db.define_table('user',
                Field('name'),
                Field('origin'), db.country))

Btw, you can ask your questions on the web2py Googlegroup where Massimo will probably be more reactive


text:
Q: File conflig on package updates I have a CentOS 5.X with Kloxo panel.
It's a test enviroment but i have 2 pages there.
I noticed theres 113 packets to be update (php, kloxo, wget, openssl, and a long etc)
But when i do the command
yum update

I get a conflig with /etc/my.cnf file.
This is the message

Transaction Check Error:
file /etc/my.cnf from install of mysql-5.0.95-1.el5_7.1.i386
  conflicts with file from package mysql-libs-5.0.92-lxcenter.1.i386
file /usr/lib/mysql/libmysqlclient.so.15.0.0 from install of
  mysql-5.0.95-1.el5_7.1.i386 conflicts with file from package
  mysql-libs-5.0.92-lxcenter.1.i386
file /usr/lib/mysql/libmysqlclient_r.so.15.0.0 from install of
  mysql-5.0.95-1.el5_7.1.i386 conflicts with file from package
  mysql-libs-5.0.92-lxcenter.1.i386

The problem is, i dont really know what is happening here.
For me, there is 2 installs of mysql.
One is from lxcenter (kloxo) an the other one maybe was there from the beginin?
If it's that, how i can uninstall the second one and don't touch the kloxo mysql?
Thanks a lot!

A: If you want to uninstall the original one you have to find out the name of the package and be careful when uninstalling it. You will find out name of the packages by running:
rpm -qa|grep mysql

then once you are sure you found the right package to remove you'd have to run:
rpm -e <package_name>

You might have to run it with --no-deps option so that it doesn't mess other things up - also you might want to try the --test option which is basically dry-run and see whether everything will go fine. It looks like the kloxo mysql libs are conflicting with the ones which are already in place on the server.


text:
Q: Javascript How can I tell if an object is a Map Iterator? I'm writing a some NodeJS code that is being passed a Map Iterator.  What is the correct way to examine a Javascript object to determine that it is a "Map Iterator"?
I've tried:
typeof myMap.keys() returns 'Object'
typeof myMap.keys().next === 'function' returns true

So I'm checking to see if the object being passed has a next() function.  Is there a better way to do this?
The Chrome debugger the object is a Map Iterator, so I'm guessing there is a more correct Javascript way to do this.

A: If all you want to do is check if it's a Map (which can be iterated over), you can do that with myMap instanceof Map, which returns a boolean.

A: You you get the Symbol.toStringTag property of the object

var m = new Map;
m.set(1, [123]);
var gen = m.entries();

console.log(gen.toString()); // "[object Map Iterator]";
console.log(gen[Symbol.toStringTag] === "Map Iterator"); // true