text:
Q: NetworkOnMainThreadException for register function I am new to Android programming and I am trying to create a register and login function with php, mysql and sqlite. I am having this error after I clicked the register or login button. How do I fix this?
FATAL EXCEPTION: main
 android.os.NetworkOnMainThreadException
      at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133)
      at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
      at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
      at libcore.io.IoBridge.connect(IoBridge.java:112)
      at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
      at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
      at java.net.Socket.connect(Socket.java:842)
      at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
      at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
      at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
      at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
      at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
      at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
      at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
      at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
      at my.fyp.classifieds.library.JSONParser.getJSONFromUrl(JSONParser.java:42)
      at my.fyp.classifieds.library.UserFunctions.registerUser(UserFunctions.java:59)
      at my.fyp.inticlassifieds.Register$1.onClick(Register.java:80)
      at android.view.View.performClick(View.java:4240)
      at android.view.View$PerformClick.run(View.java:17721)
      at android.os.Handler.handleCallback(Handler.java:730)
      at android.os.Handler.dispatchMessage(Handler.java:92)
      at android.os.Looper.loop(Looper.java:137)
      at android.app.ActivityThread.main(ActivityThread.java:5103)
      at java.lang.reflect.Method.invokeNative(Native Method)
      at java.lang.reflect.Method.invoke(Method.java:525)
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
      at dalvik.system.NativeStart.main(Native Method)

I am not sure which class is causing the error. This is the Register class:
public class Register extends Activity {
Button btnRegister, btnLinkToLogin;
EditText inputEmail;
EditText inputPassword, inputCPassword;
EditText inputContact;
TextView registerErrorMsg;

// JSON Response node names
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_CONTACT = "contact";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_register);

    // Importing all assets like buttons, text fields
    inputEmail = (EditText) findViewById(R.id.registerEmail);
    inputPassword = (EditText) findViewById(R.id.registerPassword);
    inputCPassword = (EditText) findViewById(R.id.confirmPassword);
    inputContact = (EditText) findViewById(R.id.registerContact);
    btnRegister = (Button) findViewById(R.id.btnRegister);
    btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLogin);
    registerErrorMsg = (TextView) findViewById(R.id.register_error);

    // Register Button Click event
    btnRegister.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            String password = inputPassword.getText().toString();
            String confirmpass = inputCPassword.getText().toString();

            //Check all fields
            if(inputContact.length()<10)
            {
                Toast.makeText(Register.this,"Please Enter correct mobile number", Toast.LENGTH_LONG).show();
                return;
            }
             if(inputPassword.length()<6)
             {
                Toast.makeText(Register.this,"Please Enter minimum 6 characters in password", Toast.LENGTH_LONG).show();
                return;
             }
             if(!password.equals(confirmpass))
             {
                 Toast.makeText(Register.this,"Password does not match", Toast.LENGTH_LONG).show();
                 return;
             }
             if(inputEmail.length()<6)
             {
                Toast.makeText(Register.this,"Please Enter valid email", Toast.LENGTH_LONG).show();
                return;
             }

            String contact = inputContact.getText().toString();
            String email = inputEmail.getText().toString();
            //String password = inputPassword.getText().toString();
            UserFunctions userFunction = new UserFunctions();
            JSONObject json = userFunction.registerUser(email,contact,password);

            // check for login response
            try {
                if (json.getString(KEY_SUCCESS) != null) {
                    registerErrorMsg.setText("");
                    String res = json.getString(KEY_SUCCESS);
                    if(Integer.parseInt(res) == 1){
                        // user successfully registred
                        // Store user details in SQLite Database
                        DatabaseHandler db = new DatabaseHandler(getApplicationContext());
                        JSONObject json_user = json.getJSONObject("user");

                        // Clear all previous data in database
                        userFunction.logoutUser(getApplicationContext());
                        db.addUser(json_user.getString(KEY_EMAIL), json_user.getString(KEY_CONTACT), json_user.getString(KEY_CREATED_AT));
                        // Launch Dashboard Screen
                        Intent dashboard = new Intent(getApplicationContext(), MainMenu.class);
                        // Close all views before launching Dashboard
                        dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(dashboard);
                        // Close Registration Screen
                        finish();
                    }else{
                        // Error in registration
                        registerErrorMsg.setText("Error occured in registration");
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

    });

    // Link to Login Screen
   /* public void btnLinkToLogin(View view) {
        Intent i = new Intent (this, LoginActivity.class);
        startActivity (i);
        finish();
    }*/

  btnLinkToLogin.setOnClickListener(new View.OnClickListener() {

       public void onClick(View view) {
            Intent i = new Intent(getApplicationContext(),LoginActivity.class);
            startActivity(i);
            // Close Registration View
            finish();
        }
    });
}}

This is UserFunctions class:
public class UserFunctions {

private JSONParser jsonParser;

private static String loginURL = "http://10.0.2.2/project/index.php";
private static String registerURL = "http://10.0.2.2/project/index.php";

private static String login_tag = "login";
private static String register_tag = "register";

// constructor
public UserFunctions(){
    jsonParser = new JSONParser();
}

/**
 * function make Login Request
 * @param email
 * @param password
 * */
public JSONObject loginUser(String email, String password){
    // Building Parameters
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("tag", login_tag));
    params.add(new BasicNameValuePair("email", email));
    params.add(new BasicNameValuePair("password", password));
    JSONObject json = jsonParser.getJSONFromUrl(loginURL, params);
    // return json
    // Log.e("JSON", json.toString());
    return json;
}

/**
 * function make Login Request
 * @param name
 * @param email
 * @param password
 * */
public JSONObject registerUser(String email, String contact, String password){
    // Building Parameters
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("tag", register_tag));
    params.add(new BasicNameValuePair("email", email));
    params.add(new BasicNameValuePair("contact", contact));
    params.add(new BasicNameValuePair("password", password));

    // getting JSON Object
    JSONObject json = jsonParser.getJSONFromUrl(registerURL, params);
    // return json
    return json;
}

/**
 * Function get Login status
 * */
public boolean isUserLoggedIn(Context context){
    DatabaseHandler db = new DatabaseHandler(context);
    int count = db.getRowCount();
    if(count > 0){
        // user logged in
        return true;
    }
    return false;
}

/**
 * Function to logout user
 * Reset Database
 * */
public boolean logoutUser(Context context){
    DatabaseHandler db = new DatabaseHandler(context);
    db.resetTables();
    return true;
}}

A: //The lazy way of handling this is to turn the check of:
   //You can put below code on create
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
  StrictMode.setThreadPolicy(policy);


text:
Q: Equidistant ticks on colorbar using SymLogNorm in matplotlib I would like to enforce that the ticks of my colorbar are equally spaced on the colorbar (not in their values) using SymLogNorm(), like they are for example in the default mode of LogNorm(). How could I do this without doing it by hand, i.e. without doing like the following:
plt.colorbar(ticks=[vmin, value1, ... , vmax])
What I want is basically to have the same ticks as I would have using LogNorm() (Magnitudes). Here is how my code basically works:
import ...
...
y    = np.loadtxt('my_data.dat')
vmin_a = y[0]
vmax_a = y[1]

norm_a = SymLogNorm(linthresh=0.5, linscale=0.03, vmin=vmin_a, vmax=vmax_a)

plt.figure(1)
plt.scatter(x[0], x[1], marker='.', s=7, linewidths=0, c=x[3], cmap= \
          plt.get_cmap('RdBu_r'), norm=norm_rs)
plt.xlabel(xax)
plt.ylabel(yax)
plt.colorbar()

pl.xlim([vmin_a, vmax_a])
pl.ylim([vmin_a, vmax_a])

plt.show()

I think the following picture explains very well how I do not want it, i.e. how it actually looks like:

I am thankful for any hint.
Regards

A: As far as I can see, one has to set ticks by hand using SymLogNorm. I solved my problem by defining:
tick_locations_plot=( [vmin]
                  + [-(10.0**x) for x in range(minlog-1,-logthresh-1,-1)]
                  + [0.0]
                  + [(10.0**x) for x in range(-logthresh,maxlog-1)]
                  + [vmax] )

where
maxlog=int(np.ceil( np.log10(vmax) ))
minlog=int(np.ceil( np.log10(-vmin) ))

Then using
plt.colorbar(ticks=tick_locations)

does what I was looking for.

redpajama_set_name: RedPajamaStackExchange


text:
Q: hiding text on mobile and hiding on sizes above mobile I'm hiding some text with the following code
/* Smartphones in portrait mode (0-401px) */
@media only screen and ( max-width: 401px ) {
    .dontdisplayonmobile    {
    display: none !important;
}
}

It stops it displaying on mobile. but the spacing it creates is still there so it's making the text go but not completely going as if there's nothing there.
I tried adding , but it didn't work
margin: 0 !important;
padding: 0 !important;

Any ideas.?
EDIT
Does anyone know the best way to media query when you want to hide something on anything above 401 px for example.
Do you just put 100000000 or similar so it never shows ?

A: On your site you have a span class called 'dontdisplayonmobie' that hides correctly when the viewport is less than 401 px. But your span class is in a paragraph (

). P has a padding-bottom: 1em; which is the empty space you still see. Remove the padding-bottom of that paragraph when the viewport is less than 401 px and it should look fine.

A: you only should need html like this
Free Quotes. Call today.  0121-663-1202

@media only screen and ( max-width: 401px ) {
  .dontdisplayonmobile    {
    display: none;
  }
}

so you are only hiding the part with "Free Quotes"


text:
Q: Torch - Apply function over dimension I would like to be able to apply a function which is designed for a 3D tensor to each 3D tensor in a 4D tensor, namely image.translate(). For example, I can apply the function individually to two images of dimension (3,50,50) but it would be great if I could feed their 4D concatenation of (2,3,50,50).
This could probably be done in a for loop but I was wondering if there was any built in function for this. Thanks.

A: I haven't managed to find such a function in Torch. You can, of course, define one yourself to make your life a little bit happier:
function apply_to_slices(tensor, dimension, func, ...)
    for i, slice in ipairs(tensor:split(1, dimension)) do
        func(slice, i, ...)
    end
    return tensor
end

Example:
function power_fill(tensor, i, power)
    power = power or 1
    tensor:fill(i ^ power)
end

A = torch.Tensor(5, 6)

apply_to_slices(A, 1, power_fill)

 1  1  1  1  1  1
 2  2  2  2  2  2
 3  3  3  3  3  3
 4  4  4  4  4  4
 5  5  5  5  5  5
[torch.DoubleTensor of size 5x6]

apply_to_slices(A, 2, power_fill, 3)

   1    8   27   64  125  216
   1    8   27   64  125  216
   1    8   27   64  125  216
   1    8   27   64  125  216
   1    8   27   64  125  216
[torch.DoubleTensor of size 5x6]


text:
Q: .load() issue when adding selector I'm having an issue loading html after a click event and then performing an animation on the new element. When I add a selector suffix to the load call the html doesn't load, but the event handler returns "success." Without the selector appended the html loads but then I have no way to select it with jquery.
Html:
<button id="btn-click">Click me</button>

JS:
$("#btn-click").click( function () {
    $("#placeholder").load("dynamicContent.html #new-content", function () {
        $("#new-content").css( "color", "red");
    });
});

dynamicContent.html

just some text for now.

This wont load the new file at all. Is there a reason this might be happening?

A: If I understand you, you want to load new content then do something with that content. It may work like this:
("#btn-click").click( function () {
    $("#placeholder").load("dynamicContent.html", function () {
        $(this).find("#new-content").css( "color", "red");
        //or: $("#new-content", this).css( "color", "red");
    });
});

According to jQuery doc: "If a "complete" callback is provided, it is executed after post-processing and HTML insertion has been performed." So within the complete function you should be able to access the new content with the above or: $("#new-content", this)
update
On re-reading the question, if you want to change the color on the
 that is in the loaded HTML, get to it like $("p", this).css( "color", "red");.
If you want to change the color on the entire placeholder, then use this: $(this).css( "color", "red");

A: As I have explained in my comment, the content you are trying to load doesn't have an element with ID new-content, so there is nothing to load for jQuery.
Your new content contains a p element, so if you want to target that one, simply .find it:
$("#btn-click").click( function () {
    $("#placeholder").load("dynamicContent.html", function () {
        $(this).find('p').css( "color", "red");
    });
});

Inside the .load callback, this refers to the selected element, and you can use any traversal method to find the elements you want to manipulate.


text:
Q: Caching an action in a multi-language website using Play Framework's Cached API In order to cache actions per label and language for a given number of seconds, I wrote the following helper method (where label, is the name I give to my action):
def cacheResponseFor(label: String, duration: Int)(action: EssentialAction) = {
   Cached({r: RequestHeader => (label + getLanguage(r))}, duration){ action }
}

def getLanguage(request: RequestHeader): String = {
   request.cookies
     .get(helpers.SessionHelpers.LANGUAGE_SESSION)
        .map(_.value)
          .getOrElse(helpers.LanguageHelpers.FRENCH)
}

But I'm experiencing something weird, when I try to cache an Action for 60s and switch languages in the meantime to English from French for example, I keep getting the French version for 60s then it switches to english.
After investigating, I found that method getLanguage is not called at each call to that action as if the Key gets evaluated only after the caching period ends.
This is not right, I would want this cacheResponseFor to be called everytime I request my page, the language gets evaluated using getLanguage and I get the right cached version, i.e. I should end up with 2 cached actions (one per language).
Am I missing something?

A: Maybe the problem is in the getLanguage method. Try this, as recommended by the docs:
def getLanguage(request: RequestHeader): String = {
    request.acceptLanguages
           .map(_.code)
           .headOption
           .getOrElse(helpers.LanguageHelpers.FRENCH)
}

Also, take a look at Controller.request2lang() method and see if it could be helpful to you.

A: I do not know what is the issue you are facing but I did a small proof of concept and there is no issue at all.
package controllers

import play.api.cache.Cached
import play.api.mvc.{Action, Controller, EssentialAction, RequestHeader}

object Caches {
  import play.api.Play.current

  def cacheResponseFor(label: String, duration: Int)(action: EssentialAction) = {
    Cached({r: RequestHeader => label + getLanguage(r)}, duration){ action }
  }

  def getLanguage(request: RequestHeader): String = {
    request.cookies
      .get("language")
      .map(_.value)
      .getOrElse("fr")
  }
}

class CachedApplication () extends Controller {

  import Caches._

  def index = cacheResponseFor("homePage", 60) {
    Action { implicit req =>
      getLanguage(req) match {
        case "fr" =>
          Ok("Bonjour le monde")
        case _ =>
          Ok("Hello world")
      }
    }
  }
}


text:
Q: How to get other column values in ORACLE trigger I have a trigger on delete on particular table as shown below. When the trigger is executed it seems like only providing the values of the column which are modified using old.columnName. How can I get the values of other columns so that I can insert all the needed column values in another table?
Below is the trigger:
create or replace TRIGGER AUDIT_TRIGGER
  AFTER DELETE ON TABLE_T2
  FOR EACH ROW

DECLARE
    FILE_HANDLER UTL_FILE.FILE_TYPE;

BEGIN
    FILE_HANDLER := UTL_FILE.FOPEN('Test_Dir','trigger_log_file_delete.txt','w');
    UTL_FILE.PUT(FILE_HANDLER, '----START LOG---- '||+CHR(10));
    UTL_FILE.PUT(FILE_HANDLER,to_char(sysdate,'YYYY/MM/DD:HH:MI:SSAM')||+CHR(10));
    UTL_FILE.PUT(FILE_HANDLER, ':OLD.OBJECT_ID = '||:OLD.OBJECT_ID||+CHR(10));
    UTL_FILE.PUT(FILE_HANDLER, ':OLD.PRIMARY_KEY = '||:OLD.PRIMARY_KEY||+CHR(10));
    UTL_FILE.PUT(FILE_HANDLER, '----END LOG---- '||+CHR(10));
    UTL_FILE.FCLOSE(FILE_HANDLER);
END;

Below is the content of the file to which I am printing:
----START LOG----
2017/11/23:08:27:49PM
:OLD.OBJECT_ID =
:OLD.PRIMARY_KEY = 46
----END LOG----

Here in the output, I cant get the OBJECT_ID although I am getting the PRIMARY_KEY of the deleted row. I know that OBJECT_ID has value in it. Please let me know how can I get the values of the other columns.


text:
Q: ActionMailer::Base.deliveries returns array with duplicated values ActionMailer::Base.deliveries returns array with duplicated values. I am using rails 3.0.9 ruby 1.9.2 and delayed_job3.0.pre. On test env it returns not duplicated values but in production they are duplicated.Can you help me? Thanks in advance

A: ActionMailer::Base.deliveries is for testing purposes. You shouldn't use it on production.


text:
Q: React-router Link Changes URL ID but Component Does Not Reload I use Link to redirect a list of items to another detail component. But now the URL changes with the selected IDs but the detail component does not called. Please help with my react-router issue. Below is my code:
```
index.js
 <BrowserRouter>
   <Switch>
      <Route path='/' component={App} />
      <Route path='/course/:ID' component={CourseDetail} />
   </Switch>
</BrowserRouter>

  CourseList.js

            const CourseList=({Courses})=>{
             //map list
            const renderedList= Courses.map(course=>{
                return (

                <Link  to={{ pathname: 'course/'+course.ID}}
                                    key={course.ID}>
                                    View More
                                </Link>

            )
            });
            return (
            <Router>

                {renderedList}
                <Route path="course/:ID" component={CourseDetail} />

</Router>);
            }
            export default CourseList;

CourseDetail.js

            class CourseDetail extends Component {
              state={
                 ID: this.props.match.params.ID,
                 course:null};
                componentDidMount(){
                 //this.runSearch only get called when URL loads, but not when Link        //clicked
                  this.runSearch();

               }

               runSearch=async()=>{

                 const response= await axios.get('API\?{this.props.match.params.ID}')
                 this.setState({course: response.data});

               }
            render(){
               //course is null below
            //const course=this.state.course;

            return (

                Course Detail: ID {this.props.match.params.ID}

            ); }
            };
            export default withRouter(CourseDetail);

A: You need to specify the attribute exact for your indexRoute, otherwise for even /course/:ID route it will still match with / .
Can you please update your index.js file as below.
 <BrowserRouter>
   <Switch>
      <Route exact path='/' component={App} />
      <Route path='/course/:ID' component={CourseDetail} />
   </Switch>
</BrowserRouter>

Hope this will work for you!

A: You need to change the order of the Route declarations. <Switch> returns the first matching route and since your first route is for /, that's the one will be returned even though URL is for course detail with ID.
<Route path='/course/:ID' component={CourseDetail} />
<Route path='/' component={App} />

Or, You can also put exact in your default route. like,
<Route exact path='/' component={App} />

A: The issue is that you are using two different routers.
Add exact for the / route.
 <BrowserRouter>
   <Switch>
      <Route exact path='/' component={App} />
      <Route path='/course/:ID' component={CourseDetail} />
   </Switch>
</BrowserRouter>

return (
            <React.Fragment>
                {renderedList}
            </React.Fragment>
)


text:
Q: Deprecate MySQL query error when restoring a backup of website Any help, as if teaching a complete noob (step by step; without too much technical terms), would be very much appreciated.
I just restored a copy of my website to a new domain via CPanel. The website on the previous domain was working absolutely fine. Now that I have restored this backup to the new domain, I am getting these errors:

Deprecated: mysql_query(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in /home/xxx/public_html/header.php on line 5
Warning: mysql_query(): Access denied for user ''@'localhost' (using password: NO) in /home/xxx/public_html/header.php on line 5
Warning: mysql_query(): A link to the server could not be established in /home/xxx/public_html/header.php on line 5
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in /home/xxx/public_html/header.php on line 5

These errors are also appearing on my index.php file.
I was searching this issue on the web and if I am correct, there is some sort of incompatibility between my PHP code and my databases.
The thing that troubles me is that this code/database was working just fine on the previous domain and now I am getting these errors.
I think that this issue can be somewhat solved by changing some settings on my database. I have come to this conclusion due to the fact that the .php files that make reference to the databases are absolutely identical as the previous domain and it was working just fine.
If I am wrong, or any solutions to this issue are known to any of you and you can let me know, I'd greatly appreciate it.


text:
Q: Cross-Browsers css <asp:ImageButton ID="Bt_1" runat="server" CausesValidation="false" CssClass="clr_bt" />
.clr_bt
{
    -webkit-transform: rotate(-50deg);
    -webkit-transition: -webkit-transform 0.5s ease-in;
}

Can some one please help me fix it for Opera, IE, Mozilla.
For a moment working only for Chrome.

A: You have to add the vendor prefixes for the browsers to your css like this:
.clr_bt {
    -webkit-transform: rotate(-50deg);
    -moz-transform: rotate(-50deg);
    -ms-transform: rotate(-50deg);
    -o-transform: rotate(-50deg);
    transform: rotate(-50deg);

    -webkit-transition: 0 .5s ease-in;
    -moz-transition: 0 .5s ease-in;
    -o-transition: 0 .5s ease-in;
    transition: transform .5s ease-in;
}

*

*webkit prefix is added for Chrome and Safari

*moz prefix is added for Firefox

*ms prefix is added for IE

*o prefix is added for Opera


text:
Q: 26.02.2017 - External Sqlite 'User' table not found but DB has been copied. [Android] A big hello to the Stackoverflow Community,
I am currently working on a login form in Android Studio and trying to connect to an External Sqlite DB, however I am encountering a problem where there seem to be no table in the copied DB. For a select on the table User, result in the following erro :
*E/SQLiteLog: (1) no such table: User*

Even though my database has been copied and is opened:
Database is open

Can someone please tell me what I am doing wrong? I have added the code I am using in my Databasehelper class:
public class DatabaseHelper extends SQLiteOpenHelper {

    private Context mycontext;
    Connection sqliteConnection;
    // Database Version
    private static final int DATABASE_VERSION = 1;

    //Database Path
    private static String DB_PATH ="/data/data/"+ BuildConfig.APPLICATION_ID+"/databases/";

    // Database Name
    private static final String DATABASE_NAME = "mystockdb.db";

    // User table name
    private static final String TABLE_USER = "User";

    // User Table Columns names
    private static final String COLUMN_USER_ID = "user_id";
    private static final String COLUMN_USER_NAME = "name";
    private static final String COLUMN_USER_PASSWORD = "user_password";

    public SQLiteDatabase myDataBase;

    public DatabaseHelper(Context context)  {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        this.mycontext=context;
        boolean dbexist = checkdatabase();
        if (dbexist) {
            System.out.println("Database exists");
            opendatabase();
        } else {
            System.out.println("Database doesn't exist");
            createdatabase();
        }
    }
    private void copydatabase() throws IOException {
        //Open your local db as the input stream
        InputStream myinput = mycontext.getAssets().open(DATABASE_NAME);

        // Path to the just created empty db
        String outfilename = DB_PATH + DATABASE_NAME;

        //Open the empty db as the output stream
        OutputStream myoutput = new FileOutputStream(outfilename);

        // transfer byte to inputfile to outputfile
        byte[] buffer = new byte[1024];
        int length;
        while ((length = myinput.read(buffer))>0) {
            myoutput.write(buffer,0,length);
        }

        //Close the streams
        myoutput.flush();
        myoutput.close();
        myinput.close();
    }

    private boolean checkdatabase() {

        boolean checkdb = false;
        try {
            String myPath = DB_PATH + DATABASE_NAME;
            File dbfile = new File(myPath);
            checkdb = dbfile.exists();
        } catch(SQLiteException e) {
            System.out.println("Database doesn't exist");
        }
        return checkdb;
    }
    public void opendatabase() throws SQLException {
        //Open the database
        String mypath = DB_PATH + DATABASE_NAME;
        System.out.println(DB_PATH);
        myDataBase = SQLiteDatabase.openDatabase(mypath, null, SQLiteDatabase.OPEN_READWRITE);
        if (myDataBase.isOpen()) {
            System.out.println("Database is open");

        }

    }

    public void createdatabase()  {
        boolean dbexist = checkdatabase();
        if(dbexist) {
            System.out.println(" Database exists.");

        } else {
            this.getReadableDatabase();
            try {
                copydatabase();
            } catch(IOException e) {
                throw new Error("Error copying database");
            }
        }
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        if (newVersion >oldVersion){
            try{
                copydatabase();
            }catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * This method will return if user is in db or not
     *
     * @param name
     * @param password
     * @return true/false
     */
    public boolean checkUser(String name, String password) {

        // array of columns to fetch
        String[] columns = {
                COLUMN_USER_ID
        };
        opendatabase();
        myDataBase = getReadableDatabase();
        // selection criteria
        String selection = COLUMN_USER_NAME + " = ?" + " AND " + COLUMN_USER_PASSWORD + " = ?";

        // selection arguments
        String[] selectionArgs = {name, password};

        // query user table with conditions
        /**
         * Here query function is used to fetch records from user table this function works like we use sql query.
         * SQL query equivalent to this query function is
         * SELECT user_id FROM user WHERE user_email = 'jack@androidtutorialshub.com' AND user_password = 'qwerty';
         */
        Cursor cursor = myDataBase.query(TABLE_USER, //Table to query
                columns,                    //columns to return
                selection,                  //columns for the WHERE clause
                selectionArgs,              //The values for the WHERE clause
                null,                       //group the rows
                null,                       //filter by row groups
                null);                      //The sort order

        int cursorCount = cursor.getCount();

        cursor.close();
        myDataBase.close();
        if (cursorCount > 0) {
            return true;
        }

        return false;
    }

}

A: I have decided to use json instead to save my data,which the user will access via wifi.


text:
Q: NSUserDefaults won't write values, logs about non-persistent preferences domain I've got a Mac app where I use NSUserDefaults to save a per-install identifier for use in analytics. I have code like this:
-(NSString *)getInstallId
{
  NSString *settingsKey = @"install_id_key";
NSString *result = [[NSUserDefaults standardUserDefaults] objectForKey:settingsKey];
if (result.length == 0)
{
    result = [[NSUUID UUID] UUIDString];
    [[NSUserDefaults standardUserDefaults] setObject:result forKey:settingsKey];
}

return result;
}

But on at least some High Sierra systems, this returns a different value each time. Stepping through it in debug shows that [objectForKey:settingsKey] returns nil, even if I try calling it right after setting. I've tried calling synchronize even though that's not necessary.
I also see a log message like this:

2019-04-08 11:35:26.249938-0700 MyApp[11283:59125] [User Defaults] attempt to set 8E548BCF-97E0-431F-B36A-B06913424010 for key in install_id_key in non-persistent preferences domain CFPrefsPlistSource<0x6080000e0900> (Domain: com.myapp.MyApp, User: kCFPreferencesCurrentUser, ByHost: No, Container: (null), Contents Need Refresh: Yes)

Google doesn't show anything useful for this error message beyond just "I restarted and it was fixed" results.
What's going on here? Do I have to worry about this happening in production somewhere? It happens in archived and debug builds.
Turning on logging from the defaults system produces some error messages:

rejecting read of { com.olivetree.BibleReaderMac, ianfallon, kCFPreferencesAnyHost, /Users/username/Library/Containers/com.olivetree.BibleReaderMac/Data, managed: 0 } from process 8028 because accessing preferences outside an application's container requires user-preference-read or file-read-data sandbox access
Couldn't read values in CFPrefsPlistSource<0x60c0000f3600> (Domain: com.olivetree.BibleReaderMac, User: kCFPreferencesCurrentUser, ByHost: No, Container: (null), Contents Need Refresh: Yes): accessing preferences outside an application's container requires user-preference-read or file-read-data sandbox access, detaching from cfprefsd


text:
Q: Piccaso not loading Image on First Attempt android In my application I have a fragment which loads image from remote server to set background of FrameLayout  using AsynTask and in onPostExeccute() method I am trying to render Bitmap images using Picasso. But as my Fragment starts first time no image is loaded in the background of FrameLayout but as I refresh the particular fragment then I can see the Image as background.
Updated Code segment inside AsyncTask
      private class AsyncDataClass extends AsyncTask<String, Void, String> {

        @Override

        protected String doInBackground(String... params) {

            String responseBody = "";

            HttpParams httpParameters = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
            HttpConnectionParams.setSoTimeout(httpParameters, 5000);
            HttpClient httpClient = new DefaultHttpClient(httpParameters);
            HttpPost httpPost = new HttpPost(params[0]);
            String jsonResult = "";
            try {

                HttpResponse response = httpClient.execute(httpPost);
                jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
                System.out.println("Returned Json object " + jsonResult.toString());
            } catch (ClientProtocolException e) {

                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return jsonResult;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(ctx);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(true);
            pDialog.show();
        }

        @Override

        protected void onPostExecute(String result) {

            super.onPostExecute(result);
            System.out.println("Resulted Value: " + result);
            if(result.equals("") || result == null){
                Toast.makeText(ctx, "Server connection failed", Toast.LENGTH_LONG).show();

            }
            int jsonResult = returnParsedJsonObject(result);
            if(jsonResult == -1){

                    Toast.makeText(ctx, "Sorry No Places Found", Toast.LENGTH_LONG).show();

            }
            if(jsonResult == 1){
                //Toast.makeText(ctx, "", Toast.LENGTH_LONG).show();
                try {
                    JSONObject jsonObj = new JSONObject(result);
                    // Getting JSON Array node
                    places = jsonObj.getJSONArray("result");
                    // looping through All Contacts
                    for (int i = 0; i < places.length(); i++) {
                        JSONObject place = places.getJSONObject(i);
//                        String slot = c.getString(TAG_SLOT);
//                        serverReturn.add(slot);
                        UserPlaces placeFroServer = new UserPlaces();
                        placeFroServer.setId(place.getString(TAG_PID));
                        placeFroServer.setName(place.getString(TAG_PNAME));
                        placeFroServer.setDescription(place.getString(TAG_DESC));
                        placeFroServer.setImg(place.getString(TAG_IMG));
                        placeFroServer.setLat(place.getString(TAG_LAT));
                        placeFroServer.setLng(place.getString(TAG_LNG));
                        placesList.add(placeFroServer);

                    }

                    UserPlaces myPlace =  placesList.get(counter);

                    pid=myPlace.getId();
                    lat = myPlace.getLat();
                    lng = myPlace.getLng();
                    Picasso.with(ctx).load(myPlace.getImg()).into(new Target() {
                        @Override
                        public void onPrepareLoad(Drawable arg0) {
                            // TODO Auto-generated method stub

                        }

                        @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
                        @Override
                        public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom arg1) {
                            // TODO Auto-generated method stub
                            Toast.makeText(ctx,"Loaded",Toast.LENGTH_LONG).show();
                            pImg.setBackgroundDrawable(new BitmapDrawable(ctx.getResources(), bitmap));
                            pImg.invalidate();

                        }

                        @Override
                        public void onBitmapFailed(Drawable arg0) {
                            // TODO Auto-generated method stub
                            Toast.makeText(ctx, "Failed Loading", Toast.LENGTH_SHORT).show();
                        }
                    });

                    pname.setText(myPlace.getName());
                    pdes.setText(myPlace.getDescription());
                    rl.setVisibility(View.VISIBLE);

                    counter++;

                } catch (JSONException e) {

                    String ex = e.getMessage();
                    e.printStackTrace();
                }

            }
            if (pDialog.isShowing())
                pDialog.dismiss();
        }

        private StringBuilder inputStreamToString(InputStream is) {
            String rLine = "";
            StringBuilder answer = new StringBuilder();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            try {
                while ((rLine = br.readLine()) != null) {
                    answer.append(rLine);
                }
            } catch (IOException e) {
// TODO Auto-generated catch block
                e.printStackTrace();
            }
            return answer;
        }
    }

A: For particular problem of week reference try creating a global Target object. As demonstrated in the code below.
Code Sample:
    Target target;
    target = new Target(){
                    @Override
                    public void onPrepareLoad(Drawable arg0) {
                        // TODO Auto-generated method stub

                    }

                    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
                    @Override
                    public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom arg1) {
                        //Toast.makeText(ctx,"Loaded",Toast.LENGTH_LONG).show();
                        // TODO Auto-generated method stub
                        pImg.setBackgroundDrawable(new BitmapDrawable(ctx.getResources(), bitmap));
                        pImg.invalidate();

                    }

                    @Override
                    public void onBitmapFailed(Drawable arg0) {
                        // TODO Auto-generated method stub
                        Toast.makeText(ctx, "Failed Loading", Toast.LENGTH_SHORT).show();
                    }
                };

   Picasso.with(ctx).load(myPlace.getImg()).into(target);

A: You should call invalidate() on pImg after setting the background.

A: You can use the alternative of it Univerasal Image Loader


text:
Q: How to bind an Image's Source to an attached property? I created a custom control which contains an Image control.
I'd like to have the Source of the Image Control bound to an ImageSource Dependency Property.
The Dependency Property is created as such:
public static class ImageSourceProperty
{
    public static readonly DependencyProperty CustomImageSourceProperty;

    public static ImageSource GetCustomImageSource(DependencyObject dependencyObject)
    {
        return (ImageSource)dependencyObject.GetValue(CustomImageSourceProperty);
    }

    public static void SetCustomImageSource(DependencyObject dependencyObject, ImageSource value)
    {
        dependencyObject.SetValue(CustomImageSourceProperty, value);
    }

    static ImageSourceProperty()
    {
        CustomImageSourceProperty = DependencyProperty.RegisterAttached("CustomImageSource", typeof (ImageSource), typeof (ImageSourceProperty), new PropertyMetadata(default(ImageSource)));
    }
}

And I'm trying to bind the Source of the Image of the Custom Control as such:
<UserControl
(...)
xmlns:AttachedProperties="clr-namespace:Codex.UserControls.AttachedProperties"
x:Class="Codex.UserControls.CustomControls.ImageWithBorder"
d:DesignWidth="640" d:DesignHeight="480">

<Grid x:Name="LayoutRoot">
    <Border BorderBrush="White" BorderThickness="3" CornerRadius="3">
        <Image Source="{Binding AttachedProperties:ImageSourceProperty.CustomImageSource}" Width="50" Height="50"/>
    </Border>
</Grid>

I placed the user control in my view like this:
<CustomControls:ImageWithBorder (...) AttachedProperties:ImageSourceProperty.CustomImageSource="(...)"/>

I obtain the following error in the Output window upon launching the application:
System.Windows.Data Error: 40 : BindingExpression path error: 'AttachedProperties:ImageSourceProperty' property not found on 'object' ''ToolbarViewModel' (HashCode=20169503)'.

Why isn't the user control able to bind to the dependency property ? Is it looking for the dependency property in its code-behind and can't find it ?

A: Found the problem. I was not specifying the relative source of the binding.
Here's the correct UserControl declaration:
<Image Source="{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type CustomControls:ImageWithBorder}},Path=(AttachedProperties:ImageSourceProperty.CustomImageSource), Mode=TwoWay}" Width="50" Height="50"/>

The problem was that the Dependency Property was not able to return the value since the dependency object wasn't valid.


text:
Q: Ensure move in std vector with trivial type Say I have a vector of ints
std::vector<int16_t> samples;
Is there a nice way to disable copying into this vector so that only moving is allowed? I know about std::move, but I'd like something like a compile error (like unique_ptr) if copying is attempted, rather than just relying on the programmer to "do the right thing"(tm)

A: If it's a class member, then just make it private and only allow access in the ways you want:
std::vector<int16_t> const & get_samples() {return samples;}
void set_samples(std::vector<int16_t> && s) {samples = std::move(s);}

Otherwise, there's not much you can do to enforce particular access patterns.

A: Make an uncopyable wrapper:
#include <vector>

template<typename T>
class   uncopyable
{
public:
  uncopyable(const uncopyable&) = delete;

  uncopyable(uncopyable&&) = default;

  uncopyable(T&& data)
    :
    data_(std::move(data))
  {
  }

public:
  uncopyable&   operator=(const uncopyable&) = delete;

  uncopyable&   operator=(uncopyable&&) = default;

  uncopyable&   operator=(T&& data)
  {
    data_ = std::move(data);
    return *this;
  }

private:
  T       data_;
};

int     main()
{
  std::vector<int>      big(10000);

  uncopyable<std::vector<int>>  uncopyable_big(std::move(big));

  std::vector<int>      other_big(10000);

  uncopyable_big = std::move(other_big);
}

And use this type instead of your vectorif you want to guarantee no copies are made.


text:
Q: Determine if the content of a file/directory exist for more than 2 hours I try to create a bash script that determine if the content of a .txt file or a directory is older than 2 hours and then return it to me, where hour should be a configurable variable.
What  I have till now is not working unfortunately. Can you help :) ?
#!/bin/sh

#Determine how old is the file
old=`find /opt/import/dev -ctime -20m`

If [ -n $old ]
then
echo "old files found:"
echo /n $old

A: To get the list of files modified less than $hour hours ago, you have to use next arguments for the command find:
((min = hour * 60))
old=$( find /opt/import/dev -cmin -$min )


text:
Q: How to bring a navigation bar in front of view I am working on an App in which clicking on message icon in navigation bar in one view segues to other view where CometChat extension is used.
However when I go to the other view my entire navigation bar is hidden and all i see is the Cometchat on all the view.
I've tried to add a button by going through code in Cometchat UI kit but without luck. So is there any way I can make my nav bar visible or anything what I can use to return to the app?
The storyboard with Message View Controller
The Cometchat embedded view controller


text:
Q: get notified when result of useContractCall from useDapp arrives in react hook? This is more a react question I think;
export function useData() {
    const [Data]: any = useContractCall({
        abi: myContractInterface,
        address: myContractAddress,
        method: "getAllData",
        args: [],
    }) ?? [];
    return Data;
}
let myData = useData();
<div>{myData ? myData.name : "no Data yet"}</div>

UseData() is called and the view is rendered when myData is propagated; but how could I use myData somewhere else in my logic? Tried with an async wrapper and await, didn't work.
I tried to use useEffect to listen on changes of myData and react, but useEffect is fired immediately and myData is null.
  let myData = useData();

  useEffect(() => {
    console.log("Fresh Data is here",myData);//rotten undefined, not fresh data
  }, [myData ])

Should I just use something like this? I mean it is working.. but
const x = useData();

(async() => {
    console.log("waiting for variable");
    while(!x) // define the condition as you like
        await new Promise(resolve => setTimeout(resolve, 1000));
    console.log("variable is defined",x);
})();

A: it's hard to figure out whole the bunch of custom hooks calling each other. I have in the end some "last in the chain" hook does async request and after receiving response triggers re-render with new value in const x.
With this assumption, I want to say you don't need to
(async() => {
    console.log("waiting for variable");
    while(!x) // define the condition as you like
        await new Promise(resolve => setTimeout(resolve, 1000));
    console.log("variable is defined",x);
})();

right in the render logic. Moreover it will never work. const x = useData() will never changed during this specific render execution. It will/may be re-assigned only on next re-render run.
Instead you should return some rendering result as if it is there. And it will be - initially null(by your words), but later component will re-render with actual data in x:
const x = useData();

....
return <SomeComponent prop={x} />

Also you should also see that with your
useEffect(() => {
  console.log("Fresh Data is here",myData);
}, [myData])

As at first it prints null and later dumps actual data.
Once re-render does not happen as I described above - the issue is somewhere within your custom hooks. And you will need to debug that with debugger.


text:
Q: Expr is not parsing the mathematical expression in Bash I have my bash code like this for example :
res=`expr $1+$2`
echo $res

or
res=$(expr $1+$2)
echo $res

then when I execute my code like this ./script01.sh 3 4 I get:
3+4

Weirdly enough that my code is the exact same as many other tutorials, either there is something wrong with my computer or the problem is stemming from some other thing.

A: [~]$ a=1;b=2
[~]$ expr $a+$b
1+2
[~]$ expr $a + $b
3
[~]$ expr $a * $b
expr: syntax error
[~]$ expr $a \* $b
2

From the man page:
ARG1 + ARG2
              arithmetic sum of ARG1 and ARG2

As we can see, you need a space between arguments and operator. In addition you have to escape operators that can be interpreted as globs in bash:
Beware that many operators need to be escaped  or  quoted  for  shells.

A: bash has arithmetic operators built-in, so you don't need to call out to expr:
res=$(( $1 + $2 ))

https://www.gnu.org/software/bash/manual/bashref.html#Arithmetic-Expansion
https://www.gnu.org/software/bash/manual/bashref.html#Shell-Arithmetic

A: Your second version should be like this:
#!/usr/bin/env bash

res=$(expr "$1" + "$2")

echo "$res"

And your first version should be:
#!/usr/bin/env bash

res=`expr "$1" + "$2"`

echo "$res"

Note the spaces between the + operator. And finally using more modern syntax:
#!/usr/bin/env bash

res=$(( $1 + $2 ))

echo "$res"

Note the last version is the preferred way.


text:
Q: How to create valid CSV file with DictWriter in Python? I create CSV file with this code below:
dwf = open(file_name, 'w')
fw = csv.DictWriter(dwf, fieldnames=fields, delimiter='\t')
fw.writeheader()

data_dict = {'name':name, 'text': text, 'type':type 'URL': this_url}
fw.writerow(data_dict)

The 'text' field contains textual data, and when I created the 'text' variable, I did this:
text = text.strip().replace('\t', '  ').replace('\n', ' ').replace('\r', ' ')

I intended to remove any potential trouble maker that may be a column delimiter. But still, the csv file created is sometimes invalid, because when I opened it in Numbers on my Mac, some columns are in the same column, not alined with the delimiter.
How can I avoid this?

A: Try using the quoting parameter of csv.DictWriter to make sure that all of the fields are wrapped with quotes.
csv.DictWriter(dwf, fieldnames=fields, delimiter="\t", quoting=csv.QUOTE_ALL)

https://docs.python.org/3/library/csv.html#csv.QUOTE_ALL


text:
Q: jQuery Inconsistent text() val() selection and populating input $name and $id are only copied properly a small portion of the time. Selection is expected to populate the input #user_search but selections come up undefined. The text is copied properly at what seems like random...
HTML
<input type="text" name="user" id="user_search" autocomplete="off"
class="user_live form-control" data-parsley-required="true" value="" />

HTML Added to DOM

                    First Last

                    First Last

JS
$('#user_result').on('click',function(e){
    var $clicked = $(e.target);
    var $name = $clicked.find('.name').text(); //removed .html($name)
    alert($name);
    $('#user_search').val($name);
});

A: The issue lies with e.target and .find() not working quite right with that layout. Try this:
$('#user_result').on('click',function(e){
    var $name  = $(e.target).closest('.showResult').find('.name').text();
    alert($name);
    $('#user_search').val($name);
});

https://jsfiddle.net/feab9ms0/

A: When the click event is triggered, the actual target is the img tag and not the div itself. Since the element with class .name is not contained in the img, you do not get any matching results back. Therefore you need to use the .closest to navigate to the least parent tag which contains the img tag.
$("#user_result").on("click",function(e){
    var $clicked = $(e.target);
    var $name = $clicked.closest(".box-body").find('.name').text();
    alert($name);
    $('#user_search').val($name);
});

A: You have not initialize the $name before assigning to here html($name).text(),
which is causing t render the decision as undefined.


text:
Q: Element with line-clamp too wide I am using the @tailwindcss/line-clamp plugin to clamp a text element () to one line (line-clamp-1). The text element is inside a flex box, and is followed by another text element that's supposed to "stick" to its right side.
My problem is that the width of the clamped text element is not computed properly. Even though the text is clamped correctly, the width of the element remains too wide and the following text does not "stick" closely like I want to.
Below is a screenshot. The "problem element" is the one that says "Human-Computer Interaction". It should look like the others, where the "post count" in parentheses "sticks" closely to the topic label.

Here is my code:
{{#foreach tags}}

         {{name}}
         ({{count.posts}})

{{/foreach}}

How does one reduce the width of the clamped text element to fit the clamped text inside?
P.S. I have tried replacing s with
 elements, and using other CSS approaches that don't involve the line-clamp plugin, and have not found a solution so far.

A: There is no need to use an extra package because you only one have line and for achieve you can use text-overflow property with white-space and overflow to get the same result.
You can use it as inline or create you own  class with @layer.

       Music
       (7)

       Architecture
       (2)

       Graphic Design
       (10)

       Human-Computer Interaction
       (5)

       Human-Computer Interaction
       (7)

       Art
       (4)

       Education
       (5)

       Graphic Design
       (10)


text:
Q: Import SSRS Reports from Development CRM into Production I have created custom reports in SSRS using BIDS in the development instance of CRM. I want to now export/import this report into Production CRM. Can somebody help me here please?

A: We add SSRS reports to CRM all the time. All you do is click on Reports > New > and from the drop down menu (three choices) select existing file. Select the RDL file (yes, you can simply copy this file from your server to local machine)
Once you selected the RDL file, select where you would like it to be displayed etc from the bottom of the form.

A: Check this article, in the end there is the procedure to upload the RDL file inside CRM
How To: Creating Custom Report with Microsoft Dynamics CRM 2011 BIDS Fetch Extension


text:
Q: unknown error caused every innerHTML to break button = document.getElementById("button");
//creates "clicker" in js
clicker = document.getElementById("clicker");
//creates "reset" in js
reset = document.getElementById("reset");

//Random Number Chooser
var random;
document.getElementById("ret").innerHTML = "_";

//randomize button
button.addEventListener("click", function() {
  random = Math.floor(Math.random() * 100) + 1;
  document.getElementById("ret").innerHTML = random;
});

//Click Counter
var clickerNum = 0;
document.getElementById("clicky").innerHTML = clickerNum;

//reset button
reset.addEventListener("click", function() {
  clickerNum = 0;
  document.getElementById("clicky").innerHTML = clickerNum;
  document.getElementById("ret").innerHTML = "_";
});

//click button
clicker.addEventListener("click", function() {
  clickerNum++;
  document.getElementById("clicky").innerHTML = clickerNum;
});

//input receive/return
document.getElementById("retAnswer").innerHTML = "You submitted: ";
//submit button function
function submitAnswer() {
  var answer = document.getElementById("input1").value;
  document.getElementById("retAnswer").innerHTML = "You submitted: " + answer;
}

//Guess which button
var gameOrder = "";
var playerInput = "";
document.getElementById("order").innerHTML = gameOrder;

//this part
function startGame(){
  gameOrder = "";
  playerInput = "";
  document.getElementById("order").innerHTML = gameOrder;
  memoryGame();
}

function memoryGame(){
  var randomNum = Math.floor(Math.random() * 3) + 1;

  if(randomNum == 1){
    //make button 1 turn green
    gameOrder += "1";
  }
  else if(randomNum ==2){
    //make button 2 turn green
    gameOrder += "2";
  }
  else{
    //make button 3 turn green
    gameOrder += "3";
  }

  document.getElementById("order").innerHTML = gameOrder;
}

function addInput(var input){
  playerInput += input;
}

I am learning web development and I am trying to add a little memorization game to my website. The problem is that when I added the last part (commented "this part") all the innerHTML parts broke. Every one on the page so it doesn't even have a space for it. I was wondering if maybe it is because there may be a limit to how many innerHTML you can use? I don't really think that's it, but I can't find any error that would cause all the innerHTML to break. I commented out the last part and everything worked again, so I know that the problem is in the last section.

    Random Number Chooser

    <button type="button">Randomize!</button>

    Click Counter

    <button type="button">Reset</button>

    <button type="button">Click</button>

    Input Receive/Return

    <input type="text" id="input1" />
    <button onclick="submitAnswer()">Submit</button>

    Guess which button

    <button onclick="startGame()">Start/Reset</button>

    <button onclick="addInput("1")">1</button>

    <button onclick="addInput("2")">2</button>

    <button onclick="addInput("3")">3</button>

    <button>Submit</button>

```

A: Your problem is in the last function of your code, noticed how instead of saying function addInput(input) you said function addInput(var input)
You can't declare variables there, the section between parentheses is used to pass parameters. This broke the script. So if you just remove var from the function it will work.
Here's the function should look like
function addInput(input){
    playerInput += input;
}

Good luck with your learning!


text:
Q: What is the difference between egrep, fgrep, find and grep commands? i know i can use grep to find files however i am wondering what the particular difference between these common commands ? They all seems to be equal in meaning to me.
egrep
fgrep
grep
find
locate

as windows search and find command.

A: From grep man page, you can see:
In addition, three variant programs egrep, fgrep and rgrep are available.
egrep is the same as grep -E. fgrep is the same as grep -F. rgrep is the same
as grep -r. Direct invocation as either egrep or fgrep is deprecated, but is
provided to allow historical applications that rely on them to run unmodified.

Then:
Matcher Selection
       -E, --extended-regexp
              Interpret PATTERN as an extended regular expression (ERE, see below).  (-E is specified by POSIX.)

       -F, --fixed-strings
              Interpret  PATTERN  as  a  list  of  fixed strings, separated by newlines, any of which is to be matched.  (-F is specified by
              POSIX.)


text:
Q: Multiple rows of footer widget areas I have a function on my functions.php that adds a bootstrap col class to the footer sidebars depending on the number of active sidebars.
What I intend to achieve with this is having footer widgets expand to the maximum space available. So, for example if I have only one footer widget area active a class of col-md-12 with be applied. If I have two a class of col-md-6 would be applied and so on. This is my code:
// Count the number of footer sidebars to enable dynamic classes for the footer top row.
if( ! function_exists( 'mytheme_footer_sidebars_top' ) ) {
    function mytheme_footer_sidebars_top() {

        $active_sidebars = 0;

        if ( is_active_sidebar( 'footer-sidebar-1' ) ) {
            $active_sidebars++;
        }

        if ( is_active_sidebar( 'footer-sidebar-2' ) ) {
            $active_sidebars++;
        }

        if ( is_active_sidebar( 'footer-sidebar-3' ) ) {
            $active_sidebars++;
        }

        if ( is_active_sidebar( 'footer-sidebar-4' ) ) {
            $active_sidebars++;
        }

        $class = '';

        switch ( $active_sidebars ) {
            case '1':
                $class = ' col-sm-12';
                break;
            case '2':
                $class = ' col-sm-6';
                break;
            case '3':
                $class = ' col-sm-4';
                break;
            case '4':
                $class = ' col-sm-3';
                break;
        }

        echo $class;
    }
}

// Count the number of footer sidebars to enable dynamic classes for the footer bottom row.
if( ! function_exists( 'karnivorz_footer_sidebars_bottom' ) ) {
    function karnivorz_footer_sidebars_bottom() {

        $active_sidebars = 0;

        if ( is_active_sidebar( 'footer-sidebar-5' ) ) {
            $active_sidebars++;
        }

        if ( is_active_sidebar( 'footer-sidebar-6' ) ) {
            $active_sidebars++;
        }

        if ( is_active_sidebar( 'footer-sidebar-7' ) ) {
            $active_sidebars++;
        }

        if ( is_active_sidebar( 'footer-sidebar-8' ) ) {
            $active_sidebars++;
        }

        $class = '';

        switch ( $active_sidebars ) {
            case '1':
                $class = ' col-sm-12';
                break;
            case '2':
                $class = ' col-sm-6';
                break;
            case '3':
                $class = ' col-sm-4';
                break;
             case '4':
                 $class = ' col-sm-3';
                 break;
        }

        echo $class;
    }
}

then my sidebar-footer.php looks like this:
<?php
    // Check if the any of the footer widget areas has widgets.
    if ( ! is_active_sidebar( 'footer-sidebar-1' )
            && ! is_active_sidebar( 'footer-sidebar-2' )
            && ! is_active_sidebar( 'footer-sidebar-3' )
            && ! is_active_sidebar( 'footer-sidebar-4' )
            && ! is_active_sidebar( 'footer-sidebar-5' )
            && ! is_active_sidebar( 'footer-sidebar-6' )
            && ! is_active_sidebar( 'footer-sidebar-7' )
            && ! is_active_sidebar( 'footer-sidebar-8' )
    )
    return;

    // Check which footer widget areas are active and apply formatting classes to them according to the number of active areas.
    ?>

                <?php if ( is_active_sidebar( 'footer-sidebar-1' ) ) : ?>
                    <div class="footer-widget-area col-xs-12 <?php mytheme_footer_sidebars_top(); ?>">
                        <?php dynamic_sidebar( 'footer-sidebar-1' ); ?>

                <?php endif; ?>

               <?php if ( is_active_sidebar( 'footer-sidebar-2' ) ) : ?>
                   <div class="footer-widget-area col-xs-12 <?php mytheme_footer_sidebars_top(); ?>">
                      <?php dynamic_sidebar( 'footer-sidebar-2' ); ?>

               <?php endif; ?>

               <?php if ( is_active_sidebar( 'footer-sidebar-3' ) ) : ?>
                   <div class="footer-widget-area col-xs-12 <?php mytheme_footer_sidebars_top(); ?>">
                       <?php dynamic_sidebar( 'footer-sidebar-3' ); ?>

               <?php endif; ?>

               <?php if ( is_active_sidebar( 'footer-sidebar-4' ) ) : ?>
                   <div class="footer-widget-area col-xs-12 <?php mytheme_footer_sidebars_top(); ?>">
                       <?php dynamic_sidebar( 'footer-sidebar-4' ); ?>

              <?php endif; ?>

        <?php if ( is_active_sidebar( 'footer-sidebar-5' ) ) : ?>
        <div class="footer-widget-area col-xs-12 <?php mytheme_footer_sidebars_bottom(); ?>">
            <?php dynamic_sidebar( 'footer-sidebar-5' ); ?>

        <?php endif; ?>

        <?php if ( is_active_sidebar( 'footer-sidebar-6' ) ) : ?>
        <div class="footer-widget-area col-xs-12 <?php mytheme_footer_sidebars_bottom(); ?>">
            <?php dynamic_sidebar( 'footer-sidebar-6' ); ?>

        <?php endif; ?>

        <?php if ( is_active_sidebar( 'footer-sidebar-7' ) ) : ?>
        <div class="footer-widget-area col-xs-12 <?php mytheme_footer_sidebars_bottom(); ?>">
            <?php dynamic_sidebar( 'footer-sidebar-7' ); ?>

        <?php endif; ?>

        <?php if ( is_active_sidebar( 'footer-sidebar-8' ) ) : ?>
        <div class="footer-widget-area col-xs-12 <?php mytheme_footer_sidebars_bottom(); ?>">
            <?php dynamic_sidebar( 'footer-sidebar-8' ); ?>

        <?php endif; ?>

This works fine for a single row of widget areas. But, what I want to achieve now is to be able to have another row exactly with the same functionality so the users could also add multiple rows of widgets in the footer. If I repeat exactly the same code and have another function called mytheme_footer_sidebars_bottom, for example, I will be able to achieve this but I am sure its not the best way as I will be repeating and renaming code. So I am wondering whats the best way to achieve this functionality without repeating all the code I have above.

A: Just add a variable to the function so you can call it differently from the template...
EDITED: pass the footer row to function and return class...
function mytheme_footer_sidebar_class($row) {

    if ($row == 1) {$i = 1; $j = 5;}
    elseif ($row == 2) {$i = 5; $j = 9;}

    $active_sidebars = 0;

    for ($i; $i < $j; $i++) {
        if ( is_active_sidebar( 'footer-sidebar-'.$i ) ) {
            $active_sidebars++;
        }
    }

    switch ( $active_sidebars ) {
        case '1':
            $class = ' col-sm-12';
            break;
        case '2':
            $class = ' col-sm-6';
            break;
        case '3':
            $class = ' col-sm-4';
            break;
         case '4':
             $class = ' col-sm-3';
             break;
    }

    return $class;
}

And at the top of footer-sidebar.php you can just do this once instead of repeating the checks all over again:
$rowclass1 = mytheme_footer_sidebar_class(1);
$rowclass2 = mytheme_footer_sidebar_class(2);

if ( ($rowclass1 == '') && ($rowclass2 == '') ) {return;}

Then in place of <?php mytheme_footer_sidebars_top(); ?> and <?php mytheme_footer_sidebars_bottom(); ?> use <?php echo $rowclass1; ?> and ` respectively.
You can also then use the same variables to wrap and display each row...
 <?php if ($rowclass1 != '') : ?>

     .......................

 <?php endif; ?>

...of course you would need to register 4 more widget areas... this could get confusing for the end user too on the widget page also, so you may want to add a theme option to turn the second footer widget area on/off.


text:
Q: No enclosing instance of TYPE is available due to some intermediate constructor invocation I keep getting this error about No enclosing instance of my WallpaperService is available. So my program will not compile. What exactly does this error mean...?
Where should I go from here. Below is my constructor for myEngine class. The error happens at my super(); method call.
public final class myEngine extends Engine implements OnSharedPreferenceChangeListener {
    LWPService a;
    private i b;
    private SharedPreferences c;
    private LWPService r4_LWPService;

    myEngine(LWPService lwpService) {
        super();
        this.a = r4_LWPService;
        this.b = new i(getSurfaceHolder(),
                r4_LWPService.getApplicationContext());
        this.c = r4_LWPService.getSharedPreferences("settings", 0);
        this.c.registerOnSharedPreferenceChangeListener(this);
        onSharedPreferenceChanged(this.c, null);
    }
... OTHER CODE...

}

Here is the LWPService class
public class LWPService extends WallpaperService {
    public void onCreate() {
        super.onCreate();
    }

    public Engine onCreateEngine() {
        return new m(this);
    }

    public void onDestroy() {
        super.onDestroy();
    }

A: Your myEngine class should not be static - make it as inner class for LWPService.


text:
Q: Pandas: convert series of time YYYY-MM-DD hh:mm:ss.0 keeping the YYYY-MM-DD format only Pandas: convert series of time YYYY-MM-DD hh:mm:ss.0 keeping the YYYY-MM-DD format only
python 3.6, pandas 0.19.0
     timestamp
0    2013-01-14 21:19:42.0
1    2013-01-16 09:04:37.0
2    2013-03-20 12:50:49.0
3    2013-01-03 17:02:53.0
4    2013-04-13 16:44:20.0

I tried:
df['timestamp'] = df['timestamp'].dt.strftime('%Y-%m-%d')

`AttributeError: Can only use .dt accessor with datetimelike values.`

Any thoughts?  Thank you!

A: convert the series into datetime datatype and try,
df['timestamp'] = pd.to_datetime(df['timestamp']).dt.strftime('%Y-%m-%d')

A: it may satisfy your demand
df['timestamp'] = pd.to_datetime(df['timestamp']).dt.strftime('%Y-%m-%d')

A: Using the below shown method also helps to achieve the same.
df['timestamp'] = pd.to_datetime(df['timestamp']).dt.date
You can refer to the documentation provided in the below link as a handy guide for date time handling:
https://pandas.pydata.org/pandas-docs/stable/api.html#datetimelike-properties


text:
Q: What does this mean $\mu\{x:\bigcap_\limits{k\geqslant 1}^{}\bigcup_\limits{n}^{}\bigcap_\limits{l\geqslant n}^{}{|f_l-f|}\leqslant \frac{1}{k}\}$ I am studying the following theorem: Consider $E\in\mathscr{F}$(sigma-algebra), and $E\in\Omega$ defined on a measure space $(\Omega,\mathscr{F},\mu)$. Suppose $\mu(E)<\infty$, and $\{f_n\}$ is a sequence of measurable functions on $E\to\mathbb{R}$ which are finite almost everywhere and converge almost everywhere to a function $f:E\to\mathbb{R}$ which is also finite almost everywhere. Then $f_n\to f$ almost uniformly in $E$.
The proof starts with the following: $\epsilon$>0
What does this mean? How do I read this intersection and union signs in this case? Thanks!$\mu\{x:\bigcap_\limits{k\geqslant 1}^{}\bigcup_\limits{n}^{}\bigcap_\limits{l\geqslant n}^{}{|f_l-f|}\leqslant \frac{1}{k}\}$

A: Define $E(k,l) = \{x \in \Omega: |f_l(x) -f(x)| \le \frac{1}{k}\}$.
This is a well-defined measurable set in $(\Omega,\mathscr{F})$ whenever all $f_n$ and also $f$ are measurable.
Then reformulate $f_n(x) \rightarrow f(x)$ for a certain $x \in \Omega$. The statement of pointwise convergence at $x$ means by definition:
$$\forall \varepsilon > 0: \exists n \in \mathbb{N} \forall l \ge n: |f_l - f(x)| < \varepsilon$$
WE cna uee $\le$ instead of $<$ as well,and as the values of $\frac{1}{k}$ get as small as we like we can replace the $\forall \varepsilon>0$ by $\forall k$ and $\varepsilon$ by $\frac{1}{k}$, to make everything countable (Which is what you want in measure theory). So $f_n(x) \rightarrow f(x)$ means for some $x$:
$$\forall k \in \mathbb{N} :\exists n \in \mathbb{N}: \forall l \ge n: |f_l(x) -f(x)| \le \frac{1}{k}$$
We can write that last statement using the definition of $E(k,l)$ as:
$$\forall k \in \mathbb{N} :\exists n \in \mathbb{N}: \forall l \ge n: x \in E(k,l)$$
And as we have sets now, we can also reformulate as intersections and unions, so $f_n(x) \rightarrow f(x)$ iff (indices implicitly over $\mathbb{N}$):
$$x \in \bigcap_{k} \bigcup_{n} \bigcap_{l \ge n} E(k,l)$$
which is a measurable set $P = P((f_n, f))$ say (it depends only on the sequence and its pointwise limit a.e.),as all $E(k,l)$ are, which is the whole point of writing it like this. So saying that $f_n$ converges to $f$ almost everywhere on $E$, means that the complement of $P$ in $\Omega$ has measure $0$, which seems to be used in the remainder of the proof, I'm guessing. It implies that $\mu(P \cap E) = \mu(E)$.
Your notation of the set sort of confuses the quantor definition with the operations write-up in terms of unions and intersections.


text:
Q: Debugging FBPlacePickerViewController loaddata method I want to use [FBPlacePickerViewController loadData], and do some logic on the data received, before using the view.
How can I see the location information received in the loadData method?

A: You may look into using the FBPlacePickerDelegate: https://developers.facebook.com/docs/reference/ios/3.1/protocol/FBPlacePickerDelegate
It's not quite clear what you want to do, but if you're looking to filter the places, you can check out the placePickerViewController:shouldIncludePlace: delegate method.


text:
Q: Got an error "ZONE_RESOURCE_POOL_EXHAUSTED" when creating a new instance on Google Cloud Recently I created a number of GPU instances on Google Cloud across 5 regions.
However when I tried to create more than a number of instances in one region, I got an error ZONE_RESOURCE_POOL_EXHAUSTED.
I googled about the error, and found here mentioned about it's a resource limit on the corresponding region.
I wonder if it's actually a quota limit per user account or project, or  the only way is to wait for other users to release their resources ?

A: If you see 'ZONE_RESOURCE_POOL_EXHAUSTED' error meaning you are encountered with the temporary resource stock-out issue at that particular zone. I would like to point you to this post made by "Paul Nash", who thoroughly explained the resource stock-out issue at Google Cloud Platform (GCP). The recommended workaround is to try a different zone or later if you are looking to get resources in the same zone as those issues are to be expected transiently.
This is apparently not a Quota issue and if you encounter any Quota issue then you should get an error related to "Quota Exceed".


text:
Q: State is behind I have a state pageSize, user will select the pageSize they wish to size their pages.
UI
I was able to get my currentPage to update, as well as got my list to fit based on pageSize using useMemo().
  const PAGE_SIZES = [15, 25, 50, 100];

  function BlogList() {

  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(PAGE_SIZES[0]);

  const updatePage = (pageNum) => {
    setCurrentPage(parseInt(pageNum))
  };

  const updateRowsPerPage = (rows) => {
    setPageSize(parseInt(rows));
  };

  const currentPaginationData = useMemo(() => {

    const start = Math.floor( (currentPage*pageSize) - pageSize);
    const end = Math.floor(currentPage*pageSize);

    if(currentPage >= Math.floor(blogs.posts.length/pageSize)) {
      return blogs.posts.slice(start, blogs.posts.length)
    }else{
      return blogs.posts.slice(start, end)
    }

  }, [currentPage]);

Now, I was having trouble with all my states, they were behind, until obviously the page rerendered, but after some research I used useMemo() for currentPagination, worked fine, then updatePage() is working without an issue. In my experience state is always behind when you try setting morew than one state in a function LINE 20. I know its right in front of me, the solution, but I just can't see it, help please!


text:
Q: Rsync daemon: is it really useful? Are there any practical benefits in using rsyncd compared to rsync over ssh? Does it really increase speed, stability, anything?

A: The function of rsyncd is to run on a server and respond to (remote) rsync requests.
(when we say rsyncd we mean rsync running as a daemon, and when we say 'remote', we mean remote from the point of view of the machine running rsyncd)
Both would use ssh in order to talk to each other securely.
It's not really a question of using one or the other, although if rsync is used to copy files and directories on the same machine, I don't think it needs to run as a daemon.
I think the rsync man page clarifies this.

A: This is an old question, but there is another very valid reason for using rsync in daemon mode versus over ssh:

*

*Lower CPU overhead.

I have one 10 TB NAS that is backed up to another 10 TB NAS, and the encryption overhead for just the SSH tunnel is the limiting factor for the transfer. Both NASes are fairly low-powered 1.8 Ghz Intel Atoms, and even with easier crypto options for ssh (e.g. ssh -c arcfour passed as the ssh call to rsync), the encryption overhead still results in at best 200-300 Mbps, on a gigabit ethernet network.
Using a rsync daemon on one end removes the crypto overhead, and achieves >800 Mbps transfers for large, contiguous files.

A: I think the big difference is that if you're using rsyncd on the server end, instead of rsync over ssh, the server already knows what it has, so building the file lists to determine what needs to be transferred is much simpler.  It won't make a difference if you're just pushing around a few files, but if you're making, for example, CPAN available over rsync, you don't want to have to build the file list on the source side every time.

A: rsyncd (rsyncd with daemon) uses by default port 873.
This will use the native rsync protocol, but does not encrypt anything. It is meant only for local or trusted networks.
If you want security, always you have to use rsync or rsyncd over SSH, all your data transfers will be entrypted by the ssh protocol.

A: I don't think comparing running rsyncd to rsync over SSH makes much sense.  They are generally  used for completely different things.
rsync over ssh is usually used for backups, or syncing servers over the internet.
rsyncd is usually used for things like software mirrors, so it makes more sense to compare rsyncd to a plain HTTP or FTP mirror or even bittorrent.
There is also software like zsync, which allows you to get many of the benefits of rsync while still using a standard HTTP server

A:

*if no other remote tools are available on local host, but rsync then using rsync in conjunction with rsync-daemon on the remote location is useful.

afaik, a distro might come with only scp and rsync and no other remote tools to transfer files...

*if the user is not familiar with using scp...

*if there are reasons to prefer unencrypted file tranfers .


text:
Q: Prevent logged out users from accessing url links which are available for logged in users I have done a login page by using session variable to store username based on which users are made to login, I would like to know whether it is possible to make url links which are accessible only for the logged in users, but the url links should not be available to users who are not logged in , for example a person who is logged in , if he tries to copy the url and give it to another person and if that person pastes the url in his address bar without logging in he should redirected to a login page or some message should be displayed saying that he needs to be logged in inorder to view that particular url link .
I have searched in google regarding this , not able to find any solution.
*EDIT *
Actually the link  is a https page whose url needs to be hidden , similar to the way we hide the path of pdf which are used for downloading using header .
For Example i make a php page where if the username is in session and he clicks a link he will be redirected to this link page but he cannot see the url .
Thanks

A: Create a session variable when login is successful.
$_SESSION['logged_in'] = $_POST['username'];

Then at the start of every page use session_start()
Immediately after that check
if(! isset($_SESSION['logged_in'])) { /* redirect to login page */ }

A: Presuming the "URL Links" are to PHP pages, at the top of each page simply verify that the web browser requesting the page has established a valid session.

A: Do like this :
<?php

session_start();

if(isset($_SESSION['loggeduser']){
echo "Welcome";
}
else{
echo "Unauthorized User";
//redirect user to login page
}

?>


text:
Q: How to provide multiple options to link a function I have 3 object files :
main.o

general.o

specific.o

in main.o there is a call to function :   void handle(void),
general.o implement a generic functionality to   handle() ,
specific.o might or might not have an implementation to   handle() ,
I want to specify in my cmake that "search to link handle with specific.o if fail then try with general.o"
Is that possible ?

A: There certainly is nothing in standard C++ which allows this.
For Gcc/clang toolchain you can define handle as a weak symbol in general TU with __attribute__((weak)) and as ordinary symbol in specific.
Be very careful with this though, ensure that handle itself is not called in general. Because if it is, the call might be inlined before the linker sees anything, resulting in some code calling the general method, the rest specific. Link-time optimization might be actually more safe here.


text:
Q: How to send JavaScript command when HTML form  is chosen? I have this simple HTML form:
 <form action="">
  <select name="channel">
   <option value="#channel1">channel1</option>
   <option value="#channel2">channel2</option>
  </select>
 </form>

and this JavaScript function:
/* Use this method to send a command to lightIRC with JavaScript */
function sendCommand(command) {
  swfobject.getObjectById('lightIRC').sendCommand(command);
}

I want it so when I user clicks on a dropdown option the JavaScript command sendCommand('JOIN value'); is sent.
Value is the value from the <option>.
Is it possible to do this? There is no submit button etc. I want it to work when the user simply clicks on a dropdown option.

A: You can send option value by passing this.value to javascript function on change event.
<form action="">
  <select name="channel" onchange="sendCommand(this.value)">
   <option value="#channel1">channel1</option>
   <option value="#channel2">channel2</option>
  </select>
 </form>

A: Or using jQuery:
$('document').ready(function() {
  $('select[name="channel"]').bind('change', function() {
    sendCommand($(this).val());
  });
});

A: You can directly wire the event with jQuery and concatenate JOIN to it.
$(function(){
   $("select[name='channel']").on("change", function(){
     swfobject.getObjectById('lightIRC').sendCommand("JOIN "+ $(this).val());
   });
});

Hope this helps


text:
Q: javascript regex get different answer with same expression in Chrome console I want to test Javascript Regex in Chrome Console. However, I get different answers with the same expression (refer to the picture). If I use original literal to test, the I can get right answer. What is the reason for that?

re = /^[a-z][0-9a-z]*$/g;
console.log(re.test("a34"));
console.log(re.test("a34"));
console.log(re.test("a34"));
console.log(re.test("a34"));
console.log(/^[a-z][0-9a-z]*$/g.test("a23"));
console.log(/^[a-z][0-9a-z]*$/g.test("a23"));

A: Straight from the docs:

Use test() whenever you want to know whether a pattern is found in a string. test() returns a boolean, unlike the String.prototype.search() method, which returns the index (or -1 if not found). To get more information (but with slower execution), use the exec() method (similar to the String.prototype.match() method). As with exec() (or in combination with it), test() called multiple times on the same global regular expression instance will advance past the previous match.


text:
Q: Deriving London Equation from Helmholtz energy I'm trying to derive the London equation of superconductivity following the book Ginzburg-Landau
Phase Transition Theory and Superconductivity. So I arrived to:
\begin{gather}
\mathcal{F} = \mathcal{F}_S + \frac{1}{2}\int_V\left(h^2+\lambda_L^2\left|\overrightarrow{\nabla}\times\overrightarrow{h}\right|^2\right)d\overrightarrow{r}
\end{gather}
Now I have to minimize the free energy. $\mathcal{F}_S$ is a constant so it doesn't matter when taking variations. The problem I have is taking variations of the term $\overrightarrow{\nabla}\times\overrightarrow{h}$, I did this:
\begin{gather}
\delta\left(\left|\overrightarrow{\nabla}\times\overrightarrow{h}\right|^2\right) = \delta\left(\overrightarrow{\nabla}\times\overrightarrow{h}\cdot\overrightarrow{\nabla}\times\overrightarrow{h}\right)=2\delta\left(\overrightarrow{\nabla}\times\overrightarrow{h}\right)\cdot\overrightarrow{\nabla}\times\overrightarrow{h}
\end{gather}
but I need to show that that is equal to $-\nabla^2h$, but I don't know how to prove it.

A: Use the equation
$$
{\rm div}(\delta{\bf h} \times {\rm curl\,}{\bf h})={\rm curl\,}{\bf h}\cdot  {\rm curl \,}\delta{\bf h}- \delta{\bf h}\cdot({\rm curl}({\rm curl\,} {\bf h}))
$$
to integrate by parts, and
then  the usual expression relating  ${\rm curl}({\rm curl\,} {\bf h})$ to $\nabla^2 {\bf h}$.


text:
Q: Auth0 - auth.isAuthenticated not working I'm trying to hide buttons in my nav bar depending on if the user is authenticated.
Auth0 is up and running but I can't seem to use it in a ng-if.
Here is my code:
NavCtrl.js
/* global myApp*/
myApp.controller('navCtrl', function($scope, auth, store, $location){
    $scope.isActive = function(destination){
        return destination === $location.path();
    }

    $scope.login = function doAuth() {
    auth.signin({
      authParams: {
        scope: 'openid offline_access',
        device: 'Mobile device'
      }
    }, function(profile, token, accessToken, state, refreshToken) {
      // Success callback
      store.set('profile', profile);
      store.set('token', token);
      store.set('refreshToken', refreshToken);
      $location.path('/');
    }, function(error) {
      console.log("There was an error logging in", error);
    });
  };

    $scope.logout = function() {
        auth.signout();
        store.remove('token');
        store.remove('profile');
        store.remove('refreshToken');
        $location.path('/');
    };
});

app.js
var myApp = angular.module('myApp',
                        [
                            'ngRoute',
                            'ngResource',
                            'auth0',
                            'angular-storage',
                            'angular-jwt'
                        ]);
myApp.run(function($rootScope, auth, store, jwtHelper, $location) {
    auth.hookEvents();

  var refreshingToken = null;
  $rootScope.$on('$locationChangeStart', function() {
    var token = store.get('token');
    var refreshToken = store.get('refreshToken');
    if (token) {
      if (!jwtHelper.isTokenExpired(token)) {
        if (!auth.isAuthenticated) {
          auth.authenticate(store.get('profile'), token);
        }
      } else {
        if (refreshToken) {
          if (refreshingToken === null) {
            refreshingToken = auth.refreshIdToken(refreshToken).then(function(idToken) {
              store.set('token', idToken);
              auth.authenticate(store.get('profile'), idToken);
            }).finally(function() {
              refreshingToken = null;
            });
          }
          return refreshingToken;
        } else {
          $location.path('/login');
        }
      }
    }
  });
});

myApp.config(function($routeProvider, authProvider, $httpProvider, $locationProvider,
  jwtInterceptorProvider){

  authProvider.init({
    domain: 'DOMAIN.eu.auth0.com',
    clientID: 'CLIENTID',
    loginUrl: '/'
  });

  $routeProvider

    .when('/', {
        templateUrl: 'partials/home.html',
        controller: 'homeCtrl'
    })

    .when('/dashboard', {
        templateUrl: 'partials/dashboard.html',
        controller: 'dashCtrl',
        requiresLogin: true
    })

    .when('/capture', {
        templateUrl: 'partials/capture.html',
        controller: 'captureCtrl',
        requiresLogin: true
    })

    .when('/profile', {
        templateUrl: 'partials/profile.html',
        controller: 'profileCtrl',
        requiresLogin: true
    })

    .otherwise({redirectTo: '/'});

    $locationProvider.html5Mode({enabled:true, requireBase: false});

  jwtInterceptorProvider.tokenGetter = function(store, jwtHelper, auth) {
    var idToken = store.get('token');
    var refreshToken = store.get('refreshToken');
    // If no token return null
    if (!idToken || !refreshToken) {
      return null;
    }
    // If token is expired, get a new one
    if (jwtHelper.isTokenExpired(idToken)) {
      return auth.refreshIdToken(refreshToken).then(function(idToken) {
        store.set('token', idToken);
        return idToken;
      });
    } else {
      return idToken;
    }
  }

  $httpProvider.interceptors.push('jwtInterceptor');
});

index.ejs
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />

    <link rel="icon" href="../../favicon.ico">

    <title>Birdspotter</title>

    <link href="lib/bootstrap/dist/css/bootstrap.css" rel="stylesheet">

          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            Toggle navigation

          </button>
          Birdspotter

Dashboard

Capture

Login

Profile

Logout

As you can see, on the nav i'm trying to do ng-if="auth.isAuthenticated" and ng-if="!auth.isAuthenticated" but it doesn't seem to do anything.
I also tried a console.log(auth.isAuthenticated); to see if it even works and it always gives 'false'.

A: You need to keep track of the authentication state with the scope:
//NavCtrl.js
    $scope.login = function doAuth() {
      auth.signin({
        authParams: {
          scope: 'openid offline_access',
          device: 'Mobile device'
        }
      }, function(profile, token, accessToken, state, refreshToken) {
        // Success callback

        //Store the status in the scope
        $scope.isAuthenticated = auth.isAuthenticated
        store.set('profile', profile);
        store.set('token', token);
        store.set('refreshToken', refreshToken);
        $location.path('/');
      }, function(error) {
        console.log("There was an error logging in", error);
      });
    };

To handle re-authentication after page reloads:
//app.js
myApp.run(function($rootScope, auth, store, jwtHelper, $location) {
    auth.hookEvents();

  var refreshingToken = null;
  $rootScope.$on('$locationChangeStart', function() {
    var token = store.get('token');
    var refreshToken = store.get('refreshToken');
    if (token) {
      if (!jwtHelper.isTokenExpired(token)) {
        if (!auth.isAuthenticated) {
          auth.authenticate(store.get('profile'), token);

          //Store the status in the scope
          $rootScope.isAuthenticated = auth.isAuthenticated
        }
      } else {
        if (refreshToken) {
          if (refreshingToken === null) {
            refreshingToken = auth.refreshIdToken(refreshToken).then(function(idToken) {
              store.set('token', idToken);
              auth.authenticate(store.get('profile'), idToken);
            }).finally(function() {
              refreshingToken = null;
            });
          }
          return refreshingToken;
        } else {
          $location.path('/login');
        }
      }
    }
  });
});

Then in the html:

Login


text:
Q: CGPoint Scalar Multiplication Swift I am building a platformer game in SpriteKit and was going to implement an update function for my entities so they would move according to gravity and their velocity. However, I need to make the amount of velocity added proportional to delta time to prevent frame rate from affecting how my entities move, so I was going to import GLKit so I could use the scalar functions. However swift is not compatible. Is there some other way of implementing scalar multiply to CGPoints or making velocity propositional to delta time?
PS: Could someone also explain what scalar multiply is and how it works?

A: There is currently no built-in way of doing math with CGPoints. There are many third party libraries that do this, mostly built in the pre-GLKit days. As you mentioned, the best way of doing this now is with GLKit, when it supports Swift. Hopefully soon.
Scalar multiplication is super easy. You just need to multiply each component of the CGPoint with the same number (also called scalars).
CGPoint CGPointMultiplyScalar(CGPoint point, CGFloat scalar) {
    return CGPointMake(point.x * scalar, point.y * scalar);
}


text:
Q: Activity/Fragment and ViewModel in Adapter good practice? Let's assume that we have Activity/Fragment which contains a RecyclerView. Furthermore, it sets an Adapter. For the sake of the example, let's say the Adapter has to have access to Fragment in order to call a method which displays a Snackbar. Moreover, Let's say there are a couple of items in the adapter. I want to delete one and remove it from the database. Therefore I should call ViewModel's methods. I've made a research but I couldn't find any information if referencing a fragment into the Adapter is good or not.
Could you help me and explain? Also for the ViewModel I've found some ideas here.
But what are the best practices?

A: *

*good Adapter Classes should be STATIC helping developers to keep it separated from Activity/Fragment part

*don't save Activity/Fragment reference inside Adapters

*ViewModels should belongs to Activities or Fragments

*Adapters should execute Activity/Fragment's actions via Callbacks/Listeners or LiveData

Pseudo-code:
public class MainActivity extends Activity {

    private interface Listener {
        void OnRemoved(@NonNull xxx removedItem);
    }

    private static final class MyAdapter extends ArrayAdapter<xxx> {
        private final Listener mListener;
        private MyAdapter(@NonNull final Listener listener) {
            super(...);
            this.mListener = listener;
        }
        @Override
        public void remove(xxx item) {
            super.remove(xxx); //<-- this removes item from Adapter
            this.mListener.OnRemoved(item); //<-- this triggers Activity's code
        }
    }

    public void onCreate(...) {
        ...
        new MyAdapter(new Listener() {
            @Override
            public void OnRemoved(@NonNull final xxx removedItem) {
                Snakbar.makeText(....).show();
            }
        });
    }
}


text:
Q: Ajax не реагирует на вторую и последующие кнопки из цикла while php В php вытаскиваю данные из БД через цикл while в блок с информацией, в котором есть кнопка Подробнее, чтобы перейти на страницу именно в этой записью. Переменная $date это просто отфармотированная под нужный вид дата.
$sql=mysqli_query($connect, "SELECT * FROM `event` ORDER BY `date_event` DESC");
    while ($res=mysqli_fetch_array($sql)) {

$event = sprintf('

%s

Дата: %s

%s

    <button id="more_event" value="%s">Подробнее</button>

',$res['img_event'], $res['title_event'],$date, $res['description_event'],$res['id_event']);
echo $event;
}

Далее ловлю клик на кнопку и передаю айди записи в файл event.php с помощью ajax.
$(document).ready(function(){

    $('#more_event').click(function(){
    id=$(this).val();
    $.post('event.php', {id:id}, function(html){$('#events').html(html)
    });
    });});

Проблема в том, что когда кликаешь на первую кнопку все нормально, но со второй и последующими не происходит вообще ничего. Скрипт вставлял и перед циклом, и после, и даже в сам цикл умудрился запихнуть. Сталкивался с этой проблемой и раньше, но абсолютно не помню, как решал ее. Помогите новичку разобраться

A: Делайте так:
<button class="more_event" value="%s">Подробнее</button>

....

$('.more_event').click(function() ...

И будет Вам Счастье


text:
Q: Dynamic database connection in Symfony I have a second entity manager, and i want to get parameters from a database and change the DATABASE_URL to connect to another database.
# config/packages/doctrine.yaml
my_entity:
    url: '%DATABASE_URL%'
    driver: 'pdo_mysql'
    server_version: '5.7'
    charset: utf8mb4

I try to add a parameter from the process function from Kernel.php, but it's apparently run only one time.

A: This can be done by changing the data of the Connection class. You need to create your own Connection class and hook it up to the project.
Let's create the required class Connection
// src/Doctrine/DatabaseConnection.php

use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Driver;

class DatabaseConnection extends Connection
{

    public function __construct(array $params, Driver $driver, $config, $eventManager )
    {
        // First, let symfony connect to the default database from env so that a Connection instance appears in order to execute a sql query to get the necessary data
        parent::__construct($params, $driver, $config, $eventManager);

        // Getting data and changing it
        $user_database =  $this->executeQuery('SELECT * FROM database WHERE user_id = :user_id',['user_id'=>1])->fetch();
        $params['dbname'] = $user_database['dbname'];
        $params['user'] =  $user_database['user'];
        $params['password'] = $user_database['password'];
        parent::__construct($params, $driver, $config, $eventManager);

    }
}

Note: As you can see in the example, to begin with, we connect to our main database from .env so that we can access the desired database by executing an sql query. After receiving the data, we modify it and call the parent's constructor method again to replace the Connection instance with the database we want.
Initialize DatabaseConnection
# config/packages/doctrine.yaml
doctrine:
    dbal:
        url: '%env(resolve:DATABASE_URL)%'
        wrapper_class: App\Doctrine\DatabaseConnection

Note: Here we have connected our handler using the DBAL wrapperClass option


text:
Q: How to combine 'blocktanslate' with 'humanize' tag in templates? blocktranslate allows me to display a localized plural, whereas humanize allows me to display a grouped-by-hundred number.
Each of them works when used independently but I'd like to have both in the same time.
I've tried:
(words_number is the integer sent by the view)
{% load humanize %}
{% blocktranslate count counter=words_number %}
1 word
{% plural %}
{{ counter|intcomma }} words
{% endblocktranslate %}

But it displays: words (empty space where the number should be)
EDIT: Before a solution will be found, I'm using Javascript to group by hundred:
{% blocktranslate count counter=words_number %}
1 word
{% plural %}
{{ counter }} words
{% endblocktranslate %}

A: As described in the documentation for the blocktranslate template tag to use filters or expressions on variables you need to bind them to some local variable using with, so you can do something like follows:
{% load humanize %}
{% blocktranslate with count_humanized=words_number|intcomma count counter=words_number %}
1 word
{% plural %}
{{ count_humanized }} words
{% endblocktranslate %}