text:
Q: Only load ListFragment once via AsyncTask I'm trying to learn Android development and am still trying to wrap my head around how the framework works and how to properly extend all these classes.
My goal is this: An Activity that has a ViewPager that cycles through five ListFragments. The data being bound to each ListFragment is coming from a web API, which is called using an AsyncTask.
My problem is that whenever I switch to a new fragment, the MyListFragment.newInstance() is called again, which calls the AsyncTask every time.  I'm trying to have the AsyncTask called once, the first time the ListFragment is loaded, to cut down on the web calls and save the page state.  Eventually I want to do a "Pull down to refresh" type thing, which would mean not reloading the data when I switch a page.
I've been following this guide on Android Developers to try to make this happen.  What I ended up with is this:
public class MainActivity extends FragmentActivity {

    MyPagerAdapter mMyPagerAdapter;
    ViewPager mViewPager;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mMyPagerAdapter = new MyPagerAdapter(getSupportFragmentManager());

        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mMyPagerAdapter);
    }

    public class MyPagerAdapter extends FragmentPagerAdapter {
        public static final int NUM_PAGES = 5;

        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int i) {
            return MyListFragment.newInstance(getPageTitle(i).toString());
        }

        @Override
        public int getCount() {
            return NUM_PAGES;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            String[] titles = getResources().getStringArray(R.array.thing_sort_titles);
            return titles[position];
        }

    }

    public static class MyListFragment extends ListFragment {
        public static final String ARG_CATEGORY = "category_title";
        ArrayList<HashMap<String, String>> mylist;

        public MyListFragment() {
            mylist = new ArrayList<HashMap<String, String>>();
        }

        @Override
        public void onActivityCreated(Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);

            Bundle args = getArguments();
            URI url = new URI("http://api.remotesite.com/" + args.getString(ARG_CATEGORY));
            new MyListAsyncTask().execute(url);
        }

        static MyListFragment newInstance(String category) {
            MyListFragment f = new MyListFragment();

            Bundle args = new Bundle();
            args.putString(ARG_CATEGORY, category);
            f.setArguments(args);

            return f;
        }

        private class MyListAsyncTask extends AsyncTask<URI, Integer, ArrayList<HashMap<String, String>>> {

            protected ArrayList<HashMap<String, String>> doInBackground(URI... uris) {
                try {
                    JSONArray json = JSON.getJSONfromURL(uris[0]);
                    for (int i = 0; i < json.length(); i++) {
                        HashMap<String, String> map = new HashMap<String, String>();
                        JSONObject obj = json.getJSONObject(i)
                        map.put("title", obj.getString("title"));
                        map.put("author", obj.getString("author"));
                        map.put("id", obj.getString("id"));
                        mylist.add(map);
                    }
                } catch (Exception ex) {
                }
                return mylist;
            }

            protected void onPostExecute(ArrayList<HashMap<String, String>> list) {
                ListAdapter adapter = new SimpleAdapter(
                    getActivity(),
                    mylist,
                    R.layout.list_item,
                    new String[] { "title", "author" },
                    new int[] { R.id.text_title, R.id.text_author }
                );
                MyListFragment.this.setListAdapter(adapter);
            }
        }
    }
}

I tried doing an array of ListFragments in the FragmentPagerAdapter, and only call MyListFragment.newInstance if that index was null, but it didn't end up changing anything.

A: I'll suggest you use the Loaders (http://developer.android.com/guide/components/loaders.html) for your case.
The loaders are quite clever on that regard that it automatically deliver back to the calling component the same data as before if you use the same ID.
for example:
Fragment position 0 calls initLoader(0, null, this); then Fragment position 1 calls initLoader(1, null, this); and so on....
that way whenever initLoader(1 << id is called the second (3rd, 4th) time, it will not execute the web call and directly deliver the same result that was delivered on the 1st call.

A: Please try to use setOffscreenPageLimit to resolve your issue.
If you use it it will cache your fragment and it would not be called again.


text:
Q: Get Computer, assigned to particular User, via API in ServiceNow We have a User table with sys_id value and Computer table with value
assigned_to={
  "link": "https://ourdomain.service-now.com/api/now/table/sys_user/47d293bddber3d0d01b31a5ca0b961988",
  "value": "47d293bddber3d0d01b31a5ca0b961988"
}

I cannot just do "assigned_to = 47d293bddber3d0d01b31a5ca0b961988" as its an object
where "Value" is sys_id from User table.
So the question is - how do I find Computer assigned to particular user if I know User sys_id , with API?
Thanks

A: If you using the REST Table API, you can add the following parameter to your URL:
&sysparm_query=assigned_to=47d293bddber3d0d01b31a5ca0b961988
From the API perspective, assigned_to is not actually an object. It just a sys_id. ServiceNow adds the link to the JSON as a convenience. However, I usually find it to be inconvenient. I always get rid of it by adding the following parameter to my URL:
&sysparm_exclude_reference_link=true
This will cause your JSON will return:
"assigned_to": "47d293bddber3d0d01b31a5ca0b961988"

redpajama_set_name: RedPajamaStackExchange


text:
Q: sftp put command fails when in shell script I am trying to make a shell script that creates a mysql dump and then puts it on another computer.  I have already set up keyless ssh and sftp.  They script below creates the mysql dump file on the local computer when it is run and doesn't throw any errors, however the file "dbdump.db" is never put on the remote computer.  If I execute the sftp connection and put command by hand then it works.
contents of mysql_backup.sh
mysqldump --all-databases --master-data > dbdump.db
sftp -b /home/tim tim@100.10.10.1 <<EOF
put dbdump.db
exit
EOF

A: Try to use scp that should be easier in your case.
scp dbdump.db tim@100.10.10.1:/home/tim/dbdump.db

Both sftp and scp are using SSH.

A: Please write mput/put command into one file (file_contains_put_command) and try below command.
sftp2 -B file_contains_put_command /home/tim tim@100.10.10.1 >> log_file

Example:
echo binary > sample_file
echo mput dbdump.db >> sample_file
echo quit >> sample_file
sftp2 -B sample_file /home/tim tim@100.10.10.1 >> log_file

A: Your initial approach is a few characters off working though. You're telling sftp to read it's batch-commands from /home/tim -b /home/tim. So, if you change this to -b -, it should read it's batch commands from stdin.
Something along these lines, if -b /home/tim were intended to i.e. change directory remotely, you can add cd /home/tim to your here document.
mysqldump --all-databases --master-data > dbdump.db
sftp -b - tim@100.10.10.1 <<EOF
put dbdump.db
exit
EOF


text:
Q: Two basic examples of trace diagrams? In the wikipedia entry on Trace Diagrams (see http://en.wikipedia.org/wiki/Trace_diagram), the statement is made that "The simplest trace diagrams represent the trace and determinant of a matrix".
Could anyone provide me with the graphic representation of those 2 cases for, say, a 3x3 quadratic matrix with any arbitrary number entries?
Thanks in advance.


text:
Q: Stray lines when using overlays in tikz-uml I show a UML diagram in my slides and I want to put some notes into an overlay. When I do this,the connecting lines appear from the beginning. How do I get rid of them?
\documentclass{beamer}
\usepackage{tikz-uml}
\begin{document}

\begin{frame}
    \begin{tikzpicture}
        \umlemptyclass{Class}
        \visible<2>{\umlnote[x=5]{Class}{Lorem Ipsum etc}}
    \end{tikzpicture}
\end{frame}
\end{document}

A: Using \only<> instead of \visible<> did the trick.


text:
Q: Hiding products without thumbnail in WooCommerce shop page I use importer which imports thousands of products to the shop. Although I must insert picture and description for the product before I want to sell the item.
I would like to hide product from the store at all IF there is no thumbnail image assigned. This way new products appear to the shop only after I have set the thumbnail image.
I tried this in header.php, but did not work:
 <?php if($_product->getImage() && $_product->getImage() != 'no_selection'){
?>
 <style>
  /* Css to hide Featured image Div */
 </style>
<?php
}?>

This gave me error:

Fatal error: Call to a member function getImage() on a non-object

Is there any quick way to hide WordPress WooCommerce products from the Shop page, if they do not have a thumbnail picture placed?
Thanks

A: You can use a custom function hooked in woocommerce_product_query action, hook that will change the shop query and will not display on shop page products without an image, this way:
add_action( 'woocommerce_product_query', 'custom_pre_get_posts_query' );
function custom_pre_get_posts_query( $query ) {

    $query->set( 'meta_query', array( array(
       'key' => '_thumbnail_id',
       'value' => '0',
       'compare' => '>'
    )));

}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
This code is tested and works on WooCommerce 2.6.x and 3.0+

A: Woo-commerce usually inserts a placeholder picture on products which don't have a thumbnail picture. What you can do is target products which don't have a thumbnail using Jquery easily.
on my website it puts an imame named "placeholder.png" which will be in site_url()."/wp-content/plugins/woocommerce/assets/images/placeholder.png", site url which is your website's url.
enqueue a javascript to your theme or create a child theme and add it in the functions.php file.
here goes the code.
hideproduct.js
jQuery(document).ready(function(){

    jQuery(".products a img.woocommerce-
            placeholder").parents(".product").css("display","none");

})

A: Well, you could save yourself a lot of struggle and import your products initially with the post_status set to draft, which will result in not showing them on the front page. Then, every time you add an image to your product, which I assume you do via the WP backend, you "publish" your product, since you have to save it anyway.
If you have a separate import-script for images, you can set the post_status to public from there.


text:
Q: Embed Python 3 Tkinter module as Widget in PyQT5 First post and new to python so apologies if the post formatting is weird or the coding errors are dumb.
I created a module using tkinter that I want to embed into a pyQt5 MainWindow widget.
This is the tkinter module, titled Del.py, I'm trying to import.
class Delfiles(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.mw = self.mainwindow()

    def mainwindow(self):
        # mainwindow formatting

    def dellist(self):
        # delete function for buttons in mainwindow

class Results(tk.Toplevel):
    def __init__(self):
        tk.Toplevel.__init__(self)
    # toplevel popup that appears after dellist function runs

# root = Delfiles()
# root.mainloop()

This is the part of the pyqt5 module where I've been trying to embed the tkinter module into.
class SpreadSheet(QMainWindow):
    def __init__(self, rows, cols, parent=None):
        super(SpreadSheet, self).__init__(parent)
        self.rows = rows
        self.cols = cols
        self.cells = {}

        self.create_table1()
        self.create_table2()
        deletefiles = Del.mw()
        self.centralwidget = QWidget()

        self.vlayout = QVBoxLayout()
        self.hlayout = QHBoxLayout()
        self.vlayout.addWidget(self.table1)
        self.vlayout.addWidget(self.table2)
        self.hlayout.addLayout(self.vlayout)
        self.hlayout.addWidget(deletefiles)
        self.centralwidget.setLayout(self.hlayout)

        self.table1.cellDoubleClicked.connect(self.celldoubleclicked)
        self.table2.installEventFilter(self)

        self.setCentralWidget(self.centralwidget)
        self.show()

if __name__ == __main__:
    app = QApplication(sys.argv)
    sheet = SpreadSheet(5, 5)
    sheet.resize(1500, 900)
    sheet.show()
    sys.exit(app.exec_())

# https://negfeedback.blogspot.com/2017/12/a-simple-gui-spreadsheet-in-less-than.html
#link to source code for the pyqt5 module I'm working with

Every time I try to run the pyqt module with the tkinter module embedded, the tkinter module either opens on top of the pyqt5 module or i get the following error.
Exception in Tkinter callback
AttributeError: module 'Del' has no attribute 'mw'

Any help is greatly appreciated

A: You can't create windows in tkinter and use them in a PyQT5 application. Each GUI toolkit has a rendering model that knows nothing about the other.


text:
Q: Time difference between all particles and waves Since all elementary particles and waves were created simultaneously in the big-bang (t0) would there be any time difference between any interacting elementary particles and/or waves after t0? I'm assuming that all the energy and information present in our universe today was present at t0. Which implies to me that everything today has shared information in the past.

A: Once the collision energies get above a few MeV particles are surprisingly transient objects. Even the early particle colliders were able to create and destroy particles, and the Large Hadron Collider creates hundreds of new particles with every collision.
As we approach the Big Bang the energy becomes orders of magnitudes larger than anything possible at the LHC, so particles were being created all over the place in a chaotic and random fashion. The result is that the particles we see today were not created at the same time or in any form of synchronised process. They will have been created at random times by random and unrelated processes.
So the end result is that we cannot expect any two particles chosen at random to have properties that are correlated due to them being created at the same instant.


text:
Q: IF statement Python I have this code:
def Gradiente(grado):
   suma = 0
   for i in range(porcent):
       x1 = entrenamiento[i][0]
       x2 = entrenamiento[i][1]
       y = entrenamiento[i][2]
       h = 1 / (1 + math.exp(-(t0 + t1 * x1 + x2))

       if (grado == 1):
           suma = suma + (h - y)
       elif(grado == 2):
           suma = suma + (h - y) * x1

   return suma / porcent

at the if, it keeps saying invalid syntax (at the ":"), is it wrong?

A: 97.2% of all problems people have with Python involves incorrect indentation :-) In your original question, your indentation was incorrect and you need to indent it properly:
def Gradiente(grado):
    suma = 0
    for i in range(porcent):
        x1 = entrenamiento[i][0]
        x2 = entrenamiento[i][1]
        y = entrenamiento[i][2]
        h = 1 / (1 + math.exp(-(t0 + t1 * x1 + x2)))  # <-- fix

        if grado == 1:                                # <-- style
            suma = suma + (h - y)
        elif grado == 2:                              # <-- style
            suma = suma + (h - y) * x1

    return suma / porcent

However, you've since made it clear that was a typo on your part when entering the question in which case it'll simply be the missing close-parenthesis on that large mathematical formula (which is also fixed in my code above).
One other change made is the removal of superfluous punctuation from the if statements. People who use them tend to come from a C (or similar language) background where they're necessary. Using them in Python usually just clutters the code unnecessarily.

A: Indent everything one tab after line 1. Indentation matters in Python.


text:
Q: Java Canvas err focus or action listener in second window I create 2 Frames:
in 1st - I make a Button which move me to 2nd Frame created by class which extends after Canvas and after the move from 1st Frame to 2nd I lose the action listener or focus
1st window here :
public class Credits extends JFrame {

public Credits() {
    super("Credits");
    setSize(300, 200);
    setLayout(new BorderLayout());

    JButton ok = new JButton("GAME");

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLocationRelativeTo(null);
    setResizable(false);
    this.add(ok);
    setVisible(true);

    ok.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            dispose();
            new WojnaSwiatow().game();

        }
    });

}

public static void main(String []args ) {
    SwingUtilities.invokeLater(new Runnable(){

        @Override
        public void run()
        {
           new Credits();
        }

    });
}
}

Second Frame:
public class WojnaSwiatow extends Canvas implements Stage, KeyListener {/**
 * @param args the command line arguments
 */

    createBufferStrategy(2);
    strategia = getBufferStrategy();
    requestFocus();

    requestFocusInWindow(true);
    addKeyListener(this);
    okno.addKeyListener(this);
    okno.pack();
    okno.setVisible(true);

public long usedTime;
public BufferStrategy strategia;
private SpriteCache spriteCache;
private ArrayList actors;
private Player player;

public WojnaSwiatow(){

    spriteCache = new SpriteCache();
    JFrame okno = new JFrame("..:Wojna Swiatow :..");
    JPanel panel = (JPanel)okno.getContentPane();
    setBounds(0,0,Stage.SZEROKOSC,Stage.WYSOKOSC);

    panel.setPreferredSize(new Dimension(Stage.SZEROKOSC,Stage.WYSOKOSC));
    panel.setLayout(null);
    panel.add(this);

    okno.setBounds(0,0,Stage.SZEROKOSC,Stage.WYSOKOSC);
    okno.setVisible(true);
    okno.setResizable(false);
    okno.setLocationRelativeTo(null);

    okno.addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent e){
            System.exit(0);
        }
    });

maybethe problem is on bufferstrategy ?


text:
Q: Keep a row for each change in column (including NULL) in SQL Server I would like to track changes to a dataset in SQL Server.
I currently have data similar to this
    Unique Ref  FromDate    ToDate     Status
           1    01/01/2020  03/01/2020  A
           1    03/01/2020  03/02/2020  NULL
           1    03/02/2020  04/04/2020  B
           1    04/04/2020  05/04/2020  B
           1    05/04/2020  06/06/2020  A
           2    03/01/2020  05/01/2020  NULL
           2    05/01/2020  06/07/2020  B
           2    06/07/2020  07/07/2020  B
           2    07/07/2020  08/07/2020  A

I'd like to keep a row for each change to a status grouped by Unique Ref, so that I only see the changes and not where the Status stays the same.
Trying to get the above to look like
Unique Ref  Status  ChangedDate
         1  A       01/01/2020
         1  NULL    03/01/2020
         1  B       03/02/2020
         1  A       05/04/2020
         2  NULL    03/01/2020
         2  B       05/01/2020
         2  A       07/07/2020

I've never done anything similar before so not sure where to start.

A: Use lag().  I think this does what you want:
select t.ref, t.status, t.fromDate as changedDate
from (select t.*,
             lag(status) over (partition by ref order by fromDate) as prev_status,
             row_number() over (partition by ref order fromDate) as seqnum
      from t
     ) t
where prev_status <> status or
      prev_status is null and status is not null or
      prev_status is not null and status is null or
      seqnum = 1;

The NULL values make this a bit tricky.  The last condition handles the case when the first row for a ref is NULL.
Another approach is a little simpler I think:
select t.ref, t.status, t.fromDate as changedDate
from (select t.*,
             lag(fromDate) over (partition by ref order by fromDate) as prev_date,
             lag(fromDate) over (partition by ref, status order by fromDate) as prev_status_date
      from t
     ) t
where prev_status_date is null or
      prev_status_date <> prev_date;

This just compares the previous date for the status to the previous date for record as a whole.


text:
Q: Run-time error in SQLite Database I've immplemented an SQLite database here. The database consists of objects of class Contact. However my app is crashing as soon as it starts. Here's the Logcat and the code.
Logcat
FATAL EXCEPTION: main
Process: com.example.nirvan.sqliteexample, PID: 30065
java.lang.RuntimeException: Unable to start activity ComponentInfo {
  com.example.nirvan.sqliteexample / com.example.nirvan.sqliteexample.MainActivity
 }: android.database.sqlite.SQLiteException: near "TABLEcontacts": syntax error(code 1): ,
 while compiling: CREATE TABLEcontacts(idINTEGER KEYname TEXT)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java: 2198)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java: 2257)
at android.app.ActivityThread.access$800(ActivityThread.java: 139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java: 1210)
at android.os.Handler.dispatchMessage(Handler.java: 102)
at android.os.Looper.loop(Looper.java: 136)
at android.app.ActivityThread.main(ActivityThread.java: 5086)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java: 515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java: 785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java: 601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.database.sqlite.SQLiteException: near "TABLEcontacts": syntax error(code 1): ,
 while compiling: CREATE TABLEcontacts(idINTEGER KEYname TEXT)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java: 889)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java: 500)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java: 588)
at android.database.sqlite.SQLiteProgram. < init > (SQLiteProgram.java: 58)
at android.database.sqlite.SQLiteStatement. < init > (SQLiteStatement.java: 31)
at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java: 1672)
at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java: 1603)
at com.example.nirvan.sqliteexample.DatabaseHandler.onCreate(DatabaseHandler.java: 28)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java: 252)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java: 164)
at com.example.nirvan.sqliteexample.DatabaseHandler.addContact(DatabaseHandler.java: 40)
at com.example.nirvan.sqliteexample.MainActivity.onCreate(MainActivity.java: 21)
at android.app.Activity.performCreate(Activity.java: 5248)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java: 1110)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java: 2162)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java: 2257)
at android.app.ActivityThread.access$800(ActivityThread.java: 139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java: 1210)

FATAL EXCEPTION: main
Process: com.example.nirvan.sqliteexample, PID: 32547
java.lang.RuntimeException: Unable to start activity ComponentInfo {
  com.example.nirvan.sqliteexample / com.example.nirvan.sqliteexample.MainActivity
 }: android.database.sqlite.SQLiteException: near "TABLEcontacts": syntax error(code 1): ,
 while compiling: CREATE TABLEcontacts(idINTEGER KEYname TEXT)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java: 2198)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java: 2257)
at android.app.ActivityThread.access$800(ActivityThread.java: 139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java: 1210)
at android.os.Handler.dispatchMessage(Handler.java: 102)
at android.os.Looper.loop(Looper.java: 136)
at android.app.ActivityThread.main(ActivityThread.java: 5086)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java: 515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java: 785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java: 601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.database.sqlite.SQLiteException: near "TABLEcontacts": syntax error(code 1): ,
 while compiling: CREATE TABLEcontacts(idINTEGER KEYname TEXT)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java: 889)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java: 500)

MainActivity.java
package com.example.nirvan.sqliteexample;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity
{

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

    DatabaseHandler db = new DatabaseHandler(this);

    // Inserting Contacts
    //Log.d("Insert: ", "Inserting ..");
    db.addContact(new Contact(1, "one"));
    db.addContact(new Contact(2, "two"));
    db.addContact(new Contact(3, "three"));

    TextView text=(TextView) findViewById(R.id.text);
    Contact cn;
    cn=db.getContact(2);
    text.setText(cn.name);
}

}

Contact.java
public class Contact
{
public String name;
public int id;

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

}

DatabaseHandler.java
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHandler extends SQLiteOpenHelper
{
 private static final int DATABASE_VERSION=1;
 private static final String DATABASE_NAME="contactsManager";
 private static final String TABLE_CONTACTS="contacts";
 private static final String KEY_ID="id";
 private static final String KEY_NAME="name";

public DatabaseHandler(Context context)
{
    super(context, DATABASE_NAME, null, DATABASE_VERSION);}

@Override
public void onCreate(SQLiteDatabase db)
{
    String CREATE_CONTACTS_TABLE="CREATE TABLE"+TABLE_CONTACTS+"("+KEY_ID+"INTEGER PRIMARY KEY"+KEY_NAME+" TEXT"+")";
    db.execSQL(CREATE_CONTACTS_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
 db.execSQL("DROP TABLE IF EXISTS"+TABLE_CONTACTS);
    onCreate(db);
}

void addContact(Contact contact)
{
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_NAME, contact.name);
    values.put(KEY_ID, contact.id);

    // Inserting Row
    db.insert(TABLE_CONTACTS, null, values);
    //2nd argument is String containing nullColumnHack
    db.close(); // Closing database connection
}

Contact getContact(int id)
{
    SQLiteDatabase db = this.getReadableDatabase();

    Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
                    KEY_NAME}, KEY_ID + "=?",
            new String[] { String.valueOf(id) }, null, null, null, null);
    if (cursor != null)
        cursor.moveToFirst();

    Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
            cursor.getString(1));
    // return contact
    return contact;
}

public int updateContact(Contact contact)
{
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_NAME, contact.name);

    // updating row
    return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
            new String[] { String.valueOf(contact.id) });
}

}

activityMain.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.nirvan.sqliteexample.MainActivity">

<TextView
    android:id="@+id/text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!" />
</RelativeLayout>

A: it is simple error with your query that you are doing in your database. add some spaces to keywords not to confuse Sqlite and do so as i shown below
@Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "(" + KEY_ID + " INTEGER PRIMARY KEY, " + KEY_NAME + " TEXT " + ")";
    db.execSQL(CREATE_CONTACTS_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
    onCreate(db);
}

A: Refer this on how to properly create a database.You are missing spaces after "CREATE TABLE" and TABLE_CONTACTS

A: Try this,
You have missed a space after CREATE TABLE statement and I think comma(,) after PRIMARY KEY
String CREATE_CONTACTS_TABLE="CREATE TABLE "+ TABLE_CONTACTS + "(" + KEY_ID + " INTEGER PRIMARY KEY, " + KEY_NAME + " TEXT"+")";


text:
Q: Como o representar fluxo de um caso de uso que estende\inclui outro caso de uso no documento de especificação? Meu caso de uso:

Exemplo de como estou fazendo a especificação do fluxo:
[...]

*

*Fluxo x.

*Fluxo y.

*Fluxo z.

*Aqui precisaria entrar a parte do caso de uso "Fornecer Identificação" \ "Cadastrar Times"
Minha dúvida: Na hora de fazer a especificação dos fluxos do caso de uso "Realizar Aposta" \ "Administrar Times" qual seria a forma mais recomendada de descrever que esse caso de uso tem um <<extends>> ? E no caso de ser um <<include>> ?


text:
Q: MS-Access 2007: One-to-one relationship in form, not showing all records helpful folk of the internet.
Background info about the data:
I work for a research station and we spend part of the summer live trapping mammals. Occasionally an animal dies in the trap and we retain it to send to a museum.
I'm making a database for our mammal trapping data. We have a table for captures which contains the following fields:

*

*CaptureID (unique identifier for each capture & primary key)

*MammalID (identifier for each mammal so we can track recaptures across days & sites)

*SurveyID (links back to tables w/ site & date information)

*A bunch of fields about different measurements we take everytime we capture a mammals

*Dead? (Says "Y" if the animal was dead, "N" if the animal was alive)

*CatNum (unique id for each sample. This is assigned to the dead animals when we collect them and used to keep the specimens linked to their data as well as track them as they move through our collections & to other museums)

Here's my problem. We'd really like to have a separate table for our Mort Samples where everything is identified by a catnum and then has info about where the sample is and other info we get back from museums when we send them samples. I want to link this table to the capture table using either Catnum or capture id. I want them in separate tables because they're different kinds of data.
I'm currently using capture id as the link in this One-to-One because not every capture id has a catnum and so I can't link the primary key from MortTable to a field with null values.
Here's my problem.
In an ideal world we would be able to let anyone enter this data. So we made an easy to use form that looks very similar to our data sheet, with Capture Table being a sub-form in table form under the info about site & date and such.
On the data form there's a space for catnum, and it's currently a field in the capture table and on the capture sub-form. I want to make it so that entering a value in "catnum" on this form creates that primary key in another table.
I've tried doing this with an "AfterUpdate" (though I may have done that wrong), and by replacing the catnum from the capture table with the one from the mort table (and I would ultimately remove the catnum field from the capture table if this works). This last solution sort of works. In that it lets me do what I want, but means I can only display captures where the animal died on the form (since the others have no catnum associated with them and don't show up).
Is there a better way to do this without

*

*Restricting which records are displayed on this general form?

*Requiring potentially wildcard seasonal employees to leave this general form that looks exactly like what is in their hands and... GASP! ask them to do something strange and different.

We'd really rather just have the catnum records created automatically during data entry & then let one of the collections people go back and fill in the collection info than have the field crews leave the basic form to do it or have the collections people generate an entirely new list at the risk of missing something.
Thanks for your help!


text:
Q: Laravel Algolia Scout, whereIn on relationships I am working on a Laravel project. I am using Scout based on Algolia. But I struggling to apply whereIn on the relationships. I have 2 models as follow.
Place.php
class Place extends Model
{
    use Searchable, Localizable;

    protected $with = [
        'images',
        'phones',
        'emails',
        'categories'
    ];

    protected $casts = [
        'is_featured' => 'boolean'
    ];

    public function categories()
    {
        return $this->belongsToMany(Category::class, 'place_category');
    }

    public function searchableAs()
    {
        return "places_index";
    }

    public function toSearchableArray()
    {
        $record = $this->toArray();
        $record['_geoloc'] = [
            'lat' => $record['latitude'],
            'lng' => $record['longitude'],
        ];
        $record['categories'] = $this->categories->map(function ($data) {
            return [
                'id' => $data['id'],
                'en_name' => $data['en_name'],
                'mm_name' => $data['mm_name'],
            ];
        })->toArray();
        unset($record['created_at'], $record['updated_at'], $record['latitude'], $record['longitude']);
        unset($record['images'], $record['phones'], $record['emails']);

        return $record;
    }
}

Category.php
class Category extends Model
{
    use Searchable;

    protected $touches = [
        'places',
    ];

    public function places()
    {
        return $this->belongsToMany(Place::class, 'place_category');
    }
}

Now, I am searching the Place models/ data filtering by category. As you can see, I have also indexed the categories with places in toSearchableArray method.
I am trying to achieve something like this.
Place::search($keyword)->whereIn('categories', ????);//how can I filter by the Ids here

How can I do that?


text:
Q: reading blocking mode from com port rs232 I have a code in c++ that read and write data rs232 but i want it was blocking mode i.e i want it wait on read line until one character is received. this is my code:
#include <windows.h>
#include <stdio.h>
#include <string.h>

HANDLE hPort;

BOOL WriteByte(BYTE bybyte)
{
    DWORD iBytesWritten=0;
    DWORD iBytesToRead = 1;
    if(WriteFile(hPort,(LPCVOID)
        &bybyte,iBytesToRead,&iBytesWritten,NULL)==0)
        return FALSE;
    else return TRUE;
}

BOOL ReadByte(BYTE  &resp)
{
    BOOL bReturn = TRUE;
    BYTE rx;
    DWORD dwBytesTransferred=0;

    if (ReadFile (hPort, &rx, 1, &dwBytesTransferred, 0)> 0)
    {
        if (dwBytesTransferred == 1)
        {
            resp=rx;
            bReturn  = TRUE;
        }
        else bReturn = FALSE;
    }
    else    bReturn = FALSE;
    return bReturn;
}

void ClosePort()
{
    CloseHandle(hPort);
    return;
}

HANDLE ConfigureSerialPort(LPCSTR  lpszPortName)
{
    HANDLE hComm = NULL;
    DWORD dwError;
    DCB PortDCB;
    COMMTIMEOUTS CommTimeouts;
    // Open the serial port.
    hComm = CreateFile (lpszPortName, // Pointer to the name of the port
        GENERIC_READ | GENERIC_WRITE,
        // Access (read-write) mode
        0,              // Share mode
        NULL,           // Pointer to the security attribute
        OPEN_EXISTING,  // How to open the serial port
        0,              // Port attributes
        NULL);          // Handle to port with attribute
    // to copy

    // Initialize the DCBlength member.
    PortDCB.DCBlength = sizeof (DCB);
    // Get the default port setting information.
    GetCommState (hComm, &PortDCB);
    // Change the DCB structure settings.
    PortDCB.BaudRate = 9600;              // Current baud
    PortDCB.fBinary = TRUE;               // Binary mode; no EOF check
    PortDCB.fParity = TRUE;               // Enable parity checking
    PortDCB.fOutxCtsFlow = FALSE;         // No CTS output flow control
    PortDCB.fOutxDsrFlow = FALSE;         // No DSR output flow control
    PortDCB.fDtrControl = DTR_CONTROL_ENABLE;
    // DTR flow control type
    PortDCB.fDsrSensitivity = FALSE;      // DSR sensitivity
    PortDCB.fTXContinueOnXoff = TRUE;     // XOFF continues Tx
    PortDCB.fOutX = FALSE;                // No XON/XOFF out flow control
    PortDCB.fInX = FALSE;                 // No XON/XOFF in flow control
    PortDCB.fErrorChar = FALSE;           // Disable error replacement
    PortDCB.fNull = FALSE;                // Disable null stripping
    PortDCB.fRtsControl = RTS_CONTROL_ENABLE;
    // RTS flow control
    PortDCB.fAbortOnError = FALSE;        // Do not abort reads/writes on
    // error
    PortDCB.ByteSize = 8;                 // Number of bits/byte, 4-8
    PortDCB.Parity = NOPARITY;            // 0-4=no,odd,even,mark,space
    PortDCB.StopBits = ONESTOPBIT;        // 0,1,2 = 1, 1.5, 2

    // Configure the port according to the specifications of the DCB
    // structure.
    if (!SetCommState (hComm, &PortDCB))
    {
        printf("Could not configure serial port\n");
        return NULL;
    }
    // Retrieve the time-out parameters for all read and write operations
    // on the port.
    GetCommTimeouts (hComm, &CommTimeouts);
    // Change the COMMTIMEOUTS structure settings.
    CommTimeouts.ReadIntervalTimeout = MAXDWORD;
    CommTimeouts.ReadTotalTimeoutMultiplier = 0;
    CommTimeouts.ReadTotalTimeoutConstant = 0;
    CommTimeouts.WriteTotalTimeoutMultiplier = 0;
    CommTimeouts.WriteTotalTimeoutConstant = 0;
    if (!SetCommTimeouts (hComm, &CommTimeouts))
    {
        printf("Could not set timeouts\n");
        return NULL;
    }
    return hComm;
}

int main(void)
{
    //  Can also use COM2, COM3 or COM4 here
    hPort = ConfigureSerialPort("\\\\.\\COM12");
    if(hPort == NULL)
    {
        printf("Com port configuration failed\n");
        return -1;
    }
    // Call your ReadString and WriteString functions here
    BYTE b = 'm';
    WriteByte(b);
    ReadByte(b); //read line i want the program wait on this line until at least one character came(was not pooling).

    ClosePort();
    return 0;
}

any idea for that?

A: A blocking read is the normal behavior of ReadFile, but you have changed that by setting ReadTotalTimeoutConstant to MAXDWORD. Study the MSDN page for COMMTIMEOUTS. Use zero instead.


text:
Q: How to use RestTemplate efficiently in Multithreaded environment? I am working on a project in which I need to make a HTTP URL call to my server which is running Restful Service which returns back the response as a JSON String.
Below is my main code which is using the future and callables -
public class TimeoutThreadExample {

    private ExecutorService executor = Executors.newFixedThreadPool(10);

    public String getData() {
        Future<String> future = executor.submit(new Task());
        String response = null;

        try {
            response = future.get(100, TimeUnit.MILLISECONDS);
        } catch (TimeoutException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        return response;
    }
}

Below is my Task class which implements the Callable interface and uses the RestTemplate...
class Task implements Callable<String> {

    private RestTemplate restTemplate = new RestTemplate();

    public String call() throws Exception {

        String url = "some_url";
        String response = restTemplate.getForObject(url, String.class);

        return response;
    }
}

And now I have below code in another class DemoTest which calls the getData method in TimeoutThreadExample class 5000 times sequentially -
public class DemoTest {
   public static void main(String[] args) {

        TimeoutThreadExample bc = new TimeoutThreadExample();

        for (int i = 0; i <= 5000; i++) {
        //  TimerTest timer = TimerTest.getInstance(); // line 1
            bc.getData();
        //  timer.getDuration(); // line 2
        }
    }
}

So my question is should RestTemplate be static here in my Task class as if I see it correctly, I am recreating the whole connection pool for each request in RestTemplate which is not the right way I guess..
NOTE: If I am making RestTemplate static, then I see better performance end to end as compared to non static RestTemplate after commenting out line1 and line2 in DemoTest class which measures the performance.
In general what is the right way to use RestTemplate in Multithreading environment? Currently I am calling sequentially getData method 5000 times one by one but some customer will call it in a multithreaded way so need to know what is the best way to have RestTemplate in a multithreaded environment..
May be to use ConnectionFactory in the RestTemplate constructor? Any thoughts?
UPDATE:-
public class TimeoutThreadExample {

    private ExecutorService executor = Executors.newFixedThreadPool(10);
    private RestTemplate restTemplate = new RestTemplate();

    public String getData() {
        Future<String> future = executor.submit(new Task(restTemplate));
        String response = null;

        try {
            response = future.get(100, TimeUnit.MILLISECONDS);
        } catch (TimeoutException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        return response;
    }
}

And below my TaskClass -
class Task implements Callable<String> {

    private RestTemplate restTemplate;

    public Task(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public String call() throws Exception {

        String url = "some_url";
        String response = restTemplate.getForObject(url, String.class);

        return response;
    }
}

A: A RestTemplate is thread safe once constructed, so you can construct one instance and have all your tasks share it. That will be much more efficient,  because you eliminate the construction cost from each task, and reduce the load on the garbage collector.

A: I have my multi-thread-safe singleton REST template wired like this in spring:
<bean class="org.apache.commons.httpclient.params.HttpConnectionManagerParams" id="httpConnectionManagerParams">
    <property name="connectionTimeout" value="10000"/>
</bean>
<bean class="org.apache.commons.httpclient.MultiThreadedHttpConnectionManager" id="httpConnectionManager">
    <property name="params" ref="httpConnectionManagerParams"/>
</bean>
<bean class="org.apache.commons.httpclient.params.HttpClientParams" id="httpClientParams">
    <property name="authenticationPreemptive" value="true"/>
    <property name="soTimeout" value="10000"/>
</bean>
<bean class="org.apache.commons.httpclient.HttpClient" id="httpClient">
    <constructor-arg ref="httpClientParams"/>
    <constructor-arg ref="httpConnectionManager"/>
</bean>
<bean class="org.springframework.http.client.CommonsClientHttpRequestFactory" id="httpClientFactory">
    <constructor-arg ref="httpClient"/>
</bean>
<bean class="org.springframework.security.oauth.consumer.client.OAuthRestTemplate" id="restTemplate">
    <constructor-arg ref="httpClientFactory"/>
    <constructor-arg ref="myResource"/>
    <property name="messageConverters">
        <list>
            <ref bean="marshallingHttpMessageConverter"/>
        </list>
    </property>
</bean>

Please note I'm using an OAuthRestTemplate, and myResource refers to the oauth resource stuff which I've omitted as it's not relevant.  Instead of an OAuthRestTemplate you could just as easily use a org.springframework.web.client.RestTemplate http://docs.spring.io/spring/docs/3.2.4.RELEASE/javadoc-api/org/springframework/web/client/RestTemplate.html

A: Correct me if I didn't understand your question. It seems very similar to the previous one here.
There, we determined that RestTemplate is thread-safe. There is therefore no reason not to share it wherever it makes sense to, ie. wherever you are using it in the same way.
Your example seems like the perfect place to do so.
As you stated, recreating a new instance of RestTemplate for each Task instance is wasteful.
I would create the RestTemplate in TimeoutThreadExample and pass it to the Task as a constructor argument.
class Task implements Callable<String> {

    private RestTemplate restTemplate;

    public Task(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public String call() throws Exception {

        String url = "some_url";
        String response = restTemplate.getForObject(url, String.class);

        return response;
    }
}

This way you share the RestTemplate instance between all your Task objects.
Note that RestTemplate uses SimpleClientHttpRequestFactory to create its connections.


text:
Q: Rounding in jinja2 brackets I guess just generally I'm curious about what operations are allowable in jinja2 brackets, e.g. what I'm trying to do is perform an operation on embedded data like so:
{{ round(255*(mileage['chevy'] - mileage['ford']))/1000 }}

This throws the error on traceback:

UndefinedError: 'round' is undefined

Similarly when I try to use 'abs' in a bracketed jinja block, I get an Undefined error--even though they're both standard lib functions. Is there some way to perform this operation during template-rendering, rather than before passing the data?

A: The jinja2 templating language is different from the python language. In jinja2, operation on values are often done during filters : {{ something | operation }}. You can find a list of filters in the jinja2 documentation.
For example, to round, you can do :
{{ 42.55|round }}

This will display "42" on the web page. A abs filter exist in the same way.
Please note that these filters can only be used to alter values before display, and can be used for calculations. Calculations shouldn't be done in the template anyway.

A: According to Jinja Docs [round]
{{ 42.55|round }}

will returns float so result will be 43.0. Iif you need to specify precision use:
{{ 42.55321|round(2) }}

will return 42.55, also you can choose method of rounding, eg. round(2, 'ceil')
also when performing some math operations take it into brackets like:
{{ (x*y/z)|round(2) }}

A: If you really need to use the parentheses style, you can pass the required functions as rendering parameters.
For example, this small code:
from jinja2 import Environment, BaseLoader

mytemplate = '{{ round(3.7) }}'
result = Environment(loader=BaseLoader).from_string(mytemplate).render(round=round)
print(result)

prints:
4

You can also pass all functions from a module:
from jinja2 import Environment, BaseLoader
import math
from inspect import getmembers

mytemplate = '{{ fabs(sin(-pi/3)) }}'
result = Environment(loader=BaseLoader).from_string(mytemplate).render(getmembers(math))
print(result)

which prints:
0.8660254037844386


text:
Q: How To draw black colored border around each image in AQGridView I am using AQGridView in my project. we need to create a black colored border around each image. Can anyone help me on this.
Thanks in advance.
Regards,
Jas.

A: for UIImageView it is like something :-
[imageView.layer setBorderColor: [[UIColor blackColor] CGColor]];
[imageView.layer setBorderWidth: 2.0];

Hope it works on AQGridView...
Cheers

A: You could also put your AQGridView in a larger UIImageView that was empty but had the background set to black.


text:
Q: Android: Sharing lists between two threads I'm doing an app in which I have 2 views which extend from SurfaceView, called CanvasView.
I have a left CanvasView, and a right CanvasView.
Both these CanvasView instantiate a UIThread, which extends from Thread.
The CanvasView itself is passed into the thread like this:
public void surfaceCreated(SurfaceHolder holder) {
  uiThread = new UIThread(this);
  uiThread.setRunning(true);
  uiThread.start();
}

In each CanvasView, onDraw() , I do an access to a list. This list basically consists of a list of things to draw, which are essentially the same on both left and right canvases.
for (CharSequence line : lineList) {
...
..
}

Whenever my app needs to draw the items in lineList, it crashes saying
java.util.ConcurrentModificaitonException.
What is the correct way to "share" the Arraylist lineList between the two threads?
Thank you.

A: The ArrayList class is not Thread Safe.
Use Collections.synchronizedList() instead of ArrayList.

A: Don't use the simplified version of for loop
for (CharSequence line : lineList) {
    ...
    ..
}

Instead, use the traditional one. However, you have to handle data consistency by yourself.
for (int i = 0; i < lineList.size(); i++) {
    CharSequence line = lineList.get(i)
    ..
}

A: List is not thread safe and when multiple threads attempts to modify the same list, it will end up with concurrent modification exception.
Use ConcurrentLinkedQueue or CopyOnWriteArrayList.
Refer the link - Is there a concurrent List in Java's JDK?
Collections.synchronizedList() is an other alternative which will provide the synchronized access to the list.


text:
Q: Normal mapping on flat water surface produces incorrect specular highlights I have a flat water surface with a dudv and a normal map attached to it. The dudv map works correct and the normal map is attached correct as well (visualizing the normal map looks like it should).
The specular highlights are always showing at the wrong place though as if the light direction is incorrect. The lighting works correct without normal mapping, so I don't believe it is the light direction, but probably something with the tangent space. Since I calculate the tangent space from a static set of vectors I'm confused where it could go wrong.
Here in the vertex shader I create the TBN matrix that I use to create the tangent space vectors that I send to the fragment shader:
const vec3 TANGENT = vec3(1.0, 0.0, 0.0);
const vec3 NORMAL = vec3(0.0, 1.0, 0.0);
const vec3 BITANGENT = vec3(0.0, 0.0, -1.0);

out vec3 FragPos;
out vec3 TangentFragPos;
out vec3 TangentLightDir;
out vec3 TangentPlayerPos;

void main()
{
    FragPos = vec3(model * vec4(vertex, 1.0));
    mat3 mod = transpose(inverse(mat3(model)));
    [...]
    vec3 n = normalize(mod * NORMAL);
    vec3 t = normalize(mod * TANGENT);
    vec3 b = normalize(mod * BITANGENT);
    mat3 TBN = transpose(mat3(t, b, n));
    TangentFragPos =  TBN * FragPos;
    TangentLightDir =  TBN * sun.Position.xyz;
    TangentPlayerPos =  TBN * playerPos;
}

In the fragment shader I then sample a normal vector from the normal map and use the transformed tangent space vectors to calculate specular highlights:
in vec3 FragPos;
in vec3 TangentFragPos;
in vec3 TangentLightDir;
in vec3 TangentPlayerPos;

uniform sampler2D normalMap;

void main()
{
    [...]
    vec3 normal = texture(normalMap, vec2(TexCoords * TextureScale) + vec2(Time)).xyz;
    normal = normalize(normal * 2.0 - 1.0);
    // normal = vec3(0.0, 0.0, 1.0); // this gives proper specular highlights, but not mapped

    // Specular lighting
    vec3 lightDir = normalize(-TangentLightDir);
    viewDir = normalize(TangentPlayerPos - TangentFragPos);
    vec3 reflectDir = normalize(reflect(-lightDir, normal));
    float spec = pow(max(dot(viewDir, reflectDir), 0.0), 64);
    vec3 lighting = sun.Specular * spec * fresnel;

    color.xyz *= lighting;
}

Note that I do the lighting in world-space.
The lighting works fine without normal mapping, but as soon as I introduce the TBN matrix into the equations the specular highlights are not in the right direction on the water.
EDIT
I've added an image to see how it currently looks and where the specular light should be. That might add some extra insight into the problem:

EDIT2
Here's the weird thing. If I manually define the normal vector as vec3(0.0, 0.0, 1.0) (pointing upwards in tangent space) I get perfect specular highlights (but with no mapped variation) and once I take the normal from the normal map, I get incorrect highlights again so I'd say the cause of the issue would be at the normals. The normal map I'm using however is a default normal map you'd usually see as you can see below:

Why is it that once I take a normal from this normal map (which already should be in tangent space), the specular highlights break down?

A: It's been more than a week of debugging now and I finally found the issue. I've been using gamma correction and my texture class by defaults loads texture with the GL_SRGB property as the texture's internal format so OpenGL properly converts gamma corrected textures to their linear brothers.
The problem was that I also loaded the dudv and Normal map with this texture class without changing this property so the normal and dudv maps had OpenGL's gamma->linear correction applied and thus gave incorrect results.
Loading these textures with GL_RGB solved the issue.

A: Are you on a left-hand or right-hand coordinate system? Have you considered checking the validity of your static TBN matrix vectors?
EDIT:
The bitangent is extracted by crossing normal and tangent. So, normal(0,1,0) x tangent(1,0,0) equals bitangent(0,0,-1)


text:
Q: Recursion with test case I am trying to code following recursion problem. Every time I run the test case it gives me out of bound error on the else if line. How do I fix the out of bound error. under the code is the test case.
static boolean allEqual(int[] a, int start, int end) {

 if( a[start + 1]>=a.length){return false;}
 if (start == end && a[start] == a[end]) {
        return true;
    }
    ///recursive
    else if (a[start] == a[start + 1]) // Error over here
{
        return allEqual(a, start + 1, end);
    }
    // else if (start == end && a[start] == a[end]) {
    //   return true;
    else {
        return false;
    }

}
// Following is the test case
    Random rng = new Random(SEED);
    for(int i = 0; i < RUNS; i++) {
        int[] a = new int[i];
        int v = rng.nextInt();
        for(int j = 0; j < i; j++) {
            a[j] = v;
        }
        assertTrue(rp.allEqual(a, 0, i-1));
        for(int j = 1; j < i; j++) {
            assertTrue(rp.allEqual(a, j, i-1));
            assertTrue(rp.allEqual(a, 0, j));
            a[j] = a[j] - 1;
            assertTrue(rp.allEqual(a, 0, j-1));
            assertTrue(rp.allEqual(a, j + 1, i-1));
            assertFalse(rp.allEqual(a, 0, i-1));
            a[j] = a[j] + 2;
            assertTrue(rp.allEqual(a, 0, j-1));
            assertTrue(rp.allEqual(a, j + 1, i-1));
            assertFalse(rp.allEqual(a, 0, i-1));
            a[j] = a[j] - 1;
        }
    }


text:
Q: Find Data Patterns from Database automatically We want to Extract Data Patterns from Data smartly and automatically.
We have the following Phone Database Struture (Few Fields noted to give example)-
PhoneName(string), LaunchDate(Date), LaunchPrice(Currency), AmoutOfRam(Number), IsTouchScreen(Bit), IsProximitySensor(Bit), IsCompassSensor(Bit)
We have around 1500 phones in database. We want to derive smart rules like-

*

*If the launchdate is 2016 and LauchPrice is above 200$ then AmountOfRam will be more than 2GB.

*If the phone has a TouchScreen than it will definitely have a ProximitySensor.

*If the launchdate is 2016 and LauchPrice is above 400$ then it will Definitely have a Compass.
Analyzing the data in the database, we want an algorithm to AUTOMATICALLY find these patterns.
Can someone suggest a framework, reliable technique to do this? Any starting point shall help as well.
Regards,
Swapneel Shah

A: Discretize the numerical attributes, and use association rule mining.
For details, see any textbook on data mining. Your question is too brad to be answered in this format - the answer fills a chapter of an introductory book.

A: After spending some time over reading a Data Mining book, and Google search, use BI (Business Intelligence) algorithms with MS SQL server.
Here is the link - https://msdn.microsoft.com/en-us/library/ms175595.aspx
[And there should be parallel solutions with databases as well]
All the basic algorithms are available and can be used with a Quick Configuration Wizard.


text:
Q: Jenkins Copy Artifact "Unable to find a build for artifact copy from ..." I am trying to copy the artifacts from one build (Coverity Test), to another build (MainBuild).
MainBuild uses a declarative pipeline. I have added the following step to build Coverity Test as the final step in MainBuild.
stage('Coverity Test') {
    when { expression { params.CoverityReport ==true } }
    steps{
        build job: 'Coverity Test',
        parameters: [
            string(name: 'COVERITY_TOOL_HOME',
                  value: '/home/coverity/cov-analysis-linux64-2020.03'),
            string(name: 'GIT_BRANCH', value: "${env.PROJ_GIT_BRANCH}")
        ]

        copyArtifacts filter: 'CoverityCrit*Issues.txt', fingerprintArtifacts: true, projectName: 'Coverity Test', selector: specific ('${BUILD_NUMBER}')
    }
}

The files CoverityCrit*Issues are created in a script through the Coverity Test build, I have confirmed that these files display as artifacts of the Coverity Test in Jenkins.
The copyArtifacts command returns an error "ERROR: Unable to find a build for artifact copy from: Coverity Test"
I used this as an example to create the copyArtifacts command
What am I doing wrong?

A: Inside
selector: specific ('${BUILD_NUMBER}')

You need to use double quotes "" instead of single quotes ''.


text:
Q: Multiple variables initialization in objective C I'm working on a project in objective C, and on another project in Java too. And i ask me a question, because i know how to make mulitple declaration in Java, like this :
for (int l = 7; l>0; l--)
    {
        for (int g = 1; g<8; g++)
        {
            ButtonTest = new JButton();
            ButtonTest.setBorderPainted(false);
            ButtonTest.setOpaque(true);
            ButtonTest.setName("Bouton"+l+g);
            ButtonTest.addActionListener(this);
            PanelTest.add(ButtonTest);
        }
    }

How can i make this sort of code in objective C, with UIButtons for example ?
Thanks a lot !

A: It's pretty much the same as in Java:
for (int l = 7; l>0; l--)
{
    for (int g = 1; g<8; g++)
    {
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(x, y, width, height)];
        // Do any other configuration here.
        [button setTitle:@"foo" forState:UIControlStateNormal];
        [myView addSubview:button];
    }
}

This will generate UIButtons and add them to a view. You'll probably have to generate the coordinates and size yourself though, I don't know if that's different in Java.


text:
Q: Swing JTextField - Max 3 digits before decimal and max 2 digits after decimal Can anyone help me with the validation for JTextField which can only allow up to 3 digits before the decimal and up to 2 digits after the decimal?
I used regex \\d{3}\\.\\d{2} for InputVerifier. This is allowing exactly 3 and 2 before and after decimal. I need <=3 and <=2 before and after decimal.
My project only needs JTextField.

A: To validate such strings, you can use the following regex:
^\d{0,3}\.\d{1,2}$

It will require at least 1 digit on the right side of the decimal, and the first part can be 0 to 3 digits long (due to {0,3} quantifier).
Note that it allows .2-like input.


text:
Q: Synchronous detector question
The author explains it as a synchronous demodulator. Here we can see that two multipliers which multiply both the inverted and non inverted signals.
Can I do the same with only one switch for non inverted signal?
Circuit shown here is from a lock in amplifier milliohm meter.
5 V pulses are coming from the reference oscillator.
1.8 V pulses are input signal coming from a preamp that amplifies drop across a milliohm resistance.
Here is the link http://cappels.org/dproj/dlmom/dlmom.html

A: Yes, you can. You'd have to multiply your results with two.
But, you're multiplying with an on/off sequence in that case, and thus you'd obviously lose all info on the negative cycle of your input signal, and atop of that, reduce the amount of signal energy that reaches the integrator by a factor of two.
That reduces your SNR. And since you're building a lock-in amplifier, that's the worst you can do.
So, analog switches are cheap, and easy to acquire. Don't skip on them. In fact, the part that the author is using comes with four switches in one package, it's unclear why you'd want to use only one of them.


text:
Q: How do I add dependency javadocs in Visual Studio Code? I've set up a maven project in visual studio code with the red hat java support. Everything works great, except that the intellisense doesn't include the javadoc descriptions for the functions and classes from my dependency. Is there a way to explicitly link VSCode to my library's jdocs? If so, how do I do it?

A: you could try this:
for example, i have a project :
/project
 /lib
  test-1.0.0.jar
 /doc
  test-1.0.0-javadoc.jar

add in your .classPath :
<classpathentry kind="lib" path="lib/test-1.0.0.jar">
  <attributes>
    <attribute name="javadoc_location" value="jar:platform:/resource/project/doc/test-1.0.0-javadoc.jar!/" />
  </attributes>
</classpathentry>


text:
Q: Accessing USB printer without drivers Wondering if there is a way to send and receive information form specifically this printer over USB. There are no supported drivers for this.
My goal is to build a print server with a raspberry pi to connect the printer to the network to enable network printing.


text:
Q: Using a Lambda in a struct initializer I have an array of a struct of which one member is a function pointer. The rest of the members are pure data. The struct and function pointer acts as a poor man's class object and virtual method (pre C++ code C code). The function pointer signature is the same for all instances of the struct.
(Please, no comments about just converting the struct to a class object. I would if I could, but this is part of a huge code base of legacy code. And it's impossible for me to substantially change)
There are several hundred of these structs in one giant array with a giant struct initializer. Each one of these struct's contents are different, each with a different tiny, one-line function to fill the function pointer. This is a maintenance nightmare. I would like to replace these hundreds of tiny functions with just the body of a Lambda directly in the struct initializer itself.
it seems Lambdas are right solution for this, but I'm struggling to figure how, or if this can even be done.


text:
Q: Using a FQP30N06L MOSFET on a 3.3v microcontroller I'm trying to drive a 2.5A/12V load controlled by a 3.3v micro-controller.
In the past I've used a TIP120. In this case I'm trying to drive a solenoid and the voltage drop I'm getting across the TIP120 is too high.
I was looking at other options and people recommend using a MOSFET. The problem I'm having is I need to drive it from 3.3v. Many people and tutorials suggest devices that -may- work at 3.3v but in reality may require up to 4.5v to fully switch. And this minimum voltage can vary from transistor to transistor.
I'm not an expert and this is confusing. I'm not very good at reading data sheets but keep finding recommendations for devices that upon looking, seem as if they need at minimum 4.5v to guarantee saturation.
So to clear it up I thought I would ask here: can I use a FQP30N06L (which is cheap for me to obtain and in the package (TO-220) that I require) to power my load if I drive it's base from a 2N2222 transistor?
The datasheet for the FQP30N06L states: 32A, 60V, RDS(on) = 0.035Ω @VGS = 10V.
So I guess I need 10V to fully saturate it?
If so that is fine. I was wondering if I could use a 2N2222 like this:

Very rough drawing I made up at the time in mspaint. Would this work and be acceptable?
Thanks!

A: Similar question: Transistor Push Pull Stage to drive Mosfet
The simplest driver would be a common emmitter NPN configuration which would invert your logic but give you the voltage gain needed to drive your FET gate. Keep in mind the high side 470 ohm resistor will almost always be conducting since your application is mostly keeping the solenoid in the "off" state, so if you go with this configuration there will always be a 24mA drain on your 12V power supply (choose the size to balance constant power drain and required turn on speed). If constant drain is unacceptable (battery powered for example), you can add another common emitter PNP stage or try to build a push-pull stage with complementary NPN/PNP trasnsistors/FETs to actively drive the FET base both directions (hard, be careful with shoot-through).
Here's the common emitter NPN driver you could start with:

simulate this circuit – Schematic created using CircuitLab
The orange plot shows the voltage across the solenoid (modeled by series resistor and inductor) which you'll notice is inverted from the 3.3V drive signal.

Alternatively, if you want to try driving the FET gate straight from your microcontroller, start with a light bulb or power resistor capable of drawing the same 2.5A current (4.8 ohm capable of handling 30W) and use at least a 165 ohm gate resistor to prevent you from exceeding the maximum source/sink GPIO pin current (assuming it's 20mA, check the datasheet).
\begin{equation}
165\Omega = \frac{3.3 V}{20 mA}
\end{equation}
The MOSFET datasheet shows the max threshold voltage for 250uA is 2.5V but looking at Figure 6: Gate Charge Characteristics, the Miller plateau is at about 4V which suggests 3.3V won't be able to fully drive the FET open for the current you require (thanks to @Chris Stratton for pointing that out)... but you could still give it a shot if the power dissipation during "on" time is manageable (it'll have a higher Ron when partially switched on).
Note on powering the relay (big inductor): if your microcontroller starts doing weird things like freezing or resetting, it may be from the electrical noise of manipulating large currents. In that case you'll need to take measures to buffer the microcontroller drive signal to protect the microcontroller pins (something like an optocoupler would work great).

A: Yes, this circuit will work fine as you have it. 12V on the gate of the FQP30N06L is more than the 10V you need to get guaranteed Rds(on) and it's well under the 20V absolute maximum voltage. The switch-on is a bit slow (meaning more power dissipation in the MOSFET) but that's not too much of a concern unless you're trying to do PWM, in which case I suggest using a proper gate driver circuit.
Keep in mind that the default is "on" (with connection from the Arduino open-circuit or high impedance), which may not be desirable.
You can avoid that by adding another inverting stage, or using a simple common-base level shifter with no current gain (I won't recommend that because it exposes the Arduino to accidental damage a bit more).
The 220 ohm is also on the low side, drawing unnecessarily large current from the MCU. 10K would be fine with a 10K pullup, with either 3.3V or 5V drive.
By the way, you show an Arduino UNO, which I believe runs the MCU off of 5V.


text:
Q: One-To-One functions Let $A$ be the set with $n$ elements and $B$ be the set with $m$ elements. How many one-to-one functions are there from $A$ to $P(B)$ (power set of $B$).
There are $n!$ total functions from $A$ to $B$.
and $(2^m)^n$ from $A$ to $P(B)$
Since $P(B)$ is a power set, there are $2^m$ elements in $P(B)$.
Therefore total one-to-one functions from $A$ to $P(B)$ are:
$P(n,2^m) = n!/(n-2^m)!$ for $n \ge 2^m$
or $P(2^{mn},2^m) = (2^{mn})!/(2^{mn} - 2^m)!$ ?
Is my reasoning correct in any case?

A: There are $2^{m}$ such elements in $\mathcal{P}(B)$. So assuming $2^{m} \geq n$ (as otherwise, no such function will be one to one), we have $P(2^{m}, n)$ such functions.
You can see this in the following way. Take $a_{1} \in A$. So a function $f$ has $2^{m}$ choices to map $a_{1}$. It then has $2^{m} - 1$ choices to map $a_{2}$. We continue this through $a_{n}$. We continue this in the following way to get:
$$\prod_{i=0}^{n-1} (2^{m} - i) = P(2^{m}, n)$$


text:
Q: Class cannot be cast to class java.lang.reflect.ParameterizedType (java.lang.Class and java.lang.reflect.ParameterizedType ) I have the following classes in the follwing pattern: public abstract class BaseDAOMongoImpl<K, E extends Entity> implements BaseDAO<K, E> {
public BaseDAOMongoImpl() {
    ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();
    entityClass = (Class<E>) pt.getActualTypeArguments()[1];
    entityClassName = entityClass.getSimpleName();

}

.
.
.}
 @Repository
public class TestDAO1Impl extends BaseDAOMongoImpl<String, Test1MockEvent>{
public String getOverridingCollectionName() {
    return "test1";
}

}`
`@Repository
public class Test123 extends TestDAO1Impl {
public void testing(){
}`

Now,when I am Autowiring  Test123 in some class I am getting the following exception:
Class cannot be cast to class java.lang.reflect.ParameterizedType (java.lang.Class and java.lang.reflect.ParameterizedType )
I tried writing a recursive function that returns a the proper class name in the base class constructoe like below:
`public BaseDAOMongoImpl() {
    ParameterizedType pt = (ParameterizedType)getClassThatExtendsBaseDAOMongoImpl(this.getClass()).getGenericSuperclass();
    this.entityClass = (Class) pt.getActualTypeArguments()[1];
    this.entityClassName = this.entityClass.getSimpleName();
    this.isAuditable = this.isAuditableEntity(this.entityClass);
    LOGGER.debug("entity class:{}, isAuditable:{}", new Object[]{this.entityClass, this.isAuditable});

}`
private Class<?> getClassThatExtendsBaseDAOMongoImpl(Class<?> source) { if (BaseDAOMongoImpl.class.getCanonicalName().equals(source.getSuperclass().getCanonicalName())) return source; return getClassThatExtendsBaseDAOMongoImpl(source.getSuperclass()); }
But I am getting the below exception:
nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'Test1DAOImpl' available: expected single matching bean but found 2: test123,test1DAOImpl
`

A: I tried writing a recursive function that returns a the proper class name in the base class constructoe like below: `public BaseDAOMongoImpl() {
ParameterizedType pt = (ParameterizedType)getClassThatExtendsBaseDAOMongoImpl(this.getClass()).getGenericSuperclass();
this.entityClass = (Class) pt.getActualTypeArguments()[1];
this.entityClassName = this.entityClass.getSimpleName();
this.isAuditable = this.isAuditableEntity(this.entityClass);
LOGGER.debug("entity class:{}, isAuditable:{}", new Object[]{this.entityClass, this.isAuditable});

}`
private Class getClassThatExtendsBaseDAOMongoImpl(Class source) { if (BaseDAOMongoImpl.class.getCanonicalName().equals(source.getSuperclass().getCanonicalName())) return source; return getClassThatExtendsBaseDAOMongoImpl(source.getSuperclass()); }
But I am getting the below exception: nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'Test1DAOImpl' available: expected single matching bean but found 2: test123,test1DAOImpl


text:
Q: how to call my webservice from url I have an endpoint to my REST webservice like this:
http://www.example.com/example_endpoint/user

and the content-type is: application/x-www-form-urlencoded
And I want to call it by url with the parameters:
firstname=firstname_test
lastname=lastname_test
pass=123

I'm calling like this, but I get no results:
http://www.example.com/example_endpoint/user?firstname=firstname_test&lastname=lastname_test&pass=123

How should I call the webservice???


text:
Q: java webcam adjust shutter speed I want to (manually) adjust the "shutter speed" of my webcam with Java code.

*

*Is it possible to do this (with java) ?

*How do I realize it ?

Extra info:

*

*Windows vista and NetBeans IDE 7.3.1

*Webcam : Logitech webcam pro 4000

*Driver : Quickcam v11

*Language : java

*Library : LTI-CIVIL with example code for image capturing

*I think I need to adjust somewhere the time between the command for
the camera to collect light and stop collecting light. (half thinking of
an SLR camera).

A: There are certain available API's that can be used to control your webcam using java.

*

*Java Media Framework (JMF)
The Java Media Framework API (JMF) enables audio, video and other time-based media to be added to applications and applets built on Java technology. This optional package, which can capture, playback, stream, and transcode multiple media formats, extends the Java 2 Platform, Standard Edition (J2SE) for multimedia developers by providing a powerful toolkit to develop scalable, cross-platform technology.

*

*Freedom for Media in Java (FMJ)
FMJ is an open-source project with the goal of providing an alternative to Java Media Framework (JMF), while remaining API-compatible with JMF. It aims to produce a single API/Framework which can be used to capture, playback, process, and stream media across multiple platforms.Since FMJ is API-compatible with latest JMF, you may use existing JMF codes and run them.

*

*Xuggler
Xuggler is the easy way to uncompress, modify, and re-compress any media file (or stream) from Java. This is more widely used for manipulation of media files and related operations.
You can refer the following links:

*

*Java Media Framework

*Freedom for Media in Java

*Xuggler
You can find tons of tutorials on them. I'm sure you can figure out an efficient way to control the shutter speed of your webcam using any of these API's. :)


text:
Q: Use CSS3 perspective and transform to render image as 3d cube I have been using PHP and ImageMagick for to generate a 3D preview of a canvas print (see image below).

There are options to change the edge type, depth, size etc which are AJAX calls to a PHP support file which re-renders the preview with new settings and I reload it into the DOM.
This is starting to overload our server when busy. So I thought I could do this in CSS3 and do all the preview rendering client-side instead.
Here's what I have so far:

.wrapper {
  perspective: 500px;
  margin: 4em auto;
  width: 37em;
}

.inner {
  transform: rotateY(40deg);
}

.inner div {
  width: 11em;
  display: inline-block;
  margin-right: 1em;
}

.inner img {
  display: block;
  height: auto;
  max-width: 100%;
  margin: 0 auto;
}

The problem I am having is wrapping the image around the edges like in the image above. How can I do this?

A: I have done a demo, with 2 elements holding the same image.
Just set the image origin on them accordingly to the dimension, and it will match.

.main {
  width: 400px;
  height: 300px;
  border: solid 1px red;
  background-image: url(http://lorempixel.com/400/300);
  background-size: 0px 0px;
  perspective: 500px;
  position: relative;
}

.front {
  position: absolute;
  width: 360px;
  height: 100%;
  left: 40px;
  top: 0px;
  transform: rotateY(45deg);
  transform-origin: left center;
  background-image: inherit;
  background-position: -40px 0px;
}
.side {
  position: absolute;
  width: 40px;
  height: 100%;
  left: 0px;
  top: 0px;
  transform: rotateY(-45deg);
  transform-origin: right center;
  background-image: inherit;
  background-position: 0px 0px;
}


text:
Q: Is it true that every subspace contain a primitive element? Let $R = GF(q), q = p^r$, be a field with identity $e$, where $p$ is a prime number. Let $S=GF(q^n)$ be an extension of $R, n\geq 2$ and $K = GF(q^{mn})$ be an extension of $S$, where $m$ is prime. Let $_RW$ be a subspace of $_RK$ such that
$$
\operatorname{dim}_RW =n, e\in W, W\neq S
$$
I want to prove that there exist a primitive element of $K$ (that is the element of multiplicative order $q^{mn}-1$) in $W$.
But so far my attempts have not been successful. Experiments on the computer confirm this hypothesis.

A: This does not work in general: the problem is you have no control over $m$.
Let $r = 1$. There's a sequence of embeddings of fields $$\mathit{GF}(p)\subset\mathit{GF}(p^2)\subset\mathit{GF}(p^4)\subset\mathit{GF}(p^8)\subset\dotsb.$$
Let $S = \mathit{GF}(p^2)$, so $n = 2$. Let $W$ be any $2$-dimensional subspace of $\mathit{GF}(p^4)$ containing the identity but not equal to $S$.
Let $K = \mathit{GF}(p^8)$. $W$ is still a $2$-dimensional subspace of $K$, but since $\mathit{GF}(p^8)\hookrightarrow K$ as a subfield, any element of $W$ can generate at most $\mathit{GF}(p^4)$, which is not all of $K$.
For $r\ne 1$, you can do the same thing with
$$\mathit{GF}(p^r)\subset\mathit{GF}(p^{2r})\subset\mathit{GF}(p^{4r})\subset\mathit{GF}(p^{8r})\subset\dotsb.$$


text:
Q: Why does my julia code run so slowly? redim = 2;
# Loading data
iris_data = readdlm("iris_data.csv");
iris_target = readdlm("iris_target.csv");

# Center data
iris_data = broadcast(-, iris_data, mean(iris_data, 1));
n_data, n_dim = size(iris_data);

Sw = zeros(n_dim, n_dim);
Sb = zeros(n_dim, n_dim);

C = cov(iris_data);

classes = unique(iris_target);

for i=1:length(classes)
    index = find(x -> x==classes[i], iris_target);
    d = iris_data[index,:];
    classcov = cov(d);
    Sw += length(index) / n_data .* classcov;
end
Sb = C - Sw;

evals, evecs = eig(Sw, Sb);
w = evecs[:,1:redim];
new_data = iris_data * w;

This code just does LDA (linear discriminant analysis) for the iris_data.
Reduct the dimensions of the iris_data to 2.
It will takes about 4 seconds, but Python(numpy/scipy) only takes about 0.6 seconds.
 Why?

A: This is from the first page, second paragraph of the introduction in the Julia Manual:

Because Julia's compiler is different from the interpreters used for languages like Python or R, you may find that Julia's performance is unintuitive at first. If you find that something is slow, we highly recommend reading through the Performance Tips section before trying anything else. Once you understand how Julia works, it's easy to write code that's nearly as fast as C.

Excerpt:

Avoid global variables
A global variable might have its value, and therefore its type, change at any point. This makes it difficult for the compiler to optimize code using global variables. Variables should be local, or passed as arguments to functions, whenever possible.
Any code that is performance critical or being benchmarked should be inside a function.
We find that global names are frequently constants, and declaring them as such greatly improves performance

Knowing that the script (all procedural top level code) style is so pervasive among many scientific computing users, I would recommend you to at least wrap the whole file inside a let expression for starters (let introduces a new local scope), ie:
let

redim = 2
# Loading data
iris_data = readdlm("iris_data.csv")
iris_target = readdlm("iris_target.csv")

# Center data
iris_data = broadcast(-, iris_data, mean(iris_data, 1))
n_data, n_dim = size(iris_data)

Sw = zeros(n_dim, n_dim)
Sb = zeros(n_dim, n_dim)

C = cov(iris_data)

classes = unique(iris_target)

for i=1:length(classes)
    index = find(x -> x==classes[i], iris_target)
    d = iris_data[index,:]
    classcov = cov(d)
    Sw += length(index) / n_data .* classcov
end
Sb = C - Sw

evals, evecs = eig(Sw, Sb)
w = evecs[:,1:redim]
new_data = iris_data * w

end

But I would also urge you to refactor that into small functions and then compose a main function that calls the rest, something like this, notice how this refactor makes your code general and reusable (and fast):
module LinearDiscriminantAnalysis

export load_data, center_data

"Returns data and target Matrices."
load_data(data_path, target_path) = (readdlm(data_path), readdlm(target_path))

function center_data(data, target)
    data = broadcast(-, data, mean(data, 1))
    n_data, n_dim = size(data)
    Sw = zeros(n_dim, n_dim)
    Sb = zeros(n_dim, n_dim)
    C = cov(data)
    classes = unique(target)
    for i=1:length(classes)
        index = find(x -> x==classes[i], target)
        d = data[index,:]
        classcov = cov(d)
        Sw += length(index) / n_data .* classcov
    end
    Sb = C - Sw
    evals, evecs = eig(Sw, Sb)
    redim = 2
    w = evecs[:,1:redim]
    return data * w
end

end

using LinearDiscriminantAnalysis

function main()
    iris_data, iris_target = load_data("iris_data.csv", "iris_target.csv")
    result = center_data(iris_data, iris_target)
    @show result
end

main()

Notes:

*

*You don't need all those semicolons.

*anonymous functions are currently slow but that will change in v0.5. You can use FastAnonymous for now, if performance is critical.

*In summary read carefully and take into account all the performance tips.

*main is just a name, it could be anything else you like.


text:
Q: Is it possible to create Python-based Application in Xcode or equivalent? So I have a lot of python scripts that I have written for my work but no one in my lab knows how to use Python so I wanted to be able to generate a simple Mac App where you can 'Browse' for a file on your computer and type in the name of the file that you want to save . . . everything else will be processed by the application for the python script I have generated.
Does anyone know if this is possible? I watched some tutorials on people generating applications in Xcode with Objective C but I don't want to have to learn a new language to reconstruct my Python scripts.
Thank you

A: If you only want this to run on OS X, you could use pyobjc (see https://stackoverflow.com/a/2393530) to develop a Cocoa application, but there are also quite a few cross-platform GUI frameworks for Python, which will work on OS X as well as other operating systems.

A: For me, the easiest way to do this would be using the Automator program that comes with OSX. Create a new application, then choose Run Shell Script from within the Utilities sub-category. The pop-up at the top of the resulting window has a /usr/bin/python option. Put your python in there. You can connect inputs and outputs to that script using the Ask for Text item, etc...
The input from Ask for Text are most easily obtained if you choose "as arguments" from the Pass input: pop-up in the right of the Run Shell Script module. They come in as a list of strings, but not split on spaces like they would be in a normal line.
Try this code and I think it will become clear (for this test, put several strings separated by spaces as the text value that you pass):
import sys

print sys.argv
items = sys.argv[1:][0].split()

for f in items:
    print f

A: Open Automator
Choose "Application"
Drag a "Run Shell Script" onto the workflow panel
Choose "/usr/bin/python" as the shell. Paste in your script, and select Pass Input: "to stdin"
Or, choose bash as the shell, and simply have the automator script run your Python script with Pass Input "as arguments" selected on the top right. You'll then use the contents of $@ as your arguments.
Save the application.
Done. You have a .app onto which files can be dragged.


text:
Q: Rails many to many relation, exist? query I have one to many relation between folders and docs tabels. I want to look whether a folder includes a doc like:
q = Doc.new(blabla)

folder.docs.inludes?(q)

A: I think you should try
folder.docs.exists?(q)

A: If you're creating a new Doc like that, irrespective of the content of the Doc, it will never be identical to any other Doc in the database (as far as include? is concerned) as the Doc's will have differing id's/object instance hashes.
If you wanted to be able to compare Doc's based off of content rather than the actual record (referenced by id), you could eql? (==) - see here: http://ruby-doc.org/core-1.9.3/Object.html#method-i-eql-3F. I would not recommend doing that though.
I would re-think your solution here ideally. What are you trying to check, to see if a folder contains a document by a particular name?
folder.docs.find_by_name('blabla')

If you get a non-nil result, you have a doc in the folder with the name 'blabla', if it's nil you don't.


text:
Q: caesar cypher decryptor Alright so I have been "Tasked" with writing a program to decrypt the simple caesar cyphers.
I have everything working correctly, only my input stops about 29 characters in. It's reading from a very large file and the text stops at: "the declaration of independe" mid sentence. Any ideas what could cause this? I"m assuming I'm abusing and misusing something here. Feel free to throw rocks at my head. I'm sure I could use more "learning"
EDIT: upon further investigation I believe my issue is to do with my loops and sizeof(myarray)
edit 2: I've edited the code and now it breaks because of "Access violation reading location 0x002A4000":
 for (int i = 0; i < myArray.length(); i++)
    {
        // pritns each occurance cout << char(i + 'a') << " has " << count_Array[i] <<" occuarnces"  <<endl;
        if (count_Array[i] > tester)
        {
            //finds largest
            tester = count_Array[i];
            max_array_value = i;
        }
    }
    // print

Thanks for any tips :]

code:

   #include <iostream>
#include <string>
#include <cctype>
#include <fstream>
using namespace std;

int decipher(string myArray, string outputFileName);

int main ()
{
    string outputFileName;
    string inputFileName;
    ifstream inputFile;
    string reply;
    char myArray;
    string all_text = "";

    //getting input and output files
    cout << "Please input filename: ";
    getline(cin,inputFileName);
    cout <<"please enter output filename:";
    getline(cin,outputFileName);
    //opens file
    inputFile.open(inputFileName);

    if (!inputFile.is_open())
    {
        //file failed to open
        cout <<"unable to open input file." <<endl << "Press enter to continue...";
        getline(cin,reply);
        exit(1);
    }
    //read file into all_text
    while(inputFile.peek() != EOF)
    {
        inputFile.get(myArray);
            all_text+=myArray;

    }
    // prints out file cout <<all_text;
            inputFile.close();
            //send to decipher
            decipher(all_text, outputFileName);
    cout << "press enter to continue";
    getline(cin,reply);
    return 0;
}

int decipher(string myArray, string outputFileName)
{
    char default_alp[26] = {'a', 'b' ,'c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z' };
    int count_Array[26] = { 0 };
    int tester = count_Array[0];
    int max_array_value = 0;
    string my_Message;
    char temp;
    ofstream outputFile;
    //gets count of occurances
    for (int i = 0; i < myArray.length(); i++)
    {
        count_Array[tolower(myArray[i]) - 'a']++;
    }

    for (int i = 0; i < myArray.length(); i++)
    {
        // pritns each occurance cout << char(i + 'a') << " has " << count_Array[i] <<" occuarnces"  <<endl;
        if (count_Array[i] > tester)
        {
            //finds largest
            tester = count_Array[i];
            max_array_value = i;

        }
    }
    // prints useful information cout << "Largest number of occurances " << default_alp[max_array_value] <<endl << "shift amount is: " << default_alp[max_array_value]-'e' <<endl;
    for (int i = 0; i < myArray.length(); i++)
    {
//prints out each letter    cout << myArray[i];
    }

    for (int i = 0; i < myArray.length; i++)
    {
        cout <<myArray.length();
        //shifts the text based on value in dec
        int shift = default_alp[max_array_value]-'e';
        temp = myArray[i];
        if (isalpha(temp))
        {
            if(tolower(myArray[i])-shift >= 97)
            {
                my_Message += tolower(myArray[i]) - shift;
            }
            else
            {
                my_Message += tolower(myArray[i]) + 26-shift;
            }
        }
        else
        {
                my_Message +=myArray[i];
        }
    }
    outputFile.open(outputFileName);
    outputFile << my_Message;
    return 0;
}

A: What compiler are you using. For me, it does not compile because
//opens file
    inputFile.open(inputFileName);
needs to be
//opens file
    inputFile.open(inputFileName.c_str());
http://www.cplusplus.com/reference/fstream/ifstream/open/
but when it does compile, things seem to work ok. The whole file is read.

A: In decipher, sizeof(myArray) gives you the size of a string instance. The string instance may contain the actual length of the string, some space for very small strings and a pointer to the actual data, but it does not contain the data, i.e. the string, itself.
Instead of sizeof(myArray), use myArray.length()!


text:
Q: BrowserRouter basename prop issue when upgrading to v6 I am upgrading from React Router v5 to v6. When I run the app there is no basename in the url and nothing loads, when I add /config2 to the url everything shows up. I'm getting an error with v5 BrowserRouter basename prop. I'm trying to solve this issue with React router v6 but haven't found a solution. It was working fine with v5. Any solutions?
Root.tsx
<BrowserRouter basename="/config2">
  <IntlProvider
    messages={
      LanguageOptions.find((option) => {
        return option.locale === appState.locale;
      })?.fileName
    }
    locale={appState.locale}
    defaultLocale="en"
  >
    <ThemeProvider>{children}</ThemeProvider>
  </IntlProvider>
</BrowserRouter>

This is where I am using browser router.
App.tsx
<>
  <GlobalAlert />
  {/* TODO: remove this once no longer necessary, after disconnecting legacy DCUI */}
  {isAuthenticated && !legacyView && (

      {loadingCountryOptions ? (

          <CircularProgress size="30px" />

      ) : (
        <>

            <Routes>
              <Route path="/" element={<ProtectedRoutes />}>
                <Route path="/configuration/configure" element={<Configuration />} />
                <Route path="/configuration" element={<SummaryPage />} />
                <Route path="/dashboard" element={<Dashboard />} />
                <Route path="/appointments" element={<Appointments />} />
                <Route path="/" element={<Navigate replace to="/configuration" />} />
                <Route path="*" element={<NotFound />} />
              </Route>
            </Routes>

        </>

This is where I am listing all of my other page routes.
The console error I am getting

A: The basename prop should match where your app is deployed/running from. In this case it is running from a "/config2" subdirectory. You are currently accessing "localhost:3000/" and not "localhost:3000/config2".
The local development server doesn't know to start from the "./config2" directory.
The errors occur when the app is trying to match absolute paths to the router's basename that is a different directory. I can't reproduce any of the errors when running the app from the "/config2" directory like the app is expecting.
Manually navigate to "/config2" locally. You may want to also add a "homepage": "./config2" or "homepage": "." entry to your package.json so routes can work relative from the deployment directory.

See Building for Relative Paths for more detail.


text:
Q: General error: 1005 when creating a key constraint - Laravel When trying to add a foreign key constraint in Laravel I am getting the following error.
[PDOException]
SQLSTATE[HY000]: General error: 1005 Can't create table 'ts.#sql-5769_62' (errno: 150)

I have 2 tables, users and teams. The relationship is teams can have many users and users have one team.
Users
$table->increments('id');
        $table->integer('team_id');

        $table->string('name', 255);
        $table->string('username', 32)->unique();
        $table->string('email', 320);
        $table->string('password', 64);

        $table->foreign('team_id')->references('id')->on('teams');

        $table->timestamps();

Teams
        $table->increments('id');

        $table->string('team_name', 255);
        $table->string('website', 255);

        $table->timestamps();

What am I doing wrong? Also this is my first time using migrations so any help in pointing out silly errors is welcomed.

A: Try to specify unsigned for team_id:
$table->integer('team_id')->unsigned();

You primary key $table->increments('id'); is an unsigned integer, so the foreign key $table->integer('team_id'); should match it's type.
Quoted from Laravel docs:

Note: When creating a foreign key that references an incrementing
  integer, remember to always make the foreign key column unsigned.

Update
Also make sure you create the team table first, so the Schema builder don't attempt to create a foreign key on a non existing table.


text:
Q: mongodb: Select the latest entry in an embedded array Given the following data of Items with a price history:
{
  item: "Item A",
  priceHistory: [
    {
      date: ISODate("2021-04-01T08:32:45.561Z"),
      value: 100
    },
    {
      date: ISODate("2021-04-02T08:32:45.561Z"),
      value: 200
    },
    {
      date: ISODate("2021-04-04T08:32:45.561Z"),
      value: 400
    },
    {
      date: ISODate("2021-04-03T08:32:45.561Z"),
      value: 300
    },
  ]
},{
  item: "Item B",
  priceHistory: [
    {
      date: ISODate("2021-04-01T08:32:45.561Z"),
      value: 1
    }
  ]
}, ...

Note that the priceHistory field is not sorted.
I want to find the latest price for each item:
{
  item: "Item A",
  price: 400
},{
  item: "Item B",
  price: 1
}, ...

Now I'm struggling to select the LATEST entry of the priceHistory
What I tried already

*

*I know that I can use { $unwind: "$priceHistory" } to get a result for each entry in priceHistory.

*With $max: "$priceHistory.date" I can find the latest date

*I know that since MongoDB 4.4 there is $last to get the last item in an array -> not useful here since items are not in order

But I struggle to bring it all together.

On a side note, maybe the problem lies within the data model itself? Would it make sense to segregate price history into its own collection, and only store the latest price on the item itself?

A: Demo - https://mongoplayground.net/p/-LQPcTn_-Aj
db.collection.aggregate([
  { $unwind: "$priceHistory" }, // unwind to individual documents
  { $sort: { "priceHistory.date": -1 } }, // sort by priceHistory.date to get max date at the top (descending)
  {
    $group: {
      _id: "$_id", // group by id back and get priceHistory sorted in descending order by date
      price: { $first: "$priceHistory.value" }, // get the first price which is for max date record
      item: { $first: "$item"}
    }
  }
])


text:
Q: Zend Framework 3 Hydrator I have this code:
        $settingsModel = new Settings();
        $hydrator = new ReflectionHydrator();
        $incomingData = array('[meta_title]' => 'CMS');
        $datas = $hydrator->hydrate($incomingData, $settingsModel);

When i print $datas i get empty object
Admin\Model\Settings Object
(
)

On top my Controller i have:
use Zend\Hydrator;
use ReflectionClass;
use Zend\Hydrator\Reflection as ReflectionHydrator;

Any advice?


text:
Q: Expected value for a sorted collection We have a collection of n numbers (duplicates can appear). We try to sort the collection by randomly shuffling the collection. What is the expected number of times we have to shuffle the collection to get it sorted? We assume that every permutation has an equal chance.

A: Assuming all the numbers are different, the probability is $\frac{1}{n!}$ of getting the right permutation in one try. Suppose $k$ of them are the same number, the probability is $\frac{k!}{n!}$ of getting the right permutation in one try. Suppose we have classes of sizes $k_1,\ldots,k_m$ such that each number in a class is equal. Then we have probability $\frac{k_1!k_2!\cdots k_m!}{n!}$ of getting the right permutation in one try. Since this is a geometric proces, we get expected value $\frac{n!}{k_1!k_2!\cdots k_m!}$.


text:
Q: PHP Undefined index... but it is defined I know there's a ton of these questions and I'm prepared to take the flak for asking another one as after an hour reading through them all I just can't see what's wrong. It's my first day using PHP so maybe I'm missing something obvious.
I'm using Twitter-Bootstrap and have set up a checkbox:
<div class="checkbox">
    <label><input type="checkbox" id="mailing" name="mailing"> My label message </label>
</div>

In the php I have:
$mailing=$_POST['mailing'];
echo $mailing;

As well as a number of other POSTS. They all work fine except for this one which triggers the error "Undefined index: mailing in (my file etc, at line 14)"
The name 'mailing' is identical in the HTML and PHP, so what's going wrong?
Thanks.

A: Have you tried it with the checkbox checked? See How to read if a checkbox is checked in PHP? - you should check the value with isset, because if the checkbox is not checked, there is not $_POST['mailing].