text:
Q: How to insert values into a sqlite database using beans and retrieving those table values into json array Inserting values into table using beans
public static void addGetAssessmentDetail(Context context,
        GetAssessmentBean getassessmentDetail) {
    DBHelper dbHelper = null;
    SQLiteDatabase sqlDBRead = null;
    SQLiteDatabase sqlDBWrite = null;
    try {

        dbHelper = new DBHelper(context, LektzDB.DB_NAME, null,
                LektzDB.DB_VERSION);
        sqlDBRead = dbHelper.getReadableDatabase();
        sqlDBWrite = dbHelper.getWritableDatabase();

        ContentValues book = new ContentValues();
        book.put(TB_FinalAssessmentValues.CL_1_ID, getassessmentDetail.getId());
        book.put(TB_FinalAssessmentValues.CL_2_USER_ID , getassessmentDetail.getUser_id());
        book.put(TB_FinalAssessmentValues.CL_3_BOOK_ID, getassessmentDetail.getBook_id());
        book.put(TB_FinalAssessmentValues.CL_4_CHAPTER_ID,
                getassessmentDetail.getChapter_id());
        book.put(TB_FinalAssessmentValues.CL_5_QUESTION_TYPE,
                getassessmentDetail.getQuestion_type());
        book.put(TB_FinalAssessmentValues.CL_6_QUESTION_ID,
                getassessmentDetail.getQuestion_id());
        book.put(TB_FinalAssessmentValues.CL_7_OPTION_ID,
                getassessmentDetail.getOption_id());
        book.put(TB_FinalAssessmentValues.CL_8_MARK,
                getassessmentDetail.getMark());
        book.put(TB_FinalAssessmentValues.CL_9_NOTES,
                getassessmentDetail.getNotes());
        book.put(TB_FinalAssessmentValues.CL_10_MATCH_OPTION, getassessmentDetail.getMatchOption());
        book.put(TB_FinalAssessmentValues.CL_11_DRAG_VALUES,
                getassessmentDetail.getDragValues());
        book.put(TB_FinalAssessmentValues.CL_12_ADDED_TIME,
                getassessmentDetail.getAdded_time());
        Log.i("", "assessment values insertion success" );

    } catch (Exception e) {
        e.printStackTrace();
    }

}

And trying to retrieve those table values into JSON array
public JSONArray getFullAssessmentData(Context mContext, String bookid,
        int UserId) {
    DBHelper dbh = new DBHelper(mContext, LektzDB.DB_NAME, null,
            LektzDB.DB_VERSION);
    SQLiteDatabase db = dbh.getReadableDatabase();
    JSONArray resultSet = new JSONArray();
    try {
        Cursor c = db.rawQuery("SELECT * FROM " + TB_FinalAssessmentValues.NAME
                + " WHERE " + TB_FinalAssessmentValues.CL_3_BOOK_ID+ "='"+ bookid + "'", null);
        Log.i("tag", "msg vachindi");

        if (c.getCount() > 0) {

            c.moveToFirst();
            do {
                c.moveToFirst();
                while (c.isAfterLast() == false) {
                    int totalColumn = c.getColumnCount();
                    JSONObject rowObject = new JSONObject();
                    for (int i = 0; i < totalColumn; i++) {
                        if (c.getColumnName(i) != null) {
                            try {
                                rowObject.put(c.getColumnName(i),
                                        c.getString(i));
                            } catch (Exception e) {
                            }
                        }
                    }
                    resultSet.put(rowObject);
                    c.moveToNext();
                }

                c.close();
                db.close();
                    }
             while (c.moveToNext());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return resultSet;
}

And finally trying to store those values into JSON array
JSONArray fullassessmentjson =  rdb.getFullAssessmentData( getContext(), BookId, UserId);
                    Log.i("Tag123456","Finalcheck"+fullassessmentjson);

DBHelper
db.execSQL("CREATE TABLE IF NOT EXISTS " + TB_FinalAssessmentValues.NAME + "("
                + TB_FinalAssessmentValues.CL_1_ID + " TEXT, "
                + TB_FinalAssessmentValues.CL_2_USER_ID  + " TEXT, "
                + TB_FinalAssessmentValues.CL_3_BOOK_ID + " TEXT, "
                + TB_FinalAssessmentValues.CL_4_CHAPTER_ID + " TEXT, "
                + TB_FinalAssessmentValues.CL_5_QUESTION_TYPE + " TEXT, "
                + TB_FinalAssessmentValues.CL_6_QUESTION_ID + " TEXT, "
                + TB_FinalAssessmentValues.CL_7_OPTION_ID + " TEXT, "
                + TB_FinalAssessmentValues.CL_8_MARK + " TEXT, "
                + TB_FinalAssessmentValues.CL_9_NOTES + " TEXT, "
                + TB_FinalAssessmentValues.CL_10_MATCH_OPTION + " TEXT, "
                + TB_FinalAssessmentValues.CL_11_DRAG_VALUES + " TEXT, "
                + TB_FinalAssessmentValues.CL_12_ADDED_TIME + " TEXT)");

and the error is its showing nothing in the Json array

A: Seems like you're adding the values to your ContentValues object, but do not perform the actual insert into the database.
(because of this you're basically querying an empty table)
You should call the insert() method of SQLiteDatabase at the end of addGetAssessmentDetail() to insert the data into your table:
sqlDBWrite.insert(TABLE_TO_INSERT, null, book);


text:
Q: Как получить значения из ArrayAdapter? Создал адаптер, унаследовав его от ArrayAdapter. Существует список List View, который заполняет пользователь в ручную. Стоит задача, после нового включения приложения(если список ранее составлялся) вывести список на экран.
Адаптер:
     public class MyAdapter extends ArrayAdapter<Info> {

     ArrayList<Info> nameInfo = new ArrayList<Info>();

     public MyAdapter(Context context, ArrayList<Info> nameInfo) {
     super(context, 0, nameInfo);

     }

     @Override
     public View getView(int position, View convertView, ViewGroup parent) {

     Info data = getItem(position);
     if (convertView == null) {
        convertView =
    LayoutInflater.from(getContext()).inflate(R.layout.row, parent, false);
    }

    TextView column1 = (TextView) convertView.findViewById(R.id.col1);
    TextView column2 = (TextView) convertView.findViewById(R.id.col2);

    column1.setText(data.par1);
    column2.setText(data.par2);

    return convertView;
    }
   }

`
Вот список и адаптер в мэйн активити:
    MyAdapter = new MyAdapter(this, nameInfo);

    ListView lvMain = (ListView) findViewById(R.id.lvMain);
    lvMain.setAdapter(MyAdapter);

A: Определите метод на получением айтемов getItems:
public class MyAdapter extends ArrayAdapter<Info> {

   List<Info> nameInfo = new ArrayList<Info>();

   public MyAdapter(Context context, List<Info> nameInfo) {
     super(context, 0, nameInfo);

   }

   public List<Info> getItems(){
        return nameInfo ;
   }
   [...]
}

Ну и как я в прошлом вашем вопросе описывал:
public void onSaveInstanceState(Bundle savedState) {

    super.onSaveInstanceState(savedState);

    // здесь берём данные из адаптера
    List<Info> items = mAdapter.getItems();
    savedState.putParcelableArrayList("my_data", items);

}

Для этого ещё в вашем классе Info надо реализовать Parcelable интерфейс.

A: Как я понял, нужно чтобы сохранялся ListView после выхода из приложения.
Тогда лучше использовать ArrayAdapter. В onDestroy (А лучше в onPause) вытащить из него ArrayList, преобразовать его в массив и сохранить в SharedPrefences.
При загрузке из SharedPrefences доставать массив, из него сделать ArrayList и из него создать адаптер.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to bypass Facebook "Social Reader"-type apps, to view content without installing? In Facebook, some links to articles or videos appear to be genuine links, but in fact there are leading to some "content viewing" Facebook apps, like "Dailymotion", "The Guardian", or "Yahoo!". Those apps usually require access to my email address, basic info, birthday, location, plus right to post on my behalf. Some even say in small letters "To use this app, you will be upgraded to Facebook Timeline":

Workaround:

*

*Copy the name of the article/video

*Paste it into Google within quotes

*First result is the original unencumbered content.

I don't want to install Facebook spyapps that provide zero value, so I do this every time.
QUESTION:Is there a Greasemonkey script or similar, that would perform these 3 steps for me?
I am using Chrome on Linux.
I hesitated to post this question on WebApps, but over there they are clear that such questions should be posted on SuperUser.

A: The latest version of the FB Purity browser extension (compatible with Firefox, Chrome, Safari and Opera) has a built in option for fixing these redirect links, see here: http://www.fbpurity.com

A: Some apps that ask if you would give permission to post on your behalf, or use your email, sometimes you can deny this esp. if it is a reputable company or trying to be (Yahoo, etc) and still get through without consequence. Not really a "best answer" but a work around if need be.

A: I created a user script for Greasemonkey which does this after not finding a good solution for Firefox. It works in Chrome too. You can find it on here on userscripts.org.

A: If you're running chrome, there's Facebook Unsocial Reader that will fix those links

Rewrites Facebook Social Reader links to just be links and not require you to install.
Facebook Unsocial Reader rewrites Facebook's Social Reader links to just be Google "I'm feeling lucky" searches for the article's title. Now you don't need to install an app and provide your demographic information to the publisher of the content for content that's free anyway.

A: I know for a fact that with links to The Guardian if you attach ?fb=native to the end of the link, it will direct the link to the proper page and not the social reader app page.


text:
Q: Converting weeks of year to dates I have a data set with number of weeks from the beginning of the year (%W), which I would like to convert to dates in order to plot it using date on x-axis
dat <- structure(data.frame(week = c(22, 34, 15), year = c(2009, 2009, 2010), x = c(3.4, 5.2, 1.3)))

I try to convert the weeks based on earlier questions here, but end up getting "YYYY-10-01" for each date.
as.Date(paste("01", dat$week, dat$year, sep = "-"), format = "%d-%W-%Y")

Why is this and how can do it right?

A: Try this instead:
as.Date(paste("1", dat$week, dat$year, sep = "-"), format = "%w-%W-%Y")

A week and a year don't specify a date, so you do need a "day", but you need the "day of the week", or %w, rather than "day of the month", or %d. In this case, I used Monday (i.e. 1). Also, apparently %w doesn't like leading zeros.


text:
Q: ¿Cómo usar JSON_SEARCH dentro de JSON_EXTRACT en MySQL (con ruta dinámica)? Buen día
Tengo una situación.
tengo un campo tipo json array y necesito acceder a un campo con su respectivo index
ej:
la tabla bill tiene un campo details que es de tipo json array y en una de sus iteraciones arroja algo como esto:
[
   {
      "id":"6",
      "code":"85967412",
      "name":"ASROCK RX VII 16GB",
      "unitCost":2998800,
      "quantity:"2"
   },
   {
      "id":"7",
      "code":"32+612",
      "name":"CAMARA LOGITECH C920",
      "unitCost":257040,
      "quantity:"3"
   },
   {
      "id":"8",
      "code":"8796587",
      "name":"COOLER MASTER MASTERCASE H500P MESH GUN ME",
      "unitCost":785400,
      "quantity:"4"
   }
]

Y requiero que muestre la cantidad cuando el code es es 32+612 en todas la iteraciones pero no se como redactar la consulta, intente con JSON_SEARCH y JSON_EXTRACT pero aun no lo consigo.
para el caso específico de esta iteración sería algo como esto:
SELECT details->>'$[1].code' as Code FROM bills

sin embargo en las otras iteraciones el índice del objeto json será diferente.
¿Cómo podría construir la consulta?
Muchas gracias.


text:
Q: Change logo image in VLC player dynamically I want to control VLC player via command line in windows 7 64 bit. I want to overlay an image in particular position on a video stream. This can be done easily via vlc command line option.
Now I want to change this logo image while video is playing. Is there any way to o it? ie change logo image while vlc player play some video.
I will call this commands from net beans Java....

A: Have a look at vlcj. (I never used it but looking at the listed features it seems like it's capable of what you are trying to achieve.)


text:
Q: Matlab error using nlinfit, ill-conditioned Jacobian I am using the nlinfit function in Matlab to plot a line of best fit to sets of data that I have. The function I am using is f = @(a, b) 1 - exp(-(x/a)^b). For most of the data sets this works fine, but for some the graphs are way off, and I'm getting the warning:

Warning:
  The Jacobian at the solution is ill-conditioned, and some model parameters may not be estimated well (they are not identifiable). Use caution in making predictions.

I found that usually we roughly have a=5, b=5, but that for the incorrect fits nlinfit gives a=0, b=-0.02 or a=4.6, b=174. I have included the graphs and data points below.

x    y3    y2    y1
0.8  0     0.08  0
1.8  0     0     0.17
2.8  0     0     0
3.3  0.08  0     0
3.7  0     0     0.17
4.0  0     0     0.33
4.6  0.75  0.67  0.67
4.9  0.92  0.42  0.75
5.3  0.83  0.5   0.83
5.8  0.92  0.83  1
6.8  1     0.92  1
7.8  1     1     1

What is going wrong?!


text:
Q: adding slidedown event on a jquery menu Ok I have this code:

var timeout         = 0;
var closetimer      = 0;
var ddmenuitem      = 0;

function jsddm_open()
{   jsddm_canceltimer();
jsddm_close();
ddmenuitem = $(this).find('#as').eq(0).css('visibility', 'visible');
bb = $(this).css("background","#0099FF");
}

function jsddm_close()
{
if(ddmenuitem)
ddmenuitem.css('visibility', 'hidden');
}

function jsddm_timer()
{   closetimer = window.setTimeout(jsddm_close, timeout);
bb = $(this).css("background","none");
}

function jsddm_canceltimer()
{   if(closetimer)
    {   window.clearTimeout(closetimer);
        closetimer = null;}}

$(document).ready(function()
{

$("#sinputbox").watermark("Search item here...");
$('#menu > li').bind('mouseover', jsddm_open);
$('#menu > li').bind('mouseout',  jsddm_timer);});

document.onclick = jsddm_close;

Home

Gallery

Clothing

Furniture

Household-items

Automotive

Food

About

Contact

Now, I am planning to add a slidedown to that dropdown menu but I don't know how. I tried to add this line: "$('this').slideDown('slow');" inside this function: "function jsddm_timer()" but nothing work so far. Could someone here help me to this pls? I'm open in any suggestion thanks.

A: Try this JSFiddle and tell if you want functionality like this:
Updated Link:
http://jsfiddle.net/qFEJh/1/
And this is the UPDATED Code
function jsddm_open()
{
    $(this).find('#as').slideDown('slow');
    bb = $(this).css("background","#0099FF");
}

function jsddm_close()
{
    $(this).find('#as').slideUp('slow');
}

$(document).ready(function()
{
    $('#menu > li:has(ul)').hover(jsddm_open,jsddm_close);
});

document.onclick = jsddm_close;

A: In your case wouldn't it be:
$(this).find('#as').eq(0).slideDown('slow');

Assuming you put this in your jsddm_open function.


text:
Q: Keras Input add dimension autoly error I am a new hand of using Keras. After searching without results. Please Please save me!
Here is my problem:
print(input_shape)

X_input = Input(input_shape)

print(X_input)

result in
(600, 64, 64, 3)
Tensor("input_5:0", shape=(?, 600, 64, 64, 3), dtype=float32)

It add one dimension autoly and error
ValueError: Input 0 is incompatible with layer conv0: expected ndim=4, found ndim=5

A: Your problem lies in the fact that in keras a first dimension is connected to a number of samples (I guess it's 600 in your case) and it's skipped while defining an input shape. So try:
X_input = Input(input_shape[1:])

in order to skip a sample dimension.


text:
Q: How to add iOS Storyboard to an existing C++ project Working with an existing Qt Xcode project implemented in C++. Therefore the application launches by the execution of the main
int main(int argc, char **argv)
{
    QApplication app(argc, argv);
    MainWindow window;
    window.show();

    return app.exec();
}

How can I add a Storyboard as an initial View Controller under iOS? I suppose I have to change the main.cpp into a main.mm and invoke the Storyboard instead of the MainWindow?!?
Normally each Objective-C or Swift project has it's own Application Delegate, which doesn't exists inside a C++ Xcode project.
EDIT: Another and maybe the easiest solution is to create a new Swift/Objective-C project and include the C++ Xcode project.


text:
Q: Rest API method get How should I check, that I receive an entity from DB and return correct response? I use restController.
I want to check that I receive a user from DB or not. If I found the user, I want to return the user and HttpStatus.OK, if not - HttpStatus.NOT_FOUND.
public ResponseEntity<User> getUser(@PathVariable("id") int id) {
        User User= this.userService.getUserById(id);
        ResponseEntity<User> responseEntity = new ResponseEntity<>(HttpStatus.NOT_FOUND);
        if (Objects.nonNull(user)) {
            responseEntity = new ResponseEntity<>(user, HttpStatus.OK);
        }
        return responseEntity;
    }

A: In simple terms, if you want to use Optional for checking availability of user in the database:
public ResponseEntity<User> getUser(@PathVariable("id") int id) {
    User User= this.userService.getUserById(id);
    ResponseEntity<User> responseEntity = new ResponseEntity<>(HttpStatus.NOT_FOUND);
    if (Optional.ofNullable(user).isPresent()) {
        responseEntity = new ResponseEntity<>(user, HttpStatus.OK);
    }

    return responseEntity;
}

A: Path parameters can't be made optional, you'll have to map 2 URLs to your get controller method.
Try below:
@RequestMapping(method=GET, value={"/", "/{id}"})
 public ResponseEntity<User> getUser(@PathVariable Optional<Integer> id) {

    if(!id.isPresent()){
      return ResponseEntity.notFound().build();
    }
    User User= this.userService.getUserById(id);
    ResponseEntity<User> responseEntity = new ResponseEntity<>(HttpStatus.NOT_FOUND);
    if (Objects.nonNull(user)) {
        responseEntity = new ResponseEntity<>(user, HttpStatus.OK);
    }
    return responseEntity;
}

This solution requires Spring 4.1+ and Java 1.8.

A: For me this an elegant way to do it, normally id is Long type
public ResponseEntity<User> getUser(@PathVariable ("id") Long id) {
            return Optional.of(this.userService.getUserById(id))
                    .map(u -> new ResponseEntity<>(u, HttpStatus.OK))
                    .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
        }


text:
Q: Unable to create a map between a C++ vector and an object I am trying to create a map between a particle and the location it is on. Essentially, I want my map M[loc] = p where loc is a std::vector <int> and p is a Particle.
This is the code that I have:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <map>
class Particle{
public:
    std::vector <int> coords;                                        // the coordinates of the particles
    std::string ptype;
    int orientation;
    bool operator<(const Particle& rhs)const{
        return coords < rhs.coords;
    }

    // constructor
    Particle (std::vector <int> crds, std::string type_, int orientation_): coords (crds), ptype (type_), orientation (orientation_){

    }

    // destructor
    ~Particle(){

    }

    Particle( const Particle &other); // copy constructor

    // print location of the particle
    void printCoords();

};

int main(int argc, char* argv[]){

  std::map <std::vector <int>, Particle> OccupancyMap;

  Particle p ({0,0,0}, "monomer", 0);
  std::cout << p.ptype;
  Particle pdash = p;
  OccupancyMap[p.coords] = pdash ;

}

when I try to compile this code, I get a massive error message:
In file included from main.cpp:1:
In file included from /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/v1/iostream:37:
In file included from /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/v1/ios:215:
In file included from /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/v1/__locale:14:
In file included from /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/v1/string:506:
In file included from /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/v1/string_view:175:
In file included from /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/v1/__string:57:
In file included from /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/v1/algorithm:643:
In file included from /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/v1/memory:677:
/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/v1/tuple:1401:7: error: no matching constructor for initialization of 'Particle'
      second(_VSTD::forward<_Args2>(_VSTD::get<_I2>(__second_args))...)
      ^
/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/v1/utility:507:11: note: in instantiation of function template specialization 'std::__1::pair<const std::__1::vector<int>, Particle>::pair<const std::__1::vector<int> &, 0>' requested here
        : pair(__pc, __first_args, __second_args,
          ^
/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/v1/memory:1684:31: note: in instantiation of function template specialization 'std::__1::pair<const std::__1::vector<int>, Particle>::pair<const std::__1::vector<int> &>' requested here
            ::new((void*)__p) _Up(_VSTD::forward<_Args>(__args)...);
                              ^
/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/v1/memory:1562:21: note: in instantiation of function template specialization 'std::__1::allocator<std::__1::__tree_node<std::__1::__value_type<std::__1::vector<int>, Particle>, void *>>::construct<std::__1::pair<const std::__1::vector<int>, Particle>, const std::__1::piecewise_construct_t &, std::__1::tuple<const std::__1::vector<int> &>, std::__1::tuple<>>' requested here
                __a.construct(__p, _VSTD::forward<_Args>(__args)...);
                    ^
/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/v1/memory:1413:14: note: in instantiation of function template specialization 'std::__1::allocator_traits<std::__1::allocator<std::__1::__tree_node<std::__1::__value_type<std::__1::vector<int>, Particle>, void *>>>::__construct<std::__1::pair<const std::__1::vector<int>, Particle>, const std::__1::piecewise_construct_t &, std::__1::tuple<const std::__1::vector<int> &>, std::__1::tuple<>>' requested here
            {__construct(__has_construct<allocator_type, _Tp*, _Args...>(),
             ^
/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/v1/__tree:2194:20: note: in instantiation of function template specialization 'std::__1::allocator_traits<std::__1::allocator<std::__1::__tree_node<std::__1::__value_type<std::__1::vector<int>, Particle>, void *>>>::construct<std::__1::pair<const std::__1::vector<int>, Particle>, const std::__1::piecewise_construct_t &, std::__1::tuple<const std::__1::vector<int> &>, std::__1::tuple<>>' requested here
    __node_traits::construct(__na, _NodeTypes::__get_ptr(__h->__value_), _VSTD::forward<_Args>(__args)...);
                   ^
/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/v1/__tree:2139:29: note: in instantiation of function template specialization 'std::__1::__tree<std::__1::__value_type<std::__1::vector<int>, Particle>, std::__1::__map_value_compare<std::__1::vector<int>, std::__1::__value_type<std::__1::vector<int>, Particle>, std::__1::less<std::__1::vector<int>>, true>, std::__1::allocator<std::__1::__value_type<std::__1::vector<int>, Particle>>>::__construct_node<const std::__1::piecewise_construct_t &, std::__1::tuple<const std::__1::vector<int> &>, std::__1::tuple<>>' requested here
        __node_holder __h = __construct_node(_VSTD::forward<_Args>(__args)...);
                            ^
/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/v1/map:1521:20: note: in instantiation of function template specialization 'std::__1::__tree<std::__1::__value_type<std::__1::vector<int>, Particle>, std::__1::__map_value_compare<std::__1::vector<int>, std::__1::__value_type<std::__1::vector<int>, Particle>, std::__1::less<std::__1::vector<int>>, true>, std::__1::allocator<std::__1::__value_type<std::__1::vector<int>, Particle>>>::__emplace_unique_key_args<std::__1::vector<int>, const std::__1::piecewise_construct_t &, std::__1::tuple<const std::__1::vector<int> &>, std::__1::tuple<>>' requested here
    return __tree_.__emplace_unique_key_args(__k,
                   ^
main.cpp:51:15: note: in instantiation of member function 'std::__1::map<std::__1::vector<int>, Particle, std::__1::less<std::__1::vector<int>>, std::__1::allocator<std::__1::pair<const std::__1::vector<int>, Particle>>>::operator[]' requested here
  OccupancyMap[p.coords] = pdash ;
              ^
main.cpp:35:5: note: candidate constructor not viable: requires single argument 'other', but no arguments were provided
    Particle( const Particle &other); // copy constructor for some reason i dont know
    ^
main.cpp:26:5: note: candidate constructor not viable: requires 3 arguments, but 0 were provided
    Particle (std::vector <int> crds, std::string type_, int orientation_): coords (crds), ptype (type_), orientation (orientation_){
    ^
1 error generated.

I don't quite understand what is going on here. What is the nature of the error here? What concept is it pointing towards?
I would appreciate any advice you have for me. I apologize if this is an obvious question.


text:
Q: Query not working, when I try to increment existing record I am using codeigniter.
Trying to use query (I got this by using get_compiled_update('invoice'))
UPDATE `invoice` SET `paid` = 'paid + 100' WHERE `invoice_id` = '46'

but it is not working, saying
0 rows affected

In my model
 $this->db
            ->where('invoice_id',$invoice_id)
            ->set('paid',"paid + ".$payment_price)
            ->update('invoice');

What should I do to make it work.


text:
Q: How to get custom post type posts with certain multiple tags names and category id? Here is my query:
$args = array(
    'post_type' => 'jobs',
    'cat' => $category_id,
    'tag' => $searchval,
    'paged' => $paged
);
query_posts($args);

But this not working.

A: It's highly recommended NOT to use query_posts() function as this can affect a LOT of different things.
While this question is especially difficult to answer when you don't specify how it's not working and the source of your variables, the better way to formulate this query would be by using the filter entitled 'pre_get_posts'.
Example:
add_filter( 'pre_get_posts', 'wpse_267038_jobs_posts' );
function wpse_267038_jobs_posts( $query ) {
    if ($query->is_main_query() ) {
        $query->set( 'post_type', 'jobs' );
        $query->set( 'cat', $category_id );
        $query->set( 'tag', $searchval );
        $query->set( 'paged', $paged );
    }
}

While we can't check to be sure that achieves the proper results because of your lack of details, this is the way to go about it.


text:
Q: Trying to figure out a less clunky way of utilising a single UITableview I have a UITableViewController segueing to a UIViewController.
I have made a global counter to keep track of what row in the UITableView was selected. Because depending on what row selected some information in the presented UIViewController will change.
I think its possible to tidy it up so that the dayx segue only has to be called once and the counter can change accordingly depending on what row is selected? But I am having trouble figuring it out.
This is what I currently have, it works but seems messy?:
//what happens when row is selected
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if indexPath.row == 0 {
        counter = 0
        self.performSegue(withIdentifier: "dayx", sender: self)
    } else if indexPath.row == 1 {
        counter = 1
        self.performSegue(withIdentifier: "dayx", sender: self)
    }
    else if indexPath.row == 2 {
        counter = 2
        self.performSegue(withIdentifier: "dayx", sender: self)
    }
    else if indexPath.row == 3 {
        counter = 3
        self.performSegue(withIdentifier: "dayx", sender: self)
    }
    else if indexPath.row == 4 {
        counter = 4
        self.performSegue(withIdentifier: "dayx", sender: self)
    }
    else if indexPath.row == 5 {
        counter = 5
        self.performSegue(withIdentifier: "dayx", sender: self)
    }
    else if indexPath.row == 6 {
        counter = 6
        self.performSegue(withIdentifier: "dayx", sender: self)
    }
}

A: Use flatMap:
Swift 4.0
indexPath.flatMap {
    print($0)
    counter = $0
    self.performSegue(withIdentifier: "dayx", sender: self)
}

Later:
let _ = indexPath.compactMap {
     counter = $0
     self.performSegue(withIdentifier: "dayx", sender: self)
 }

To understand the basics of flatMap. Read this article Replacing flatMap With compactMap
Update
If all your rows are intended to do a performSegue. Simple:
//what happens when row is selected
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

   counter = indexPath.row
   self.performSegue(withIdentifier: "dayx", sender: self)
}


text:
Q: is there a way to get a random line from a file that has a size greater than 0 bytes? Hopefully you people can help me with that because im completely lost..
I tried many different codes but none of them worked
is there a way to get a random line from a file that has a size greater than 0 bytes?
i want to get a random line from a variable file (name will be based on the user input) and print it to the screen
the conditions are that the file must be more than zero bytes (meaning that it has lines to begin with)
if the file does not exist i want it to be created
the below code doesnt work at all, gives me a second input and while i enter it the program crashes
with open(tokens + '.txt') as f:
        if os.path.getsize(tokens + '.txt'):
            lines = f.readlines()
            print(random.choice(lines))
        elif os.stat(f).st_size > 0:
            with open(tokens + '.txt', 'a') as the_file:
                    the_file.write(user_input)
                    the_file.write('\n')
                    the_file.close()


text:
Q: undefined index using update statement Im trying to update a field in my database by adding to the original number value that is already in there.
i have a system where staff are able to log in and update a the balance of a normal user. Currently i have a test user and staff. the users balance is set to 100. i have the following code:
<?php

if(isset($_POST['search'])){
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$result = $mysqli->query( "SELECT * FROM Users WHERE Username ='$searchq'");
    if ($result){

        //fetch result set as object and output HTML
        if($obj = $result->fetch_object())
        {
            echo '
';
            echo '<form method="POST" id = "books" action="">';
            echo '

Student Username: '.$obj->Username.'
';
            echo '
';
            echo '
First Name: '.$obj->FirstName.'
';
            echo '
Last Name: '.$obj->LastName.'
';
            echo '
';
            echo '
 Current Balance '.$obj->Balance.'
';
            echo 'New Balance: <input type="number" name="newBalance" value = "1" min = "1" />';
            echo '

';
            echo '<button name="submit_btn" class="save_order">Top Up</button>';
            echo '
';
            echo '</form>';
            echo '
';
        }
    }
}

    $newBalance="";
$newBalance = $_POST['newBalance'];

if(isset($_POST['submit_btn']) ){
    $upsql = "UPDATE users SET Balance = Balance + '$newBalance' WHERE Username='" . $obj->Username . "'";
    $stmt = $mysqli->prepare($upsql);
    $stmt->execute();
}

?>

Ive tried a few things however i kept getting an error saying:
( ! ) Notice: Undefined index: newBalance

Im not sure what ive done wrong.
Any idea how to fix it?
Edit: Full code
<?php
session_start();
include_once("config.php");

?>
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Search</title>
<link href="style/style.css" rel="stylesheet" type="text/css">

Home

New Books

Search

Update Balance

        Welcome, <?=$_SESSION['Username'];?>!
 Logout

Update a Students Balance

<form id = "adsearch" action="updateBalance.php"  method="post">
    <input type="text" name ="search" placeholder="Search For a Student">
    <button name="submit" value="search">Search</button>
</form>

<?php

if(isset($_POST['search'])){
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$result = $mysqli->query( "SELECT * FROM Users WHERE Username ='$searchq'");
    if ($result){

        //fetch result set as object and output HTML
        if($obj = $result->fetch_object())
        {
            echo '
';
            echo '<form method="POST" id = "books" action="">';
            echo '

Student Username: '.$obj->Username.'
';
            echo '
';
            echo '
First Name: '.$obj->FirstName.'
';
            echo '
Last Name: '.$obj->LastName.'
';
            echo '
';
            echo '
 Current Balance '.$obj->Balance.'
';
            echo 'New Balance: <input type="number" name="newBalance" value = "1" min = "1" />';
            echo '

';
            echo '<button name="submit_btn" class="save_order">Top Up</button>';
            echo '
';
            echo '</form>';
            echo '
';
        }
    }
}

    $newBalance="";

    if(isset($_POST['submit_btn']) && !empty($_POST['newBalance']) ){

        $newBalance = $_POST['newBalance'];

        $upsql = "UPDATE users SET Balance = Balance + '$newBalance' WHERE Username='" . $obj->Username . "'";
        $stmt = $mysqli->prepare($upsql);
        $stmt->execute();
    }

?>

A: It's throwing that notice because you need to place $newBalance = $_POST['newBalance']; inside if(isset($_POST['submit_btn'])){...} and verify that it is not empty (or set).
$newBalance="";

if(isset($_POST['submit_btn']) && !empty($_POST['newBalance']) ){

$newBalance = $_POST['newBalance'];

    $upsql = "UPDATE users SET Balance = Balance + '$newBalance'
              WHERE Username='" . $obj->Username . "'";
    $stmt = $mysqli->prepare($upsql);
    $stmt->execute();
}

You can also use isset($_POST['newBalance']) instead of !empty($_POST['newBalance'])

Sidenote: You may want to add a submit type for your button.
echo '<button type="submit" name="submit_btn" class="save_order">Top Up</button>';

Yet, it may not be required; do try it if you're still experiencing problems.

Edit:
Under
echo '

Student Username: '.$obj->Username.'
';

add
echo '<input type="hidden" name="username" value = "'.$obj->Username.'"  />';

then under
$newBalance = $_POST['newBalance'];

add
$username = $_POST['username'];

and modify your query to read as
$upsql = "UPDATE users SET Balance = Balance + '$newBalance'
          WHERE Username='".$username ."'";

My quoting may be a bit off for
echo '<input type="hidden" name="username" value = "'.$obj->Username.'"  />';

where you may have to change it to
echo '<input type="hidden" name="username" value = '".$obj->Username."'  />';

Edit #2:
Another way to do this since you're already using sessions <?=$_SESSION['Username'];?> would be to assign a variable to it and pass it in your query.
$username = $_SESSION['Username'];

$upsql = "UPDATE users SET Balance = Balance + '$newBalance'
          WHERE Username='".$username ."'";

Edit #3:
Where you have
if(isset($_POST['search'])){
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);

replace it with
if(isset($_POST['search'])){
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);

$student = $_POST['search'];
$_SESSION['student'] = $student;

echo $_SESSION['student']; // see what echos here

then in your query, do:
$upsql = "UPDATE users SET Balance = Balance + '$newBalance'
          WHERE Username='".$student ."'";

*

*If that doesn't work, I don't know what else to do that will be of further help. My tests were conclusive and worked. Your query may be failing, I have no more ideas at this point.

Base yourself on this scenario:
$_POST['search'] = "student1";

$student = $_POST['search'];

$_SESSION['student'] = $student;

// echo $_SESSION['student'];

$student2 = $student;

echo $student2; // will echo student1


text:
Q: Triggering another function in method lifetime in sequence diagram I have a specific question about sequence diagram demonstration. I have a method that have flags that trigger other methods. I don't call other methods in this method, however the flag variables are affecting other methods. Should I include those methods that are notified in the lifetime of this method and how?
(I can not put my code it is too long and complex, if the question is not clear I can draw what I mean.)


text: Q: Java Apache CLI how to handle unkown argument excetion while keep the program to run normally? I am creating a CLI based application using Apache Commons CLI. I want my program to run normally even if the user has provided some extra arguments. In this case the program should ignore the extra argument. For example, my program is designed to accept 6 arguments and I provided 7th argument. In this case, the program will print the usages and the arguments will not be parsed. I want my application to parse all the 6 arguments and ignore the 7th argument. It is possible with Apache Commons CLI?


text:
Q: Navigate to Facebook Page using Swift The goal is simple, I want to allow a user to connect their Facebook page to the iOS app i've been developing so that when they press a button in my app, it will navigate them to the appropriate Facebook page. If the user has the Facebook app installed, it will launch and use the Facebook app and if not, it will use Safari.
I was able to implement this exact functionality for another app with the following code:
    if let facebookPageId = facebookPageIdTextField.text {
        let facebookHook = "fb://profile/" + facebookPageId
        if let url = URL(string: "\(facebookHook)") {

            if UIApplication.shared.canOpenURL(url) {
                UIApplication.shared.open(url)
            } else {
                UIApplication.shared.open(URL(string: "https://www.facebook.com/placeholder")!)
            }
        }
    }

However, I had to browse the Facebook HTML source code in order to find the value to use for facebookPageId and asking a user to dive into the source code seems pretty impractical.
Does Facebook not want developers to have access to this kind of functionality? Has anyone found an easy fix for this?


text:
Q: Does basinhopping of scipy changes stepsize randomly or adaptively, by default? I am confused about the 'take_step' option in scipy.optimize.basinhopping:
According to the online reference:

The default step taking routine is a random displacement of the
  coordinates ... take_step can optionally have the attribute
  take_step.stepsize. If this attribute exists, then basinhopping will
  adjust take_step.stepsize in order to try to optimize the global
  minimum search.

According to the source (line 587, see below), however,  scipy's basinhopping uses  AdaptiveStepSize by default, and  adjusts stepsize to something like 0.9*stepsize or stepsize/0.9, etc., regardless of whether take_step.stepsize is specified.
# use default
displace = RandomDisplacement(stepsize=stepsize)
take_step_wrapped = AdaptiveStepsize(displace, interval=interval,
verbose=disp)

Thus, my understanding from reading the source of basinhopping is, by default, the procedure will adaptively modify the default stepsize (0.5) to some stepsize * factor, stepsize/factor, etc., following how many samplings have been accepted in the Metropolis-Hasting procedure. I am confused because the online reference of basinhopping, on the other hand,  seems to indicate that the default stepsize will be something totally random.
Can anyone clarify? If I do not provide any take_step procedure to basinhopping, then will it try with stepsize randomly, or will it modify stepsize adaptively? Thanks.

A: The step size is adaptively updated by default.  The only time it is not updated is if you pass a custom take_step object which does not have an attribute called stepsize


text:
Q: Proving $\frac{\cot\theta-\csc\theta+1}{\cot\theta+\csc\theta-1}=\csc\theta-\cot\theta$
Prove that
  $$\frac{\cot\theta - \csc\theta + 1}{\cot\theta+\csc\theta-1}= \csc\theta-\cot\theta$$

A: $$\operatorname{cosec}^2\theta - \cot^2\theta = 1 \implies (\operatorname{cosec}\theta+\cot\theta)(\operatorname{cosec}\theta-\cot\theta) = 1$$
$$\operatorname{cosec}\theta+\cot\theta -1= \frac{1}{\operatorname{cosec}\theta-\cot\theta}-1 = \frac{1-(\operatorname{cosec}\theta-\cot\theta)}{\operatorname{cosec}\theta-\cot\theta} = \frac{\cot\theta-\operatorname{cosec}\theta+1}{\operatorname{cosec}\theta-\cot\theta} $$
$$\frac{\cot\theta +\operatorname{cosec}\theta-1}{\cot\theta-\operatorname{cosec}\theta+1}=\frac{1}{\operatorname{cosec}\theta-\cot\theta}$$

$$\frac{\cot\theta-\operatorname{cosec}\theta+1}{\cot\theta+\operatorname{cosec}\theta -1} = \operatorname{cosec}\theta-\cot\theta$$

A: $$\cot\theta-\csc\theta+1$$
$$=\cot\theta-\csc\theta+(\csc^2\theta-\cot^2\theta)$$
$$=(\cot\theta-\csc\theta)(1-\cot\theta-\csc\theta)$$
$$=-(\cot\theta-\csc\theta)(\cot\theta+\csc\theta-1)$$

A: Another way:
Write $\theta=2y$
$$\cot2y-\csc2y=-\dfrac{1-\cos2y}{\sin2y}=-\tan y$$
$$\cot2y+\csc2y=-\dfrac1{\cot2y-\csc2y}=\cot y$$


text:
Q: USB ports don't work in Gentoo Linux I have a motherboard, Gigabyte Z170-D3H, with a fresh Gentoo Linux installed (self-compiled kernel 4.9.6-gentoo-r1) and two USB devices connected (Flashdrive and Mouse). But USB ports don't work.
When I type lsblk, there is only my system disk sda.
lspci | grep USB returns:
00:14.0 USB controller: Intel Corporation Sunrise Point-H USB 3.0 xHCI Controller (rev 31)

lsusb returns:
libusb: debug [libusb_init] created default context
libusb: debug [libusb_init] libusb v1.0.19.10903
libusb: error [op_init] could not find usbfs
unable to initialize libusb: -99

dmesg | grep 'USB\|usb' returns:
[    0.293570] ACPI: bus type USB registered
[    0.293665] usbcore: registered new interface driver usbfs
[    0.293756] usbcore: registered new interface driver hub
[    0.293850] usbcore: registered new device driver usb
[    0.987392] ehci_hcd: USB 2.0 'Enhanced' Host Controller (EHCI) Driver
[    0.987449] ohci_hcd: USB 1.1 'Open' Host Controller (OHCI) Driver
[    0.987487] uhci_hcd: USB Universal Host Controller Interface driver
[    0.987548] usbcore: registered new interface driver usblp
[    0.987592] usbcore: registered new interface driver usb-storage
[    0.992362] usbcore: registered new interface driver usbhid
[    0.992376] usbhid: USB HID core driver

Here is entire dmesg log: dmesg_log.txt
usb-devices returns nothing.
grep XHCI /usr/src/linux-$(uname -r)/.config returns:
CONFIG_USB_XHCI_HCD=y
CONFIG_USB_XHCI_PCI=y
CONFIG_USB_XHCI_PLATFORM=y

A: In the dmesg output, one should see messages like
[    1.768941] ehci-pci 0000:00:1a.0: EHCI Host Controller
[    1.769021] ehci-pci 0000:00:1a.0: new USB bus registered, assigned bus number 1
...
[    1.787161] xhci_hcd 0000:02:00.0: xHCI Host Controller
[    1.787880] xhci_hcd 0000:02:00.0: new USB bus registered, assigned bus number 2

(these are from my system) if the kernel detects the USB hardware and assigns drivers, but they are not there.
As modules, you need xhci_pci and ehci_pci as drivers for the PCI USB controllers (doesn't hurt to have both, and I'm not sure how USB 2.0 on the USB 3.0 hardware is handled, so better include both, at least until the problem is fixed), and xhci_hcd and ehci_hcd for general support.
Your config screenshot doesn't match your .config output, so I'm not sure what your current configuration is. The screenshot says XHCI is a module, your .config says it's built-in.
Setting all of them to modules will make debugging easier. So change all 4 to M, recompile the kernel, reboot, verify with lsmod which are loaded. If none are loaded and in use, modprobe the pci variants and see if there are any error messages or any other messages in dmesg/syslog.
If both modules won't load, have a look at the numeric vendor and device id of your controller (lspci -n), and verify with modinfo or by inspecting the source that the modules should recognize your hardware.


text:
Q: Merge two lists of objects without duplicates I have three object classes:
public class Section{
    private Integer id;
    private List<Program> programs;
}

public class Program{
    private String title;
    private Integer id;
    private List<Broadcast> broadcasts = null;
}

public class Broadcast {
    private Integer id;
    private String title;
}

And I have two lists of Section object: List<Section> oldSections and List<Section> newSections. I need to check if oldSections contains all Sections from newSections list, to determine this I have to compare id values. if it doesn't then I need to add this Section to oldSections and if it does then I have to do the same check for Programs and Broadcasts.
I tried to iterate through all Sections, Programs and Broadcasts but it doesn't seem to be a good solution. What would the best approach?
    private void updateSections(List<Section> oldSections, List<Section> newSections){
        for(Section newSection: newSections){
            boolean alreadyAdded = false;
            for(Section oldSection: oldSections){
                if(newSection.getId() == oldSection.getId()){
                    alreadyAdded = true;
                }
            }
            if(!alreadyAdded){
                oldSections.add(newSection);
            } else {
                //HERE I HAVE TO COMPARE PROGRAMS AND THEN BROADCASTS
            }
        }
    }

A: You can also use java 8 to merge list without duplicate.
public class Test {
    public static void main(String[] args) {
        List<Student> list1 = Arrays.asList(new Student("a", 1), new Student("b", 2), new Student("f", 3));
        List<Student> list2 = Arrays.asList(new Student("b", 4), new Student("c", 5), new Student("f", 6));
        List<Student> list3 = Arrays.asList(new Student("b", 7), new Student("d", 8), new Student("e", 9));
        List<Student> dogs = new ArrayList<>(Stream.of(list1, list2, list3).flatMap(List::stream)
                .collect(Collectors.toMap(Student::getName, d -> d, (Student x, Student y) -> x == null ? y : x)).values());
        dogs.forEach(System.out::println);
    }
}

class Student {
    String name;
    int id;

    public Student(String name, int id) {
        this.name = name;
        this.id = id;
    }

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return "Student{" + "name='" + name + '\'' + ", id=" + id + '}';
    }
}

A: A Set is a list that it can help you to avoid duplicate.

You can simply override the equals and hashCode methods of your Java Bean/POJO object
  and use set. This way a duplicate entry will be rejected and you don't
  need to merge your data anymore. Your list elements are always unique.

Take a look at this thread to see how to implement Set in java -> Verify there is a combination of unique string


text:
Q: Assign matched item in list to a variable The motive is to check if any of items in a list are contained in another list, and in case there is a match, assign it to a variable in a 'pythonic' fashion
if any('a','b','c') in ['b','x','y','z']:
    #now i want to assign the matched 'b' to a variable concisely.
    #In case of multiple matches , any match/ first match may be assigned

I want to avoid this :
lst = ['b','x','y','z']
if 'a' in lst:
    var = 'a'
elif 'b' in lst"
    var = 'b'
# and so on

A: You can use a function that returns either the first matched element or None in case no matched elements are found:
li_1 = ['a','b','c']
li_2 = ['b','x','y','z']

def find(li_1, li_2):
    for e in li_1:
        if e in li_2:
            return e

print(find(li_1, li_2))
# b
print(find(['a'], ['b']))
# None

Note that this is an O(n^2) solution. If the items are hashable you can get an O(1) solution using sets intersection (and as a bonus you will get all matched elements):
li_1 = ['a','b','c']
li_2 = ['b','x','y','z']

s1 = set(li_1)
s2 = set(li_2)
print(s1.intersection(s2))  # or print(s1 & s2)
# {'b'}


text:
Q: Using VLookUp on a partial string to find associated row num from another sheet Im just trying to make a basic spreadsheet to track investments and it currently has 2 sheets. 1 sheet refreshes data from a website and the other sheet is a calculation sheet.
In the calculation sheet the following Vlookup is present
=VLOOKUP(A3&"*", 'Refresh This File'!$A$2:$H$101, 1, FALSE).
In the cell A3 the input currently is Ethereum, and the table array has the string EthereumEthereum in row 2 Col B 2nd Sheet. (the 1 argument is the row label in the other sheet)
Currently with the above formula i am getting a #N/A error.
Is there any way where i can type a partial string in the input sheet, and return the associated row num from the other sheet.
Thanks for your help! :)

A: For VLOOKUP to work, the column in which you are looking your lookup value from should be column 1.
However you can use INDEX combined with MATCH if this is not the case:
=INDEX('Refresh This File'!$A$2:$A$101,MATCH(A3&"*",'Refresh This File'!$B$2:$B$101,0))


text:
Q: Errors with /usr/bin/ld compiling Fortran 77 code Code: https://github.com/CGS-GIS/GPSPACE
OS: Linux 5.6.15-arch1-1 #1 SMP PREEMPT x86_64 GNU/Linux
Compiler: gfortran - GNU Fortran (GCC) 10.1.0
Command: gfortran -std=legacy gpspace.f */*.F -o gpsppp
Output:
/usr/bin/ld: /tmp/ccIvkFdn.o: in function `vmfintrp_':
gpspace.f:(.text+0x27fb7): undefined reference to `vmf1_ht_'
/usr/bin/ld: gpspace.f:(.text+0x27fea): undefined reference to `vmf1_'
/usr/bin/ld: /tmp/ccIvkFdn.o: in function `bodyt_':
gpspace.f:(.text+0x34ae9): undefined reference to `dehanttideinel_'
/usr/bin/ld: /tmp/ccIvkFdn.o: in function `rderp_':
gpspace.f:(.text+0x36103): undefined reference to `iers_cmp_2015_'
/usr/bin/ld: gpspace.f:(.text+0x3617f): undefined reference to `iers_cmp_2015_'
/usr/bin/ld: gpspace.f:(.text+0x3622e): undefined reference to `iers_cmp_2015_'
/usr/bin/ld: /tmp/ccIvkFdn.o: in function `rdmet_':
gpspace.f:(.text+0x367bd): undefined reference to `gpt_'
/usr/bin/ld: /tmp/ccIvkFdn.o: in function `MAIN__':
gpspace.f:(.text+0xa750f): undefined reference to `gpt_'
/usr/bin/ld: gpspace.f:(.text+0xacce9): undefined reference to `gmf_'
/usr/bin/ld: /tmp/cc9KTZfn.o: in function `oloadn_':
OLOADN.F:(.text+0x242): undefined reference to `admint_'
/usr/bin/ld: OLOADN.F:(.text+0x3ac): undefined reference to `admint_'
/usr/bin/ld: OLOADN.F:(.text+0x516): undefined reference to `admint_'
/usr/bin/ld: OLOADN.F:(.text+0x976): undefined reference to `recurs_'
/usr/bin/ld: OLOADN.F:(.text+0x9ae): undefined reference to `recurs_'
/usr/bin/ld: OLOADN.F:(.text+0x9e6): undefined reference to `recurs_'
collect2: error: ld returned 1 exit status

No clue what the problem is...


text:
Q: C++ Type Traits Overview Has anybody put together a list of all the type traits available in standard <type_traits> (GCC-4.6.1) and Boost's own <boost/type_traits.hpp>?

A: The full lists of traits are available online:

*

*The Boost documentation lists the traits in <boost/type_traits.hpp>;

*The C++0x draft lists the traits in <type_traits>.

However, the GCC implementation is not yet complete. GCC 4.6 is missing:

*

*The std::underlying_type trait. This one will be on GCC 4.7.

*The std::is_trivially_X series of traits. Instead it has std::has_trivial_default_constructor and similar that seem to have the name from an earlier draft. The one about the move constructor is missing.

*The std::is_nothrow_X series of traits. These also use an older name like std::has_nothrow_default_constructor. The one about the move constructor is missing too.

*The std::aligned_union trait. This one can be easily implemented in terms of std::aligned_storage, which is currently supported.


text:
Q: how to common data entry from whole application
I am working with MVC in my application I have one _layoutPage that is like master page for all application

and other then views are there who handle data entry section & gridview section both commonly

Now I want to move DateEntry section as commonly for all application
How can I do this ?

one layout is common for header , navigation , footer , body  now i want to make two part of body in which
1. Data Entry header section - common
2. Data entry section        - dynamic
3. Data entry footer section - common


text:
Q: Buffer overflow in async js' eachSeries I'm trying to crawl a directory. I think I'm hitting an overflow using async js' eachSeries because I keep adding items to the array in my breadth-first search function.
Is there anything I can use that pops / dequeue an array in async manner until it's empty? Or is there a workaround to this issue I'm having?
Thank you.

A: I just created my own function e.g.
var async2 = {
  popEachSeries: function(stack, callback, callbackFinished) {
    if (stack && stack.length > 0) {
      var item = stack.pop();
      callback(item, function() {
        async2.popEachSeries(stack, callback, callbackFinished);
      });
    } else {
      if (callbackFinished) {
        callbackFinished();
      }
    }
  }
}


text:
Q: Entity Framework POCO with WCF software design question I am going to use Entity Framework and WCF in my application. The suggested practice, as I saw, is using POCO with Entity Framework and also using POCO classes as DataContracts. That is actually what POCO and Attributes are used for, -if I am not wrong.
However I am asked to use seperate classses for Entity Framework POCO's and WCF DataContracts. And to use a mapper between POCO's and DataContracts. Like, Foo and FooContract with same properties.
I am on the first approachs side but I wonder if the second approach (seperate classes approach) provides flexibility to the application or is it just a waste of effort.
I will be grateful if you can share your thoughts and experiences about using seperate classes for POCO and DataContracts, pros and cons about that.

A: Having separate classes for your POCOs and your Contracts will allow you to create Message Oriented services rather than RPC Style services.
Having Message Oriented services will allow your services to be more flexible, do more work, and be less tied to the objects that each service uses.
Message Based services also fall more in line with the spirit of Service Oriented Architectures. You can read more about Message Oriented services at Wikipedia.
I would also suggest picking up Service-Oriented Architecture: Concepts, Technology & Design by Thomas Erl if you are interested in the principles behind good service design.

A: Having different data classes at persistence layer and contract level gives you the most flexibility. For example, you may not want to expose all your persistent fields over a contract or you may want to expose different hierarchy of data over a contract etc. It also allows to change both independently of each other.
It may seem at first that using different classes at both level is duplication - but over long term, efforts are not so much (compared to flexibility that you get). You may get tempted to use same classes and develop different one when need arises but issue with that approach is that within short time frame, your services get tightly coupled with data classes rather than information/data that services should be exposing/working with.

A: I agree with @JustinNiessner and the best guidance I have found for architecting .NET applications using SOLID principles is a series of posts by .Net Junkie and the associated codeplex project. Clearly stated and informative, well worth reading.


text:
Q: Posts gathered from WPEMatico feeds are being mixed in different languages. Polylang is used for language separation I have set up RSS feeds in WPEMatico in different campaigns, each one gathering news in different languages. The campaigns are then connected to different Post Categories, each of which is set up in a specific language and the feeds are turned into posts.
The language differentiation in the website is done through the PolyLang plugin, where each page represents one language and all the posts in that specific language, from their respective category.
The problem is that the posts of different languages are being mixed somehow. Any ideas what the problem might be?
I've checked to make sure that each campaign is set to the right category, and everything is correct. However, somewhere along the way the category is switched, which results in them being posted in the wrong page.


text:
Q: Ruby dynamically build and assign varibles I am building a rails app that i need to update totals of managers each time someone is added. The method that updates the totals to me is looking really bad there is a lot of repetition going on that could be solved with a bit of metaprogramming. so i have a private method being called on before_save called update_totals
So we categorize them like this there is four races, african, coloured, indian and white there are three kinds of managements senior, middle and junior and then obviously two kinds of genders male and female. I need to be able to assign each possible variation of the three so i end up with something like this.
self.number_of_african_female_senior_managers = managers.native.african.female.senior.count
self.number_of_african_male_senior_managers = managers.native.african.male.senior.count
self.number_of_african_female_middle_managers = managers.native.african.female.middle.count
self.number_of_african_male_middle_managers = managers.native.african.male.middle.count
self.number_of_african_female_junior_managers = managers.native.african.female.junior.count
self.number_of_african_male_junior_managers = managers.native.african.male.junior.count

I would need to do this for each race. So i thought of building them dynamically and then having them assigned.
So something like this:
["african", "indian", "coloured", "white"].each do |race|
  ["senior","middle","junior"].each do |management_type|
    ["male","Female"].each do |gender|
      "number_of_#{race}_#{gender}_#{management_type}_managers" = managers.native.race.gender.management_type.count
    end
  end
end

But this will return strings and not variables that be assigned. I saw there is a define_method method that can dynamically build methods but that looks like you have to call it outside of the constructor in this example, and i saw that you can use Object#send like this example, but i cant see that working in this situation either.
Is this a good ruby practice? Its adding a bit of complexity but removing a lot of DRY code.

A:
Is this a good ruby practice?

DRY is a good ruby practice, so the answer to your question is: YES
Regarding your code you will probably use send in such a situation.
something like self.send("number_of_#{race}_#{gender}_#{management_type}_managers=", managers.send(native).send(race).send(gender).send(management_type).count)
This still looks pretty ugly to me. I am kind of asking myself why that datastructure is so insane. Why are you not using a simple hash structure here?


text:
Q: Create managed property via powershell? Is this possible to do via powershell?
http://www.glynblogs.com/2011/01/create-a-content-type-search-refinement-panel-in-sharepoint-2010.html#comment-23134
there is nothing to improve in the question, I need to create a managed property  via powershell, the link shows how to do it visually but doesnt show how to do it via powershell, the real question is that, I know its possible, I just dont know the spcmdlets to use for this and the syntax

A: Yes, it is possible to do it via powershell.
If you want to create a managed property for Sharepoint Enterprise Search via Powershell, Use :
New-SPEnterpriseSearchMetadataManagedProperty

Check out here for the usage and parameters.
If you want to create a managed property for Fast Search for SharePoint via Powershell, Use:
New-FASTSearchMetadataManagedProperty

Check out here for the usage and parameters.

A: Here is an example.
You can also use Command Builder to build some powershell commands.


text:
Q: FusedLocationProviderClient could not be found in Google Play Services I am trying to use Location Service of Google Play Services with Xamarin by following this link:
https://learn.microsoft.com/en-us/xamarin/android/platform/maps-and-location/location
IsGooglePlayServicesInstalled function returns true, and Xamarin.GooglePlayServices.Maps is installed.
What am I doing wrong?

A: The solution is: Install Xamarin.GooglePlayServices.Location nuget package.
In the docs here, they didn't mention this package, I even didn't know that it exists.


text:
Q: Creating a dataframe of unequal length list in R I'm currently running into the issue of creating a dataframe of an unequal length list. The issue I have is that there are corresponding categorical data to each list I have.
This is what I have so far
#Extract raster values to polygons
v <- extract(burnclass, ws_proj2)
v

#Get class counts for each polygon depending on the number of polygons

v.counts <- lapply(v,table)
v.counts

Result
[[1]]

  1   2   3   4   5   6   7
 17  81 210 127  83  59 172

[[2]]

  3   4   5   6   7
660 796 612 647 348

[[3]]

  3   4   5   6   7
 11  55  76  98 323

[[4]]

 -1   1   2   3   4   5   6   7
963 229 173 136 114  97 111 322

[[5]]

   3    4    5    6    7
 664  289  192  526 1122

[[6]]

  3   4   5   6   7
450 386 158 125 144

[[7]]

  -1    3    4    5    6    7
5392  104  391  557 1221  885

I've tried the code below, to create a dataframe but the outcome attaches NA values to the end of each string and it is not what I need.
res <- as.data.frame(do.call(rbind,lapply(v.counts, `length<-`,max(indx))))

colnames(res) <- names(v.counts[[which.max(indx)]])
res

Result

The solution I'm looking for is this

I would appreciate any help with this!

A: A purrr solution
library(purrr)
map_dfr(v.counts, ~.x)[order(as.numeric(names(map_dfr(v.counts, ~.x))))]
#> # A tibble: 7 x 8
#>    `-1`   `1`   `2`   `3`   `4`   `5`   `6`   `7`
#>   <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1    NA    17    81   210   127    83    59   172
#> 2    NA    NA    NA   660   796   612   647   348
#> 3    NA    NA    NA    11    55    76    98   323
#> 4   963   229   173   136   114    97   111   322
#> 5    NA    NA    NA   664   289   192   526  1122
#> 6    NA    NA    NA   450   386   158   125   144
#> 7  5392    NA    NA   104   391   557  1221   885

Since you haven't provided any dput, I have created v.counts as
v.counts <- list(c(`1` = 17, `2` = 81, `3` = 210, `4` = 127, `5` = 83, `6` = 59, `7` = 172),
     c(`3` = 660, `4` = 796, `5` = 612, `6` = 647, `7` = 348),
     c(`3` = 11, `4` = 55, `5` = 76, `6` = 98, `7` = 323),
     c(`-1` = 963, `1` =229, `2` = 173, `3` = 136, `4` = 114, `5` = 97, `6` = 111, `7` = 322),
     c(`3` = 664, `4` = 289, `5` = 192, `6` = 526, `7` = 1122),
     c(`3` = 450, `4` = 386, `5` = 158, `6` = 125, `7` = 144),
     c(`-1` = 5392,`3` = 104, `4` = 391, `5` = 557, `6` = 1221, `7` = 885))

v.counts
#> [[1]]
#>   1   2   3   4   5   6   7
#>  17  81 210 127  83  59 172
#>
#> [[2]]
#>   3   4   5   6   7
#> 660 796 612 647 348
#>
#> [[3]]
#>   3   4   5   6   7
#>  11  55  76  98 323
#>
#> [[4]]
#>  -1   1   2   3   4   5   6   7
#> 963 229 173 136 114  97 111 322
#>
#> [[5]]
#>    3    4    5    6    7
#>  664  289  192  526 1122
#>
#> [[6]]
#>   3   4   5   6   7
#> 450 386 158 125 144
#>
#> [[7]]
#>   -1    3    4    5    6    7
#> 5392  104  391  557 1221  885

Created on 2021-06-07 by the reprex package (v2.0.0)

A: Here is a base R option using Reduce + merge + as.list (thank @AnilGoyal's data)
res <- Reduce(
  function(x, y) merge(x, y, all = TRUE),
  Map(function(k, v) data.frame(c(id = k, as.list(v))), seq_along(v.counts), v.counts)
)

res[order(names(res))][res$id, ]

which gives
  id  X.1  X1  X2  X3  X4  X5   X6   X7
1  1   NA  17  81 210 127  83   59  172
2  2   NA  NA  NA 660 796 612  647  348
3  3   NA  NA  NA  11  55  76   98  323
4  4  963 229 173 136 114  97  111  322
5  5   NA  NA  NA 664 289 192  526 1122
6  6   NA  NA  NA 450 386 158  125  144
7  7 5392  NA  NA 104 391 557 1221  885

A: I think you can also use this simple solution, using @AnikGoyal's sample data:
library(dplyr)

v.counts %>% bind_rows() %>% select(sort(names(.)))

# A tibble: 7 x 8
   `-1`   `1`   `2`   `3`   `4`   `5`   `6`   `7`
  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1    NA    17    81   210   127    83    59   172
2    NA    NA    NA   660   796   612   647   348
3    NA    NA    NA    11    55    76    98   323
4   963   229   173   136   114    97   111   322
5    NA    NA    NA   664   289   192   526  1122
6    NA    NA    NA   450   386   158   125   144
7  5392    NA    NA   104   391   557  1221   885

A: You could do:
  levs <- unique(unlist(v))
  t(sapply(v, function(x) table(factor(x, levs))))
       1   2   3   4   5    6    7   -1
[1,]  17  81 210 127  83   59  172    0
[2,]   0   0 660 796 612  647  348    0
[3,]   0   0  11  55  76   98  323    0
[4,] 229 173 136 114  97  111  322  963
[5,]   0   0 664 289 192  526 1122    0
[6,]   0   0 450 386 158  125  144    0
[7,]   0   0 104 391 557 1221  885 5392

A: A data.table approach, using the sample data provided in the answer from AnilGoyal.
library(data.table)
# Create a list of data.tables from the named vectors
L <- lapply(v.counts, function(x) data.table(names = names(x), x))
# rowbind list and cast to wide format
dcast(rbindlist(L, idcol = "id"), id ~ names, value.var = "x", fill = NA)
#    id   -1   1   2   3   4   5    6    7
# 1:  1   NA  17  81 210 127  83   59  172
# 2:  2   NA  NA  NA 660 796 612  647  348
# 3:  3   NA  NA  NA  11  55  76   98  323
# 4:  4  963 229 173 136 114  97  111  322
# 5:  5   NA  NA  NA 664 289 192  526 1122
# 6:  6   NA  NA  NA 450 386 158  125  144
# 7:  7 5392  NA  NA 104 391 557 1221  885


text:
Q: Storing data as a texture for use in Vertex Shader for Instanced Geometry (THREE JS / GLSL) I'm using a THREE.InstancedBufferGeometry, and I wish to access data in the Vertex Shader, encoded into a Texture.
What I want to do, is create a Data Texture with one pixel per instance, which will store position data for each instance (then at a later stage, I can update the texture using a simulation with a flow field to animate the positions).
I'm struggling to access the data from the texture in the Vertex Shader.
const INSTANCES_COUNT = 5000;

// FOR EVERY INSTANCE, GIVE IT A RANDOM X, Y, Z  OFFSET, AND SAVE IT IN DATA TEXTURE
const data = new Uint8Array(4 * INSTANCES_COUNT);
for (let i = 0; i < INSTANCES_COUNT; i++) {
    const stride = i * 4;
    data[stride] = (Math.random() - 0.5);
    data[stride + 1] = (Math.random() - 0.5);
    data[stride + 2] = (Math.random() - 0.5);
    data[stride + 3] = 0.0;
}

const offsetTexture = new THREE.DataTexture( data, INSTANCES, 1, THREE.RGBAFormat, THREE.FloatType );
offsetTexture.minFilter = THREE.NearestFilter;
offsetTexture.magFilter = THREE.NearestFilter;
offsetTexture.generateMipmaps = false;
offsetTexture.needsUpdate = true;

// CREATE MY INSTANCED GEOMETRY
const geometry = new THREE.InstancedBufferGeometry();
geometry.maxInstancedCount = INSTANCES_COUNT;
geometry.addAttribute( 'position', new THREE.Float32BufferAttribute([5, -5, 0, -5, 5, 0, 0, 0, 5], 3 )); // SIMPLE TRIANGLE

const vertexShader = `
    precision highp float;

    uniform vec3 color;
    uniform sampler2D offsetTexture;

    uniform mat4 modelViewMatrix;
    uniform mat4 projectionMatrix;

    attribute vec3 position;

    varying vec3 vPosition;
    varying vec3 vColor;

    void main(){
        vPosition = position;

        vec4 orientation = vec4(.0, .0, .0, .0);
        vec3 vcV = cross( orientation.xyz, vPosition );
        vPosition = vcV * ( 2.0 * orientation.w ) + ( cross( orientation.xyz, vcV ) * 2.0 + vPosition );

        vec2 uv = position.xy;
        vec4 data = texture2D( offsetTexture, uv );
        vec3 particlePosition = data.xyz * 1000.0;

        gl_Position = projectionMatrix * modelViewMatrix * vec4( vPosition + particlePosition, 1.0 );
    }
`;

const fragmentShader = `
    precision highp float;
    varying vec3 vColor;

    void main() {
        gl_FragColor = vec4(vColor, 1.0);
    }
`;

const uniforms = {
    size: { value: 1.0 },
    color: {
        type: 'c',
        value: new THREE.Color(0x3db230),
    },
    offsetTexture: {
        type: 't',
        value: offsetTexture,
    },
};

// CREATE MY MATERIAL
const material = new THREE.RawShaderMaterial({
    uniforms,
    vertexShader,
    fragmentShader,
    side: THREE.DoubleSide,
    transparent: false,
});

scene.add(new THREE.Mesh(geometry, material));

At the moment it seems that the data from the image isn't accessible in the vertex shader (if I just set the vUv to vec2(1.0, 0.0), for example, and change the offset positions, nothing changes), and also I'm not sure how to go about making sure that the instance can reference the correct texel in the texture.
So, my two issues are:
1) How to correctly set the Data Image Texture, and access that data in the Vertex Shader
2) How to correctly reference the texel storing the data for each particular instance (e.g, instance 1000 should use vec2(1000,1), etc
Also, do I have to normalize the data (0.0-1.0, or 0–255, or -1 – +1)
Thanks

A: You need to compute some kind of an index into the texture per instance.
Meaning, you need an attribute that is going to be shared by each instance.
if your triangle is
[a,b,c]

your index should be
[0,0,0]

Lets say you have 1024 instances and a 1024x1 px texture.
attribute float aIndex;

vec2 myIndex = ((aIndex + 0.5)/1024.,1.);

vec4 myRes = texture2D( mySampler, myIndex);


text:
Q: How can I make Windows 8.1 NOT sync across devices? I was wondering if there is a setting somewhere that will let me make Windows 8.1 not sync things like wallpapers, lock screens, and such across multiple devices with the same MS account.
I have a laptop and desktop that I am signed into with the same account and when I change something on the laptop, it automatically changes on the desktop as well, and vice versa. It is a minor annoyance, but it would be nice if it were fixable.

A: (skydrive is now called OneDrive)
To choose which settings to sync:
Swipe in from the right edge of the screen, tap Settings, and then tap Change PC settings.
(If you're using a mouse, point to the lower-right corner of the screen, move the mouse pointer up, click Settings, and then click Change PC settings.)
Tap or click SkyDrive, and then tap or click Sync settings.
Under the different settings categories, turn off the settings you no longer want to sync.
To Stop sync for all settings:
Swipe in from the right edge of the screen, tap Settings, and then tap Change PC settings.
(If you're using a mouse, point to the lower-right corner of the screen, move the mouse pointer up, click Settings, and then click Change PC settings.)
Tap or click SkyDrive, and then tap or click Sync settings.
Under the Sync settings with SkyDrive heading, turn off Sync your settings on this PC.


text:
Q: Split an asset into two assets in Hyperledger Composer. Is it possible to split an asset into two or more assets in Hyperledger Composer?
For an instance consider a usecase of using blockchain for food supply chain where food items are considered as assets (batch wise). In the supplychain, at a distribution node, each food item batch (asset) is distributed to several other nodes which means the asset is divided into many smaller assets.
In Hyperledger composer, is there a way to address this kind of scenarios? If not how can we achieve the requirement?

A: I think you could create to different assets:

*

*the batch

*the food item, which is the part of food distributed.

The food item contains the reference to the batchID.
In the transaction processor you could implement a logic in which the batch quantity is decremented each time the food is distributed.

asset Batch identified by batchId {
  o String batchId
  o Integer batchQuantity
  // other fields
}

asset FoodItem identified by foodId{
 o String foodId
 --> Batch batchId
 o Integer quantity
 //Other fields
}


text:
Q: How many USB flash-drive do I need to install FreeBSD? I want to install FreeBSD from usb flash drive and I don't know how many usb flash drive do I need to install FreeBSD!

A: There are mini-memstick and memstick images for each FreeBSD release (example). The former is about 300 Mb and the latter is 700 Mb. Just dd these images to your flash.


text:
Q: Taylor Expansion with Integral Remainder Question I have the following question at hand and I have to admit that I am not used to integral remainder form of taylor approximation. I am still trying to work around, so a couple of hints would be useful before a full answer.
Basically I have to determine the constant $c$ such that:
$\int\limits_{0}^{x}f(t)dt=\int\limits_{x}^{1}t^2f(t)dt + \frac{x^8}{8}+\frac{x^6}{6}-\frac{c}{24}$
Thanks in advance!
EDIT: I am sorry, I forgot to mention that:
$f:[0,1]\to\mathbb R$
I suppose thats important. And f is continuous, although I would imagine that is implicit...
EDIT_2:
Now, I would like to know if there is any other trickier solution or any approach using the integral remainder form of taylor expansion. Thanks!

A: Plugging in $x=0$ and $x=1$ in the desired identity, one sees that
$$
24\int_0^1t^2f(t)\,\mathrm dt=c=7-24\int_0^1f(t)\,\mathrm dt.
$$
There is no reason to expect that the LHS and the RHS coincide hence, in general, there is no $c$ such that the identity holds for every $x$ in $(0,1)$ (and in fact, for $x=0$ and $x=1$).
Finding $f$ such that the identity holds is another question: assuming that $f$ is a solution and differentiating with respect to $x$ yields $f(x)=-x^2f(x)+x^7+x^5$, hence $f(x)=x^5$. This is indeed a solution and, using the LHS of the identity above, one sees that $c=24\cdot\frac18=3$.


text:
Q: sql server sql query in my application user can give username or emailid to login how can i write the query like
select username,password from employee
where username='xxxx' or 'xxxx@yahoo.com' and password='******'

how can i write the query so that user can give username or emailid to login.
please send query for this problem thank u

A: Solution:
select username,password from employee where (username='xxxx' or username='xxxx@yahoo.com') and password='******'

Why?
There was operator precedence bug:
A or B and C === A or (B and C)

When no brackets specified AND operator has 1st priority.
In boolean math AND op is like multiplication and OR op like addition in regular math.

A: You have given the query already.
The only thing you need to do, is add braces so that the conditiosn are logically grouped together so that  ...
Like this:
WHERE ( username = '' and password = '' ) or (email = '' and password = '' )

A: try this
select username,password from employee
where (username='xxxx' and password='******')
or (username='xxxx@yahoo.com' and password='******')


text:
Q: Prove a formula in terms of n: $1+5+9+...+(4n+1)$
I HAVE to use induction, but I am new to induction, so I am a bit confused...
I believe I have to use the base case first: so $n=1$ is $4(1)+1=5$, but i get the second term in the sequence instead of the first term? is this ok? Next I tried to substitute k+1 in the formula and got: $4(k+1)+1=4k+5$. Is my approach feasible or what do I do next?
Thanks!
Edit: I realise the formula would be $n+4$... but how would I go about proving it and explaining it using induction?

A: You may know the formula $1+2+\cdots+n=\frac{n(n+1)}{2}$. By this formula we get
$$
\begin{aligned}
1+(4+1)+(4\cdot 2+1)+\cdots + (4n+1)
&=4(1+2+\cdots +n )+(n+1)
\\&=2n(n+1)+(n+1)
\\&=(2n+1)(n+1).
\end{aligned}
$$
So desired formula is $(2n+1)(n+1)$. If you want to prove by induction, First you check $1+5=(2+1)(1+1)$ and you check $1+5+9+\cdots+(4n+1)=(n+1)(2n+1)$ implies $1+5+9+\cdots+(4n+1)+(4n+5)=(n+2)(2n+3)$.

A: Draw 5 dots on a paper and connect them with drawing segments between them.  You'll notice that $4+3+2+1$ how many lines you draw (try it!).  But luckily we have another way of counting this using the binomial coefficient, and that's $5 \choose 2$, So in general, ${\sum_1^n j} = {n+1 \choose 2} = n(n+1)/2$.  So if you can prove the formula by induction then you'll be okay.  Try to look at some other examples of it being used. I was hoping this answer would be helpful because it shed some light on the formula mentioned in the previous answer..

A: Induction is targeted at verifying a proposition.
Let us establish the Proposition
Using the summation formula of Arithmetic progression
$$1+5+9+\cdots+(4n+1)=\frac{n+1}2\{1+(4n+1)\}=(n+1)(2n+1)$$
Let $f(n):1+5+9+\cdots+(4n+1)=(n+1)(2n+1)$
Clearly, $f(n)$ is true for $n=1$
Let $f(n)$ is true for $n=m\implies 1+5+9+\cdots+(4m+1)=(m+1)(2m+1)=2m^2+3m+1$
Putting $n=m+1,$
$\implies 1+5+9+\cdots+(4m+1)+\{4(m+1)+1\}=2m^2+3m+1+(4m+5)$ using $f(m)$
$\implies 1+5+9+\cdots+(4m+1)+\{4(m+1)+1\}=2m^2+7m+6=2m^2+4m+3m+6=2m(m+2)+3(m+2)=(m+2)(2m+3)=\{(m+1)+1\}\{2(m+1)+1\}$
So, $f(n)$ holds true for $n=m+1$ if  $f(n)$ holds true for $n=m$


text:
Q: Confused between push-pull and open-drain I am planning to use i2c based port expander (earlier I was using atmega328P's GPIO) for inputs and outputs. On a digikey search, I found MCP23008, MCP23009 and MCP23017 as possible replacements. Out of these three, only MCP23017 is push-pull. Other two are open-drain. I have an understanding that push pull can actively source and sink and open-drain cannot actively source. I am not very sure how does this affect my use case and hence I need some expert advise.
Here is the use case:

SS1 and TRIAC1 are supposed to go on GPIO of port expander. SS1 is supposed to be digitally read and TRIAC1 is supposed to be driven HIGH or LOW.
As such does it matter whether I use open drain or push pull type? If yes, which is the better option? Also, I want to keep the component to a minimal. Ex - I want to drive the triac driver directly by the port expander rather than using another transistor. So, please take this in consideration as well.
Note: Both circuits will be replicated 4-10 times on the PCB and hence the requirement of port expander.

A: Push-pull or open drain is relevant only for output ports. So for the SS1 pin, it does not matter.
However, to drive the TRIAC1 wire, given the schematic you gave, it is mandatory that you use push-pull. If you use open drain, either TRIAC1 is pulled to ground (with logical state 0), or unconnected (with state 1). In both cases, the optotriac LED wouldn't turn on and the triac wouldn't trigger. If you use push-pull, you can source current to the led (with state 1) so it's ok.
Now, there would be ways to make it work also with open-drain outputs, without using more components: if you connect the anode of the led to +3.3V and the cathode to the resistor and then to the TRIAC1 output of the MCU, you can use both push-pull or open-drain, as you wish. In both cases, you'd be able to turn the light on by setting the output to logical state 0 and turn it off by setting it to 1.


text:
Q: compiling multiple java classes in linux i used netbeans to code the classes and they are all included in a package but when i try to compile the application class in linux it spits out errors on class definitions for the classes i am working with. points at the class names for the objects and says "cannot find symbol" i need help!!!

A: use javac -sourcepath < your source code path >
Better check -help option as it mostly solve your problems

A: cd to the directory containing your package then run:
javac -classpath . your_package_name/*

A: I'm not a Java guru, but I have a small java project that I developed years ago and have recently ported to compile with javac on Linux.
I got this to work in two different ways:

*

*Created a single Java source file that held all of my classes

*Put each of my classes in a separate file but all in the same directory

In each case, I can compile and run with the following:
javac *.java && java name_of_main_class

Notice that I did not specify a "-classpath" option when I compiled.  I guess this works because I have not used a directory substructure or created a package.  If you are dealing with those issues, this page appears to have some examples that may help you: Help with packages in java - import does not work
A key thing to understand about Java packages: They correspond to subdirectories where the classes are defined (or to JAR files which just bundle and compress those subdirectories into a single file).  Therefore, anytime you specify the package keyword in your source, you need to make sure that the source files (and the class files) are distributed to subdirectories correspondingly.  The -classpath option to javac may provide a workaround when subdirectory structures do not exactly match what is specified by the package keyword.

A: If you built the project using NetBeans, you can use Ant to build the project on command line. NetBeans generate Ant Build script.
just cd into the directory where the project is located then type 'ant'
it should build the project for you automagically


text:
Q: Moving an Ellipse that has been drawn So I add an Ellipse2D.Float to a JPanel (and to an ArrayList) when clicked. I want to know if after this has been done I can then move the shape (say, through shift-click). At the moment it seems to be static and I cannot drag it anywhere.
Furthermore, is it possible to connect two circles with a line in such a fashion that the line connects the two circles permenantly; when a circle is move the line is altered to follow the circles.
I'm just looking to see if this is feasible, I have started coding but can't find out how to do these two things. Any answers, links, code snippets appreciated!

A: You've got the basic idea.  Detect mouse click, paint new shape.
The next step is to know when the shift key is pressed and knowing what the last (or selected) shape was and then be able to update it's position.
For me, the easiest solution would be to maintain information about the shape and it's position in some manner.  In this example, I've used a simple Drawable class which not only combines the position and the shape, but also has a simple draw method to make life easier.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Shape;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Ellipse2D;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class ShiftShape {

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

    public ShiftShape() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private List<Drawable> drawables;

        public TestPane() {
            drawables = new ArrayList<Drawable>(25);
            addMouseListener(new MouseAdapter() {

                @Override
                public void mouseClicked(MouseEvent e) {
                    Drawable drawable = null;

                    if ((e.getModifiersEx() & MouseEvent.SHIFT_DOWN_MASK) == MouseEvent.SHIFT_DOWN_MASK) {

                        if (!drawables.isEmpty()) {

                            drawable = drawables.get(drawables.size() - 1);

                        }

                    } else {

                        drawable = new Drawable();
                        drawables.add(drawable);

                    }

                    if (drawable != null) {

                        drawable.setLocation(e.getPoint());
                        repaint();

                    }
                }
            });
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            for (Drawable drawable : drawables) {
                drawable.draw(g2d);
            }
            g2d.dispose();
        }

        public class Drawable {

            private Point location;
            private Shape shape;

            public Drawable() {

                shape = new Ellipse2D.Float(0, 0, 20, 20);

            }

            public void setLocation(Point location) {
                this.location = location;
            }

            public Point getLocation() {
                return location;
            }

            public void draw(Graphics2D g2d) {

                Point p = getLocation();
                int x = p.x - 10;
                int y = p.y - 10;
                g2d.translate(x, y);
                g2d.draw(shape);
                g2d.translate(-x, -y);

            }

        }
    }
}


text:
Q: How to prevent a modal from opening to everyone but the admin I have a modal that opens when clicked to display customer data. Currently, the modal opens to all users. However, it displays a permission error "Permission not allowed." to all users except the admin which is fine but I need to prevent the modal from opening entirely for these other users.
The code:
print '
';

I tried wrapping the Customer.add_new inside this condition but the issue is that it prevents even the admin from opening the modal.
Here is how I did it:
print '
 <?php if ( user_can( $current_user, "administrator" )):
    print 'data-load-modal="Customers.add_new"';
    endif;
print 'data-parameter-id="'.(int)$customer['customer_id'].'">';


text:
Q: I've tried to change my font size and it still has no affect. How do I actually change the font size? I'm trying to change the font size of my buttons in Tkinter so it's not so small. Does anyone have any idea on what I can do that might have the result that I'm looking for? Why is there so much text required for me to ask a question when I can ask it plainly and simply with less text?!
from Tkinter import *
from tkFont import *

class App:
    def __init__(self):
        guiWindow = Tkinter.Tk()
        guiWindow.wm_title("FooBar")

        # Creates a custom font
        customFont = Font(size=18)

        # code to add widgets will go here
        buttonFrame = Frame()

        # colors the "ChangeLicense" button
        color = '#005DA6'

        # tells licenseChange what to do
        def openLicenseChange():
            print('Change License')

    #button properties
        licenseChange = Button(guiWindow,
                               command=openLicenseChange,
                               bd=20, bg=color, font=customFont,
                               text="Change License")

        buttonFrame.pack(side="top", fill="x")

        guiWindow.mainloop()
app=App()

A: I'm not familiar with Font, but you can denote it also using a string:
customFont = '{arial} 18'

For default font uer
customFont = '{} 18'

A: When you create a tk.button object, use the font option, and specify the font style as a string like so:
"Arial 10 Bold"
I used your code as an example and made the font Arial, size 18, bolded.
from Tkinter import *
from tkFont import *

class App:
    def __init__(self):
        guiWindow = Tkinter.Tk()
        guiWindow.wm_title("FooBar")

        # Creates a custom font
        customFont = "Arial 18 Bold"

        # code to add widgets will go here
        buttonFrame = Frame()

        # colors the "ChangeLicense" button
        color = '#005DA6'

        # tells licenseChange what to do
        def openLicenseChange():
            print('Change License')

    #button properties
        licenseChange = Button(guiWindow,
                               command=openLicenseChange,
                               bd=20, bg=color, font=customFont,
                               text="Change License")

        buttonFrame.pack(side="top", fill="x")
        licenseChange.pack()
        guiWindow.mainloop()
app=App()

If that doesnt work, instead of "Arial 18 Bold", try quoting each word in the string like so "'Arial' '18' 'Bold'" in your customFont variable.

A: You can create a new font and then just applying it to your widgets using my_widget['font']=my_font, example out of your code:
from Tkinter import *
from tkFont import *

class App:

    def __init__(self):
        guiWindow = Tkinter.Tk()
        guiWindow.wm_title("FooBar")

        # Creates a custom font
        customFont = Font(size=18)

        # code to add widgets will go here
        buttonFrame = Frame()

        # colors the "ChangeLicense" button
        color = '#005DA6'

        # tells licenseChange what to do
        def openLicenseChange():
            print('Change License')

        # button properties
        helv36 = Font(family='Helvetica', size=36, weight='bold')
        licenseChange = Button(guiWindow,
                               command=openLicenseChange,
                               bd=20, bg=color, font=customFont,
                               text="Change License")
        licenseChange['font'] = helv36
        buttonFrame.pack(side="top", fill="x")

        guiWindow.mainloop()

app = App()

You can read more about tkFont.Font here


text:
Q: How to group object properties by there pattern structure? I have a kind of complicated algorithm to write using Javascript.
I have a data structure like this:
const data = [
  {
    some_fees_dent_0: true,
    some_fees_name_0: "junao",
    some_fees_name_1: "adhm",
    some_fees_name_2: "uio",
    some_fees_rate_0: "45",
    some_fees_rate_1: "1",
    some_fees_rate_2: "22",
    some_fees: [],                # HERE
    initial_fees: [],             # HERE
    initial_fees_dent_0: true,
    initial_fees_name_0: "james",
    initial_fees_name_1: "daiep",
    initial_fees_name_2: "moaip",
    initial_fees_rate_0: "7",
    initial_fees_rate_1: "11",
    initial_fees_rate_2: "88",
    initial_fees_type_0: "foo",
    initial_fees_type_1: "bar",
    initial_fees_type_2: "random",
  }
]

I want to achieve this:
const data = [
  {
    some_fees: [
      {
        some_fees_name: "junao",  # was initially some_fees_name_0
        some_fees_rate: "45",     # was initially some_fees_rate_0
        some_fees_dent: true,     # was initially some_fees_dent_0
      },
      {
        some_fees_name: "adhm",   # was initially some_fees_name_1
        some_fees_rate: "1",      # was initially some_fees_rate_1
      },
      {
        some_fees_name: "uio",    # was initially some_fees_name_2
        some_fees_rate: "22",     # was initially some_fees_rate_2
      },

    ],
    initial_fees: [
      {
        initial_fees_name: "james",   # was initially initial_fees_name_0
        initial_fees_rate: "7",       # was initially initial_fees_rate_0
        initial_fees_type: "foo",     # was initially initial_fees_type_0
        initial_fees_dent: true,      # was initially initial_fees_dent_0
      },
      {
        initial_fees_name: "daiep",   # was initially initial_fees_name_1
        initial_fees_rate: "11",      # was initially initial_fees_rate_1
        initial_fees_type: "bar",     # was initially initial_fees_type_1
      },
      {
        initial_fees_name: "moaip",  # was initially initial_fees_name_2
        initial_fees_rate: "88",     # was initially initial_fees_rate_2
        initial_fees_type: "random", # was initially initial_fees_type_3
      },

    ],
  }
]

Basically what happened is the initial data array that include objects now only include only two fields: some_fees initial_fees.
The other fields were put together in the same object based on the last number on their key, Which can be considered as index differentiator.

A: You must initialized parent first (some_fees, initial_fees) then group them by there pattern...

let data = [{ some_fees_dent_0: true, some_fees_name_0: "junao", some_fees_name_1: "adhm", some_fees_name_2: "uio", some_fees_rate_0: "45", some_fees_rate_1: "1", some_fees_rate_2: "22", some_fees: [], initial_fees: [], initial_fees_dent_0: true, initial_fees_name_0: "james", initial_fees_name_1: "daiep", initial_fees_name_2: "moaip", initial_fees_rate_0: "7", initial_fees_rate_1: "11", initial_fees_rate_2: "88", initial_fees_type_0: "foo", initial_fees_type_1: "bar", initial_fees_type_2: "random", }],
    groups = new Map,
    result = [];

for (let item of data) {
    let root = {}, entries = Object.entries(item);
    result.push(root);

    for (let [key, value] of entries)
        if (Array.isArray(value))
            root[key] = []; // initializing parent node

    for (let [key, value] of entries) {
        let [k0, k1, k2, k3] = key.split('_'),
            modefiedKey = `${k0}_${k1}_${k2}`,
            groupID = `${k0}_${k1}_${k3}`,
            group = groups.get(groupID);

        if (!k2) continue;
        if (group) group[modefiedKey] = value;
        else {
            let node = { [modefiedKey]: value }, parentNode = root[`${k0}_${k1}`];
            groups.set(groupID, node);
            if (parentNode) parentNode.push(node);
        }
    }
}
console.log(result);

A: I was wondering if there might be some kind of more general solution to this sort of thing. The idea with create_object_from_structured_key_entries (which could probably be written a fair bit better) is that it'll take entries with 'structured' keys as per the example in the first console.log(), and then create an object with the appropriate structure. For your data there's a create_structured_key function to convert your keys to structured ones so that it'll run through create_object_from_structured_key_entries.

const data = [{"some_fees_dent_0":true,"some_fees_name_0":"junao","some_fees_name_1":"adhm","some_fees_name_2":"uio","some_fees_rate_0":"45","some_fees_rate_1":"1","some_fees_rate_2":"22","some_fees":[],"initial_fees":[],"initial_fees_dent_0":true,"initial_fees_name_0":"james","initial_fees_name_1":"daiep","initial_fees_name_2":"moaip","initial_fees_rate_0":"7","initial_fees_rate_1":"11","initial_fees_rate_2":"88","initial_fees_type_0":"foo","initial_fees_type_1":"bar","initial_fees_type_2":"random"}];

const create_object_from_structured_key_entries = (entries) =>
  entries.reduce(
    (acc, [key, val]) => {
      let current_object = acc;
      const dot_parts = key.split('.');

      dot_parts.forEach((dot_part, i) => {
        const arr_parts = dot_part.replace(/]/g, '').split('[');
        const for_array = arr_parts.length > 1;
        const array_index = for_array ? +arr_parts[1] : null;

        if(!current_object[arr_parts[0]])
          current_object[arr_parts[0]] = for_array ? [] : {};

        if(for_array && !current_object[arr_parts[0]][array_index])
          current_object[arr_parts[0]][array_index] = {};

        if(i === dot_parts.length - 1) {
          if(for_array) {
            current_object[arr_parts[0]][array_index] = val;
          } else {
            current_object[arr_parts[0]] = val;
          }
          return;
        }

        if(for_array) {
          current_object = current_object[arr_parts[0]][array_index];
        } else {
          current_object = current_object[arr_parts[0]];
        }
      });

      return acc;
    }, {}
  );

const create_structured_key = (key) => {
  const [k0, k1, k2, k3] = key.split('_');
  if(!k2) return null;
  return k0 + '_' + k1 + '[' + k3 + ']' + '.' + k0 + '_' + k1 + '_' + k2;
};

const data_item_to_structured_object = (item) =>
  create_object_from_structured_key_entries(
    Object.entries(item)
      .map(([key, val]) => [create_structured_key(key), val])
      .filter(([key, val]) => key)
  );

const data_to_structured_object = (arr) => arr.map(data_item_to_structured_object);

console.log(create_object_from_structured_key_entries( Object.entries({
  'a.aa[0].aaa[1]': 'bob',
  'a.aa[0].ddd': 'fred',
  'a.bb.eee': 'jane'
}) ));

console.log(data_to_structured_object(data));