text:
Q: Autoit update image not working I have a code that should update a image but it does not. It works with a lable (text) but not a image. Can any one help heres my code:
$tmppic="Images\tmp\Nodata.bmp"
GUICreate("CPU Temp")
Opt("GUIOnEventMode", 1)
$tmpimg=GUICtrlCreatePic($tmppic,100,100,200,100)
GUISetState()
while 1
   $tmppic="Images\tmp\1.bmp"
   GUICtrlSetdata($tmpimg,$tmppic)
WEnd

A: Replace GuiCtrlSetData with GuiCtrlSetImage and it should work ;)


text:
Q: Delete orphaned one way lookup data I have a set of records supplier__c which have a lookup to an address__c record.
So I'd like to gather all those up:
//Make a list of ID's of addresses on Suppliers : supadrs
List<Id> supadrs = [ SELECT Address__c FROM Supplier__c ];

Then lets gather all the address__c ids:
//Make a list of all address IDs : adrids
List<Id> adrids = [ SELECT Id FROM Address__c ];

And let's find all the address ids which are not on a supplier record:
//Make a list of ID's in List 2 which are not in List 1 and assign to List 3
list< Id > deletelist =[ SELECT Id FROM adrids where Id not in:supadrs ];

And then delete the list:
delete deletelist;

What would be the correct syntax for this action?

A: You want a anti-join here:
SELECT Id FROM Address__c WHERE Id NOT IN (SELECT Address__c FROM Supplier__c)

That will give you all Address records that are not looked up to from any Supplier.

A: You can do this all in a single query. In fact, you can do this in a single line of code:
delete [SELECT Id FROM Address__c WHERE Id NOT IN (SELECT Address__c FROM Supplier__c)];

The second query automatically maps the Address__c values to the Id, allowing for an efficient query that doesn't involve any extra lines of code or clever manipulation.

redpajama_set_name: RedPajamaStackExchange


text: Q: Ubuntu 20.04 HP M125a scanner problem I have an HP USB LaserJet MFP printer/scanner M125a. I installed the printer using hp-update and it works. For scanning I tried to use simple-scan. It opens the GUI and finds the scanner. However when I click the "scan" button it says "Unable to connect to scanner". Tried both as root and user.


text:
Q: How to declare anonymous type for Json serialization, if one of the Json keys contains a dot? I am serializing an anonymous object to use as a request message for an HTTP post request. The problem is that one of the JSON keys contains a dot in its name. VS throws out ''invalid anonymous type member declarator'' error.
return JsonConvert.SerializeObject(new
{
    query = "something",
    firstname.keyword = "xyz"
});

What can I do to solve this issue?
Edit: the real json request looks something like this, so I don't think I can use a dictionary:
{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "firstname.keyword": ""
          }
        }
      ],
      "must_not": [ ],
      "should": [ ]
    }
  },
  "from": 0,
  "size": 10,
  "sort": [ ],
  "aggs": { }
}

A: Json can generally be represented using arrays, dictionaries and anonymous objects.
The first part of your Json can be generated as follows:
return JsonConvert.SerializeObject(new
{
    query = new
    {
        @bool = new
        {
            must = new[]
            {
                new
                {
                    term = new Dictionary<string, object>
                    {
                        ["firstname.keyword"] = string.Empty,
                    }
                }
            }
        }
    }
});


text:
Q: Play 2.2.2 @Transactional of eBean does not rollback transaction in Exception thrown It seems that when using Play Framework 2.2.2 with eBean ORM the @play.db.ebean.Transactional
does not rollback transaction when an Exception is thrown.
Does someone of you know something about the issue and how it could be solved ?
I saw that eBean has a BUG about that issue in their avaje-ebeanorm-agent 3.2.2. : https://github.com/ebean-orm/avaje-ebeanorm/pull/44 which is fixed in version avaje-ebeanorm 3.2.3
Also play 2.2.2 seems use avaje-ebeanorm-agent 3.2.2 and when I change it to higher version in
Built.scala (3.2.5) some crashes with the used JPA annotations appeared (like orphanRemoval is not recognised)
P.S. There is similar discussion with Play 2.1.1 , play 2.1.1: Unable to rollback transaction with ebean orm, but no clear resolving of the issue with using @Transactional in Action is found.

A: I experienced similar problems, however I have only tested with play version 2.3.7.:
I noticed that there are two different libs that contain the Transactional-annotation: @com.avaje.ebean.annotation.Transactional and @play.db.ebean.Transactional.
Apparently each of them only work in a certain type of classes and when used wrong, no rollback will be performed. This is what I found out by testing:

*

*@com.avaje.ebean.annotation.Transactional:
only works for methods in classes that represent a model, i.e. they have the @javax.persistence.Entity annotation. However there seems to be a bug in ebean enhancement, which causes the classes to always recompile although no changes were made

*ebean's documentation gives two other ways of implementing transactions, e.g. you can use a try/finally block. In my tests this way has always worked well and a rollback was performed.

*@play.db.ebean.Transactional: only works for actions, i.e. the class is derived from play.mvc.Controller. I'm not sure whether this behaviour is intended or not, but the documentation of play-framework only talks about transactional actions and doesn't mention model-classes at all.


text: Q: Plotly change function color after certain threshold I have some data X, y, which I want to plot. I also want to make the function change color after a certain threshold t and the description to change after that threshold (I mean, when I hover on it, it should just display something else like "Background" instead of plotly data). I have uploaded a picture to clarify what I want to achieve. Does someone know how to do it?


text:
Q: Is MVVM possible/viable in a DHTML RIA application (no Silverlight/WPF)? Note: This is a long winded question and requires a good understanding of the MVVM "design pattern", JSON and jQuery....
So I have a theory/claim that MVVM in DHTML is possible and viable and want to know if you agree/disagree with me and why.  Implementing MVVM in DHTML revolves around using ajax calls to a server entity that returns JSON and then using html manipulation via javascript to control the html.
So to break it down.  Lets say I'm building a search page that searches for People in a database.....
The View would look something like this:

            Search:

            <input type="text" bindto="SearchString" />

            <input type="button" value="Search" command="Search" />

                        First Name
                        Last Name

                        ${FirstName}
                        ${LastName}

Using some non standard attributes on my html elements, I have declaritively defined a View and how it will interact with my ViewModel.  I've created a MVVM parser in javascript that interprets the non-standard attributes and associates the View with a JSON object that represents the ViewModel.
The ViewModel would be a JSON object:

        //View Model SearchViewModel would be assocaited with View because of
        var SearchViewModel = {
            //SearchString variable has a TwoWay binding
            //to <input type="text" bindto="SearchString" /><
            //if a user types into the text box, the SearchString property will "auto-magically" be updated
            //because of the two way binding and how the element was interpreted via my MVVM parser
            SearchString: '',

            //SearchResults has a OneWay binding to

            SearchResults: new Array(),

            //Search function will get "auto-magically" get called because of
            //the command binding to <input type="button" command="Search" />
            Search: function() {
               //using jquery to call into the server asynchronously
               //when the server call is completed, the PopulateSearchResults method will be called
               $.getJSON("www.example.com/SearchForPerson",
                         { searchString: SearchViewModel.SearchString },
                         SearchViewModel.PopulateSearchResults);
            }

            PopulateSearchResults: function(data) {
                //set the JSON array
                SearchViewModel.SearchResults = data;
                //simulate INotifyPropertyChanged using the MVVM parser
                mvvmParser.notifyPropertyChanged("SearchResults");
            }
        }

The Model can be any server side asset that returns JSON...in this example, I used asp MVC as a restful facade:

        public JsonResult SearchForPerson(string searchString)
        {
            PersonDataContext personDataContext = new PersonDataContext(); //linq to sql.....

            //search for person
            List<Person> results =
                personDataContext.Persons
                                 .Where(p => p.FirstName.Contains(searchString)
                                             || p.LastName.Contains(searchString))
                                 .ToList();

            return Json(results);
        }

So, again the question:
Is MVVM possible/viable in a DHTML RIA application (no Silverlight/WPF) or have I lost my mind?
Could this "MVVM framework" be a good idea?
Proof of Concept: kaboom.codeplex.com.

A: Take a look at the ASP.NET data binding features in .NET 4.0 - comes out with Visual Studio 2010.  This is exactly what you are looking for if you are ok with MS technology.
Blog that details the feature
Community technology preview on codeplex
Theoretically you could just include the ASP.NET AJAX js file from your HTML files & make the solution cross-platform.
So to directly answer your question - it absolutely is a viable solution to the problem of creating maintainable, loosely coupled web user interfaces.  And yes, the server side of your application is doing less - it becomes more of a true service layer, where all it deals with is data exchange.  This is actually a good thing, b/c it promotes reuse across clients.    Imagine your WPF app and your web app using the same middle tier server to send/receive data?  Clients have a lot of available processing power anyway - why not leverage it to make you solution more scalable (the less the server is doing, the more work your clients are doing, which is distributed across ALL clients)
The tricky part is two way binding - where you hook into the event that some object had changed, and the event that something in the user interface has changed (user typed something into an input control, for example).  One way binding would still be useful.
It seems like Microsoft is the only company right now building a full solution in the pattern you want.  Yahoo's YUI library does do data binding that is semi-coherent, but not in the same pattern as WPF/Silverlight like you have built.

A: This would probably be a good time to link to knockout JS, which is a javascript mvvm framework.
You may also want to look at backbone, a javascript MVC framework:

A: It looks possible and viable, with the only downside being that your code is relying on a whole lot of client side processing to get to the end result.
In my opinion, you're still a whole lot better of using a server side MVC architecture rather than trying to create a client side MVVM framework.

A: I'm using a similar concept and added JQuery Templating & DataLink (http://weblogs.asp.net/scottgu/archive/2010/10/04/jquery-templates-data-link-and-globalization-accepted-as-official-jquery-plugins.aspx) to the equation as a way to have clean views and declarative binding (the binding part is giving me some problems, but I think it might work fine).
Using this in an scenario where I have to consume services async, and I'm really liking it.
I'm wondering how your MVVM Parser looks like, I used a pub/sub plugin for communications.


text:
Q: what are the difference between metric space and metric linear space? I know the meaning of metric space and vector space. but i want to differentiate metric space from metric linear space. so basically what are metric space and linear space?

A: Consider the graph of $y=x^2$ where $x\in[0,1]$. This is a metric space that is not linear.
A metric and linearity are simply different structures that can be imposed on sets (simultaneously if necessary).

A: "Linear space" is just a synonym for "vector space".  A metric linear space is something that is both a metric space and a vector space, such that the vector space operations (addition and scalar multiplication) are both jointly continuous.


text:
Q: How to call function from other files like headers in C? I'm trying to build a simple program that tells the user their Zodiac sign and life path number. The problem is even when given a wrong birth date it keeps writing the life path number. I am using Euclidean division exmp 12/02/1999
year 1999 = 1 + 9 + 9 + 9 = 28  2 + 8 = 10  1 + 0 = 1
I want to call this function from the main.c. How can I do that? thanks
#include <stdio.h>
#include <stdlib.h>

int year_verif(year,q3,ql,r,q2,q1,q4,xy,xt,xt2)
{
  printf("Enter your birth year\n");
  scanf("%d", &year);
  while (year <= 1920 || year >= 2020) {
    printf("Invalid Year of Birth \n");
    printf("Re-enter your birth year\n");
    scanf("%d", &year);
  }

  q1 = year / 1000;
  r = year % 1000;
  q2 = r / 100;
  r = r % 100;
  q3 = r / 10;
  r = r % 10;
  q4 = r;
  xy = q1 + q2 + q3 + q4;

  if (xy >= 10 )
  {
    xt = xy / 10;
    xt2 = xy % 10;
    xy = xt + xt2;
  }

  printf("year ""%d\n",xy);
  return 0;
}

A: "I want to call this function from the main.c."
Jump to bottom if you simply want the answer to this question.  Otherwise, following are some observations and suggestions...
As mentioned in comments under your question, some implementations of the C standard (eg. Clang, GCC, and MSVC) allow functions declared with identifier lists, such as this
int year_verif(year,q3,ql,r,q2,q1,q4,xy,xt,xt2)

...but always expect explicit typed declarations before use.  For example, called in main():
int main(void)
{
    int year = 0;
    int q3 = 0;
    int ql = 0;//note - que ell
    int r = 0;
    int q2 = 0;
    int q1 = 0;// note que one
    int q4 = 0;
    int xy = 0;
    int xt = 0;
    int xt2 = 0;
    year_verif(year,q3,ql,r,q2,q1,q4,xy,xt,xt2);

(Your original code is missing this step and needs to be added.)
Although identifier lists are accommodated by the standard, it is more common and acceptable to use parameter type lists (differences are discussed here) in the function argument list,
int year_verif(int year,int q3,int ql,int r,int q2,int q1,int q4,int xy,int xt,int xt2);

If you need updated values of variables to be passed back to the calling function (otherwise ignore this section.), one other important addition is needed before any of these variables can be used to pass back results of the work done in the function.  The changed value of a variable can only be returned via a pointer argument, as shown in the following adaptation of the original prototype:
int year_verif(int *year,int *q3,int *ql,int *r,int &q2,int *q1,int *q4,int *xy,int *xt,int *xt2);

Now when called in main() the address of (&) each argument will be passed so that the updated values can be passed back:
year_verif(&year,&q3,&ql,&r,&q2,&q1,&q4,&xy,&xt,&xt2);

One more suggestion however, since there are so many arguments, it would be more readable and otherwise manageable to collect all arguments into one construct, then pass
that single object:
typedef struct {
   int year;
   int q3;
   int ql;//note - que ell
   int r;
   int q2;
   int q1;//note - que one
   int q4;
   int xy;
   int xt;
   int xt2;
}date_s;

Then your function prototype becomes:
int year_verif(date_s *date)
{
    //...
}

this can be called in main like this:
int main(void)
{
    ...
    date_s date = {0};
    int ret = year_verif(&date);
    ...

A quick comment about your title question, i.e.:

"How to call function from other files like headers in C?"

This is possible, but architecturally really not a good idea, as laid out in this answer to a similar question.

"How to call a function residing in one .c file from a function  (eg. main()) residing in another file":

Say your function (no matter what form it has taken.) is defined in a file called date.c

date.c

...
int year_verif(date_s *date)
{
    ...
}

Place the prototype for the function:  int year_verif(date_s *date); into a header file named for example date.h

date.h

int year_verif(date_s *date);

Then, in main.c, add the line: #include "data.h" along with other header files at the top of the main.c file:

main.c

#include <stdio.h>
#include <stdlib.h>
#include "date.h"

Now the function can be called just as shown above.

A: You only need one parameter in your function.  Also, you need to declare your local variables and parameters (you can do the way you are doing, but that's legacy code that should be avoided for new programs, just to compile very old code)  Here is a possible way of what you are trying to do, to compute the verification year number of the passed value.  I think this is what you are trying to do in your program, but I'm  not sure.  Anyway, it seems to work, and illustrates you how you can define two functions in a single compilation unit, and call year_verif() from main() and passing it one parameter (the year value, computed in main())
#include <stdio.h>
#include <stdlib.h>

int year_verif(int yr)
{

  int q1 = yr / 1000;
  int r = yr % 1000;
  int q2 = r / 100;
  r = r % 100;
  int q3 = r / 10;
  r = r % 10;
  int q4 = r;
  int xy = q1 + q2 + q3 + q4;

  if (xy >= 10 )
  {
    int xt = xy / 10;
    int xt2 = xy % 10;
    xy = xt + xt2;
  }

  return xy;

}

int main(void)
{
  printf("Enter your birth year\n");
  int year;
  int res = scanf("%d", &year); /* scanf returns the number of matched
                                 * parameters, so it should be 1 on
                                 * good reading. */
  while (res == 1 && (year <= 1920 || year >= 2020)) {
    printf("Invalid Year of Birth \n");
    printf("Re-enter your birth year\n");
    res = scanf("%d", &year);
  }
  if (res == 1)
    printf("year_verif(%d) => %d\n", year, year_verif(year));
  return 0;
}

It compiles and runs like this:
$ a.out
Enter your birth year
13600
Invalid Year of Birth
Re-enter your birth year
142
Invalid Year of Birth
Re-enter your birth year
1962
year_verif(1962) => 9
$ _


text:
Q: How to keep MongoDB connection alive for a user until he/she leaves the site nextjs I'm using Nextjs and MongoDB to create a full-stack portfolio website, insert, find, update, delete, ... is fine but for everything I want to do I need to create a new connection whit MongoDB.
I create a models folder inside the project root directory. in the model folder, I have a model.js class file inside that I wrote my connection query:
model.js code:
import { MongoClient } from "mongodb";

    class Model {
      constructor(collectionName) {
        this.collectionName = collectionName;
      }

      async getDb() {
        try {
          const client = await MongoClient.connect(process.env.dbUri);

          const db = client.db();

          return db.collection(this.collectionName);
        } catch (err) {
          console.log("Model", err);
          throw err;
        }
      }
    }

    export default Model;

and in the models folder, I have another class model named skills.js
skills.js code:
import { ObjectId } from "mongodb";
import Model from "./model";

class Skills extends Model {
  constructor(id, title, slug, rate) {
    super("skills");
    this._id = id ? id : null;
    this.title = title ? title : null;
    this.rate = rate ? rate : null;
    this.slug = slug ? slug : null;
    this.created_at = new Date().valueOf();
    this.updated_at = new Date().valueOf();
  }

  async save() {
    const db = await this.getDb();

    if (db) {
      try {
        const data = await db.insertOne({
          title: this.title,
          slug: this.slug,
          skillRate: this.rate,
          created_at: this.created_at,
          updated_at: this.updated_at,
        });

        return data.acknowledged;
      } catch (err) {
        throw err;
      }
    }
  }

  async all() {
    const db = await this.getDb();
    if (db) {
      try {
        const data = await db.find({}).toArray();
        return data;
      } catch (err) {
        console.log("Skill model", err);
        throw err;
      }
    } else {
      throw new Error("db notfound");
    }
  }

  async getOne() {
    const db = await this.getDb();

    if (db) {
      try {
        const data = await db.findOne({ _id: ObjectId(this._id) });

        return data;
      } catch (err) {
        throw err;
      }
    }
  }

  async update() {
    const db = await this.getDb();

    if (db) {
      try {
        const data = await db.updateOne(
          { _id: ObjectId(this._id) },
          {
            $set: {
              title: this.title,
              slug: this.slug,
              skillRate: this.rate,
              updated_at: this.updated_at,
            },
          }
        );

        return data;
      } catch (err) {
        throw err;
      }
    }
  }

  async getDeleteOne() {
    const db = await this.getDb();

    if (db) {
      try {
        const result = await db.deleteOne({ _id: ObjectId(this._id) });

        const data = await db.find({}).toArray();

        return data;
      } catch (err) {
        throw err;
      }
    }
  }
}

export default Skills;

I call Skill class from api/test.js route folder:
test api code:
    import slugMaker from "../../../../helpers/slug-maker";
import Skills from "../../../../models/skills";

export default async function handler(req, res) {
  const { id } = req.query;
  if (req.method === "GET") {
    const skill = new Skills();
    skill._id = id;
    try {
      const data = await skill.getOne();

      return res.status(200).json({ message: "fetch successful.", data });
    } catch (err) {
      console.log("find", err);
    }
  } else if (req.method === "POST") {
    const { title, skillRate } = req.body;

    const slug = slugMaker(title);

    const skill = new Skills();
    skill._id = id;
    skill.title = title;
    skill.slug = slug;
    skill.rate = skillRate;

    try {
      const result = await skill.update();

      return res
        .status(201)
        .json({ message: "تغییرات با موفقیت اعمال شد.", result });
    } catch (err) {
      console.log(err);
      throw err;
    }
  } else {
    return res
      .status(405)
      .json({ message: "Only POST or GET request supported for this route." });
  }
}

I noticed for every request I made a new connection and get limited by MongoDB, I need to create one connection for every user visiting the site and keep it until he/she leaves the site.
is that possible, and how do I do this?


text:
Q: How to do Image clipping by using SVG shapes? Anyone could guide me with how to do CSS Image Clip path with SVG unique shapes?
Some people were suggesting to a third-party plugin like SVG Injector and all. Anyone could help me how to achieve this task that will work in all the browsers?
I have given one example image to make it better understanding. Kindly check the below image.

http://ktdev.khaleejtimes.ae/shape.jpg
Thanks & Appreciated.

A: First you need to draw a path with the desired shape. Next you use the shape to clip the image using <clipPath>

svg{border:1px solid}
<svg viewBox="0 0 643 525">

  <defs>
    <clipPath id="shape">
      <path fill="none" d="M109,120c0,0,163,46,220,9s34-97,34-97s39.138-16.341,70-11c26.406,4.57,66.618,73.939,105,138
 c37.199,62.089,73,119,73,119s10.398,18.504,0,44c-8.608,21.105-22.685,41.421-88.85,85.03C468.32,442.51,411,474,411,474
 s-85,45-192,9l-5,1c0,0-34.254,15.226-60.675,10.088c-36-7-48.249-32.676-48.249-32.676S172,402,160,327S60,220,60,220
 s-8.444-34,0-52C77.666,130.345,109,120,109,120z"/>
    </clipPath>

  </defs>
<image width="643" height="643" clip-path="url(#shape)"  xlink:href="https://s3-us-west-2.amazonaws.com/s.cdpn.io/222579/beagle400.jpg" >
</image>

</svg>


text:
Q: Rails 4 how to keep form data upon redirect I have a view, where I list data, and allow users to create new records (on a partial). The problem is, the form lives under the index action, so I lose the form's data if the user input is invalid upon redirect.
I want to keep the data, so the user doesn't have to type it all over again.
Controller:
def index
    @instance = Instance.new
end

def create
    w = current_user.workspaces.find_by_id(params[:"..."]
 if w.present?
  @instance =  current_user.workspaces.find_by_id( [:"..."]).instances.create(...)
  [:info] = "Please check your email to activate your account."
      redirect_to root_url
    else
      flash[:info] = "Please check your data"
      redirect_to root_url
    end

end

index.html.haml
= render :partial => 'partial1'

partial1.html.haml
= form_for @instance , url: {action: "create"}  do |f|

I know that 'render' keeps the form's data, but doing:
def create
    if something
       ...
    else
       flash[:info] = "Please check your data"
       render :index
    end

end

I get the error

First argument in form cannot contain nil or be empty
= form_for @instance , url: {action: "create"}  do |f|

How can I fix it?
I don't want to initialize @instance on the create action, like this
def create
 ...
 flash[:info] = "Please check your data"
 @instance = Instance.create
 render :index

because I would be repeating code, which is already written on the index action.

to wrap it up:
I have a complex index view which has a form partial, with a complex controller.
I Can't render :index on the create action, because I would have to load all the index's instances variables.
I can't create an @instance variable if the data is incorrect, since I have a nested form.

A:
I don't want to initialize @instance on the create action...

Well, you should, since you want an instance. However, you should 'initialize' one with the parameters that were filled in the form, not 'create' one. So do something like:
def create
 ...
 flash[:info] = "Please check your data"
 @instance = Instance.new(params[:instance])
 render :index


text:
Q: Why is this create table/ insert query not working in SQLite/Android? Create table or the Insert query is not working!
public class dbHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "AppointmentsDB";
private static final String TABLE_APPOINTMENTS = "tblAppointments";
private static final String COLUMN_DATE = "dateofapp";
private static final String COLUMN_NAME = "appointment";
private static final String COLUMN_LOCATION = "location";
private static final String COLUMN_Priority = "priority";
private static final String COLUMN_STATUS = "status";

public dbHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
    super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    String sql = "CREATE TABLE " + TABLE_APPOINTMENTS + "(" + COLUMN_DATE + " TEXT, "
            + COLUMN_NAME + " TEXT,"
            + COLUMN_LOCATION + " TEXT," +
            COLUMN_Priority + " TEXT," +
            COLUMN_STATUS + " TEXT);";

    db.execSQL(sql);
}

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

//add new row
public void addAppointment(Appointments appointment) {
    ContentValues values = new ContentValues();
    values.put(COLUMN_DATE, appointment.getDate());
    values.put(COLUMN_NAME, appointment.getName());
    values.put(COLUMN_LOCATION, appointment.getLocation());
    values.put(COLUMN_Priority, appointment.getPriority());
    values.put(COLUMN_STATUS, appointment.getStatus());
    SQLiteDatabase db = getWritableDatabase();
    db.insert(TABLE_APPOINTMENTS, null, values);
    db.close();
}

//delete
public void deleteAppointment(String appName) {
    SQLiteDatabase db = getWritableDatabase();
    db.execSQL("DELETE FROM" + TABLE_APPOINTMENTS + "WHERE" + COLUMN_NAME + "=\"" + appName + "=\";");
}

//display
public String databaseToString() {

    String dbString = "";
    SQLiteDatabase db = getWritableDatabase();
    String sql = "SELECT * FROM " +TABLE_APPOINTMENTS+ "WHERE 1";

    Cursor c = db.rawQuery(sql,null);
    c.moveToFirst();
    while(!c.isAfterLast()){
        if(c.getString(c.getColumnIndex("appointment"))!= null){
            dbString += c.getString(c.getColumnIndex("appointment"));
            dbString += "\n";
        }
    }

    db.close();

    return dbString;
}

public Cursor getAllData (){
    SQLiteDatabase db = getWritableDatabase();
    Cursor res = db.rawQuery("SELECT * FROM " + TABLE_APPOINTMENTS,null);
    return res;
}

}
Error says there is no column for date. But when i test it with some other string it gives some other column is missing so i'm guessing the table is not getting created

12-08 00:28:37.443 1436-1436/com.example.user.testerapp
  E/SQLiteLog: (1) table tblAppointments has no column named priority
  12-08 00:28:37.445 1436-1436/com.example.nadeeshherath.singervistalife E/SQLiteDatabase: Error inserting priority=android.widget.EditText{304f0d2f VFED..CL ........ 0,372-600,496 #7f0c005e app:id/priText} dateofapp=android.widget.EditText{45cf210 VFED..CL ........ 0,0-630,124 #7f0c005c app:id/dateText} status=android.widget.EditText{9071f3c VFED..CL ........ 0,496-600,620 #7f0c005f app:id/statusText} location=android.widget.EditText{15b8ff0e VFED..CL ........ 0,248-1350,372 #7f0c005d app:id/locText} appointment=android.widget.EditText{35b42109 VFED..CL .F...... 0,124-1350,248 #7f0c005b app:id/appText}
                                                                                android.database.sqlite.SQLiteException: table tblAppointments has no column named priority (code 1): , while compiling: INSERT INTO tblAppointments(priority,dateofapp,status,location,appointment) VALUES (?,?,?,?,?)
                                                                                at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
                                                                                at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
                                                                                at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
                                                                                at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
                                                                                at android.database.sqlite.SQLiteProgram.(SQLiteProgram.java:58)
                                                                                at android.database.sqlite.SQLiteStatement.(SQLiteStatement.java:31)
                                                                                at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1469)
                                                                                at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
                                                                                at com.example.user.testerapp.dbHandler.addAppointment(dbHandler.java:52)
                                                                                at com.example.user.tester.events_activity.addDataButtonClick(events_activity.java:117)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at android.view.View$1.onClick(View.java:4002)
                                                                                at android.view.View.performClick(View.java:4756)
                                                                                at android.view.View$PerformClick.run(View.java:19749)
                                                                                at android.os.Handler.handleCallback(Handler.java:739)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5221)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)


text:
Q: How to assign the multiple users to a Custom object?(in Salesforce) I made a custom object called Job Requisition that has records I would like to be able to assign to only Recruiter profile Users so they could view their access. I created a lookup from this object to the user. Is there a way to assign multiple users to this record other than Public groups?

A: I happened across your question while looking of ran answer to a similar issue I'm having. The best answer I've been able to find is apparently a junction object.
The best description I've found, and I've found lots of descriptions, is at the link below.
https://salesforce.stackexchange.com/questions/252144/allow-a-custom-field-to-select-multiple-users-in-salesforce-lightning


text:
Q: Trim function before validating form input in Codeigniter 4 With Codeigniter 3 it was possible to use "trim" as a validation rule.
It seems it is no more possible with Codeigniter 4.
Then how can I trim input values before validating, in case the user left whitespaces at the beginning or the end of the input?
$validation->setRule('username', 'Username', 'trim|required|min_length[3]');

I thought using a custom rule but these functions can only return true or false. They can't modify the input. The other solution is using the php trim function but I can't see where to use it.
Thanks for your help!

A: I'm guessing you're validating the post request directly. For what you need I would validate your modified array instead of the post request directly.
One of the great things in codeigniter 4 validation is that your can actually validate anything. Unlike codeigniter 3 where you could only use it to validate the $_POST data.
Let's say you have two fields, username and password and want to trim the username.
In you controller that would get the post date you would do the following.
$validation =  \Config\Services::validation();
$validation->setRules([
   'username' => 'required',
   'password' => 'required|min_length[10]'
]);

$data = $this->request->getPost();
$data['username'] = trim($data['username']);

if (!$validation->run($data)) {
    // handle validation errors
}

If you're doing the validation in the model, I'm not sure if the validation is run before the callbacks but its worth a try. So You would define a function in your beforeInsert callback and handle the trim there.
More about callbacks here:
https://codeigniter.com/user_guide/models/model.html#specifying-callbacks-to-run
If that does not work you can even remove the username from your validation rules in your model and then in a beforeFind and beforeUpdate function validate the username yourself and trim it.

A: I had the exact same question. For me, it makes sense to trim most POST variables before any validation. Even some of the common validation rules are best executed with already-trimmed values.
As @micthi stated, CodeIgniter 3 offered an easy way to trim just before validation. CodeIgniter 4 makes it much less straightforward. A custom validation rule can't modify data for us, and the model event methods such as beforeInsert and beforeUpdate also don't help us in running callbacks as they all execute after validation.
Below is a CodeIgniter 4 solution that works to allow trimming of POST variables before any validation. In brief, a filter is created and then configured to run before any controller code is executed for any POST method. It loops thru the $request object to trim the POST variables and then allows the newly-trimmed version if the $request to proceed to the controller.
Create: app/Filters/TrimFilter.php
namespace App\Filters;

use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Filters\FilterInterface;

class TrimFilter implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null) {

        $trimmed_post = [];

        foreach($request->getPost() as $var => $val) {
            $trimmed_post[$var] = trim($val);
        }

        $request->setGlobal('post', $trimmed_post);
    }
}

Modify: app/Config/Filters.php
// Add to the use statements
use App\Filters\TrimFilter;

// Add to the $aliases array
public $aliases = [
    'trim' => TrimFilter::class
];

// Add to the $methods array
public $methods = [
    'post' => ['trim']
];

ANOTHER OPTION: Instead of using the filter approach, you could instead perform the trimming loop within the BaseController.php file. In this case, remember to use $this-> to reference the request while within the BaseController.


text:
Q: List columns with sqoop I have found the following commands very usefull to see what my source database looks like:
sqoop-list-databases
sqoop-list-tables

However, there does not appear to be a command to list the columns in a table, which would be a logical step.
My question is now:
How can I get the list of columns from a table via Sqoop?

A: Unfortunately there is no command like sqoop-list-columns, however with some creativity there is a workaround:
Run an import, and import the fieldnames.
Here is an example, for how this can be done when connecting to a SQL Server database:
sqoop import --m 1 --connect 'jdbc:sqlserver://nameofmyserver; database=nameofmydatabase; username=dennisjaheruddin; password=mypassword' --query "SELECT column_name, DATA_TYPE FROM INFORMATION_SCHEMA.Columns WHERE table_name='mytableofinterest' AND \$CONDITIONS" --target-dir 'mytableofinterest_column_name'

This will retreive the column names and write them to a file, which you can then inspect manually.
Of course this can be expanded to get other metadata (e.g. field types).
Note that you will need a slightly different SELECT statement if you are connecting to a different database type, but that should be easy to find.

A: Use "Describe DB_name.table_name" in sqoop eval.
sqoop eval --connect Connection_string --username username --password password --query "describe DB_Name.Table_Name"

A: If you just want to know the column names for some source table, Below is the easiest way to deal
SQOOP EVAL
Below is the example for pulling the column names from oracle database, its the same for all the RDBMS
sqoop eval -libjars /var/lib/sqoop/ojdbc6.jar --connect jdbc:oracle:thin:@hostname:portnumber/servicename --username user -password password --query "select *  from schemaname.tablename where rownum=10"
This will print the schema on the terminal. in the query section you can run any query that you want to run on the rdbms.
Lets say you want to store the output, just append it to a file as below.
sqoop eval -libjars /var/lib/sqoop/ojdbc6.jar --connect jdbc:oracle:thin:@hostname:portnumber/servicename --username user -password password --query "select *  from schemaname.tablename where rownum=10" >> sqoop_results.txt

A: use the below command in sqoop eval query:
"describe database_name.table_name"
This command worked for me :
sqoop eval --connect jdbc:mysql://localhost/database_name --username root -P --query "describe database_name.table_name"
The command output will be as below :
[cloudera@localhost ~]$ sqoop eval --connect jdbc:mysql://localhost/mytestdb --username root -P --query "describe mytestdb.CustomersNew3"
17/01/26 22:13:08 INFO sqoop.Sqoop: Running Sqoop version: 1.4.3-cdh4.7.0
Enter password:
17/01/26 22:13:12 INFO manager.MySQLManager: Preparing to use a MySQL streaming resultset.
| COLUMN_NAME          | COLUMN_TYPE          | IS_NULLABLE | COLUMN_KEY | COLUMN_DEFAULT       | EXTRA                |
| ID                   | int(11)              | NO  |     | (null)               |                      |
| NAME                 | varchar(20)          | NO  |     | (null)               |                      |
| AGE                  | int(11)              | NO  |     | (null)               |                      |
| ADDRESS              | char(25)             | YES |     | (null)               |                      |
| SALARY               | decimal(18,2)        | YES |     | (null)               |                      |

A: You can leverage sqoop eval command for this purposes.
Example in Netezza:
sqoop eval --connect 'jdbc:netezza://host:port/db' --username 'your_user' --password 'your_pass' --query "SELECT column_name, DATA_TYPE FROM INFORMATION_SCHEMA.Columns WHERE table_name='your_table'"

This will output result to console:
-----------------------------------------------
| column_name          | data_type            |
-----------------------------------------------
| col1                 | bigint               |
| col2                 | bigint               |
| col3                 | bigint               |
| col4                 | integer              |


text:
Q: Show that $x=2\ln(3x-2)$ can be written as $x=\frac{1}{3}(e^{x/2}+2)$
Show that $x=2\ln(3x-2)$ can be written as $x=\dfrac{1}{3}(e^{x/2}+2)$.

Is there a rule for this?

A: Solve for the "other" $x$. Notice that:
$$ \begin{align*}
x &= 2\ln(3x-2) \\
\dfrac{x}{2} &= \ln(3x-2) \\
e^{x/2} &= 3x-2 \\
e^{x/2}+2 &= 3x \\
\dfrac{1}{3}(e^{x/2}+2) &= x \\
\end {align*} $$
as desired.

A: It's just the relationship between logs and exponents. Starting with $x=2\ln(3x-2)$, divide both sides by $2$ to get
$$\frac{x}2=\ln(3x-2)\;.$$
Now exponentiate on both sides:
$$e^{\frac{x}2}=e^{\ln(3x-2)}=3x-2\;,$$
because by definition $e^{\ln u}=u$ for all $u>0$. Finally, add $2$ to both sides to get
$$e^{\frac{x}2}+2=3x\;,$$
and multiply both sides by $\frac13$, and you're done.

A: exponential function is injective, so $x = y$ iff $e^x = e^y$. use this fact and then some elementary symbol manipulations should give you the desired result (if it's true of course)


text:
Q: Problem with Protext Setup I downloaded ProText.exe, and was about to start Setup according to protext-install-en.pdf. But an error popped up. And in Setup.exe, it says this.
Traceback (most recent call last):
  File "protext-setup.py", line 298, in <module>
  File "protext-setup.py", line 97, in __init__
  File "wx\_controls.pyc", line 494, in __init__
UnicodeDecodeError: 'cp949' codec can't decode bytes in position 4-5: illegal multibyte sequence

What does this mean? What should I do?


text:
Q: How to "inherit static fields" in different OOP languages? Short question
As I know, most OOP languages do not enable to inherit static fields. (C++, Java, C#)
 On the other hand, OOP says that you shouldn't duplicate code.

*

*Is there a common way in OOP languages, that makes something like "static field inheritance"?

*Do you know an easier, language-specific unique way to solve the problem?

*Are there languages which have that "integrated"? (I mean like a keyword.)

(Anyway, I know the basic intent of the static fields, I just want to go deeper and avoid any duplication.)
My concrete problem
I want to make a framework (C# or Java), and make it the easier way to expand. Therefore I want the constrains and informations about inherited classes to put in a base class as soon as possible.

I know, that each inherited class must have an own static field. (I want to make an object counter per subclass.)
Therefore it seems logical to make something like "static field inheritance" - where the static field is needed for the subclasses, not for the base class.
I've seen some tricky solutions (for example: in C#, used generics in C# abstract class static field inheritance) , but i can't believe there is no easier way.
If there is no easier way, please explain me how should I find out to use generics? How should I look on generics in this context? What kinds of problems should i associate with them?
(In school we learned it only "to avoid code duplicating", the static field detachment was not emphasizing! It seems to me in this context, that generics are classes and instanties at the same time, but i have not found any understandable, logic approach for that yet.)

A: @Pezo,  you are misunderstanding both static fields and generics.
Static fields are not inheritable because they are accessible without an instance, and utilizing the concept of inheritance only applies to objects, not to classes.
Unless you have an instance of a class derived from a given base class, you cannot use an inherited [non-static] field from that base class.  But you can ALWAYS use a static field, from ANY class, whether you have an instance of it or not, or an instance of anything else for that matter.  They are accessible by every instance of the class, as well as accessible without any instance of any class.
As to Generics, Generics and static fields are different topics that have very little in common.  Generics allow you to write a definition or a pattern for a class (or a method) that is not type specific, so that later, you can use it to create an actual concrete class by specifying the type you want it to use.  It can contain static and non-static fields and properties and methods the same as a on-generic can.

A: You are trying to misuse a simple mechanism (static fields) for something much more complicated. Don't do it. It seems you fixed yourself to the idea of using static fields to hold some singleton-like information for each of your descendant classes while unifying access to it somehow, but that's a completely wrong approach.
Forget static fields, and build a separate facility to hold the information you need for each class. It can essentially be a Dictionary<Type, Something> static field somewhere, or something a lot more complicated. Depends largely on your use case. You will then see that you won't repeat yourself, and gain a lot more good features.
You should also read something about Inversion of Control and Dependency Injection. It may be that what you are trying to achieve was already successfuly solved by many IoC frameworks (like Ninject or Structure Map to name just a few).
Side note: Consider finding a suitable framework instead of building your own.

A:
Is there a common way in OOP languages, that makes something like
  "static field inheritance"?

No.


text:
Q: PyCharm coverage only measures test directory for a GAE app with Selenium tests I'm developing a GAE app in Python using the PyCharm IDE. I have developed an initial set of Selenium WebDriver unit tests, which are in directory "test", with "test" at the top level of the project directory. Note that my tests do not directly call the GAE modules. They only utilize Selenium, which in turn runs the app thru a browser.
When I use menu option "Run 'Unittests in test' with coverage", I get a report showing coverage within directory "test", and also the colors show up in the left margin for the Python modules in "test". The information looks accurate. Very cool!
However, the rest of the files in my project show "not covered", even though the tests exercise a lot of that code via Selenium remote control of a browser.
In settings, I've tried checking "Use bundled coverage.py" and, after running sudo pip install coverage, I've also tried unchecking "Use bundled coverage.py". My results are the same either way.
Is it possible that you simply cannot obtain coverage of a GAE app being exercised via Selenium?


text:
Q: Meaning of given regular expression in javascript Please explain me the meaning of the following regular expression in JavaScript with proper exploration:
/^\b_((?:__|[\s\S])+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/

A: This is the meaning.
/^\b_((?:__|[\s\S])+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/
1st Alternative: ^\b_((?:__|[\s\S])+?)_\b
^ assert position at start of the string
\b assert position at a word boundary (^\w|\w$|\W\w|\w\W)
_ matches the character _ literally
1st Capturing group ((?:__|[\s\S])+?)
(?:__|[\s\S])+? Non-capturing group
Quantifier: +? Between one and unlimited times, as few times as possible, expanding as needed [lazy]
1st Alternative: __
__ matches the characters __ literally
2nd Alternative: [\s\S]
[\s\S] match a single character present in the list below
\s match any white space character [\r\n\t\f ]
\S match any non-white space character [^\r\n\t\f ]
_ matches the character _ literally
\b assert position at a word boundary (^\w|\w$|\W\w|\w\W)
2nd Alternative: ^\*((?:\*\*|[\s\S])+?)\*(?!\*)
^ assert position at start of the string
\* matches the character * literally
2nd Capturing group ((?:\*\*|[\s\S])+?)
(?:\*\*|[\s\S])+? Non-capturing group
Quantifier: +? Between one and unlimited times, as few times as possible, expanding as needed [lazy]
1st Alternative: \*\*
\* matches the character * literally
\* matches the character * literally
2nd Alternative: [\s\S]
[\s\S] match a single character present in the list below
\s match any white space character [\r\n\t\f ]
\S match any non-white space character [^\r\n\t\f ]
\* matches the character * literally
(?!\*) Negative Lookahead - Assert that it is impossible to match the regex below
\* matches the character * literally

Well, in a really nice form:

You can check this out at Regex 101.


text:
Q: WebView как браузер по умолчанию или как открывать ссылки в своём браузере
У меня есть простой браузер. Мне надо чтобы в нём открывались ссылки, как например в Google Chrome. Как это реализовать. Гуглил, нужного ответа не нашёл. Да и в манифесте всё что нужно прописал, но в менюшке он не алё. Помогите пожалуйста, если кто с этим сталкивался. Заранее спасибо
public class BrowserActivity extends AppCompatActivity {

    private SharedPreferences mSharedPreferences;
    private static final String TAG = BrowserActivity.class.getSimpleName();
    private String mCM;
    private ValueCallback<Uri> mUM;
    private ValueCallback<Uri[]> mUMA;
    private final static int FCR=1;
    SwipeRefreshLayout swipeRefreshLayout;
    ProgressBar progressBar;
    EditText inputUrl;
    WebView webView;
    ImageButton forward, back;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent){

        super.onActivityResult(requestCode, resultCode, intent);
        if(Build.VERSION.SDK_INT >= 21){
            Uri[] results = null;

            if(resultCode== Activity.RESULT_OK){
                if(requestCode == FCR){
                    if(null == mUMA){
                        return;
                    }
                    if(intent == null){

                        if(mCM != null){
                            results = new Uri[]{Uri.parse(mCM)};
                        }
                    }else{
                        String dataString = intent.getDataString();
                        if(dataString != null){
                            results = new Uri[]{Uri.parse(dataString)};
                        }
                    }
                }
            }
            mUMA.onReceiveValue(results);
            mUMA = null;
        }else{
            if(requestCode == FCR){
                if(null == mUM) return;
                Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
                mUM.onReceiveValue(result);
                mUM = null;
            }
        }
    }

    @SuppressLint({"SetJavaScriptEnabled", "WrongViewCast"})
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setTheme(ThemeUtils.getCurrentTheme());
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_browser);

        if(Build.VERSION.SDK_INT >=23 && (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)) {
            ActivityCompat.requestPermissions(BrowserActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, 1);
        }

        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        webView = (WebView) findViewById(R.id.webView);
        registerForContextMenu(webView);
        webView.getSettings().setBuiltInZoomControls(false);
        webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        webView.getSettings().setGeolocationDatabasePath(getFilesDir().getPath() );
        mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swiperefresh);
        swipeRefreshLayout.setColorSchemeResources(
            R.color.colorAccent);

        webView.setWebViewClient(new WebKit());

        webView.setWebChromeClient(new WebChromeClient(){
                @Override
                public void onProgressChanged(WebView view, int newProgress) {
                    progressBar.setProgress(newProgress);
                    if(newProgress==100)
                        progressBar.setVisibility(View.GONE);
                    else
                        progressBar.setVisibility(View.VISIBLE);
                }
                @Override
                public void onPermissionRequest(final PermissionRequest request) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        request.grant(request.getResources());
                    }
                }
                @Override
                public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
                    callback.invoke(origin, true, false);
                }
                public boolean onShowFileChooser(
                    WebView webView, ValueCallback<Uri[]> filePathCallback,
                    WebChromeClient.FileChooserParams fileChooserParams){
                    if(mUMA != null){
                        mUMA.onReceiveValue(null);
                    }
                    mUMA = filePathCallback;
                    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    if(takePictureIntent.resolveActivity(BrowserActivity.this.getPackageManager()) != null){
                        File photoFile = null;
                        try{
                            photoFile = createImageFile();
                            takePictureIntent.putExtra("PhotoPath", mCM);
                        }catch(IOException ex){
                            Log.e(TAG, "Image file creation failed", ex);
                        }
                        if(photoFile != null){
                            mCM = "file:" + photoFile.getAbsolutePath();
                            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                        }else{
                            takePictureIntent = null;
                        }
                    }
                    Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
                    contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
                    contentSelectionIntent.setType("*/*");
                    Intent[] intentArray;
                    if(takePictureIntent != null){
                        intentArray = new Intent[]{takePictureIntent};
                    }else{
                        intentArray = new Intent[0];
                    }

                    Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
                    chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
                    chooserIntent.putExtra(Intent.EXTRA_TITLE, R.string.img_chooser);
                    chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
                    startActivityForResult(chooserIntent, FCR);
                    return true;
                }
                public class Callback extends WebViewClient{
                    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl){
                        Toast.makeText(getApplicationContext(), R.string.not_app, Toast.LENGTH_SHORT).show();
                    }
                }

                private File createImageFile() throws IOException{
                    @SuppressLint("SimpleDateFormat") String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
                    String imageFileName = "img_"+timeStamp+"_";
                    File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
                    return File.createTempFile(imageFileName,".jpg",storageDir);
                }
            });

        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    webView.reload();
                }
            });

        webView.setWebViewClient(new WebViewClient() {
                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    if( URLUtil.isNetworkUrl(url) ) {
                        return false;
                    }
                    if (appInstalledOrNot(url)) {
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                        startActivity( intent );
                    } else {

                    }
                    return true;
                }

                private boolean appInstalledOrNot(String uri) {
                    PackageManager pm = getPackageManager();
                    try {
                        pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
                        return true;
                    } catch (PackageManager.NameNotFoundException e) {
                    }

                    return false;
                }

                @Override
                public void onPageFinished(WebView view, String url) {
                    swipeRefreshLayout.setRefreshing(false);
                    super.onPageFinished(view, url);
                }

            });

        WebSettings webset = webView.getSettings();
        webset.setJavaScriptEnabled(true);
        webset.setAllowFileAccess(true);

        if(Build.VERSION.SDK_INT >= 21){
            webset.setMixedContentMode(0);
            webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        }else if(Build.VERSION.SDK_INT >= 19){
            webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        }else if(Build.VERSION.SDK_INT < 19){
            webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        }

        CookieManager.getInstance().setAcceptCookie(false);
        webView = findViewById(R.id.webView);
        Intent intent = getIntent();
        String search_bar = intent.getStringExtra("search_b");
        webView.setBackgroundColor(Color.TRANSPARENT);
        webView.getSettings().setLoadsImagesAutomatically(true);
        webView.clearFormData();
        webView.getSettings().setSavePassword(true);
        webView.getSettings().setSaveFormData(true);
        webView.getSettings().setCacheMode( WebSettings.LOAD_DEFAULT );
        webView.clearCache(false);

        if ( !isNetworkAvailable() ) {
            webView.getSettings().setCacheMode( WebSettings.LOAD_CACHE_ELSE_NETWORK );
        }

        webView.loadUrl("https://duckduckgo.com/?q=" + search_bar);

        webView.setDownloadListener(new DownloadListener() {

                @Override
                public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimeType, long contentLength) {
                    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));

                    request.setMimeType(mimeType);
                    String cookies = CookieManager.getInstance().getCookie(url);
                    request.addRequestHeader("cookie", cookies);
                    request.addRequestHeader("User-Agent", userAgent);
                    request.setDescription("Download file");
                    request.setTitle(URLUtil.guessFileName(url, contentDisposition, mimeType));
                    request.allowScanningByMediaScanner();
                    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(url, contentDisposition, mimeType));
                    DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                    dm.enqueue(request);
                    Toast.makeText(getApplicationContext(), R.string.download_toast, Toast.LENGTH_LONG).show();
                }
            });
    }

    private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService( CONNECTIVITY_SERVICE );
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }

    public void onBackPressed()
    {
        if(webView.canGoBack()){
            webView.goBack();
        }else{
            super.onBackPressed();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        Boolean password = mSharedPreferences.getBoolean(getString(R.string.pass_t), false);
        Boolean cookies = mSharedPreferences.getBoolean(getString(R.string.cookie_t), true);
        Boolean cacheWeb = mSharedPreferences.getBoolean(getString(R.string.cache_t), true);
        Boolean fontLarge = mSharedPreferences.getBoolean(getString(R.string.font_t), false);
        Boolean supportJavaScript = mSharedPreferences.getBoolean(getString(R.string.js_t), true);
        Boolean navButtons = mSharedPreferences.getBoolean(getString(R.string.nav_but_t), false);

        if (password) {
            webView.clearFormData();
            webView.getSettings().setSavePassword(false);
            webView.getSettings().setSaveFormData(false);
        }

        if (cookies) {
        CookieManager.getInstance().setAcceptCookie(true);
        }

        if (cacheWeb) {
            webView.getSettings().setCacheMode( WebSettings.LOAD_NO_CACHE);
            webView.clearHistory();
            webView.clearCache(true);

            if ( !isNetworkAvailable() ) {
                webView.getSettings().setCacheMode( WebSettings.LOAD_NO_CACHE );
            }
        }
        webView.getSettings().setJavaScriptEnabled(supportJavaScript);
        webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(supportJavaScript);

        if (fontLarge) {
            webView.getSettings().setDefaultFontSize(20);
        }

        if (navButtons) {
            showNavButtons();
        } else {
            hideNavButtons();
        }
    }

    void hideNavButtons() {

        ImageButton mWebViewBackButton = (ImageButton) findViewById(R.id.mWebViewBackButton);
        ImageButton mWebViewForwardButton = (ImageButton) findViewById(R.id.mWebViewForwardButton);

        mWebViewBackButton.setVisibility(View.GONE);
        mWebViewForwardButton.setVisibility(View.GONE);

    }

    void showNavButtons() {

        ImageButton mWebViewBackButton = (ImageButton) findViewById(R.id.mWebViewBackButton);
        ImageButton mWebViewForwardButton = (ImageButton) findViewById(R.id.mWebViewForwardButton);

        mWebViewBackButton.setVisibility(View.VISIBLE);
        mWebViewForwardButton.setVisibility(View.VISIBLE);

    }

    public void WebViewGoForward(View view) {

        if (webView.isFocused() && webView.canGoForward()) {
            webView.goForward();
        }

    }

    public void WebViewGoBack(View view) {

        if (webView.isFocused() && webView.canGoBack()) {
            webView.goBack();
        } else {
            super.onBackPressed();
            finish();
        }

    }

}

A: Чтобы открыть ссылку, пришедшую из другого приложения, нужно взять её из интента и отдать в WebView:
String url = getIntent().getDataString();
if (url != null) {
    webView.loadUrl(url); // если есть ссылка - открываем её
} else {
    webView.loadUrl(START_PAGE); // иначе открываем какую-либо стартовую страницу
}

A: Посмотрите статью Александра климова о WebView
http://developer.alexanderklimov.ru/android/mybrowser.php
Надеюсь это вам поможет.


text:
Q: Perform subtraction between two rows of the same group based on a rule via R I have a data frame where I have land use data for the year 2005 and 2018. I would like to generate a new data.frame that shows me the difference between 2005 and 2018 for each column, so that if there was a reduction, the minus sign(-). For example, if in 2005 the variable Veg had 1000 ha and in 2018 it had 8000 ha, the data.frame should indicate -200.
data.frame example:
df

df<-structure(list(place = c("F01", "F01", "F02", "F02", "F03", "F03",
"F04", "F04", "F05", "F05", "F06", "F06"), year = c(2005, 2018,
2005, 2018, 2005, 2018, 2005, 2018, 2005, 2018, 2005, 2018),
    Veg = c(12281.5824712026, 12292.2267477317, 7254.98919713131,
    7488.9138055415, 864.182200710528, 941.602680778032, 549.510775817472,
    584.104674537216, 5577.10195081334, 5688.28474549675, 1244.96456185886,
    1306.41862713264), Agri = c(113.178596532624, 1376.68748390712,
    85.2373706436, 1048.71071335262, 0, 46.236076173504, 0, 46.236076173504,
    85.2373706436, 1002.47463717912, 1.413692976528, 228.851945376768
    ), Past = c(9190.16856517738, 7855.55923692456, 5029.33750161394,
    3776.9718412309, 983.015569149264, 800.981808818688, 710.255983089744,
    572.213021852304, 3726.66100294858, 2700.40306039963, 879.982298683488,
    597.410020198656), Urb = c(146.026168634304, 200.910719487744,
    146.026168634304, 200.910719487744, 141.119822421648, 194.840155529712,
    141.119822421648, 194.840155529712, 4.906346212656, 6.070563958032,
    NA, NA), SoloExp = c(61.12143163224, 67.940421283728, 61.12143163224,
    62.451966198384, 50.144521461552, 54.801392443056, 49.146620536944,
    52.639273773072, 9.895850835696, 7.650573755328, 6.320039189184,
    1.164217745376), Hidro = c(9.230583552624, 7.983207396864,
    9.230583552624, 7.983207396864, NA, NA, NA, NA, 7.401098524176,
    6.320039189184, 5.654771906112, 4.490554160736), total = c(691953.981181971,
    691953.981181971, 691953.981181971, 691953.981181971, 691953.981181971,
    691953.981181971, 691953.981181971, 691953.981181971, 691953.981181971,
    691953.981181971, 691953.981181971, 691953.981181971)), row.names = c(NA,
-12L), class = "data.frame")

I would like to get an output like this

A: Here's a dplyr pipe that is robust to the order of rows (e.g., if 2005 ever occurs after 2018 for whatever reason).
library(dplyr)
library(tidyr) # pivot_*
df %>%
  pivot_longer(-c("place", "year")) %>%
  pivot_wider(c("place", "name"), names_from = "year", values_from = "value") %>%
  mutate(results = coalesce(`2005` - `2018`, 0)) %>%
  transmute(place, name, results = dplyr::coalesce(results, 0)) %>%
  pivot_wider(place, names_from = "name", values_from = "results")
# # A tibble: 6 x 8
#   place    Veg    Agri  Past    Urb SoloExp Hidro total
#   <chr>  <dbl>   <dbl> <dbl>  <dbl>   <dbl> <dbl> <dbl>
# 1 F01    -10.6 -1264.  1335. -54.9    -6.82  1.25     0
# 2 F02   -234.   -963.  1252. -54.9    -1.33  1.25     0
# 3 F03    -77.4   -46.2  182. -53.7    -4.66  0        0
# 4 F04    -34.6   -46.2  138. -53.7    -3.49  0        0
# 5 F05   -111.   -917.  1026.  -1.16    2.25  1.08     0
# 6 F06    -61.5  -227.   283.   0       5.16  1.16     0

A: We could do this by using across function:
library(dplyr)

df %>%
  mutate(across(-c(place, year), ~ lag(., default = .[1]) - .)) %>%
  filter(year==2018) %>%
  select(-year)

  place        Veg        Agri      Past        Urb   SoloExp    Hidro total
1   F01  -10.64428 -1263.50889 1334.6093 -54.884551 -6.818990 1.247376     0
2   F02 -233.92461  -963.47334 1252.3657 -54.884551 -1.330535 1.247376     0
3   F03  -77.42048   -46.23608  182.0338 -53.720333 -4.656871       NA     0
4   F04  -34.59390   -46.23608  138.0430 -53.720333 -3.492653       NA     0
5   F05 -111.18279  -917.23727 1026.2579  -1.164218  2.245277 1.081059     0
6   F06  -61.45407  -227.43825  282.5723         NA  5.155821 1.164218     0


text:
Q: Authenticating different kinds of users in Rails I'm making an app with 3 kinds of users: Teachers, Students and Admins.
Teachers can post Classes, with class info and assignments and stuff, and Students can enroll in those classes and do the assignments, get the materials and stuff. The Admins are just the people involved in running the site and will not be taking any of those actions, but just moderating and keeping an eye on things.
My question is, how do I built the separate authentication for those three cases? The users won't have anything in common and I'm gonna need 3 different logins/sign ups from the get-go, so it's not just a matter of assigning different roles.
How should I go about this?

A: All of those users have one important thing in common - they are all users. I don't see a reason for separating them. If you need users to sign up as a Teacher or Student, you can simply set up different views for those options and the default role that will be assigned to that user.
I don't see a reason why you think that it should be something different than assigning roles. If you really see many differences in data that will be stored for those different types of users, you can for example have have a common Users table and subclass them and store type-specific data in separate tables with reference to the User. However, for now I don't see anything in your description that can force something more than a simple role assigning.


text:
Q: Apache 2.4 & Ubuntu 14.04 error on Vagrant: "You don't have permission to access / on this server." I realize there are a lot of similar questions on here, but I've been struggling with this for hours and have been unable to find a solution.
When I try visiting my Vagrant Ubuntu box via the host name shopwise.dev (set to the Vagrant box's IP in /etc/hosts), I get the following error page:
Forbidden

You don't have permission to access / on this server.

Apache/2.4.7 (Ubuntu) Server at shopwise.dev Port 80

I created the file /etc/apache2/sites-available/shopwise.conf:
ServerName host.foxytronics.com
NameVirtualHost *:80

<Directory />
    Options FollowSymLinks
    AllowOverride All
    Require all granted
</Directory>
<Directory "/home/shopws/public_html">
    Options Indexes FollowSymLinks MultiViews
    AllowOverride All
    Require all granted
</Directory>

<VirtualHost *:80>
    ServerAdmin myemail@gmail.com
    ServerName www.shopwise.dev
    ServerAlias shopwise.dev

    DirectoryIndex index.php
    Options FollowSymLinks
    DocumentRoot "/home/shopws/public_html"

    # Logfiles
    ErrorLog  /home/shopws/logs/apache/error.log
    CustomLog /home/shopws/logs/apache/access.log combined
</VirtualHost>

Then ran:
sudo a2ensite shopwise.conf
service apache2 reload

I verified the directory permissions along the path /home/shopws/public_html are 755 and the file permissions are also currently 755 (although I think they're actually supposed to be 644?).
Is my configuration incorrect?
UPDATE:

A: As usual, my issue was totally my fault and due to my ignorance :-)
I needed to use the Directory directive to grant users permission to access the directory I chose to put my site's files in. This is my final working configuration:
<VirtualHost *:80>
    ServerAdmin myemail@gmail.com
    ServerName www.shopwise.dev
    ServerAlias shopwise.dev

    DocumentRoot /home/shopws/public_html

    # Logfiles
    ErrorLog  /home/shopws/logs/apache/error.log
    CustomLog /home/shopws/logs/apache/access.log combined
</VirtualHost>

<Directory /home/shopws/>
        Options Indexes FollowSymLinks
        AllowOverride None
        Require all granted
</Directory>

I hope that helps someone else someday!

A: By index.something I mean index.html, index.php, etc.
Here is your error file:
 ErrorLog  /home/shopws/logs/apache/error.log
step 1
tail -f /home/shopws/logs/apache/error.log
step 2
hit Refresh or F5 on the browser, you should see something here, if not do the same but with:
tail -f /home/shopws/logs/apache/access.log
And you should also see something here, and paste the last lines here.


text:
Q: Connecting database with C++ Im working on some project now and I need to connect to database on VPS. On VPS I installed phpmyadmin, mysql, apache.
I need code which connect my C++ console application with this database on VPS. I have no idea how to do it.
After connect with database I want to make login script if it changes something.

A: VPS is Virtual Private server and it is used like the normal computer. You can use the code as described in the below link for connecting the PHPmyadmin with C++ application:
 How to connect mySQL database using C++


text:
Q: How to create a new Pyspark column with a subvalue of array of udts objects? I have a column in my pyspark dataframe that has the following structure:
keywords_embedding : [
0:
    vectorType: "dense"
    length: 100
    values: [1,2,3,4,5]
1:
   vectorType: "dense"
    length: 100
    values: [4,5,6,7,8]
.
.
.
]

I need to create a new column that contains only the subvalue array 'values' from each position. I tried the following code:
from pyspark.sql.types import StructType, StructField, StringType, DoubleType

# Define the UDF
def extract_values(obj_array):
  return [obj.values for obj in obj_array]

# Define the return type of the UDF
extract_values_udf = F.udf(extract_values, ArrayType(ArrayType(DoubleType())))

# Extract the values from each object in the array
df_teste = df_teste.withColumn(
  'values_array',
  extract_values_udf(F.col('keywords_embedding'))
)

# View the results
df_teste.display()

But it gives me this error:

PickleException: expected zero arguments for construction of ClassDict
(for numpy.dtype)

I didn't understand why it gives me this error. How can i achieve this result?


text:
Q: Pacman saying no update, but pamac saying there are some? Wanting to try out Arch Linux, I installed Manjaro, and so far find it pretty good.
However, I have a problem, I am used to Debian's apt update then apt upgrade, and the fact pacman combine both with pacman -Syu is awesome.
However, pamac, the GUI for pacman installed by default in XFCE Manjaro, is telling me that there are update to be made:

Is there anything that I just didn't saw in the manual?

A: As Mioriin suggested in the comments - sudo pacman -Syyu will force a sync for pacman's database.
To make sure pamac shows the right updates:
In pamac (GUI) go to menu and choose "Refresh Databases" which will sync the package databases for pamac.
Now you should see that both will offer the same package updates (if there are any).


text:
Q: Best config for my Microsoft Designer Bluetooth keyboard and mouse Problems

*

*Intermittant nature

*The mouse will often hang (won't move)

*The kb will often not type

*Sometimes, the keys get saved up and come out later all at once, and
sometimes they never come out

*The mouse seems to have difficulty travelling to the top left of the
screen. Equipment

*

*ThinkStation P910 Tower,

*Windows 10 Professional operating system,

*microsoft designer keyboard,

*microsoft designer mouse,

both mouse and keyboard are connected via bluetooth dongle.
Troubleshooting Steps Taken
Wired keyboard and wired mouse work great.
Question
What would be a good first choice for a fix I can try that won't hurt anything (update a driver...where?)?

A: Updating the drivers would be among the first steps to try out (start by locating the keyboard, the mouse and the Bluetooth dongle in the Device Manager and clicking on "Update Driver"). Other troubleshooting steps may include:

*

*putting fresh batteries (or fully charging) your wireless devices

*reducing the distance between the dongle and the devices (if this is a USB dongle plugged at the back, use an extension cable to bring it to front)

*disabling WiFi networking (especially if WiFi and BT share the antenna)

*plugging an external antenna if your dongle has a socket for it

*using a different BT dongle

A: What class USB port are they plugged into?
I have had similar issues, with microsoft keyboard and mouse, when the bluetooth dongle reciever, was plugged into a USB 3.0 port. Plugging into 2.0 solved my issue.
Another issue may be distance from the reciever, which casues choppiness due to loss of signal integrity.


text:
Q: Custom shortcut print key I have a keyboard without the > and < keys, which sucks when I try to write code. In windows I could alt+numpad + 60/62 to print those keys, but that doesn't work on linux, so I'm trying to make a custom shortcut for it.
According to https://help.ubuntu.com/stable/ubuntu-help/keyboard-shortcuts-set.html:

The command name that you type should be a valid system command. You can check that the command works by opening a Terminal and typing it in there. The command that opens an application cannot have the same name as the application itself.

So I tried echo "<" and print "<", but without success is there another command that prints a key or am I missing something?

A: If I understand correctly you want to bind some keys to < and > system-wide. The easiest way to accomplish that is with xmodmap program.
For example, on my keyboard < and > are shifted , and ., if you like that try to put
keysym comma = comma less
keysym period = period greater

into a file ~.xmodmaprc and run xmodmap ~/.xmodmaprc
If you want to bind them to something else look out for keysym names in the header file /usr/include/X11/keysymdef.h and as usual man xmodmap is your friend.

A: The xev application can be used for getting the key codes when you press keys.
See also this question: monitoring events (keyboard, mouse) in X


text:
Q: Passing # sharp character to dialing intent The number desired to be called is 232323, but i'm adding #31# to give the user an opportunity to call privately.
if i do this :
  Intent sendIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("tel:" + "232323"));
    startActivity(sendIntent);

It will work, however, if I do this :
   Intent sendIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("tel:" + "#31#232323"));
    startActivity(sendIntent);

It won't.
How can I make it work?

A: Intent sendIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("tel:" + Uri.encode("#31#232323")));


text:
Q: Trying to make pandas python code shorter I'm fairly new to python and pandas. This code does exactly what I want it to do
dfmcomp=dfm.loc[dfm[ProgSel]=='C']
dfmcomp=dfmcomp[~dfmcomp.Code.isin(dfc.CourseCode)]
print(dfmcomp[['Code','Description']])

but I feel I should be able to do this in one line instead of three, and without creating an extra dataframe (dfmcomp). I'm trying to learn how to create better/neater code
I tried this to shorten it to two lines, by replacing dfmcomp in the second line with the code that created dfmcomp. I was hoping from there I could eliminate dfmcomp entirely and just print the sliced dfm, but it didn't work:
dfmcomp=dfm[~dfm.loc[dfm[ProgSel]=='C'].Code.isin(dfc.CourseCode)]
print(dfmcomp[['Code','Description']])

I got this error

IndexingError: Unalignable boolean Series provided as indexer (index of the boolean Series and of the indexed object do not match).

And I am stuck where to go next. Can anyone help? Can this be done better?

A: I think you should be able to do this?
print(dfm.loc[dfm[ProgSel].eq('C') & ~dfc.Code.isin(dfc.CourseCode), ['Code','Description']]

A: Separating the condition into a mask might help:
mask = (dfm[ProgSel]=='C') & (~dfm.Code.isin(dfc.CourseCode))
print(dfm.loc[mask, ['Code','Description']])

A: dfmcomp = dfm[(dfm.ProgSel == 'C') & (~dfm.Code.isin(dfc.CourseCode))][['Code', 'Description']]

print(dfmcomp)


text:
Q: The specificity of first-line and first-child in CSS? I have the following html code:
<!DOCTYPE html>

asdasdasdsad
sdfsdfs

The output is:
asdasdasdasd  <- red
sdfsdfs <- blue.
However, what I am thinking is that the p tag is the first child of body. first-child is a pseudo-class, which has a specificity of 10 and first-line is a pseudo-element, which has a specificity of 1. Therefore, both lines should be displayed as blue text, but I am apparently wrong.
Please point out my mistake. Thank you very much.

A: The :first-line selector applies directly to the first line, while the :first-child selector is inherited from the element that it applies to.
A style that applies directly to the item takes precedence over inherited styles.
You can make the selector for the element more specific, by for example adding elements, id and class selectors, but it still can't take precedence over the style applied to the first line. Demo: http://jsfiddle.net/Guffa/3H4Ab/

A: I think when you use
, sdfsdfs goes to a new line so it won't be the first line, but it will still be the first child of body tag and it will be blue. Also as you specified the color of the first line it will be red, as obvious. (Just trying to reason)

A:
p tag is the first child of body. first-child is a pseudo-class, which has a specificity of 10 and first-line is a pseudo-element, which has a specificity of 1.

Well, no. first-line is inheriting the style and adds 1 pseudo-element inside the pseudo-class(10 1), so it's absolutely normal.

A: I just read that

In CSS 3, you need to differentiate pseudo-elements from
  pseudo-classes by using a double colon (::) at the beginning of the
  element.

on http://css-tricks.com/specifics-on-css-specificity/


text:
Q: New Google Action with date/time comparison I need your help!
I have to write a new Action for Google Assistant. If you ask Google the same question in different hours of the day, Google have to reply with different phrases.
Which is the better way for develop this project?
Thank you very much!


text:
Q: Detect string contains a number then insert a space before it Consider I have such String "Abcd123", I need to first detect if my string contains numbers (0-9) or not, then insert a space before the first number so my final String is "Abcd 123"

A: You can use :
String str = "Abcd123";
if (str.replaceAll("\\D", "").length() > 0) {  // check if the string contain numbers
    str = str.replaceFirst("\\d", " $0");      // if yes put a space before the first degit
}

Output
Abcd 123

A: You could use this simple logic :
    String str = "Abcd123";
    String newStr = "";

    for (int i = 0; i < str.length(); i++) {
        if (Character.isDigit(str.charAt(i))){
            newStr = newStr + " " + str.substring(i);
            break;
        } else {
            newStr = newStr + str.charAt(i);
        }
    }
    System.out.println(newStr);

Here we iterate over each character in the string and break from the loop as soon as we find the first digit.
Output :

Abcd 123


text:
Q: Obtain scaled predictor values when using `lm` in R I'm using lm in R to do simple multilinear regression. Here's an example model:
m <- lm(formula = t ~ a + b + 0, data = df1)

where t, a and b are columns in df1. This model calculates 2 coefficients, let's call them a.coef and b.coef. If I then use this model to predict some other data, say in df2, I can get the predicted values like so:
predict(m, df2)

if I have the columns a and b in df2 as well. It essentially returns
df2$a * a.coef + df2$b * b.coef

What I'd like, however, are the columns df2$a * a.coef and df2$b * b.coef. R sums them and gives me the answer, but I'd like to see how the scaling affects these values.
Is there a convenient way to do this in R (esp in lm or predict.lm), or will I have to manually code this myself? I played with the terms argument in predict.lm, but I couldn't get anywhere.
Thanks for the help!
EDIT
I wrote this function:
scaled.fn <- function(dt, x, y, i) {
    # dt is data.table
    # x is dependent column (col name as str)
    # y are predictor columns (col names as vector of str)
    # i is name of column to multiply, as str

    dep = paste(y, collapse = " + ")
    my.formula = paste(x, " ~ ", dep, sep = "")

    m = lm(formula = my.formula, data = dt)

    # column names in dt are named in y
    return(dt[, get(i) * coef(m)[i]])
}

A: Try this:
sweep(df2, MARGIN = 2, coef(m), '*')

EDIT: more specific solution:
sweep(df2[,c("a","b")], MARGIN = 2, coef(m), '*')


text:
Q: Is it possible to look for element by it's CSS using text contains? Couldn't find the answer. As normal xpath has Contains(text(), 'text'), I cannot obtain the same within css selector.
By.CSS_SELECTOR, "div.class::contains('text')"

Is there any other way to do it  ?

A: You may want to look into sub-string matches here
So for your example, you'd be doing something like
div[class*='text']


text:
Q: The differences between "make a living" and "earn a living" Who can say the differences between them?

A: For all intents and purposes, make a living and earn a living are identical in meaning. There is a very slight difference in register, in that make is a teeny-tiny bit more informal than earn, but it's such a small difference that it can be ignored in most situations. There's also an almost-infinitesimal difference in connotation: using "make" rather than "earn" can imply that you're not working "in your field". For example, if someone with a degree in art history had a job at a museum, they'd be more likely to call it "earning a living", whereas if the same art history graduate had a job at Walmart, they'd be more likely to call it "making a living".1
1Well, OK, if they're really working at Walmart they'd actually be more likely to call it "just barely scraping by", but that's a different subject.

A: They mean the same thing but earn a living specifies how the action happens.


text:
Q: Taking too long in navigating from one page to another in Smartface App Studio It's taking too long time to show up an page from another. I kept only value bindings to the controls which are pre-dedigned.
Can any one please help me in increasing the performance of navigating between the pages.
Thanks in advance.

A: Loading images or design elemets(like map) takes a lots of time before loading page. I am trying to call empty page first and by timer start to load design elements it become not more fast but at least you don't wait until create the page  . Also I use page.reset() method after i left the page it helps in some cases to reload the same pages performance. In all cases don't expect the performance of native app.


text:
Q: How to adapt my current splash screen to allow other pieces of my code to run in the background? Currently I have a splash screen in place. However, it does not work as a real splash screen - as it halts the execution of the rest of the code (instead of allowing them to run in the background).
This  is the current (reduced) arquitecture of my program, with the important bits displayed in full. How can I adapt the splash screen currently in place to actually allow the rest of the program to load in the background? Is it possible in python?
Thanks!
import ...
(many other imports)
def ...
def ...
(many other definitions)

class VFrams(wxFrame):
    wx.Frame.__init__(self, parent, -1, _("Software"),
                      size=(1024, 768), style=wx.DEFAULT_FRAME_STYLE)
    (a lot of code goes in here)

class MySplashScreen(wx.SplashScreen):
    def __init__(self, parent=None):
        aBitmap = wx.Image(name=VarFiles["img_splash"]).ConvertToBitmap()
        splashStyle = wx.SPLASH_CENTRE_ON_SCREEN | wx.SPLASH_TIMEOUT
        splashDuration = 5000 # ms
        wx.SplashScreen.__init__(self, aBitmap, splashStyle, splashDuration, parent)
        self.Bind(wx.EVT_CLOSE, self.CloseSplash)
        wx.Yield()
    def CloseSplash(self, evt):
        self.Hide()
        global frame
        frame = VFrame(parent=None)
        app.SetTopWindow(frame)
        frame.Show(True)
        evt.Skip()

class MyApp(wx.App):
    def OnInit(self):
        MySplash = MySplashScreen()
        MySplash.Show()
        return True

if __name__ == '__main__':
    DEBUG = viz.addText('DEBUG:', viz.SCREEN)
    DEBUG.setPosition(0, 0)
    DEBUG.fontSize(16)
    DEBUG.color(viz.BLACK)
    Start_Mainvars()
    Start_Config()
    Start_Translation()
    Start_DB()
    Start_Themes()
    Start_Gui()
    Start_Get_Isos()
    Start_Bars()
    Start_Menus()
    Start_Event_Handlers()
    app = MyApp()
    app.MainLoop()

Thank you for all the help, this is how I changed the code (following the provided advice):
def show_splash():
    # create, show and return the splash screen
    global splash
    bitmap = wx.Image(name=VarFiles["img_splash"]).ConvertToBitmap()
    splash = wx.SplashScreen(bitmap, wx.SPLASH_CENTRE_ON_SCREEN|wx.SPLASH_NO_TIMEOUT, 0, None, -1)
    splash.Show()
    return splash

class MyApp(wx.App):
    def OnInit(self):
        global frame, splash
        splash = show_splash()
        Start_Config()
        Start_Translation()
        Start_DB()
        Start_Themes()
        Start_Gui()
        Start_Get_Isos()
        Start_Bars("GDP1POP1_20091224_gdp", "1 pork")
        Start_Menus()
        Start_Event_Handlers()
        frame = VFrame(parent=None)
        frame.Show(True)
        splash.Destroy()
        return True

if __name__ == '__main__':
    DEBUG = viz.addText('DEBUG:', viz.SCREEN)
    DEBUG.setPosition(0, 0)
    DEBUG.fontSize(16)
    DEBUG.color(viz.BLACK)
    Start_Mainvars()
    app = MyApp()
    app.MainLoop()

A: Your code is pretty messy/complicated.  There's no need to override wx.SplashScreen and no reason your splash screen close event should be creating the main application window.  Here's how I do splash screens.
import wx

def show_splash():
    # create, show and return the splash screen
    bitmap = wx.Bitmap('images/splash.png')
    splash = wx.SplashScreen(bitmap, wx.SPLASH_CENTRE_ON_SCREEN|wx.SPLASH_NO_TIMEOUT, 0, None, -1)
    splash.Show()
    return splash

def main():
    app = wx.PySimpleApp()
    splash = show_splash()

    # do processing/initialization here and create main window
    frame = MyFrame(...)
    frame.Show()

    splash.Destroy()
    app.MainLoop()

if __name__ == '__main__':
    main()

Just create the splash screen as soon as possible with no timeout.  Continue loading and create your application's main window.  Then destroy the splash screen so it goes away.  Showing the splash screen doesn't stop other processing from happening.

A: You'll want to use two threads: one for the splash screen, one for whatever other code you want to execute. Both threads would run at the same time, providing the result you desire.


text:
Q: Font-Awesome - icon-spin does not spin when hidden and then displayed When my page loads, I hide the icon-refresh + icon-spin icon by setting its display property to none.
Now, after some action is performed, I wish to display this icon. I invoke jQuery's .show() method on the icon. However, while the icon is shown, the icon is not spinning anymore.
If I load it without hiding it initially, it spins. But not when it is hidden and displayed later.
EDIT: If it was not clear from the title, I am using Font Awesome to display the icons

A: You have to use $element.css("display","inline-block"); instead of .show();

A: Old topic, but I had similar issue with "fa-spin" not working after the containing element was hidden with { visibility: hidden }, set with jQuery. There was also some other animation involve, which was probably causing timing issues, etc.
The fix was to set an event on the containing element to fire on making it visible again, which fired this function:
ply_obj.container.on(
            'controlsshown',
            function () {

                if (ply_obj.config.loop_tf) {
                    ply_obj.loop_icon.removeClass('fa-spin');
                    setTimeout(function () { ply_obj.loop_icon.addClass('fa-spin'); }, 100);
                }
            }
        );

So removing the "fa-spin", then adding it back with a small delay made it work as desired for me.

A: Are you calling "$('#mySpinnerElement').hide()?
I changed that to document.getElementById('mySpinnerElement').style.display = 'none';
and my spinner spins on subsequent calls
HTH
Swampy

A: Seems that IE10 does not run the spin animation if the initial display state is none. I found that dynamically changing the display to inline-block did not trigger the spin animation. Moving the spinner off-screen solved the problem. E.g:
.icon-spinner {
    position: absolute;
    left: -9999px;
}
.is-pending .icon-spinner {
    left: 0;
}


text:
Q: Find and sort in O(n) the log2(n) smallest values and the log2(n) largest values in an array of n values Let A be an array of n different numbers (positive & negative).
We are interested in the ⌊log_2(n)⌋ smallest values,
and in the ⌊log_2(n)⌋ largest values.
Find algorithm which calculates this 2⌊log_2(n)⌋ values,
and presents them in a sorted array (size = 2⌊log_2(n)⌋)
1. the running time of the algorithm must be θ(n),
2. prove that the running time is θ(n).

I thought maybe heap sort can be useful, but I'm really not sure.
I don't need a code just the idea... I would appreciate any help
Thanks :) and sorry if I have English mistakes :(

A: My general approach would be to to create 2 heap data structures, one for the max and one for the min, and heapify the array for/in in both of them. Heapifying is an operation of linear time complexity if done right.
Then I would extract ⌊log_2(n)⌋ items from both heaps where each extraction is of complexity O(log n). So, this would give us the following rough estimation of calculations:
2 * n + 2 * (log(n))^2

2 * n for two heapifying operations.
log(n) * log(n) for extracting log(n) elements from one of the heaps.
2 * (log(n))^2 for extracting log(n) elements from both heaps.
In big O terms, the ruling term is n, since log(n) even to the power of two is asymptotically smaller. So the whole expression above renders to a sweet O(n).