text:
Q: OpenCV 2.4 on Ubuntu 12.04 with QtCreator I moved to Ubuntu recently and I can't get openCV working with QtCreator. As described in the OpenCv install guide I built and installed the openCV library in /usr/local/lib, I updated opencv.conf in /etc/ld.so.conf.d/ and run sudo ldconfig -v.
But when I try to run a simple "hello world" program that shows an image in a namedWindow I get the following error:

OpenCv Error: Bad flag (parameter or structure field) (Unrecognized or unsupported array type) in cvGetMat, file /home/wedontplay/documenti/Library Installer/OpenCV-2.4.0/modules/core/array.cpp, line 2482 terminate called after throwing an instace of 'cv::Excepton' what(): /home/wedontplay/Library Installer/OpenCV-2.4.0/modules/core/src/array.cpp:2482: error: (-206) Unrecognized or unsupported array type in function cvGetMat

Why does Qt search in /home/wedontplay/Documenti/... instead of /usr/local/lib (it is searching in the folder where I have the OpenCv libs source code)?
Any suggestion would be really appreciated.

A: Add
INCLUDEPATH +=  /usr/local/include/Opencvlibname
LIBS+ = -L/usr/local/lib -[module_name1] -[module_name2] ..

in your .pro file and then try.
include module name as, for ex if its libopencvmodule1.a ,add it as LIBS+ = -L/usr/local/lib -lopencvmodule1


text:
Q: determine user-control caller i created a user-control that would be a button . On my form i have placed multiple such buttons . My question is : How do i determine in my user-control class who called me (i.e. what button ) ?

A: Your button class should have a public Clicked event, like a normal WinForms button:
 class MyButton
 {
     // this should be fired when a button is clicked
     public event EventHandler Clicked;
 }

If you have a single event handler for multiple buttons, e.g.:
 button1.Clicked += new EventHandler(button_Clicked);
 button2.Clicked += new EventHandler(button_Clicked);
 button3.Clicked += new EventHandler(button_Clicked);

You can check the sender parameter in your handler to see which control fired the event:
 private void button_Clicked(object sender, EventArgs e)
 {
     MyButton button = sender as MyButton;
     MessageBox.Show("You clicked on " + button.Text");
 }

redpajama_set_name: RedPajamaStackExchange


text:
Q: EWS Java how to find emails older than xx days and Delete all in one shot I want to find items in a folder which are older than xx days and Delete all the items found in one shot.
I was able to find the items matching my criteria. here is my code.
import org.joda.time.DateTime;
int purgeDays = 14;

    try {

        ItemView view = new ItemView(Integer.MAX_VALUE);

        Folder purgeFolder = Folder.bind(service, folderId);

        // need to convert to get Mon Sep 12 16:31:27 CDT 2016
        SearchFilter searchFilter = new SearchFilter.IsLessThanOrEqualTo(ItemSchema.DateTimeReceived, (DateTime.now().minusDays(purgeDays).toDate()));

        FindItemsResults<Item> emailsToPurge = service.findItems(purgeFolder.getId(), searchFilter, view);

        if (emailsToPurge != null && emailsToPurge.getItems() != null && emailsToPurge.getTotalCount() > 0 ) {

           // want something to delete all items at once
           emailsToPurge.deleteAll();

        } else {
            log.info("Found no emails to purge for Mailbox-"+ userName);
        }

    } catch (Exception e) {
        log.error("Exception "+ e.getMessage());
    }

A: Have a look at the deleteItems method on the ExchangeService class https://msdn.microsoft.com/en-us/library/microsoft.exchange.webservices.data.exchangeservice.deleteitems(v=exchg.80).aspx this allows you to send a batch DeleteItem request. I would suggest you page your deletes though at no more than 1000 items at a time else you may have issue with throttling and/or the requests timing out.


text:
Q: Identify first match position in a string I have a character string ("00010000") and need to identify which position do we see the first "1". (This tells me which month a customer is active)
I have a dataset that looks like this:
id  <- c(1:5)
seq <- c("00010000","00001000","01000000","10000000","00010000")
df <- data.frame(id,seq)

I would like to create a new field identifying the first_month_active for each id.
I can do this manually with a nested ifelse function:
    df$first_month_active <-
        ifelse(substr(df$seq,1,1)=="1",1,
        ifelse(substr(df$seq,2,2)=="1",2,
        ifelse(substr(df$seq,3,3)=="1",3,
        ifelse(substr(df$seq,4,4)=="1",4,
        ifelse(substr(df$seq,5,5)=="1",5,99 )))))

Which gives me the desired result:
  id  seq        first_position
  1   00010000   4
  2   00001000   5
  3   01000000   2
  4   10000000   1
  5   00010000   4

However, this is not an ideal solution for my data, which contains 36 months.
I would like to use a loop with an ifelse statement, however I am really struggling with syntax
for (i in 1:36) {
ifelse(substr(df$seq,0+i,0+i)=="1",0+i,
}

Any ideas would be greatly appreciated

A: You can use gregexpr.
> unlist(gregexpr(pattern=1,seq,fixed=T))
[1] 4 5 2 1 4

A: The following could do this job:
library(stringr)
str_locate(pattern ='1',seq)

A: Some comparisons:
library(stringi)
library(stringr)

seq <- c("00010010","00001000","10000010","10000000","00010000")
seq2 <- rep(seq, 5e6)

system.time(regexpr("1", seq2))
   user  system elapsed
   4.78    0.03    4.82

system.time(9-nchar(as.numeric(as.character(seq2))))
   user  system elapsed
   34.89    0.18   35.52

system.time(str_locate(pattern ='1',seq2))
   user  system elapsed
   6.17    0.21    6.53

system.time(stri_locate_first_fixed(seq2, "1")[, 1])
   user  system elapsed
   1.68    0.15    1.84

system.time(nchar(seq2)-round(log10(as.numeric(seq2))))
   user  system elapsed
   7.67    0.09    7.86

system.time(nchar(sub('1.*', '', seq2))+1)
   user  system elapsed
   14.61    0.11   14.93

A: Another one, using log:
  nchar(seq)-round(log10(as.numeric(seq)))

A: Another option using sub
nchar(sub('1.*', '', seq))+1
#[1] 4 5 2 1 4

A: Or try the stringi package
library(stringi)
stri_locate_first_fixed(df$seq, "1")[, 1]
## [1] 4 5 2 1 4

A: Skip the loop and the ifelse:
9 - nchar(as.numeric(seq))
## [1] 4 5 2 1 4

This won't work the same in your data.frame because you coerced seq to factor implicitly, so just do:
9 - nchar(as.numeric(as.character(df$seq)))
## [1] 4 5 2 1 4

Edit: Just for fun, since Frank didn't convert his comment into an answer, here's strsplit solution:
# from original vector
sapply(strsplit(seq, "1"), nchar)[1,] + 1
## [1] 4 5 2 1 4

# from data.frame
sapply(strsplit(as.character(df$seq), "1"), nchar)[1,] + 1
## [1] 4 5 2 1 4


text:
Q: show data from database in listview this is my database code and i want to retrieve name from my database and show it in listview which in another java file posted below as profilelist.jar .but i m not able to do it plz tell me whether this code is correct?
package a.vaccination;

import android.annotation.TargetApi;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Build;
import android.util.Log;

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public class datahandler {

    public static final String KEY_ROWID = "id";
    public static final String KEY_name = "name";
    public static final String KEY_dob = "dob";
    public static final String KEY_contact = "contact";
    public static final String KEY_email = "email";
    private static final String TAG = "DBAdapter";

    private static final String DATABASE_NAME = "profile";
    private static final String DATABASE_TABLE = "baby";
    private static final int DATABASE_VERSION = 2;

    private static final String DATABASE_CREATE = "create table if not exists"
            + DATABASE_TABLE
            + "(id integer primary key autoincrement, "
            + "name VARCHAR not null, dob date, contact VARCHAR, email
VARCHAR);";
    private final Context context;

    private DatabaseHelper DBHelper;
    private SQLiteDatabase db;

    public datahandler(Context ctx) {
        this.context = ctx;
        DBHelper = new DatabaseHelper(context);
    }

    protected static class DatabaseHelper extends SQLiteOpenHelper {
        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            // TODO Auto-generated method stub
            try {
                db.execSQL(DATABASE_CREATE);
                // db = DBHelper.getWritableDatabase();
                Log.i(DATABASE_NAME, "create");
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            // TODO Auto-generated method stub
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old
data");
            db.execSQL("DROP TABLE IF EXISTS contacts");
            onCreate(db);
        }
    }

    // ---opens the database---
    public datahandler open() throws SQLException {
        db = DBHelper.getWritableDatabase();
        return this;
    }

    // ---closes the database---
    public void close() {
        DBHelper.close();
    }

    // ---insert a record into the database---
    public long insertRecord(String name, String dob, String contact,
            String email) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_name, name);
        initialValues.put(KEY_dob, dob);
        initialValues.put(KEY_contact, contact);
        initialValues.put(KEY_email, email);
        Log.i(DATABASE_NAME, "values added");
        return db.insert(DATABASE_TABLE, null, initialValues);

    }

    // ---updates a record---
    public boolean updateRecord(long rowId, String name, String dob,
            String contact, String email) {
        ContentValues args = new ContentValues();
        args.put(KEY_name, name);
        args.put(KEY_dob, dob);
        args.put(KEY_contact, contact);
        args.put(KEY_email, email);
        return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
    }

    public Cursor getAllTitles() {
        return db.query(DATABASE_TABLE, new String[] { KEY_ROWID, KEY_name,
                KEY_dob, KEY_contact, KEY_email }, null, null, null, null,
                null, null);
    }

    // ---retrieves a particular title---

    public Cursor getTitle(long rowId) throws SQLException {
        Cursor mCursor = db.query(true, DATABASE_TABLE, new String[] {
                KEY_ROWID, KEY_name, KEY_email, KEY_dob, KEY_contact },
                KEY_ROWID + "=" + rowId, null, null, null, null, null,
null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;
    }

    public void getReadableDatabase() {
        // TODO Auto-generated method stub
        Cursor cur = db
                .rawQuery("select rowid _id,* from DATABASE_TABLE", null);
    }
}

profilelist.java
package a.vaccination;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

//this shows profies of baby and option of add new one
public class profilelist extends Activity implements OnItemClickListener {

    datahandler db = new datahandler(this);
    SimpleCursorAdapter adapter = null;
    Cursor c;

    @SuppressWarnings("deprecation")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.child);

        Button add = (Button) findViewById(R.id.button1);
        add.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // navigate to create profile
                Intent it = new Intent(profilelist.this,
createprofile.class);
                startActivity(it);

            }
        });

        db.open();
        Cursor c = db.getAllTitles();
        if (c.moveToFirst()) {
            do {
                DisplayRecord(c);
            } while (c.moveToNext());
        }
        db.close();

        // ---get a Record---
        db.open();
        c = db.getTitle(2);
        if (c.moveToFirst())
            DisplayRecord(c);
        else
            Toast.makeText(this, "No Assignments found", Toast.LENGTH_LONG)
                    .show();
        db.close();

    }

    public void DisplayRecord(Cursor c) {
        // TODO Auto-generated method stub
        Toast.makeText(
                this,
                "id: " + c.getString(0) + "\n" + "name: " + c.getString(1)
                        + "\n" + " dob: " + c.getString(2) +
"contact"
                        + c.getString(3) + "email" +
c.getString(4),

                Toast.LENGTH_SHORT).show();
        String[] columns = new String[] { datahandler.KEY_name };
        int[] to = new int[] { R.id.name };
        adapter = new SimpleCursorAdapter(this, R.layout.child, c, columns,
                to, 0);
        ListView names = (ListView) findViewById(R.id.listView1);
        names.setAdapter(adapter);
        names.setOnItemClickListener(this);

    }

i got error on at
     a.vaccination.datahandler.getTitle(datahandler.java:115)
     and
     at a.vaccination.profilelist.onCreate(profilelist.java:67)
     java.lang.NoSuchMethodError: android.database.sqlite.SQLiteDatabaseb.query
i provide both profilelist.java and datahandler.java above
plz help me i m badly stuck here
        @Override
        public void onItemClick(AdapterView arg0, View arg1, int arg2, long arg3) {
            // TODO Auto-generated method stub
        Intent i = new Intent(profilelist.this, vaccination.class);
        startActivity(i);
    }

}

A: I recently implemented this type of feature. Basically you have to create a custom BaseAdapter to show your data in the ListView. In the adapter constructor, you pass in your array of objects containing your data. The tutorial I used to get going was:
http://www.vogella.com/articles/AndroidListView/article.html. Hope this helps!

A: To answer both your first and second questions: "no, this code really is not fine".  You really must look into using a Loader.  While what you've written may work most of the time, your are very much in danger of generating Application Not Responding errors that will abruptly terminate your application.  Don't do this stuff on the UI thread.
There is a lot of Android programming that can be surprising.  I really suggest you pick up one of the standard books on how to do it, before you paint yourself into a corner.

A: You want to use a CursorAdapter like this SimpleCursorAdapter. You pass it a mapping of columns to view IDs and it handle's binding, etc.

A: You need create SimpleCursorAdapter and attach that to cursor returned from you'r database custom query selection. The data columns returned from the cursor is then mapped to you'r custom view for display. To Know more Click Here this gives proper implementation for your problem


text:
Q: C++Can't find error, double free or corruption (fasttop) I am getting the following output from my program:
$ ./list
Enter list 1:   [1,2,3,4]
[
Enter list 2:   [2,5,8,0]
[
[1,2,3,4]
[1,2,3,4]
*** Error in `./list': double free or corruption (fasttop): 0x0000000000f85100 ***
======= Backtrace: =========
/lib/x86_64-linux-gnu/libc.so.6(+0x80a46)[0x7fa0368d6a46]
./list[0x400d5f]
./list[0x400c62]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf5)[0x7fa036877ea5]
./list[0x400ae9]
======= Memory map: ========
00400000-00402000 r-xp 00000000 ca:01 410613                             /home/ubuntu/list

...
ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0                  [vsyscall]
the endAborted (core dumped)

This is what I have in main:
int main(){
  pennlist::List l1,l2;

  cout<<"Enter list 1:\t";
  cin>>l1;
  cout<<"Enter list 2:\t";
  cin>>l2;
  cout<<l1<<endl<<l2<<endl;
  cout<<"the end";
}

And this this is the overloaded >> operator.
istream& operator >>(istream& ins, List& write_me){
    char discard;
    write_me.head = new node;
    write_me.current = write_me.head;
    node* temp = write_me.head;
    ins>>discard;//get [
    cout<<discard<<endl;

    while(discard != ']'){
      ins>>temp->data;
      write_me.count += 1;
      temp->to_tail = new node;
      temp->to_head = temp;
      temp = temp->to_tail;
      ins>>discard; //get , or ]
    }
    write_me.tail = temp;
    temp = NULL;
    return ins;
  }

I have overloaded the =, ~ and copy ctr as well and get the same error before and after adding these functions.
I can't figure out how to resolve this error, please help.
EDIT
Here is the code for the destructor:
~List{
    delete head;
    delete current;
    delete tail;
}

A: I changed the destructor, and the program now works correctly. Thanks everyone.
~List{
    if (head != current && tail != current)
        delete current;
    if (tail != head)
        delete tail;
    delete head;
}


text:
Q: Not able to access Eclipse neon after installing it Today I installed Eclipse Neon on my machine but once i closed the window, I can't find where it is. I checked in the installed softwares also but there also it is not showing. Please help as I need to resume my coding classes.

A: The current repository version of Eclipse is 3.8 (Juno).  Since you mentioned you have Neon (the latest release (officially available at http://www.eclipse.org), the package doesn't require an install.  It can be run from the directory where you unpacked it.
You can run this command to locate the the folder:
$ locate -r "neon.*/eclipse$"

The results will be something similar to:

/opt/eclipse/eclipse-jee-neon-M5-linux-gtk-x86_64/eclipse

I highlighted in bold the part that you will most likely see.  In my case I have moved my root eclipse directory to the folder /opt to make it available to other users who logs into the system, instead of my personal space.  You'll most likely see yours in an area such as:
/home/username/Downloads//opt/eclipse/eclipse-jee-neon-M5-linux-gtk-x86_64/eclipse

I inferred the latter because your message said you can't find it.  By default files are downloaded to the ~/Downloads folder.  Opening a package without specifying a folder will create a folder off the Downloads directory.
To run it, just go to the folder with the eclipse files and run:
$ ./eclipse

Unless you specifically installed the jdk package it'll give the appropriate error indicating.
YOu can correct this by installing the jdk package from the repository with:
$ sudo apt install default-jdk

For convenience you might consider moving the root directory of the package (eclipse-jee-neon-M5-linux-gtk-x86_64) to a convenient location and link a path to the eclipse execute file.  You can do this with:
$ ln -s [path of directory]/eclipse /usr/local/bin/eclipse

This way you could run eclipse from the terminal commanline from anywhere just by typing (without a path):
$ eclipse


text:
Q: using client machine locale for i18n I'm trying to get my application work according to the OS locale of the client machine. For now it works with the locale of server machine. I'm using string frmae work. Apache Tomcat 7 is used as the server. Here is the configuration I used. Any help would be appriciated.
     <bean id="localeResolver"
        class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
        <property name="defaultLocale" value="en" />
    </bean>

    <bean id="localeChangeInterceptor"
        class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
        <property name="paramName" value="language" />
    </bean>

    <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" >
        <property name="interceptors">
            <list>
                <ref bean="localeChangeInterceptor" />
            </list>
        </property>
    </bean>

<!--     Register the welcome.properties -->
    <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basenames">
                    <list>
                        <value>i18n.api/api</value>
                        <value>i18n.exceptions/exceptions</value>
                        <value>i18n.common/common</value>
                        <value>i18n.login/login</value>
                        <value>i18n.plan/plan</value>
                        <value>i18n.customer/customer</value>
                        <value>org.springframework.security.messages</value>
                        <value>org.hibernate.validator.ValidationMessages</value>
                    </list>
                </property>
    </bean>

A: Please see supported handler method argument types on Spring doc. You can inject the user's Locale on your handler method like this:
@RequestMapping("/home")
public String home(Locale userLocale) {
    // do something with userLocale

    return "home";
}

Locale is of type java.util.Locale.
Also have a look at getLocale() method of ServletRequest. The client has to provide Accept-Language header on their request, otherwise server's locale is used. I'm assuming Spring behave in the same fashion as this


text:
Q: Django model fields getter / setter is there something like getters and setters for django model's fields?
For example, I have a text field in which i need to make a string replace before it get saved (in the admin panel, for both insert and update operations) and make another, different replace each time it is read. Those string replace are dynamic and need to be done at the moment of saving and reading.
As I'm using python 2.5, I cannot use python 2.6 getters / setters.
Any help?

A: Overriding setattr is a good solution except that this can cause problems initializing the ORM object from the DB.  However, there is a trick to get around this, and it's universal.
class MyModel(models.Model):
    foo = models.CharField(max_length = 20)
    bar = models.CharField(max_length = 20)

    def __setattr__(self, attrname, val):
        setter_func = 'setter_' + attrname
        if attrname in self.__dict__ and callable(getattr(self, setter_func, None)):
            super(MyModel, self).__setattr__(attrname, getattr(self, setter_func)(val))
        else:
            super(MyModel, self).__setattr__(attrname, val)

    def setter_foo(self, val):
        return val.upper()

The secret is 'attrname in self.__dict__'.  When the model initializes either from new or hydrated from the __dict__!

A: While I was researching the problem, I came across the solution with property decorator.
For example, if you have
class MyClass(models.Model):
    my_date = models.DateField()

you can turn it into
class MyClass(models.Model):
    _my_date = models.DateField(
        db_column="my_date",  # allows to avoid migrating to a different column
    )

    @property
    def my_date(self):
        return self._my_date

    @my_date.setter
    def my_date(self, value):
        if value > datetime.date.today():
            logger.warning("The date chosen was in the future.")
        self._my_date = value

and avoid any migrations.
Source: https://www.stavros.io/posts/how-replace-django-model-field-property/

A: You can also override setattr and getattr. For example, say you wanted to mark a field dirty, you might have something like this:
class MyModel:
    _name_dirty = False

    name = models.TextField()

    def __setattr__(self, attrname, val):
        super(MyModel, self).__setattr__(attrname, val)

        self._name_dirty = (attrname == 'name')

    def __getattr__(self, attrname):
        if attrname == 'name' and self._name_dirty:
            raise('You should get a clean copy or save this object.')

        return super(MyModel, self).__getattr__(attrname)

A: You can add a pre_save signal handler to the Model you want to save which updates the values before they get saved to the database.
It's not quite the same as a setter function since the values will remain in their incorrect format until the value is saved.  If that's an acceptable compromise for your situation then signals are the easiest way to achieve this without working around Django's ORM.
Edit:
In your situation standard Python properties are probably the way to go with this. There's a long standing ticket to add proper getter/setter support to Django but it's not a simple issue to resolve.
You can add the property fields to the admin using the techniques in this blog post


text:
Q: Seaborn Barplot Date Axis not formatable
How would one adjust the date formatting of a seaborn x axis? I usually use
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %Y'))

but that throws an error
ValueError: DateFormatter found a value of x=0, which is an illegal date

despite the date data is correctly formatted as dtype='datetime64[ns]' and there are no 0 values.
The chart is created by
data = data.melt('Name', var_name='country', value_name='cpi')
data.set_index('Name',inplace=True)
fig, ax = plt.subplots(figsize=(10, 6), dpi=80)
ax = sns.barplot(x=data.index, y='cpi', hue='country', data=data, ax=ax)
fig.autofmt_xdate()

this is how the date axis data looks like:
data.index
Out[286]:
DatetimeIndex(['2019-04-30', '2019-05-31', '2019-06-30', '2019-07-31',
               '2019-08-31', '2019-09-30', '2019-10-31', '2019-11-30',
               '2019-12-31', '2020-01-31', '2020-02-29', '2020-03-31',
               '2019-04-30', '2019-05-31', '2019-06-30', '2019-07-31',
               '2019-08-31', '2019-09-30', '2019-10-31', '2019-11-30',
               '2019-12-31', '2020-01-31', '2020-02-29', '2020-03-31',
               '2019-04-30', '2019-05-31', '2019-06-30', '2019-07-31',
               '2019-08-31', '2019-09-30', '2019-10-31', '2019-11-30',
               '2019-12-31', '2020-01-31', '2020-02-29', '2020-03-31',
               '2019-04-30', '2019-05-31', '2019-06-30', '2019-07-31',
               '2019-08-31', '2019-09-30', '2019-10-31', '2019-11-30',
               '2019-12-31', '2020-01-31', '2020-02-29', '2020-03-31',
               '2019-04-30', '2019-05-31', '2019-06-30', '2019-07-31',
               '2019-08-31', '2019-09-30', '2019-10-31', '2019-11-30',
               '2019-12-31', '2020-01-31', '2020-02-29', '2020-03-31',
               '2019-04-30', '2019-05-31', '2019-06-30', '2019-07-31',
               '2019-08-31', '2019-09-30', '2019-10-31', '2019-11-30',
               '2019-12-31', '2020-01-31', '2020-02-29', '2020-03-31'],
              dtype='datetime64[ns]', name='Name', freq=None)

A: Meanwhile I figured out a working solution using the following adjustment
    ax.set_xticklabels([datetime.strptime(t.get_text(), '%Y-%m-%dT%H:%M:%S.%f000').strftime('%b %Y') for t in ax.get_xticklabels()])

I don't think it's very pretty so if you have any more pythonic way of dealing with this please let me know.

A: Your solution seems fine; I upvoted it.
If you want something a little less verbose you can do:
x_dates = data.index.strftime('%b %Y').sort_values().unique()
ax.set_xticklabels(labels=x_dates, rotation=45, ha='right')

With this you don't need the fig.autofmt_xdate() call.


text:
Q: archive page sidebar not working i created a taxonomy page from archive.php , working based on thematic frame work.
i tried a lot to make the sidebar working but it show nothing and even using firebug its not exist !
<?php
/**
 * Template Name: MEDIT
 *
 * …
 *
 * @package Thematic
 * @subpackage Templates
 */

    // calling the header.php
    get_header();

    // action hook for placing content above #container
    thematic_abovecontainer();
?>

                <?php
                // action hook for placing content above #content
                    thematic_abovecontent();

                // filter for manipulating the element that wraps the content
                    echo apply_filters( 'thematic_open_id_content', '
' . "\n" );
                    ?>

                    <?php
                    $term_slug = get_query_var( 'term' );
                    $taxonomyName = get_query_var( 'taxonomy' );
                    $current_term = get_term_by( 'slug', $term_slug, $taxonomyName );
                    $args = array( 'child_of' => $current_term->term_id, 'hide_empty'=>false);
                    $terms = get_terms( 'tagportifolio', $args);
                    $assoc = taxonomy_image_plugin_get_associations();

                    if (!empty($terms)):
                ?>
                    <?php /*?><?php
                    // calling the standard sidebar
                    dynamic_sidebar('cs-project-main-category');
                    ?><?php */?>
                    <?php foreach( $terms as $child ): ?>
                        <?php thematic_abovepost(); ?>
                        <div id="cat-<?php echo $child->term_id; ?>">
                        <?php
                            if(array_key_exists( $child->term_taxonomy_id, $assoc )){
                                 echo wp_get_attachment_image( $assoc[$child->term_taxonomy_id], array(), false, 'thumbnail');
                             }
                        ?>

<a href="<?php echo get_term_link( $child->name, $taxonomyName );?>">
                        <?php echo $child->name; ?>

                        <?php thematic_belowpost();?>

                        <?php endforeach; ?>

                        <?php
                            else:
                            // start the loop
                        ?>
                        <?php /*?><?php
                        // calling the standard sidebar
                        dynamic_sidebar('cs-sub-cat-sidebar');
                        ?><?php */?>

            <?php
            endif;
            ?>
            <?php
                // action hook for placing content below #content
                thematic_belowcontent();
            ?>

<?php
    // action hook for placing content below #container
    thematic_belowcontainer();

    // calling the standard sidebar
    thematic_sidebar();

    // calling footer.php
    get_footer();
?>

any idea what is missing in my code please ?

A: It working now
this is the right template with the code i should use
Thanks for help
<?php
/**
 * Archive Template
 *
 * Displays an Archive index of post-type items. Other more specific archive templates
 * may override the display of this template for example the category.php.
 *
 * @package Thematic
 * @subpackage Templates
 *
 * @link http://codex.wordpress.org/Template_Hierarchy Codex: Template Hierarchy
 */

    // calling the header.php
    get_header();

    // action hook for placing content above #container
    thematic_abovecontainer();
?>

        <?php
            // action hook for placing content above #content
            thematic_abovecontent();

            // filter for manipulating the element that wraps the content
            echo apply_filters( 'thematic_open_id_content', '
' . "\n\n" );
                    $term_slug = get_query_var( 'term' );
                    $taxonomyName = get_query_var( 'taxonomy' );
                    $current_term = get_term_by( 'slug', $term_slug, $taxonomyName );
                    $args = array( 'child_of' => $current_term->term_id, 'hide_empty'=>false);
                    $terms = get_terms( 'tagportifolio', $args);
                    $assoc = taxonomy_image_plugin_get_associations();

                    if (!empty($terms)):
                    foreach( $terms as $child ):
                    ?>
                    <div id="cat-<?php echo $child->term_id; ?>">
                        <?php
                            if(array_key_exists( $child->term_taxonomy_id, $assoc )){
                                 echo wp_get_attachment_image( $assoc[$child->term_taxonomy_id], array(), false, 'thumbnail');
                             }
                        ?>

<a href="<?php echo get_term_link( $child->name, $taxonomyName );?>">
                        <?php echo $child->name; ?>

                       <?php
                        endforeach;
                        endif;
                        ?>

            <?php
                // action hook for placing content below #content
                thematic_belowcontent();
            ?>

<?php
    // action hook for placing content below #container
    thematic_belowcontainer();

    // calling the standard sidebar
    thematic_sidebar();

    // calling footer.php
    get_footer();
?>

A: If you have named your sidebar file sidebar.php then you should use get_sidebar() and not thematic_sidebar().  Do you use thematic_sidebar() on other template files and does this work?
EDIT
Wanted to help you debug so I have edited my answer
ok downloaded thematic and installed in local IDE,
thematic_sidebar(){

$show = TRUE;
    $show = apply_filters('thematic_sidebar', $show);

    if ($show)
        get_sidebar();

    return;
}

One way to test this since you are developing online is to echo statements to confirm if you get into the function
e.g. echo '
You made it into the sidebar function
';
Place this at the top above $show = TRUE;
If this does not echo then you will have to test previous functions, if it does then the path to your sidebar.php file may be broken. Tested locally and the echo works so give it a try, copy and paste the code into your sidebar and check, try it in other functions just to ensure these are being executed. Hope this helps


text:
Q: Reverse for '' not found Django Can't find the problem
urls.py
path("office", views.office, name="office")

views.py
def office(request):
    offices_list = Office.objects.all()
    context = {'offices_list': offices_list}
    return render(request, "auctions/office.html", context)

template

    office

Error:
Reverse for '' not found. '' is not a valid view function or pattern name.

A: had to delete html page and rebuild it.
worked like charm.
still do not know what the issue was .
Thank you all for your kind contribution !


text:
Q: Write to console Unicode (UTF-16) text with Windows WinAPI functions? I have a 64 bit masm code that outputs to a console. The problem is that by using WriteConsoleW, i'm not able to redirect the output of a command or anything since it only writes to the console buffer. But using WriteFile adds spaces between each character since the 16 bit chars have the high-order bits zeroed out. How can i print Unicode text with WriteFile ?
I read here that I could use BOM but that just doesn't work for me (I added another WriteFile call that writes the two bytes FF FE before the second WriteFile call, but it just printed a white rectangle and nothing else).
Here's the code:
extern GetStdHandle: proc
extern WriteConsoleW: proc
.data?
    written dq ?
.data
    string dw 0048h,0065h,006ch,006ch,006fh,0020h,0057h,006fh,0072h,006ch,0064h,0021h
    len equ $-string
.code
main proc
    push    rbp
    mov rbp, rsp
    sub rsp, 020h
    and rsp, -10h

    mov rcx, -11
    call    GetStdHandle
    mov rcx, rax
    mov rdx, offset string
    mov r8, len
    mov r9, written
    call    WriteConsoleW

    add rsp, 020h
    mov rsp, rbp
    pop rbp
    ret
main endp
end

When i swap WriteConsoleW to WriteFile, it prints correctly when ran through visual studio, but when i run the generated exe from a command line, instead of printing Hello World! it prints H e l l o  W o r l d !
Does anyone know how to deal with that ?
EDIT:
I'm not sure how to understand this but somehow when i use WriteFile instead, the 16 bit characters get printed wrong only when i execute the program alone. However when i redirect the output to the echo command it prints normally:

A: The same APIs in C++ produce the same console output.  WriteConsoleW performs a character translation to the console that WriteFile doesn't.
WriteFile just sends bytes to the console which interprets them in the  current code page, which for me is 437 (OEM United States).
I was able to get it to work in C++ by calling SetConsoleOutputCP(65001) (set console code page to UTF-8) nad then writing a UTF-8 string.  Note this list of code page identifiers which includes UTF-16 but it is only available for managed applications (e.g. C#).
I printed some non-ASCII to see if it came out correctly.
// compiled with MSVS "cl /W4 /utf-8 test.cpp"
// source saved in UTF-8 as well.
#include <windows.h>

int main() {
    char s[] = u8"Hello, 马克"; // Note: need a chinese font, but cut/paste
                               // to Notepad and you'll see them if you don't.
    SetConsoleOutputCP(65001);
    auto h = GetStdHandle(STD_OUTPUT_HANDLE);
    DWORD written;
    WriteFile(h, s, sizeof(s), &written, nullptr);
}

Output:
Hello, 马克

You should be able to adapt this to MASM easily.
If you are willing to use the C runtime library, then these APIs both work for UTF-16 if you set the console and file mode appropriately:
#include <stdio.h>
#include <io.h>
#include <fcntl.h>

int main()
{
    _setmode(_fileno(stdout), _O_U16TEXT);
    wchar_t s[] = L"Hello, 马克!";
    _write(_fileno(stdout), s, sizeof(s));
    int fd = _open("test.txt", _O_CREAT | _O_WRONLY | _O_U16TEXT);
    _write(fd, s, sizeof(s));
    _close(fd);
}

Output to console:
Hello, 马克!

Output to test.txt encoded in UTF-16LE.  Note that 马克 is the two unicode code points U+9A5C and U+514B:

EDIT
Here's a demo of GetFileType.  If run it writes to the console correctly.  If redirected to a file, e.g. "test > out.txt", the output file contains UTF-16LE-encoded data.
#include <windows.h>

int main()
{
    auto h = GetStdHandle(STD_OUTPUT_HANDLE);
    auto type = GetFileType(h);

    WCHAR s[] = L"Only 20\u20AC!";  // U+20AC is EURO sign.
    DWORD written;

    if(type == FILE_TYPE_DISK)
        WriteFile(h, s, sizeof(s) - sizeof(WCHAR) /* don't send the null */, &written, nullptr);
    else
        WriteConsoleW(h, s, sizeof(s) / sizeof(WCHAR) - 1, &written, nullptr);
}

Output to console:
Only 20€!

Output redirected to out.txt:


text:
Q: ag-grid copy and paste a cell with double quotation Have a question about ag-grid copy&paste.
If a cell contains a double quotation, the strings after this quotation will lose after paste.
https://www.ag-grid.com/javascript-grid-clipboard/
Go to the first example of this page, add a grid property "suppressCopyRowsToClipboard=true" to prevent whole row copy. Then change the cell Michael Phelps to Michael Michael Phelps "test", and copy this cell. When paste it into another cell, it will be Michael Phelps rather than Michael Phelps "test".
So is it the rule of ag-grid that double quotation cannot be paste?


text:
Q: Automata Language regularity proof by construction. I've been trying to prove or disprove a question that popped during our last session in Uni, we've been using automaton constructing to prove regularity for a while now and I really do have the handle of it but I'm having difficulty with this one, assume L over Sigma is regular , prove that the language xZy is regular if given that yx belongs to L. (x is a suffix y is a preffix in L). Now, if the language to prove was yZx (keep in mind Z is a letter NOT in Sigma) then I could just take 2 copies of the given DFA of the regular L and connect each state in the first copy to a state in the second copy through a Delta(q1,Z) = q2 thus creating yZx from 2 yx automatons, the issue here is that the regular language is flipped I.E. xy is given and you need to prove yZx rather than xZy, I thought about trying to prove that if yx is regular then xy is regular and then use the new ragular language like I stated but I didn't manage that as well, the only almost possible soultion I found was using Cycle(L) - I thought about proving a cycle(L) to be regular (I know thats true) so that if I have L={ab,abb} I can prove cycle(L) is regular I.E L' = {ab,abb,ba,bab,bba} and then do intersection between L and L' so I will have only the words flipped but that does not give me XY from YX....
I've also tried using 2 copies of the DFA of L, and adding a state q(-1) connected through epsilons to all other states in the first one and a q(n+1) state on the second automaton connecting every state on the second automaton to it, then if I had the expression xy , I can start from y using the epsilon then moving through the Z to the second copy and then do X on the second copy and using epsilon to go to the finishing state...
It sounded good in my head but I couldnt write it formally and stumbled upon various issues trying to do so...
So, in conclusion. I'm lost. Any suggestion or even a hint as to how to construct this language will be appriciated...

A: Hint: Let $M_y$ be the automaton that recognizes suffixes from $L$ and $M_x$ be the automaton that recognizes prefixes from $L$.  Neither automaton has any transitions on $Z$, since $Z\notin\Sigma$.
Could you connect $M_y$ to $M_x$ somehow, and let $M_y$ recognize the $y$ part of the input string, and $M_x$ recognize the $x$ part?


text:
Q: Interactive Brokers: Unable to fetch Forex Historical data I am trying IB very the first time. I am trying to fetch historical data of $EUR but I am getting an error:

Error 162, reqId 3: Historical Market Data Service error message:No
historical market data for EUR/CASH@FXSUBPIP Last 1800, contract:
Contract(secType='CASH', symbol='EUR', exchange='IDEALPRO',
currency='USD')

Below is my code:
import datetime

from ib_insync import *

if __name__ == '__main__':
    ib = IB()
    r = ib.connect('127.0.0.1', port=7497, clientId=1)
    contract = Contract()
    contract.symbol = "EUR"
    contract.secType = "CASH"
    contract.currency = "USD"
    contract.exchange = "IDEALPRO"

    data = ib.reqHistoricalData(
        contract=contract,
        endDateTime='',
        durationStr='100 D',
        barSizeSetting='30 mins',
        useRTH=True,
        whatToShow='ADJUSTED_LAST'
    )

A: https://interactivebrokers.github.io/tws-api/historical_bars.html#available_products_hd
You can see that whatToShow='ADJUSTED_LAST' needs to be something available for forex like MIDPOINT.  Obviously there are no dividends to adjust for.
Also, there is no real forex exchange and comprehensive data, all you get is what is happening at IB.


text:
Q: How to "unbind" an event handler attached to an event in the base class when I'm in a derived class? I had once a situation where I had to override the event handler in some derived class of mine. I could not unfortunately just "override" it since the implementation logic was bound strictly to that particular method implementation in the base class.
My natural idea was to first "unbind" the original event handler from the event and then to bind my own brand-new method. So I tried to use the "-=" operator like:
myObject.SomeEvent -= new EventHandler (BaseClass.SomeEventHandler)

at which point the compiler complainer that it had no access to the private method SomeEventHandler. Since the base class was a part of the library I did not really want to modify its implementation (though simply as it seems by just turning "private" into "protected");
It's so simple to attach an event handler to an event. Why is it so difficult to get rid of one?
Why I wanted it? Because the base implementation was casing some problems (just did not handle our particular case) so I wanted to redefine it. But even after I attached my event handler the base implementation was getting executed anyway. Since it was doing some kind of Redirect, my own implementation was never going to run since the request processing was being broken at server after redirect.
Is there anyway to get rid of an event handler in a base class from a library without modifying its implementation?

A: It would be just as easy to get rid of the handler if your code can officially see the handler. If absolutely necessary, it is possible to unsubscribe using reflection to get hold of the delegate, but this is messy. It would be a lot cleaner and safer to either a: avoid the requirement, or b: change the code to make the handler protected.

Reflection approach (use at own risk); uncomment the block in the Bar.ctor() to see the change.
using System;
class Foo
{
    public event EventHandler SomeEvent;
    public Foo()
    {
        SomeEvent += SecretHandler; // a bad idea, anyway
                                    //(self-subscribed events....)
    }
    protected virtual void OnSomeEvent()
    {
        EventHandler handler = SomeEvent;
        if (handler != null) handler(this, EventArgs.Empty);
    }
    private void SecretHandler(object sender, EventArgs args)
    {
        Console.WriteLine("suscribed");
    }
}
class Bar : Foo
{
    public Bar()
    {
        /*
        MethodInfo method = typeof(Foo).GetMethod("SecretHandler",
            BindingFlags.NonPublic | BindingFlags.Instance);
        EventHandler handler = (EventHandler)Delegate.CreateDelegate(
            typeof(EventHandler), this, method);
        SomeEvent -= handler;
         */
    }
    public void Test()
    {
        OnSomeEvent();
    }
}
static class Program
{
    static void Main()
    {
        Bar bar = new Bar();
        bar.Test();
    }
}


text:
Q: PCA for reducing number of variables I have 200 variables and about 300 subjects. I wanted to create a subset of variables based on the 200 variables I have. Basically, I wanted to reduce the amount of variables (currently 200) to a smaller number (ex: 10). Can I use factor analysis or PCA?
I tried to do PCA using SPSS but the results seemed weird. The results contained everything (KMO, eigen values, component matrix, etc.). However, there were no results for Bartlett's Test of Sphericity. My first question is, why was the Bartlett's Test of Sphericity not performed?
My 2nd question is: is it OK to do a PCA with 200 variables and 200 subjects?
My third question is: what are other techniques I can use to reduce the number of variables (i.e., dimension reduction)?


text:
Q: Problems with parallel axis theorem The parallel axis theorem states that $I_{\rm new} = I_{\rm original} + Mh^2$ where $h$ is the displacement from the original axis of rotation. However, I'd like to describe a situation which proves that this doesn't always work.
Say we have an equilateral triangle with one side pointed straight upwards and the vertex to the right:

Say that we take this vertical length as the axis of rotation. $I = \frac{1}{8}Ma^2$ then where $a = \rm side\ length$. Say we move the axis of rotation $a$ length $h$ to the left (situation 1) and then again $a$ length $h$ to the right (situation 2) with $h$ being equal to the height of the triangle. In both cases, according to the formula, we end up with the same final moment of inertia.

Situation 1: The longest side (with most mass) is $h$ away from the axis of rotation, and the vertex is $2h$ away.
Situation 2: The longest side (with most mass) is $h$ away from the axis of rotation, and the vertex is $0h$ away.
The moment of inertia must be smaller in situation 2. Clearly the formula can't always be applied. Could someone please describe the situations in which it can and can't?

A: The parallel axis theorem states:
Suppose a body of mass $m$ is made to rotate about an axis $z$ passing through the body's centre of gravity. The body has a moment of inertia $I_\text{cm}$ with respect to this axis. The parallel axis theorem states that if the body is made to rotate instead about a new axis $z′$ which is parallel to the first axis and displaced from it by a distance $d$, then the moment of inertia $I$ with respect to the new axis is related to $I_\text{cm}$ by
$$ I = I_\text{cm} + md^2 $$
Note the text I've emboldened. You cannot apply the parallel axis theorem to your initial situation because the axis does not pass through the centre of gravity.
Let's denote the distance from your original rotation axis to the centre of mass by $d$:

So that $I_\text{cm} = I - md^2$. Then the moment of inertia for your situation $1$ is:
$$ I_1 = I - md^2 + m(h+d)^2 $$
And the moment of inertia for your situation $2$ is:
$$ I_2 = I - md^2 + m(h-d)^2 $$
And as you rightly say $I_1 \ne I_2$.


text:
Q: Is there a way to convert DocX, OpenXml, or RTF to TextFlow in AS3? Basically we want to be able to open up a docx file in as3 or Flex 4 and convert it to a text flow while preserving formatting, embedded images, tables, columns, etc.   I know theorectically it's possible as the new Text Layout Framework is powerful enough to pull it off, but I haven't been able to find any case where someone has achieved anything along these lines except for Adobe's BuzzWord web app which does just this.   Ideally the solution would be for RTF documents as conversions to RTF from anything are pretty familiar.

A: Buzzword was built before the Text Layout Framework existed; so I do not think it uses it.  I was also under the impression--with no facts to back it up--that Buzzword did a server side conversion of the document; not a client side conversion.
I don't know of any AS3 projects that do this and would recommend taking a look at server side ways to access the data inside the word document.  The Apache POI project is one option: http://poi.apache.org/ .
From there you'd have to create your own conversion from doc to something AS3 can handle.


text:
Q: How to sort a 2d matrix by column? I have this following code where i sort a 2d matrix every element inserted in columns.
for example:
5 4

2 4 1 3
9 8 7 6
20 19 18 16
30 29 124 12
59 21 0 3

0 4 12 21
1 6 16 29
2 7 18 30
3 8 19 59
3 9 20 124

My first method of sorting is this one:
vector<vector<int>> w;
vector<int> v;
int n,m,x;

cin >> n >> m;
w.resize(n, vector<int>(m));

for(int i=1; i <= n*m; i++)
    cin >> x,v.push_back(x);

sort(v.begin(), v.end());
int k=0;

for(int i=0; i < m; i++)
{
    for(int j=0;j<n;j++)
        w[j][i]=v[k++];
}

for(int i=0; i < n; i++)
{
    for(int j=0;j<m;j++)
        cout << w[i][j] << " ";
    cout << '\n';
}

my second :
for(int i=0;i<m;i++)
    for(int j=0;j<n;j++)
        for(int k=i;k<m;k++)
        {
            int l;
            if(i==k)
                l=j;
            else
                l=0;
            for(;l<n;l++)
                if(a[j][i]>a[l][k])
                    swap(a[j][i],a[l][k]);
        }

My question is: Isn't there an easier way to sort the 2d matrix, without using two vectors and without using like the second method 3- for (it becomes too slow for thousands of rows)?

A: The 2D vector is unneeded, you might display your 1D vector as 2D:
int n,m;
std::cin >> n >> m;
std::vector<int> v;
//v.reserve(n * m);
for (int i = 0; i != n * m; i++) {
    int x;
    std::cin >> x;
    v.push_back(x);
}
std::sort(v.begin(), v.end());
for (int i = 0; i < n; i++)
{
    for (int j = 0; j < m; j++)
        std::cout << v[j * n + i] << " ";
    std::cout << '\n';
}

Demo


text:
Q: Why does cuDNN not load (GPU)? im new in Neural Networks etc. and i wanted to download Keras-/Tensorflow-GPU, but it didn't worked properly. I have a Nvidia GTX 1080, and my Graphics Drivers are the newest. The CPU Version with Tensorflow works properly.
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D

model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3), input_shape=(32, 32, 3), activation="relu"))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))

model.add(Flatten())
model.add(Dense(128, activation="relu"))
model.add(Dense(1, activation="sigmoid"))

model.compile(optimizer="rmsprop", loss="binary_crossentropy", metrics=["accuracy"])

And this is the error
Epoch 1/10
---------------------------------------------------------------------------
UnknownError                              Traceback (most recent call last)
<ipython-input-5-95e0cf113d6b> in <module>
      1 y_train_car = y_train == 1
      2
----> 3 model.fit(X_train, y_train_car, batch_size=128, epochs=10, shuffle=True)

~\.conda\envs\gputest\lib\site-packages\keras\engine\training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_freq, max_queue_size, workers, use_multiprocessing, **kwargs)
   1237                                         steps_per_epoch=steps_per_epoch,
   1238                                         validation_steps=validation_steps,
-> 1239                                         validation_freq=validation_freq)
   1240
   1241     def evaluate(self,

~\.conda\envs\gputest\lib\site-packages\keras\engine\training_arrays.py in fit_loop(model, fit_function, fit_inputs, out_labels, batch_size, epochs, verbose, callbacks, val_function, val_inputs, shuffle, initial_epoch, steps_per_epoch, validation_steps, validation_freq)
    194                     ins_batch[i] = ins_batch[i].toarray()
    195
--> 196                 outs = fit_function(ins_batch)
    197                 outs = to_list(outs)
    198                 for l, o in zip(out_labels, outs):

~\.conda\envs\gputest\lib\site-packages\tensorflow_core\python\keras\backend.py in __call__(self, inputs)
   3725         value = math_ops.cast(value, tensor.dtype)
   3726       converted_inputs.append(value)
-> 3727     outputs = self._graph_fn(*converted_inputs)
   3728
   3729     # EagerTensor.numpy() will often make a copy to ensure memory safety.

~\.conda\envs\gputest\lib\site-packages\tensorflow_core\python\eager\function.py in __call__(self, *args, **kwargs)
   1549       TypeError: For invalid positional/keyword argument combinations.
   1550     """
-> 1551     return self._call_impl(args, kwargs)
   1552
   1553   def _call_impl(self, args, kwargs, cancellation_manager=None):

~\.conda\envs\gputest\lib\site-packages\tensorflow_core\python\eager\function.py in _call_impl(self, args, kwargs, cancellation_manager)
   1589       raise TypeError("Keyword arguments {} unknown. Expected {}.".format(
   1590           list(kwargs.keys()), list(self._arg_keywords)))
-> 1591     return self._call_flat(args, self.captured_inputs, cancellation_manager)
   1592
   1593   def _filtered_call(self, args, kwargs):

~\.conda\envs\gputest\lib\site-packages\tensorflow_core\python\eager\function.py in _call_flat(self, args, captured_inputs, cancellation_manager)
   1690       # No tape is watching; skip to running the function.
   1691       return self._build_call_outputs(self._inference_function.call(
-> 1692           ctx, args, cancellation_manager=cancellation_manager))
   1693     forward_backward = self._select_forward_and_backward_functions(
   1694         args,

~\.conda\envs\gputest\lib\site-packages\tensorflow_core\python\eager\function.py in call(self, ctx, args, cancellation_manager)
    543               inputs=args,
    544               attrs=("executor_type", executor_type, "config_proto", config),
--> 545               ctx=ctx)
    546         else:
    547           outputs = execute.execute_with_cancellation(

~\.conda\envs\gputest\lib\site-packages\tensorflow_core\python\eager\execute.py in quick_execute(op_name, num_outputs, inputs, attrs, ctx, name)
     65     else:
     66       message = e.message
---> 67     six.raise_from(core._status_to_exception(e.code, message), None)
     68   except TypeError as e:
     69     keras_symbolic_tensors = [

~\.conda\envs\gputest\lib\site-packages\six.py in raise_from(value, from_value)

UnknownError:  Failed to get convolution algorithm. This is probably because cuDNN failed to initialize, so try looking to see if a warning log message was printed above.
     [[node conv2d_1/convolution (defined at C:\Users\seyaf\.conda\envs\gputest\lib\site-packages\keras\backend\tensorflow_backend.py:3009) ]] [Op:__inference_keras_scratch_graph_858]

Function call stack:
keras_scratch_graph

I have donwloaded Keras-GPU trough cmd and i use it with Anaconda, i also have updated Anaconda


text:
Q: XHTTPRequests on client side If I understand this right, on FireFox, since somewhere in august 2019,
XHTTPRequests can no longuer be made on client side.
Loading a local XML file made by oneself can't be loaded by xhr.
And the examples and tutorials on the web that were working before
now must be executed only on Server side?
Would there be any way to bypass this hindrance otherwise than by installing an old copy of FireFox?
I've developped a few local applications using xhr for more than a decade
to load xml files off line in order to create a readable/printable html version.
It's a bit disturbing having to revisit what was performing flawlessly for so long...
Any other suggestions (than using old versions or installing an Apache server)?


text:
Q: Why does flexbox container split list items in two lines? I have a flex element  which contains two flex items:  and

My goal is to display flex items horizontally in one line like in this photo:

but the result which I get is:

I have figured out that my problem may be solved by using flex-basis: 100%; But the behaviour of the flexbox container is not understandable for me.
Why does it split
 items in two lines instead of displaying them in one?
html:

   LOGO

Library

Telegram channel

Contacts

Donate

css:
span {
   border: 1px solid black;
   margin-right: 10px;
}
ul {
   padding: 10px;
}
li {
   display: inline-block;
   padding: 0 5%;
   border: 1px solid black;
}
header {
   display: flex;
   align-items: center;
}

A: use width:100% and margin:0 for ul

span {
   border: 1px solid black;
   margin-right: 10px;
}
ul {
   padding: 10px;
    margin:0;
    width:100%;
}
li {
   display: inline-block;
   padding: 0 5%;
   border: 1px solid black;
}
header {
   display: flex;
   align-items: center;
}

   LOGO

Library

Telegram channel

Contacts

Donate


text:
Q: Rename dataframe column names by switching string patterns I have following dataframe and I want to rename the column names to c("WBC_MIN_D7", "WBC_MAX_D7", "DBP_MIN_D3")
> dataf <- data.frame(
+     WBC_D7_MIN=1:4,WBC_D7_MAX=1:4,DBP_D3_MIN=1:4
+ )
> dataf
  WBC_D7_MIN WBC_D7_MAX DBP_D3_MIN
1          1          1          1
2          2          2          2
3          3          3          3
4          4          4          4
> names(dataf)
[1] "WBC_D7_MIN" "WBC_D7_MAX" "DBP_D3_MIN"

Probably,  the rename_with function in tidyverse can do it, But I cannot figure out how to do it.

A: You can use capture groups with sub to extract values in order -
names(dataf) <- sub('^(\\w+)_(\\w+)_(\\w+)$', '\\1_\\3_\\2', names(dataf))

Same regex can be used in rename_with -
library(dplyr)

dataf %>% rename_with(~ sub('^(\\w+)_(\\w+)_(\\w+)$', '\\1_\\3_\\2', .))

#  WBC_MIN_D7 WBC_MAX_D7 DBP_MIN_D3
#1          1          1          1
#2          2          2          2
#3          3          3          3
#4          4          4          4

A: You can rename your dataf with your vector with names(yourDF) <- c("A","B",...,"Z"):
names(dataf) <- c("WBC_MIN_D7", "WBC_MAX_D7", "DBP_MIN_D3")


text:
Q: Assigning an instance's method from another class? I have a finalised class called SimObject. In this class, there is a public function called Draw().
Instead of extending and overriding from SimObject in another new class, I would like to assign a method to replace Draw() from my Main class. The Main class creates the SimObject and holds an instance of it. So how can I do something like this:
public class Main {
   public static void Main() {
      //constructor
      var obj = new SimObject();
      obj.Draw = MyNewDrawMethod;
   }

   public void MyNewDrawMethod() {
      //some code
   }
}

Is this possible in c#?

A: You can use Extension Method if you do not want to inherit it but want to extend it.
public class MyList{

}

public static class MyZListExtesion
{
    public static void DrawSomethingElse(this MyList obj)
    {
        // override Draw from here
    }
}

and the usage
new MyList().DrawSomethingElse();

A: It doesn't allow you to assign the method but you can add functionality using an extension method.
public static class SimObjectExtensions
{
    public static void Draw(this SimObject obj)
    {
        // some code
    }
}

This will allow you to use the Draw method as if it were an instance method of SimObject
SimObject o = new SimObject();
o.Draw();


text:
Q: Make sure ctypes DLL is called from my extension I have scenario where my extension Javascript loads a native DLL (also built by me). I would like to know inside the native library that my extension's Javascript is making the calls.
I can figure out that the calling process is firefox, but is there anyway that Firefox forwards me information what extension is calling the native part?


text:
Q: String Interpolation in Visual Studio 2015 and IFormatProvider (CA1305) The new string interpolation style in Visual Studio 2015 is this:
Dim s = $"Hello {name}"

But if I use this the code analysis tells me I break CA1305: Specify IFormatProvider
In the old times I did it like this:
Dim s = String.Format(Globalization.CultureInfo.InvariantCulture, "Hello {0}", name)

But how can it be done with the new style?
I have to mention that I'm looking for a solution for .Net 4.5.2 (for .Net 4.6 dcastro has the answer)

A: Microsoft has made it easier to use string interpolation and comply with CA1305: Specify IFormatProvider.
If you are using C# 6 or later, you have access to the using static directive.
In addition, the static method FormattableString.Invariant is available for .NET Standard 1.3, .NET Core 1.0 and .NET Framework 4.6 and later. Putting the two together allows you to do this:
using static System.FormattableString;

string name = Invariant($"Hello {name}");

If, however, your goal is for the interpolation to be done via the current culture, then a companion static method FormattableString.CurrentCulture is proposed in .NET Core 3.0 (currently, Preview 5):
using static System.FormattableString;

string name = CurrentCulture($"Hello {name}");

A: I have found a Nuget-Package that covers the code that jessehouwing presented in his answer.
The Nuget package 'StringInterpolationBridge' (source) adds this code to every project.

A: You'd use the System.FormattableString or System.IFormattable class:
IFormattable ifs = (IFormattable)$"Hello, {name}";
System.FormattableString fss = $"Hello, {name}";

// pass null to use the format as it was used upon initialization above.
string ifresult = ifs.ToString(null, CultureInfo.InvariantCulture);
string fsresult = fss.ToString(CultureInfo.InvariantCulture);

You need to be compiling against Framework 4.6, as the IFormattable and FormattableString are classes which do not exist in older versions. So if you're targeting older versions of the .NET framework you can't use the interpolation syntax without triggering the error.
Unless you apply a little hack (adapted to compile against 4.6 RTM from Jon Skeet's gist and forked to my own account.). Just add a class file to your project containing:

Update
There is now also a Nuget package available that will provide the same functionality to your project (thanks for bringing this to my attention @habakuk).
install-package StringInterpolationBridge

Or if you want to achieve the same thing without adding an additional assembly to your product add the following code to your project:
namespace System.Runtime.CompilerServices
{
    internal class FormattableStringFactory
    {
        public static FormattableString Create(string messageFormat, params object[] args)
        {
            return new FormattableString(messageFormat, args);
        }
    }
}

namespace System
{
    internal class FormattableString : IFormattable
    {
        private readonly string messageFormat;
        private readonly object[] args;

        public FormattableString(string messageFormat, object[] args)
        {
            this.messageFormat = messageFormat;
            this.args = args;
        }

        public override string ToString()
        {
            return string.Format(messageFormat, args);
        }

        public string ToString(string format, IFormatProvider formatProvider)
        {
            return string.Format(formatProvider, format ?? messageFormat, args);
        }

        public string ToString(IFormatProvider formatProvider)
        {
            return string.Format(formatProvider, messageFormat, args);
        }
    }
}

See:

*

*https://msdn.microsoft.com/en-us/library/dn961160.aspx

A: If you're targeting the .NET Framework 4.6, you can take advantage of the fact that string interpolations are implicitly convertible to FormattableString:
From Customizing string interpolation in C# 6 by Thomas Levesque

A lesser known aspect of this feature is that an interpolated string can be treated either as a String, or as an IFormattable, depending on the context.

static string Invariant(FormattableString formattable)
{
    return formattable.ToString(CultureInfo.InvariantCulture);
}

string text = Invariant($"{p.Name} was born on {p.DateOfBirth:D}");


text:
Q: Move object creation to setup() function of arduino I've created a class that handles sending data to a led matrix (max7219).
This is what I was doing to create an instance of the LedControl class.
LedControl lc=LedControl(11, 13, 12);// data, clock, latch;

void setup()
{
   ...
}

Now I'm trying to add timer-interrupts to my class. But I found that I can't set the appropriate registries in the initializer (LedControl::LedControl()). If I move this code to setup, it all works perfectly. My guess is that the Arduino bootloader, which uses timer1 for PWM overwrites these registries, just before calling setup() but after my object has been initialized.
So my idea was to just move the object creation to the setup function like so
// FAIL
LedControl lc;

void setup()
{
   lc=LedControl(11, 13, 12);// data, clock, latch;
   ...
}

But then I get the error no matching function for call to 'LedControl::LedControl()'
I tried using pointers (LedControl *lc; lc=&LedControl(11, 13, 12);), but as far as I could tell, this would mean I would have to write (*lc).someFunction() everywhere instead of lc.someFunction(). Even less elegant than moving the registry setting code to setup().
So my question is. How do I create an object in the setup() function, but still have a global variable pointing to it?

A: I just stumbled over the same problem. I wanted to create a global debug port object, but I couldn't create it as global instance, as the port won't work after setup() was called. I have the same assumptions that the arduino code does some setup stuff after my constructor (of the global object) and before setup().
I found it the easiest solution, to declare my object as a pointer and init it in setup. In your situation it would be:
LedControl* lc;

void setup()
{
   lc = new LedControl(11, 13, 12);// data, clock, latch;
}

void loop()
{
   lc->doSomething();
}

So there's no need for additional constructors or operators.
As the object is used until power down, theres is no delete needed in this case.

A: Your first error "no matching.. " is because you have no default constructor.  You can make that approach function.
Add a no parameter, AKA default constructor, to the class, like this:
class LedControl {
  LedControl();
  LedControl(uint8_t pin1, uint8_t pin2, uint8_t pin3);

private:
  uint8_t pin1;
  uint8_t pin2;
  uint8_t pin3;
};

LedControl::LedControl() : pin1(0), pin2(0), pin3(0) {
  // this constructor leaves the class unusable
}

LedControl::Ledcontrol(uint8_t p1, uint8_t p2, uint8_t p3)
  : pin1(p1), pin2(p2), pin3(p3)
{
  // this object is ready to use
}

With this class, your approach will work, but is not the optimal method.  This line does too much work:
void setup() {
  lc = LedControl(11, 13, 12);// data, clock, latch;
}

This line of code involves the compiler creating some code for you:

*

*First another instance of the class is constructed on the stack using the parameters 11,13,12.

*Then it applies the = operator copying the data from the stack object to your global object.

*When setup() exits, the stack object is flushed.

Because the temporary object is on the stack, your program didn't use too much memory, but your code size is larger because it involves extra operations to construct the temporary then copy from the temporary to the permanent.
Note that the compiler is creating an = operator for you, to fill the function of the line
  lc = LedControl(11, 13, 12);

This may or may not work depending on what is in your constructor.  The compiler can only presume that you needed a simple = operator.  All the basic assignment operator will do is copy all the data members from the instance on the right side of the = to the instance on the left side.  The compiler constructed = will not contain any code.
If your constructor does anything significant (other than save the parameters) then the compiler constructed(guessed) assignment operator may not work as you expected.  For your case the constructor probably sets the pin modes, something like this:
LedControl::LedControl(uint8_t p1, uint8_t p2, uint8_t p3)
  : pin1(p1), pin2(p2), pin3(p3)
{
  pinMode(pin1, INPUT);
  pinMode(pin2, OUTPUT);
  pinMode(pin3, OUTPUT);
  return;
}

This happens to function, but only by chance.  The pinMode() calls are made when the temporary object is constructed and called from that object, not from the global lc.  Because pinMode()'s are global this case will achieve the correct goal, but maybe not in the way expected.  For more complex operations such as registering interrupt handlers, you will need to create your own assignment operator:
LedControl& operator= (const LedControl & other);

In that method, you could ensure that the state of the global lc is what you need.  An easier/safer approach is to not deal with that at all.
A simple and efficient approach, you may have seen in other libraries is to add a method to the class that assigns the pins:
class LedControl {
  void attach(uint8_t pin1, uint8_t pin2, uint8_t pin3);
};

void LedControl::attach(uint8_t pin1, uint8_t pin2, uint8_t pin3) {
  this.pin1 = pin1;
  this.pin2 = pin2;
  this.pin3 = pin3;
  // do other setup type operations
  return;
}

Now your program, constructs the blank object, and assigns pins during setup():
LedControl lc; // not ready to use until attach pins

void setup() {
  lc.attach(11, 13, 12);// data, clock, latch;
  ...
}

This involves no temporary object construction, and no assignment operator.  With respect to design, some people might fairly comment that the user might forget to call attach() and leave the global lc object unusable.  For a desktop application, you might add some code to prevent that failure case.  For an embedded application, that is a risk you accept which is balanced by the gains in code size or memory savings.


text:
Q: Firebase Storage share download url a security risk? I have an image saved in my Firebase Storage. I would like to display this image in multiple emails that I send. I have so far used the download URL as obtained from my Firebase console and the image displays successfully. My question is: Is this the correct way of sharing the image? Is it secure? If not, then how should I get a secure link to that image?
Here's where I got the download URL from, in the Firebase console:

Any help on this would be appreciated.

A: Using a download URL is the appropriate way to share files outside of an application, or to users who don't need to be logged in.
I'm curious what you mean by "is it secure"? If you're sharing the object with someone, they can forward the link to someone else who can download it, but they can also just download the object and share it as well.
If you want to control access based on a particular user, you'll need to have users log in and download the objects in an application, rather than using download URLs. Granted, again, here they can take the downloaded object and share it with anyone else.


text:
Q: Using Google BigQuery as a backend for Django I am considering using Google BigQuery as a back-end for Django but cannot be certain if this is possible, and if it is, what settings would apply.
Currently, my Django application uses Postgresql, and the code in settings.py is as follows:
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'mydatabase',
        'USER': 'mydatabaseuser',
        'PASSWORD': 'mypassword',
        'HOST': '127.0.0.1',
        'PORT': '5432',
    }
}

Ideally, I'd like to setup a database connection to Google BigQuery through settings.py and then use views and models as usual.

A: It's not possible, or at least not supported. You could use the API directly, but obviously you won't get any advantages of the ORM.

A: You should have a db motor like postgres, mysql, whatever...
The point is, this db motor is necessary to have it, because the structure works in that way.
but of course, you can invoke google cloud from librarys in django and use it as
from google.oauth2 import service_account
from google.auth.transport.requests import AuthorizedSession
from google.cloud import datastore
from google.cloud import bigquery
in my case I used to connect
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'OAuth2Credential.json'
for generate your .json you should go to the documentation in:
https://cloud.google.com/iam/docs/creating-managing-service-account-keys

A: It is possible by using SQLAlchemy with Django.
SQLAlchemy can connect to bigquery with the pybigquery driver.
See the following about how to
Configuring Django to use SQLAlchemy.

A: Everything is possible for sure. To create an interface would not be such a big job. But, I would just keep one note:
Bigquery is not intended to be backend database, rather it is more like data warehouse as it is defined within business intelligence discipline. This means, google will make it very hard for you to perform fast multi-user operations. As far as I can recall, update statements for example have have some thresholds.
On another hand, if this is purely for example data input, or visualisation of data, then why not. But then again, I think Azure power apps is kind of a product for it.


text:
Q: Could someone explain "%m" Im pretty new to C. And i was stumbeling on %m in scanf when i was trying to build a function similar to input() in Python3.
And i tried it and it worked i i dont know why. The code:
void *input(char *startStr){
      char *str;
      printf(startStr);
      scanf("%m[^\n]", &str);
return str; }

The %m doesn't seem to be a standard specifier in C.
My dev environment is on Ubuntu with gcc 6.2.0?
Any Captain here that could explain it for me?
And thank you for being Awesome people on this community!
EDIT:
We can close this question, all the links provided will explain it, and there's a similar question asked, that didn't show up when i searched StackOverflow for my problem. But now i'm enlightened in this question, and i hope all others in their hunt for enlightenment will follow the links provided to get their answer in this particular domain of specifiers for scanf.
difference between %ms and %s scanf
https://linux.die.net/man/3/scanf
https://linux.die.net/man/3/sscanf


text:
Q: How to have a reliable Volley request with no retries policy When I am on a slow connection and making a POST request, Volley retries my request multiple times and after it all ends up hitting my errorListener. Sometimes, these retries actually succeeded in posting data.
The user will assume that the request failed, but in truth, if they refreshed the data they'd see the data was POSTed twice to the server (or however many successful retries in the bunch).
I want give Volley a very dumbed-down retry policy:
I want it to try a request for 15 seconds and if the request doesn't reach the server within 15 seconds and comes back with a response to trigger the errorListener. I don't want it to retry at all.
The only concern is if Volley tries, the request gets to the server within 20~25 seconds, but by then it triggered the errorListener and the data still got POSTed.
Does HTTP follow a time-limit after which it is 100% the data won't get posted because the request took too long? Like maybe 40 seconds? If such, then I can have the request go on for 40 seconds.
In all:
No retries and ensure 100% that if data got posted on first try go to successListener and if it didn't get posted (request died due to taking too long or error response from server) errorListener.
I was thinking of doing something with the defaultRetryPolicy... like DefaultRetryPolicy(15000, 0, 1), though I think the last parameter doesn't matter because what is the point of back-off with no retries.
How would I achieve what I asked two paragraphs back?


text:
Q: PSEN Pin when interfacing external memory in Harvard Architecture 8051 I am a computer engineering student, we have exam soon and I am completely new to this stuff . I have thoroughly searched the Internet but couldn't find any document on how to interface external memory in Harvard Architecture in 8051 microprocessor.
I know that in Harvard Architecture, program code and other data separated by two memories. Can anyone show me that how do I interface a 2732 (4Kx8 EPROM) and 4Kx8 RAM (6116) external memory in Harvard Memory in 8051 or lead me any useful document?
At least, I need to know how PSEN pin is used when interfacing external memory in Harvard Architecture. Thanks.

A: This pdf provides diagrams on interfacing the 8051 to 2732 EPROM and also 8155 external RAM: http://www.cs.ucr.edu/~ehwang/courses/cs120b/8051.pdf
Also got this from GoogleBooks: https://books.google.com.ng/books?id=K2qH4gW-fcUC&pg=PA134&lpg=PA134&dq=2732+EPROM+psen&source=bl&ots=KmXZPDtQcq&sig=Zae0KdCCTRZfmQEwX8LFlaxpPsY&hl=en&sa=X&ved=0ahUKEwiWg72YiqPKAhWH8RQKHbXTB1gQ6AEIRzAI

Good luck.


text:
Q: Prove related to equal circles and segments Two equal circles intersect in $P$ and $Q$. A straight line through $P$ meets the circles in $A$ and $B$. How do I prove that $QA=QB$ please provide figure also.

A: Since $P,A,B$ are collinear, $\widehat{QPA} = \widehat{QPB}$ or they are supplementary. Let $r$ be the radius of the circles. Then, by the Law of sines, $QA= 2 r \sin \widehat{QPA}$ and $QB= 2r \sin\widehat{QPB}$. This yields $QA=QB$.

A:
The circum-diameters $D$  of the circles are equal as given and by virtue of  Law of Sines we have:
$$ D = \frac {QA}{\sin \beta} = \frac {QB}{\sin (\pi-\beta)} =\frac {QB}{\sin \beta} \rightarrow QA=QB. $$


text:
Q: Spring WebFlux: Merge Mono and Flux / Put Mono into Flux? I'm wondering if it is possible to put the value of a Mono as a value into a Flux just like you could append any object to a list. I know there are some methods you could use but none of them fulfills my exact purpose. What I tried so far:
Flux<T> flux;
Mono<T> mono;
Flux.merge(flux, mono); // <- returns Flux<Object>

This doesn't sound too bad but notice that it does not return Flux<T> as I would need it but Flux<Object>. Same with Flux.concat(flux, mono);. The method Flux.zip(flux, mono); would stop merging as soon as the Mono completes as far as I understand.
Has somebody a solution for this?

A: This is what I ended up doing:

I have the method return a Flux of the desired type which in my case was an 'ExtendedResourceModel'. I create a Mono of this type which gets initialized by another method that I commented out to keep this answer as concise as possible. If a certain condition is met I want to also use a Flux from a different source so I use 'Flux.concat()' to put all elements into a single Flux. The 'concat'-method works by subscribing to the first argument, letting it finish, subscribing to the second one and so on.
In case of my condition not being met I just use 'concat' again but this time with only the Mono which will put the Mono's element into a new Flux. This way both cases have the same return type.

A: It is not possible to do, if you need to do that you can convert your Flux to mono
Mono monoToFlux = flux.collectList();
Mono mono;
Mono.zip (mono, monoToFlux).flatmap(tuple -> {
... more code ...
})


text:
Q: How to list all attributes of sklearn.datasets object? Coming from R, where I can inspect the internal structure of any object with str(), I'm puzzled by how to do the same in Python. The standard is to use dir(my_object), but it does not list all attributes, including very important ones. For example:
from sklearn import datasets
iris = datasets.load_iris()
dir(iris)

dir(iris) does not list the most important attributes, such as iris.data, iris.target, etc.
Am I supposed to read the docs to know about these attributes, or is there a way to find out just from looking inside the object?

A: The datasets are loaded into a dict-like object, so you can find the data that are stored in the dict rather than everything in the namespace which includes the standard dict methods.
In [2]: iris = datasets.load_iris()

In [3]: iris.keys()
Out[3]: ['target_names', 'data', 'target', 'DESCR', 'feature_names']

A: Here are some of the attributes:
In [10]: iris.data
Out[10]: array([[ 5.1,  3.5,  1.4,  0.2],
                [ 4.9,  3. ,  1.4,  0.2],
                [ 4.7,  3.2,  1.3,  0.2],
                ...

In [11]: iris.target
Out[11]: array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
                1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
                1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
                2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
                2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2])

In [13]: iris.target_names
Out[13]: array(['setosa', 'versicolor', 'virginica'],
         dtype='|S10')

In [14]: iris.feature_names
Out[14]: ['sepal length (cm)',
          'sepal width (cm)',
          'petal length (cm)',
          'petal width (cm)']

The last one will give you a detailed description of the dataset with some summary stats.
In [15]: iris.DESCR
Out[15]: 'Iris Plants Database\n\nNotes\n-----\nData Set Characteristics:\n    :Number of Instances: 150 (50 in each of three

I truncated the output of iris.dataand iris.DESCR. Here are the dataset docs


text:
Q: Converting React TS interface to React JS I'm attempting to integrate this package into an app using this example. I'm not too familiar with typescript and I see that it uses interface in one of the utils (which javascript does not have). I've read Does JavaScript have the interface type (such as Java's 'interface')?, but I'm not sure this is the same as the one typescript uses.

Here's the TS code I am trying to convert:
import * as React from 'react'
import { Route, Redirect, RouteComponentProps } from 'react-router-dom'
import type { RouteProps } from 'react-router-dom'

import { useKeycloak } from '@react-keycloak/web'

interface PrivateRouteParams extends RouteProps {
  component:
    | React.ComponentType<RouteComponentProps<any>>
    | React.ComponentType<any>
}

export function PrivateRoute({
  component: Component,
  ...rest
}: PrivateRouteParams) {
  const { keycloak } = useKeycloak()

  return (
    <Route
      {...rest}
      render={(props) =>
        keycloak?.authenticated ? (
          <Component {...props} />
        ) : (
          <Redirect
            to={{
              pathname: '/login',
              state: { from: props.location },
            }}
          />
        )
      }
    />
  )
}

Here's what someone suggested for JS:
import * as React from 'react';
import { Route, Redirect } from 'react-router-dom';
import { useKeycloak } from '@react-keycloak/web';

export function PrivateRoute({ component, ...rest }) {
  const { keycloak } = useKeycloak();

  return (
    <Route
      {...rest}
      render={(props) =>
        keycloak?.authenticated ? (
          <Component {...props} />
        ) : (
          <Redirect
            to={{
              pathname: '/auth',
              state: { from: props.location },
            }}
          />
        )
      }
    />
  );
}

Still, I don't think that <Component /> will work in react.js.
EDIT: Added code

A: React Router takes a prop component with a lowercase c.  In order to call a custom component using JSX it must have an uppercase name. See the docs
The Typescript example code renamed the prop component to Component when destructuring it.  That allows them to call <Component /> using JSX.
When converting the code to Javascript you accidentally removed this renaming.  You probably mistook it for a type annotation.
This code should work:
import * as React from 'react'
import { Route, Redirect } from 'react-router-dom'

import { useKeycloak } from '@react-keycloak/web'

export function PrivateRoute({
  component: Component,
  ...rest
}) {
  const { keycloak } = useKeycloak()

  return (
    <Route
      {...rest}
      render={(props) =>
        keycloak?.authenticated ? (
          <Component {...props} />
        ) : (
          <Redirect
            to={{
              pathname: '/login',
              state: { from: props.location },
            }}
          />
        )
      }
    />
  )
}


text:
Q: Xpath: filter out childs I'm looking for a xpath expression that filters out certain childs. A child must contain a CCC node with B in it.
Source:
<AAA>
    <BBB1>
        <CCC>A</CCC>
    </BBB1>
    <BBB2>
        <CCC>A</CCC>
    </BBB2>
    <BBB3>
        <CCC>B</CCC>
    </BBB3>
    <BBB4>
        <CCC>B</CCC>
    </BBB4>
</AAA>

This should be the result:

<AAA>
    <BBB3>
        <CCC>B</CCC>
    </BBB3>
    <BBB4>
        <CCC>B</CCC>
    </BBB4>
</AAA>
Hopefully someone can help me.
Jos

A: XPath is a query language for XML documents. As such it can only select nodes from existing XML document(s) -- it cannot modify an XML document or create a new XML document.
Use XSLT in order to transform an XML document and create a new XML document from it.
In this particular case:
<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:template match="node()|@*">
  <xsl:copy>
   <xsl:apply-templates select="node()|@*"/>
  </xsl:copy>
 </xsl:template>

 <xsl:template match="/*/*[not(CCC = 'B')]"/>
</xsl:stylesheet>

when this transformation is applied on the provided XML document:
<AAA>
    <BBB1>
        <CCC>A</CCC>
    </BBB1>
    <BBB2>
        <CCC>A</CCC>
    </BBB2>
    <BBB3>
        <CCC>B</CCC>
    </BBB3>
    <BBB4>
        <CCC>B</CCC>
    </BBB4>
</AAA>

the wanted, correct result is produced:
<AAA>
   <BBB3>
      <CCC>B</CCC>
   </BBB3>
   <BBB4>
      <CCC>B</CCC>
   </BBB4>
</AAA>

A: In order to select all of the desired element and text nodes, use this XPATH:
//node()[.//CCC[.='B']
      or self::CCC[.='B']
      or self::text()[parent::CCC[.='B']]]

This could be achieved with a more simply/easily using XPATH with a modified identity transform XSLT:
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output indent="yes" />

    <!--Empty template for the content we want to redact -->
    <xsl:template match="*[CCC[not(.='B')]]" />

    <!--By default, copy all content forward -->
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates/>
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>

A: try this ,
         "//CCC[text() = 'B']"

It shall give all CCC nodes where the innertext is B.

A: If you want to get AAA, BBB3 and BBB4 you can use the following
//*[descendant::CCC[text()='B']]

If BBB3 and BBB4 only then
//*[CCC[text()='B']]


text:
Q: Sending file upload size exceed error to client in java Basically I have a type="file" which sends an image to server, In server I need to check that the image size is not higher than 1MB if it's send an error to client about the image size so the client could pop an error to user.
Here is my servlet script:
@MultipartConfig(
    maxFileSize=1024*1024     // 1Mb max
)
public class ProPicUploader extends HttpServlet {
private static final long serialVersionUID = 1L;
public void init() throws ServletException
{
    System.out.println("Initiate method is called in " + this.getClass().getName());
}
public void doPost(HttpServletRequest request,
      HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    try{
        MultipartRequest multipartRequest = new MultipartRequest(request, "D:\\");
    } catch(IOException e){
        out.print("Image size is bigger than 1MB");
        System.out.println(e.getMessage());
    }
    out.print("Successfully Uploaded");
}
public void destroy(){
    System.out.println("Destory method is called in: " + this.getClass().getName());
}
}

client-side script:
if(formdata){
        $.ajax({
            url: '../propicuploader',
            type: 'POST',
            data: formdata,
            processData: false,
            contentType: false,
            success: function(data){
                alert(data);
                if(data == "0x00000035"){
                    $("#NotPictureerror_spn").text("File size is too big, Please select a file upto 2MB");
                }
            }
            error: function(data){
                alert(data);
            }
        });
    }

and my web.xml script:
 <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>Duck</display-name>
  <welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>ProPicUploader</servlet-name>
    <servlet-class>/ProPicUploader</servlet-class>
  </servlet>
</web-app>

So far it does if the Image size is lower than 1MB it says Successfully Uploaded but if the image size is higher than 1MB it pop nothing although I have inputed to send an error saying out.print("Image size is bigger than 1MB") but my client never gets to receive that.
I really appreciate if somebody tell me what am i doing wrong:)

A: Remove this part
@MultipartConfig(
    maxFileSize=1024*1024     // 1Mb max
)

and retry.
By default MultipartRequest is limiting the upload size to 1 Megabyte