text:
Q: Highlight first occurrence of a reference or reference list in text This is a follow-up question. A working example of highlighting the first reference in text can be found in
Highlight first occurence of reference in text
However, there is an open question on how to handle lists of references. For now, the answer neglects lists and does not keep track of their occurrence. I require highlighting the complete list and keeping track of the highlights as if the references were standalone. So if I say
\cref{eq:1,eq:2,eq:3}

I would get highlighted
Equations (1) to (3)
If I then reference to one of these equations again, they won't be highlighted as they were already highlighted in the list?
Thanks for your help and a happy new year to you all!

A: I found a way to make this thing working via xparse and splitlist. I parse the list and set the marginnotes by processing the comma separated list.
Here is the working solution for anyone interested:
\usepackage{xstring}
\usepackage{xparse}
\makeatletter
\NewDocumentCommand\foo{>{\SplitList{,}}m}{{\ProcessList{#1}\myphantom}}
  \newcommand\myphantom[1]{%
  \ifcsname marginnote@#1\endcsname
  \else
  \expandafter\gdef\csname marginnote@#1\endcsname{}}
%Redefine \cref so that it will make a margin note if the passed label is referenced for the first time.
    \let\oldcref=\cref
\def\cref#1{%
    \IfSubStr{#1}{,}{%
      \ifcsname creflnote@#1\endcsname%
        \oldcref{#1}%
      \else
        {\foo{#1}}%
        \myul{2pt}{0.5pt}{1}{\oldcref{#1}}%
        \expandafter\gdef\csname creflnote@#1\endcsname{}%
        \fi
    }{%
    %check if the label has already been referenced.
    \ifcsname marginnote@#1\endcsname
        %already exists...therefore not the first citation
        \oldcref{#1}%
    \else
        \myul{2pt}{0.5pt}{1}{\oldcref{#1}}%}
        \expandafter\gdef\csname marginnote@#1\endcsname{}%first citation...with this defined, will not underline again
    \fi
    }}
\makeatother

Have a nice day!


text:
Q: Drop down enquiry I need help with this javascript to allow the following to start hidden and on the click of a button show the information. Please help!
$(document).ready(function(){
    /* show or hide gadget */
    $('a[rel="hide_block"]').click(function(){
        if ( $(this).parent('div').parent('div').children('div.java_content').css('height')=='auto') {
            $(this).css('background-image','url(images/gadget_dropdown.jpg)');
        } else {
            $(this).css('background-image','url(images/gadget_dropup.jpg)');
        }
        $(this).parent('div').parent('div').children('div.java_content').slideToggle();
        return false;
    });

A: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title></title>

            test test test test test test test test test test test test test test test test
            test test test test test test test test test test test test test test test test
            test test test test test test test test test test test test test test test test
            test test test test

            Show/Hide

redpajama_set_name: RedPajamaStackExchange


text:
Q: Erro: could not extract ResultSet Tenho esse método:
public List<AvaCriterio> getList(){
        List<AvaCriterio> lista = null;
        try{
           Session session = HibernateUtil.getSessionFactory().openSession();
           session.beginTransaction();
           lista = (List<AvaCriterio>)session.createQuery("from ava_criterio").list();
           session.getTransaction().commit();

        }catch(Exception e)
        {System.out.println("Erro: "+e.getMessage());}

        return lista;
    }

Dá esse erro ao executar:

fev 07, 2017 5:16:46 PM
  org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions WARN:
  SQL Error: 936, SQLState: 42000 Erro: could not extract ResultSet

Onde está o erro?


text:
Q: How to make a prepopulated form in ASP.NET MVC and Entity Framework So I have a list of clients in a database with various information about them. I need to print all of them out with a slidedown form with their current information already there, and the ability to add or change it.
I am able to print out all the clients and their info but when I try to edit the form it is disabled even though there is no disabled attribute set.
Here is the controller
public ActionResult Index()
    {
        var context = new U2XPlanningAutomationToolEntities();
        string query = "SELECT * FROM Clients";
        IEnumerable<Client> data = context.Database.SqlQuery<Client>(query);
        List<Client> clients = new List<Client>(data);

        ViewBag.Clients = clients;
        string email = Session["email"] as string;
        if (!String.IsNullOrEmpty(email))
        {
            return View();
        }

        return View("../Account/Login");
    }

The View
@foreach (var client in ViewBag.Clients)
{
    string plan_changes = client.plan_changes;
    string critical_milestones = client.critical_milestones;
    string pdd = client.pdd;
    string inbound = client.inbound;
    string outbound = client.outbound;
    string other = client.other;

@client.name

@client.oep_start

@client.oep_end

<button id="@client.id" class="btn btn-primary delete-client">Delete</button>

            @using (Html.BeginForm("UpdateClient", "Home", FormMethod.Post))
            {

                    <input type="hidden" name="id" value="@client.id" />
                    @Html.LabelFor(c => c.plan_changes, "Plan Changes")
                    @*<textarea name="plan_changes" class="form-control" cols="20" rows="2">@plan_changes</textarea>*@
                    @Html.TextArea("plan_changes", plan_changes, new { @class = "form-control" })

                    @Html.LabelFor(c => c.critical_milestones, "Critical Milestones")
                    @Html.TextArea("critical_milestones", critical_milestones, new { @class = "form-control" })

                    @Html.LabelFor(c => c.pdd, "Plan Document Design")
                    @Html.TextArea("pdd", pdd, new { @class = "form-control" })

                    @Html.LabelFor(c => c.inbound, "Inbound")
                    @Html.TextArea("inbound", inbound, new { @class = "form-control" })

                    @Html.LabelFor(c => c.outbound, "Outbound")
                    @Html.TextArea("outbound", outbound, new { @class = "form-control" })

                    @Html.LabelFor(c => c.other, "Other")
                    @Html.TextArea("other", other, new { @class = "form-control" })

                    <input type="submit" value="Update" name="update" class="btn btn-primary" />

            }

    }

If my approach seems weird to you it might be because I am brand new to MVC ASP.NET, I am coming from a PHP background.
Thanks in advance!

A: Please use a IEnumerable<Client> in you view instead of putting it into a viewbag. Can you try to pass the id in the Html.BeginForm. Do you have an UpdateClient method in your HomeController class?


text:
Q: Reuse Exchanges by Repartition in Spark SQL Query I am trying to understand Spark (2.4) Physical Plans. We interact with Spark via the SQL API.
I am using the following sql. The sql has one aggregation in Step 1 and a join operation in the next step. My intention was to repartition the source table before the aggregation step so that I could re-use this Exchange and avoid Shuffles (Exchanges) in the following steps (before the SM-Join step), but it did not work as per my expectation since Spark added Exchanges before the SMJ. Could you please help me understand where I am going wrong.
    create or replace temporary view prsn_dtl as
    select
    policy_num,
    prsn_id,
    eff_dt,
    from db.person_details
    cluster by policy_num;

    create or replace temporary view plcy_dtl as
    select
    policy_num,
    role_desc,
    prsn_actv_flg
    from plcy_detail;

    create or replace temporary view my_keys as
    select
    policy_num,
    prsn_id,
    max(eff_dt) eff_dt
    from prsn_dtl
    group by 1, 2;

    select
    keys.policy_num,
    keys.prsn_id,
    keys.eff_dt,
    plcy.role_desc,
    plcy.prsn_actv_flg
    from my_keys keys
    inner join plcy_dtl plcy
    on keys.policy_num = plcy.policy_num;

In the DAG representation I found 3 Exchanges (2 in the left branch and 1 in the right branch)-
Step 1) First one hashpartitioning(policy_num#92, 200) due to the manual cluster by before the aggregate
Step 2) Second was between the Aggregate operators on hashpartitioning(policy_num#163, prsn_id#164, 200)
Step 3) Finally hashpartitioning(policy_num#163) before the sort-merge Join
My question :
why did not the Exchange (from cluster by) from Step 1 above, get propagated downstream and was not re-used in Step 3 before the Sort-Merge Join.
My expectation was that Spark will reuse the Exchange from Step 1 (cluster by) and will not add another Exchange (before the SMJ) in Step 3, since the left-branch was repartitioned on policy_num early in the query.
Can anyone please explain where I am going wrong. Any help is appreciated.
Note: I am using Spark 2.4
Thanks

A: The issue appears to be alleviated by not renaming columns in the queries and propagating the same columns to downstream queries.


text:
Q: If $X \supseteq B \supseteq A$, then $B/A$ subspace of $X/A$ Problem 4.3.3 in Ronnie Brown's Topology and Groupoids asks

Let $A, B$ be subsets of $X$ such that $A$ is closed and $A \subseteq
 B$. Show that $B/A$ is a subspace of $X/A$.

I think I have solved it, but I'm puzzled because it seems that the hypothesis that $A$ is closed is unnecessary, so I wanted to be sure I'm not missing something.
We want to show that $B/A$ carries the same topology whether we first consider the subspace topology then the quotient topology or the other way around. This is, I believe, equivalent to showing that if $p:X \to X/A$ is the quotient map, then $q = p|_B : B \to p(B)$ is itself a quotient map. But this is true since if $U \subseteq B$ is open in $B$ and $q$-saturated, then $U = W \cap B$ for some $W$ open in $X$, an $W$ has no choice but to be $p$-saturated since $B \supseteq A$.
Is there any error in my reasoning?

A: You are right. One can generalize this a bit.

Let $X$ be a space with an equivalence relation $R$, and let $B\subset X$ be a subset such that $B\times B$ contains $R\setminus\Delta_X$, then the quotient map $q:X\to X/R$ restricts to a quotient map $q':B\to q(B)$.

One proves this by taking a closed $q'$-saturated set $C$ in $B$. Then $C=B\cap \overline C$ and the closure $\overline C$ is $q$-saturated.
So one could say, if $B$ contains all identifications, then $B/R$ is a subspace of $X/R$.


text:
Q: How do I add a single instance of an item from a List to a Cart List that show the quantity of that particular item using riverpod? This image show List of Added items in the CartList, pressing the "--" or "+" does not reflect on the UI This second image shows the quantity of the same Item after I manually rebuild the UI**Say I have two Lists: **
List of Products from API List A [];
Empty CartList where products from List A above can be added to CartList once and increment the quantity if it has already existed in the CartList;
Example
1: List of items from the API [productA, productB, productC....];
2. Add an element from a list in 1 above if it does not exist in CartList before:- CartList = [productA];
3. If it already exist in CartList increase the quantity only and make it Single instance in the CartList like this: CartList = [productA(1),productB(5)...];
This code works fine but it doesn't update the UI except if I leave the page and open it again which not what I want.
This is the code below:
//This Code add the product to the CartList
Consumer(
    builder: (BuildContext context, WidgetRef ref, Widget? child) {
      return DefaultButton(
        onTap: () {
          ref.read(cartProvider.notifier).addToCart(product);
          context.pushRoute(
            const MyCartScreen(),
          );
        },
        text: "Add to cart",
      );
    },
  ),

//This increase the count quantity of the product in the CartList
AddRemoveWidget(
      count: "$productCount",
      productDecrement: () {
        ref
            .read(cartProvider.notifier)
            .removeFromCart(index);
      },
      productIncrement: () {
        ref
            .read(cartProvider.notifier)
            .addToCart(
                cartItems[index].product!);
      },
    ),

//This the StateNotifier
class CartList extends StateNotifier<List<CartItemModel>> {
 CartList() : super([]);

//Add Product to Cart
  void addToCart(Product product) {
    // check it product is int the list
    final isInList = state
        .where((element) => element.product!.sId == product.sId).isNotEmpty;
    if (isInList) {
      final p =
          state.where((element) => element.product!.sId == product.sId).first;
      p.quantity += 1;
      // final count = state.where((element) => element.product!.sId == product.sId).length;
      // final p = state.where((element) => element.product!.sId == product.sId).first;
      // p.quantity = count;
      final index = state.indexOf(p);
      final items = state;
      items[index] = p;
      state = items;
    } else {
      state = [...state, CartItemModel(product: product)];
    }
  }

void removeFromCart(int index) {
    // check it product is int the list
    final item = state[index];
    if (item.quantity == 1) {
      // remove it from the list of cart items
      state = state
          .where((element) => element.product!.sId != item.product!.sId)
          .toList();
    } else {
      item.quantity -= 1;
      state[index] = item;
    }
  }

}

final cartProvider = StateNotifierProvider<CartList, List<CartItemModel>>(
  (ref) => CartList(),
);


text:
Q: Template argument deduction failed for function pointer The compiler is failing to deduct template argument for function pointer.
template< class Function >
class foobar {
    Function f;
public:
    foobar(Function _f) : f(_f) {}

};

The function definition is
bool foo(string a, string b) {
    // SOMETHING
}

I'm getting trouble in the following line
foobar f(foo);

The compiler error
error: missing template arguments before 'f'

A: Currently, there is no way to deduce type of the object by templated constructor. However, maker functions can help:
template<class T>
foobar<T> make_foobar(const T& t) {
    return Foobar<T>(t);
}

...
auto f = make_foobar(foo);


text:
Q: Strapi not updating API everyone.
I have an API on Strapi served by Heroku.
This is the frontend.
Thing is: logged in on Strapi admin served by Heroku (not locally), I can create/add more bands, but the API does not get updated. What can I possibly do?
Thank you all in advance.


text:
Q: What's the way to know if the view is for GET or POST in javascript? MVC use action attributes to map the same view for http get or post:
public ActionResult Index()
{
     return View();
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(int id)
{
 MyViewModel vm = new MyViewModel(id);
 return View();
}

Question is: in javascript, how can I know if the view is for http get command or http post command?

A: Write a little bit of javascript on the page to indicate whether the request generating the view was a get or post.
<script type="text/javascript">
   var requestMethod = '<%= ViewContext.HttpContext.Request.HttpMethod %>';
</script>


text:
Q: If i import exit() from sys, which exit will it run? In python if i import the exit module from sys will it run the normal exit() or sys.exit()
from sys import exit
print "Bla bla bla"
exit()

A: from a import b assigns the variable named b to the imported object, so you're overshadowing the built-in exit.
You can also just print out a string representation of exit to see this. Run
print(exit, type(exit))
from sys import exit
print(exit, type(exit))

to see:
(Use exit() or Ctrl-D (i.e. EOF) to exit, <class 'site.Quitter'>)
(<built-in function exit>, <type 'builtin_function_or_method'>)

Of course, there is rarely a reason to overshadow a built-in. Why not
import sys
sys.exit()

instead?


text: Q: aiohttp 2.2 compatible library for async OAuth requests? So, I need to make some requests to the Github API, which requires OAuth2 authentication for a much more relaxed rate limit - there is a library called aioauth-client which can provide this, but it is based on a very old version of aiohttp (1.0.5), and I am using aiohttp 2.2, so there are multiple errors when trying to make requests - is there another async library for Github OAuth 2 requests that is fully compatible with aiohttp 2.2?


text:
Q: In C++98 'dvd1' must be initialized by constructor, not by '{...}' How do I initialize dvd1?
C:\Users\SuperUser\Google Drive>g++ -o a Question1.cpp

Question1.cpp: In function 'int main()':
Question1.cpp:39:76: error: in C++98 'dvd1' must be initialized by constructor, not by '{...}'
dvd dvd1 = {"Zombie","BBC","James","English","Alw",2012,20170601,20170630};

#include <iostream>
#include <string>

using namespace std;

class dvd
{
    string movieName,movieProdComp,movieLeadActor,movieLanguage,renterName;
    int releaseYear,rentDate,returnDate;
    public:

        dvd(string mn,string mpc,string mla,string ml, string rn,int ry,int rd,int retd);
        void print();
};

dvd::dvd(string mn,string mpc,string mla,string ml, string rn, int ry,int rd,int retd){
    movieName=mn;
    movieProdComp=mpc;
    movieLeadActor=mla;
    movieLanguage=ml;
    renterName=rn;
    releaseYear=ry;
    rentDate=rd;
    returnDate=retd;
}

void dvd::print(){
    cout<<"Movie:"<<movieName<<endl;
    cout<<"Production:"<<movieProdComp<<endl;
    cout<<"Starring:"<<movieLeadActor<<endl;
    cout<<"Language:"<<movieLanguage<<endl;
    cout<<"Rented By:"<<renterName<<endl;
    cout<<"Released:"<<releaseYear<<endl;
    cout<<"Rent Date:"<<rentDate<<endl;
    cout<<"Return Date:"<<returnDate<<endl;
}

int main(){
    dvd();
    dvd dvd1 = {"Zombie","BBC","James","English","Alw",2012,20170601,20170630};
    dvd1.print();
}

A: This is called list initialization, and for non-aggregate types it's only supported in C++11:
dvd dvd1 = {"Zombie","BBC","James","English","Alw",2012,20170601,20170630};

For C++98, you might want to change it a little, to call constructor as usual:
dvd dvd1("Zombie","BBC","James","English","Alw",2012,20170601,20170630);

A: dvd is a non-aggregate type, which can't be initialized with braced intializer until C++11, which supports list initialization. (More precisely what you're trying to do is copy-list-initialization.)
For C++98 you can write
dvd dvd1 ("Zombie","BBC","James","English","Alw",2012,20170601,20170630);
dvd dvd1 = dvd("Zombie","BBC","James","English","Alw",2012,20170601,20170630);

In C++98 you can use aggregate initialization like dvd dvd1 = {...}; only when it's an aggregate type; for this case dvd has a user-defined constructor then makes it not.


text:
Q: Push Notifications: Associating a device token with a device My app is currently receiving push notifications that are associated with the previous application user account when this type of situation occurs:

*

*Player installs app and registers as "bob"

*bob's device token registered with web service

*Player reinstalled app and registers as "phil" (on same device)

*phil's device token registered with web service

Even though the player is now logged in as "phil" they will continue to receive push notifications for the account associated with "bob" as well as "phil".
If I was using UDID I could ensure that only one device token is registered per device and therefore remove the UDID and device token from the player's old web service account, "bob", thus ensuring only one active account per device. This would happen when the player registers as "phil" and the web server could see that the player has registered a new account with the same UDID and then remove the UDID and device token from any old accounts with that UDID (i.e. the "bob" account). No more push notifications would be sent to the bob account until someone logs into that account again (on the same device, or a new one).
However, this is won't work very well when using CFUDIDCreate since it is likely to change between installs.
How do I ensure that push notifications are only received for the currently logged in user? Or, to put it another way, how do I ensure that my web server stores only one device token per device?

A: You could make the APNS token the key server-side instead of a device specific identifier. When reinstalling the app, you would replace the existing (APNS token, "bob") record by (APNS token, "phil"), thus removing the link between the token and bob's account when reinstalling the app.
As far as I know the APNS token does not change between reinstalls of an app, so this should work. (If it did change between reinstalls in a future version of iOS, this would not be a problem  because the old token would not be valid anymore, so the device would not get notifications sent to bob).

A: In case of the app reinstallation the generated device token is the same as before? I think no. You have two different device token registered on your server, one for 'bob' and one other for 'phil', or not?
In this case, the token refers to 'bob' is invalid, an you can filter this using the APNS Feedback Service, which is continually updated "with a per-application list of devices for which there were failed-delivery attempts. The devices are identified by device tokens encoded in binary format. Providers should periodically query the feedback service to get the list of device tokens for their applications, each of which is identified by its topic. Then, after verifying that the application hasn't recently been re-registered on the identified devices, a provider should stop sending notifications to these devices."
Good luck!

A: After the iOS 9.x the device token is always distinct and unique on every install of the app. You can save the UUId token to Keychain. The keychain always hold the token even after the reinstall of the app. The keychain documentation from you can find here


text:
Q: Is there a way to rescue the queue after RabbitMQ crashed? RabbitMQ crashed when some test were done. For statistical reason, the number of packet remaining in the queue when crashed is needed. Under /var/lib/rabbitmq/mnesia/rabbit@VM_16_11_centos/queues/5PHK4O2BWQQNR6JA7K2PX8355, I found that there are a bunch of .idx files and an empty journal.jif (there is only one queue running at that time, so this folder is the only option)
Is there a way to rescue the queue with these files?
P.S. to prevent deleting other files, the RabbitMQ is left down to prevent erasing other necessary binary files.

A: I found this tool that can read the RabbitMQ IDX files and persistent store RDQ files. I was able to then re-import that data back into RabbitMQ one message at a time and let my consumers process the data normally.
https://github.com/jeffbryner/rdqdump
For Future precautionary measure :
The queue/exchange can be marked as Durable so that it will be recreated and survives any kind of server failure, crash or broker restart. (Durable entities can survive server restarts, by being automatically recreated once the server gets back up.)
Marking the queue Durable does not imply that the messages in the queue will also get recreated.
For that to happen the messages can be marked as Persistent.
(Persistent messages will be written to disk as soon as they reach the queue and will only be marked for garbage collection once they are consumed (and acknowledged) from a durable queue.)


text:
Q: Flask-SQLAlchemy adds unnecessary row in parents table (relational tables) I'm recently trying to build a little web-app with Flask. For the database 'stuff' I use Flask-SQLAlchemy and now I'm trying to get a relationship between two objects going.
I have a 'project' table and a 'file' table and it should be a one-to-many relation, so x files can be associated with one project (actually there are more relations coming in the future when I've figured the current problem out).
I've made a input-mask template so a user can upload a file and link it to a project via a dropdown which is populated with the existing projects stored in its table. Thats the corresponding view:
@app.route('/admin/upload/', methods=('GET', 'POST'))
def upload():
form = forms.UploadForm()

if not os.path.isdir(app.config['UPLOAD_FOLDER']):
    os.mkdir(app.config['UPLOAD_FOLDER'])
    print('Folder created')

form.projectId.choices = []

for g in models.Project.query.order_by('name'):
    form.projectId.choices.append((g.id, g.name))

if form.validate_on_submit():
    filename = secure_filename(form.fileUpload.data.filename)
    filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
    assocProject = models.Project(name=models.Project.query.filter_by(id=form.projectId.data).first().name)

    form.fileUpload.data.save(filepath)
    prepedFile = models.File(path=filepath, project=assocProject)

    print(prepedFile)
    print(form.projectId.data)

    db.session.add(prepedFile)
    db.session.commit()

    return 'success'
else:
    filename = None
return render_template('upload.html', form=form, filename=filename)

The prepared file should be an instance of the File-Class which has the linked Project-instance as an attribute, therefore the commit should work.
    class Project(db.Model):
__tablename__ = 'project'

id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64))
file = db.relationship('File', backref="projects")
post = db.relationship('Post', backref="projects")

def __init__(self, name):
    self.name = name

def __repr__(self):
    return '<Project %r>' % self.name

class File(db.Model):
__tablename__ = 'file'

id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64))
path = db.Column(db.String(64))
type = db.Column(db.String(6))

projectId = db.Column(db.Integer, db.ForeignKey('project.id'))
project = db.relationship('Project', backref='files')

def __init__(self, path, project):
    self.path = path
    self.project = project

    fullName = re.search('[a-zA-Z0-9]*\.[a-zA-Z]{2,}', path)
    splitName = fullName.group(0).split('.')
    self.name = splitName[0]
    self.type = splitName[1]

def __repr__(self):
    return '<File %r %r %r %r>' % (self.name, self.type, self.path, self.project)

And now the problem: When I try to upload a file it works and the file information are stored in the file table but it creates a new entry in the project table and link its id to the file entry. E.g., if the project entry looks like: name = TestProj1, id=1 and I try to link the uploaded to the project it will create a second project: name = TestProj1, id=2.
Thats my struggle and I cant figure out whats wrong. Maybe some of you now. I appreciate any help!
P.S. Maybe it is relevant, here the form I wrote:
class UploadForm(Form):
    fileUpload = FileField(label='Deine Datei')
    projectId = SelectField(u'Projekte', coerce=int)

A: You create a new Project each time.
assocProject = models.Project(name=models.Project.query.filter_by(id=form.projectId.data).first().name)

This does two things. First, it finds the first project with the specified id. Second, it passes that project's name to Project(), creating a new instance using that same name.
What you really want is
assocProject = models.Project.query.get(form.projectId.data)


text:
Q: Sending __string to __unsafe_unretained changes retain/release properties of pointer Following is a code segment which I learnt in a lynda iOS training course based on iOS 4 (without ARC).
I was going to implement the same code in my Xcode 4.2 which has ARC turned on with the iOS 5 SDK. It gave me this error:

error: Semantic Issue: Sending '__strong id *' to parameter of type '__unsafe_unretained id **' changes retain/release properties of pointer"

- (NSNumber *) insertRow:(NSDictionary *) record {
    // NSLog(@"%s", __FUNCTION__);
    int dictSize = [record count];

    // the values array is used as the argument list for bindSQL
    id keys[dictSize];  // not used, just a side-effect of getObjects:andKeys
    id values[dictSize];
    [record getObjects:values andKeys:keys];    // convenient for the C array

    // construct the query
    NSMutableArray * placeHoldersArray = [NSMutableArray arrayWithCapacity:dictSize];
    for (int i = 0; i < dictSize; i++)  // array of ? markers for placeholders in query
        [placeHoldersArray addObject: [NSString stringWithString:@"?"]];

    NSString * query = [NSString stringWithFormat:@"insert into %@ (%@) values (%@)",
                        tableName,
                        [[record allKeys] componentsJoinedByString:@","],
                        [placeHoldersArray componentsJoinedByString:@","]];

    [self bindSQL:[query UTF8String] arguments:(va_list)values];
    sqlite3_step(statement);
    if(sqlite3_finalize(statement) == SQLITE_OK) {
        return [self lastInsertId];
    } else {
        NSLog(@"doQuery: sqlite3_finalize failed (%s)", sqlite3_errmsg(database));
        return [NSNumber numberWithInt:0];
    }
}

** The real case came with the following segment of this whole function.**
int dictSize = [record count];

// the values array is used as the argument list for bindSQL
id keys[dictSize];  // not used, just a side-effect of getObjects:andKeys
id values[dictSize];
[record getObjects:values andKeys:keys];    // convenient for the C array

How can I resolve this?

A: There's a lot wrong with that function.  The fix for your compiler error is simply to declare keys and values with the __unsafe_unretained ownership qualifier:
__unsafe_unretained id keys[dictSize];  // not used, just a side-effect of getObjects:andKeys
__unsafe_unretained id values[dictSize];

However, the cast (va_list)values is undefined behavior.  Don't do it.
Since you're not using the keys array at all, it would be better to do something like this:
- (NSNumber *) insertRow:(NSDictionary *) record {
    int count = [record count];

    NSMutableArray * placeHoldersArray = [NSMutableArray arrayWithCapacity:count];
    for (int i = 0; i < count; i++) {
        [placeHoldersArray addObject: @"?"];
    }

    NSString * query = [NSString stringWithFormat:@"insert into %@ (%@) values (%@)",
                        tableName,
                        [[record allKeys] componentsJoinedByString:@","],
                        [placeHoldersArray componentsJoinedByString:@","]];

    [self bindSQL:[query UTF8String] arguments:[record allValues]];
    sqlite3_step(statement);
    if(sqlite3_finalize(statement) == SQLITE_OK) {
        return [self lastInsertId];
    } else {
        NSLog(@"doQuery: sqlite3_finalize failed (%s)", sqlite3_errmsg(database));
        return [NSNumber numberWithInt:0];
    }
}

And then modify bindSQL:arguments: to take an NSArray * instead of a va_list.  If you need help doing that, show us the source code of bindSQL:arguments:.
(However, I don't think it's documented that allKeys and allValues return parallel arrays…)

A: Edited for const char pointer:
- (NSNumber *) insertRow:(NSDictionary *) record {
    NSArray * placeHoldersArray = [NSArray array];
    const char * cStrings[record.count];
    NSArray * keys = [record allKeys];
    NSUInteger i=0;
    for (id key in keys) {
        id object = [record objectForKey:key];
        if ([object isKindOfClass:[NSString class]])
            cStrings[i++] = [(NSString*)object UTF8String];
        else
            @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"Expected NSString" userInfo:nil];
        placeHoldersArray = [placeHoldersArray arrayByAddingObject: @"?"];
    }
    NSString * query = [NSString stringWithFormat:@"insert into %@ (%@) values (%@)",
                            tableName,
                            [keys componentsJoinedByString:@","],
                            [placeHoldersArray componentsJoinedByString:@","]];

    [self bindSQL:[query UTF8String] arguments:(va_list)cStrings];
    sqlite3_step(statement);
    if(sqlite3_finalize(statement) == SQLITE_OK) {
        return [self lastInsertId];
    } else {
        NSLog(@"doQuery: sqlite3_finalize failed (%s)", sqlite3_errmsg(database));
        return [NSNumber numberWithInt:0];
    }
}

In the update method, you should understand that a va_list is just a group of any number of arguments.  It is assumed that the method that is called knows how to determine the type.  An example of this is with NSLog.  It uses the format string to determine the type of an unknown number of variables, which are passed in as a va_list, i.e. comma separated values.  Because you only have one value, just pass in the value.  I am sketchy on whether sqlite wants a c string or if it will take an integer in this case.


text:
Q: Reliability engineering design values from tests AS/NZS1170 To get design values (the strength of something, for example) designing to Australian/ New Zealand loading code you do $n$ tests and estimate the coefficient of variation of your parent population, $V_{sc}$,). With that, you get $k_t$ from lookup table below and divide you lowest test value(arguably ought to be the mean?) by $k_t$.

I have tried to work out what these $k_t$ values are - where they come from. Getting nowhere.
I think it 'works' on the principle that you want $\gamma$ confidence that the estimated strength, $R_{p,cover}$, covers the parent population $p$-fractile, $R_p$, so $P(R_{p,cover} < R_p) = \gamma$
NOTE: I am precising from an old uni text book!
So, assuming that the parent population mean equals test population mean, $\bar{R}$
Parent population Standard deviation, $s$
COV, $V_{sc}=s/\bar{R}$
$R_{p,\gamma}=m+\kappa(p,\gamma).s$, so
$ x_{p}=\bar{R}(1+\kappa(p,\gamma).V_{sc})$, so:
$k_t = \bar{R}/R_{p,\gamma} = \frac{1}{1+\kappa(p,\gamma).V_{sc}}$
The problem I am having is what an earth $\kappa(p,\gamma)$ is, to match the values in the lookup table. I do not know what $p$ and $\gamma$ are, though I have an inkling that they are 0.05 and 95% respectively.
I am working in R, gist here


text:
Q: Do I get Enthusiast badges for the same 100-day period for one Fanatic badge? It seems appropriate that awarding one Fanatic badge should erase 3 Enthusiast badges earned in the same period. If it's already so, please close.

A: This is never the case with any of the badges. Enthusiast can only be earned once, so you don't get three on the way to Fanatic, but it makes sense to leave the one you had. For a much simpler example, if you post a question that gets 100 score, you'll get Nice question, Good question, and Great question; the previous one isn't revoked as you get the next one, it just means you've earned both.
There's a general rule that you never lose a badge once you've gotten it, even if you no longer meet the criteria for it, so losing badges you do meet the criteria for would be massively confusing


text:
Q: When to use a custom view helper class in Rails I tend to do a lot with partials. They almost feel like small helper classes that take some parameters and spit out view snippets.
My question is, when is it appropriate to make a separate class for a view? Would this be appropriate for something with some additional logic like a menu system that needs to be available for testing?
I have a feeling I may be overusing partials.

A: you can use a helper to build a single unit of display. and you can use partial to build complex unit of display.
see Helpers vs. Partials and What belongs in a helper method?


text:
Q: java regex with preceeding and trailing (.*) slow I noticed that when I match a regular expression like the following one on a text it is a lot slower than the one without preceeding and trailing (.*) parts. I did the same on perl and found that for perl it hardly makes a difference. Is there any way to optimize the original regular expression "(.*)someRegex(.*)" for java?
Pattern p = Pattern.compile("(.*)someRegex(.*)");
Matcher m = p.matcher("some text");
m.matches();

Pattern p = Pattern.compile("someRegex");
Matcher m = p.matcher("some text");
m.matches();

Edit:
Here is a concrete example:
(.*?)<b>\s*([^<]*)\s*<\/b>(.*)

A: Your best bet is to skip trying to match the front and end of the string at all. You must do that if you use the matches() method, but you don't if you use the find() method. That's probably what you want instead.
Pattern p = Pattern.compile("<b>\\s*([^<]*)\\s*<\\/b>");
Matcher m = p.matcher("some <b>text</b>");
m.find();

You can use start() and end() to find the indexes within the source string containing the match. You can use group() to find the contents of the () capture within the match (i.e., the text inside the bold tag.
In my experience, using regular expressions to process HTML is very fragile and works well in only the most trivial cases. You might have better luck using a full blown XML parser instead, but if this is one of those trivial cases, have at it.
Original Answer: Here is my original answer sharing why a .* at the beginning of a match will perform so badly.
The problem with using .* at the front is that it will cause lots of backtracking in your match. For example, consider the following:
Pattern p = Pattern.compile("(.*)ab(.*)");
Matcher m = p.matcher("aaabaaa");
m.matches();

The match will proceed like this:

*

*The matcher will attempt to suck the whole string, "aaabaaa", into the first .*, but then tries to match a and fails.

*The matcher will back up and match "aaabaa", then tries to match a and succeeds, but tries to match b and fails.

*The matcher will back up and match "aaaba", then tries to match a and succeeds, but tries to match b and fails.

*The matcher will back up and match "aaab", then tries to match a and succeeds, but tries to match b and fails.

*The matcher will back up and match "aaa", then tries to match a and fails.

*The matcher will back up and match "aa", then tries to match a and succeeds, tries b and succeeds, and then matches "aaa" to the final .*. Success.

You want to avoid a really broad match toward the beginning of your pattern matches whenever possible. Without knowing your actual problem, it would be very difficult to suggest something better.
Update: Anirudha suggests using (.*?)ab(.*) as a possible fix to avoid backtracking. This will short circuit backtracking to some extent, but at the cost of trying to apply the next match on each try. So now, consider the following:
Pattern p = Pattern.compile("(.*?)ab(.*)");
Matcher m = p.matcher("aaabaaa");
m.matches();

It will proceed like this:

*

*The matcher will attempt to match nothing, "", into the first .*?, tries to match a and succeeds, but fails to match b.

*The matcher will attempt to match the first letter, "a", into the first .*?, tries to match a and succeeds, but fails to match b.

*The matcher will attempt to match the first two letters, "aa", into the first .*?, tries to match a and succeeds, tries to match b and succeeds, and then slurps up the rest into .*, "aaa". Success.

There aren't any backtracks this time, but we still have a more complicated matching process for each forward move within .*?. This may be a performance gain for a particular match or a loss if iterating through the match forward happens to be slower.
This also changes the way the match will proceed. The .* match is greedy and tries to match as much as possible where as .*? is more conservative.
For example, the string "aaabaaabaaa".
The first pattern, (.*)ab(.*) will match "aaabaa" to the first capture and "aaa" to the second.
The second pattern, (.*?)ab(.*) will match "aa" to the first capture and "aaabaaa" to the second.

A: Instead of doing "(.*)someRegex(.*)" , why not just split the string on "someRegex" and get the parts from the resulting array ? This will give you the same result, but much faster and simpler.  Java supports splitting by regex if you need it - http://www.regular-expressions.info/java.html

A: . matches every character
instead of . try limiting your search by using classes like \w or \s.
But I dont' guarantee that it would run fast.
It all depends on the amount of text you are matching!


text:
Q: Formal smoothness over a DVR Let $S$ be the spectrum of a discrete valuation ring $R$, with fraction field $K$, algebraically closed residue field $k$, denote by $\varpi$ an uniformizer and by $o\in S$ the closed point. Let $\delta:X\rightarrow S$ be a projective morphism such that $X_K$ is a smooth $K$-variety. Let $x\in X_k$ be a closed point. Suppose that for every $j$ and $i$ mapping to $x$ and $o$ respectively there exists a morphism $Spec(R/\varpi^2)\rightarrow X$ commuting with the diagram below
$$\require{AMScd}
\begin{CD}
Spec(k) @>{j}>> X\\
@VVV @VVV \\ Spec(R/\varpi^2) @>{i}>> S
\end{CD}$$
Does this imply $\delta$ is (formally) smooth at $x$? (see https://stacks.math.columbia.edu/tag/02GZ for the definition of formal smoothness)


text:
Q: Exception handling in thread We are working on a project to handle virtual machine managers from a Java application.
At the moment, we faced a problem where some instructions must be considered as a task because they require more time. Theses taks can also end with errors or be a success, and we can't know the result from the application unless we request the state of the task to the VM hypervisor.
To have a smooth application we wanted to have a CommandManager to handle the differents request to theses hypervisors in separated threads. The problem is that these Command might return specific errors such as that we used to catch in the view to display revelant information to the user but when we implement Runnableon our Commands interface, we can't throw any exception out of that thread back to reach the view.
What could I do to keep notifying the user of the errors that happened and their nature?
Sorry for my english!
Lets see the code below for a brief example :
First the Command
class ChangeMemorySize extends Command {
    private String name;
    private int memorySizeMb;

    public ChangeMemorySize(Hypervisor hypervisor, String server,
            String name, int memory) {
        super(hypervisor, server);
        this.name = name;
        this.memorySizeMb = memory;
    }
    protected void execute() throws ConnectionException,OperationException{

    //Some code here

    }
    public void run() //CANT THROW ANYTHING HERE :throws VmConfigFault,
        try{
            execute();
        }catch{Exception e){
            // I have to catch it all here!
        }

This isn't real code this is just an example. This command would then be passed to a manager who would run it in another thread. But I loose all the specifics exception that I used to notify the user of what really happened in there!

A: Use an ExecutorService and do one of two things.
First you can store all results in a Future and when you want to know if an Exception occurs just invoke Future.get() and handle any exception.
Second you can create the ExecutorService with a ThreadFactory in which you set it a knew UncaughtExceptionHandler like
       final UncaughtExceptionHandler handler = new UncaughtExceptionHandler() {
            public void uncaughtException(Thread t, Throwable e) {
                // notify error
            }
        });
        Executor executor = Executors.newFixedThreadPool(1, new ThreadFactory() {
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r);
                thread.setUncaughtExceptionHandler(handler);
                return thread;
            }
        });

A: While I agree with @John Vint that ExecutorService  with an UncaughtExceptionHandler is a good approach, if for some reason you really want to stick with Runnables, I'd suggest that your base class, Command, have some fields/getters for status and Exception.  e.g.
Enum Status {FAILED, CANCELLED, SUCCESS};

// protected so subclasses can set them
protected Status status;
protected Exception exception; // null means none

public Status getStatus();
public Exception getException();

You might even want to add a result field to really mimic a Callable.
For simplicity, then add a method that subclasses can call in the catch clause
protected void s***Happenned(Exception e) {
   this.exception = e;
   status = FAILED;
   // any standard cleanup can go here too...
}


text:
Q: How to Change Mobile Menu Icon Using PHP (Toggling Hamburger Menu) I'm using the hamburger toggling method from the AMP-WP website and replaced the text with a symbol ☰ to create the hamburger.
https://amp-wp.org/documentation/playbooks/toggling-hamburger-menus/

<?php echo( '☰' ); ?>

Everything works great, apart from I'd like to change the symbol to ✕ when the menu is open/active.
What PHP is required to do this please?

A: You need to take a different approach where your icon is really a set of HTML elements where each line is separate and can be targeted by animation, CSS transforms in this case:

const hamburger = document.querySelector('#hamburger-toggle');

hamburger.addEventListener('click', function() {
  if (this.classList.contains('open')) {
    this.classList.remove('open');
  } else {
    this.classList.add('open');
  }
});
#hamburger-toggle {
  position: relative;
  cursor: pointer;
  height: 40px;
  width: 50px;
  margin: 10px 0;
  padding: 10px 0;
}
.hamburger-line {
  display: block;
  width: 24px;
  height: 2px;
  background-color: black;
  margin-top: 6px;
  opacity: 1;
}
.hamburger-line-1 {
  margin-top: 0;
}
.hamburger-line-1, .hamburger-line-3 {
  transform-style: preserve-3d;
  transition: transform 200ms; /* this line animates the change in position */
  transform: translateY(0px) rotateZ(0deg);
}
.hamburger-line-2 {
  transition: opacity 200ms; /* this line animates the change in opacity fading in/out the middle hamburger line */
}
#hamburger-toggle.open .hamburger-line-1 {
  transform-style: preserve-3d;
  transition: transform 200ms;
  transform: translateY(8px) rotateZ(44deg);
}
#hamburger-toggle.open .hamburger-line-2 {
  transition: opacity 200ms;
  opacity: 0;
}
#hamburger-toggle.open .hamburger-line-3 {
  transform-style: preserve-3d;
  transition: transform 200ms;
  transform: translateY(-8px) rotateZ(-44deg);
}


text:
Q: Pylint shows "Crash ``module 'isort' has no attribute 'SortImports'``" on every file at row 1 column 1? I enabled PyLint on Visual Studio Code. My Python version is 3.6.13.
However, it shows the following lint error on every file.

Fatal error while checking 'c:\Users\xxx\source\yyy\exceptions.py'. Please open an issue in our bug tracker so we address this. There is a pre-filled template that you can use in 'C:\Users\xxx\AppData\Local\pylint\pylint\Cache\pylint-crash-2022-01-12-09.txt'.pylint(fatal)

Issue title:
Crash ``module 'isort' has no attribute 'SortImports'`` (if possible, be more specific about what made pylint crash)
Content:
When parsing the following file:

```python
'''Custom exceptions'''

class NameException(Exception):
    '''Name Exception'''

```

pylint crashed with a ``AttributeError`` and with the following stacktrace:
```
Traceback (most recent call last):
  File "C:\Users\xxx\anaconda3\lib\site-packages\pylint\lint\pylinter.py", line 1034, in _check_files
    self._check_file(get_ast, check_astroid_module, file)
  File "C:\Users\xxx\anaconda3\lib\site-packages\pylint\lint\pylinter.py", line 1069, in _check_file
    check_astroid_module(ast_node)
  File "C:\Users\xxx\anaconda3\lib\site-packages\pylint\lint\pylinter.py", line 1204, in check_astroid_module
    ast_node, walker, rawcheckers, tokencheckers
  File "C:\Users\xxx\anaconda3\lib\site-packages\pylint\lint\pylinter.py", line 1250, in _check_astroid_module
    walker.walk(node)
  File "C:\Users\xxx\anaconda3\lib\site-packages\pylint\utils\ast_walker.py", line 77, in walk
    callback(astroid)
  File "C:\Users\xxx\anaconda3\lib\site-packages\pylint\checkers\imports.py", line 562, in leave_module
    std_imports, ext_imports, loc_imports = self._check_imports_order(node)
  File "C:\Users\xxx\anaconda3\lib\site-packages\pylint\checkers\imports.py", line 725, in _check_imports_order
    isort_driver = IsortDriver(self.config)
  File "C:\Users\xxx\anaconda3\lib\site-packages\pylint\utils\utils.py", line 397, in __init__
    self.isort4_obj = isort.SortImports(  # pylint: disable=no-member
AttributeError: module 'isort' has no attribute 'SortImports'
```

A: Your isort version seems correct as pylint need between 4 and 6 currentely. This look like a bug in pylint, could you open an issue, please ?


text:
Q: pandas duplication removing nans I am trying to check for duplicates.
I use df['name_duplicated'] = df.duplicated('name', keep=False)
However, this treats any row with name = NaN as a duplicate.
Does anyone know how to get around this?
I am trying df[pd.isnull(df['name'])]['name_duplicated'] = False but I get an error.

A: You could try also checking for NaNs and doing a boolean and operation on the results of the duplicated call
df['name_duplicated'] = df.duplicated('name', keep=False) & df['name'].notnull()


text:
Q: How to deal with multiple lookup tables for beginners of SQL? I'm having a hard time wrapping my head around multiple lookup tables. I have a central table with all the info but IDs in each column:
db_supply (Main supplier information data table)
 -----------------------------------------------
| Supplier_ID | Supply_Type_ID | Itm_ID | Stock |
|-----------------------------------------------|
| 1           | 1              | 33     | 3     |
|-----------------------------------------------|
| 2           | 2              | 28     | 1     |
 -----------------------------------------------

lookup_supplier
 -----------------------------
| Supplier_ID | Supplier_Name |
|-----------------------------|
| 1           | Walter        |
|-----------------------------|
| 2           | Jesse         |
 -----------------------------

lookup_supply_type
 -----------------------------------
| Supply_Type_ID | Supply_Type_Name |
|-----------------------------------|
| 1              | Import           |
|-----------------------------------|
| 2              | Delivery         |
 -----------------------------------

lookup_itm
 ------------------------
| Itm_ID | Itm_Name      |
|------------------------|
| 33     | Pickles       |
|------------------------|
| 28     | Burger        |
 ------------------------

A query for 'Burger' will output this table:
 -----------------------------------------------------
| Supplier_Name | Supply_Type_Name | Itm_Name | Stock |
|-----------------------------------------------------|
| Jesse         | Delivery         | Burger   | 1     |
 -----------------------------------------------------

How would I actually achieve this? So far I have:
SELECT * FROM db_supply WHERE Itm_ID = (SELECT Itm_ID FROM lookup_itm WHERE Itm_Name = 'Burger')
Which would give me the second row of the db_supply table with IDs not looked up yet. Do I have to nest my selects to look up multiple tables? No idea here.

A: SELECT  b.Supplier_Name,
        c.Supply_Type_Name,
        d.Itm_Name,
        a.Stock
FROM    db_supply a
        INNER JOIN lookup_supplier b
            ON a.Supplier_ID = b.Supplier_ID
        INNER JOIN lookup_supply_type c
            ON a.Supply_Type_ID = c.Supply_Type_ID
        INNER JOIN lookup_itm d
            ON a.Itm_ID = d.Itm_ID
WHERE   d.Itm_Name = 'Burger'

*

*SQLFiddle Demo
To further gain more knowledge about joins, kindly visit the link below:

*

*Visual Representation of SQL Joins
OUTPUT
╔═══════════════╦══════════════════╦══════════╦═══════╗
║ SUPPLIER_NAME ║ SUPPLY_TYPE_NAME ║ ITM_NAME ║ STOCK ║
╠═══════════════╬══════════════════╬══════════╬═══════╣
║ Jesse         ║ Delivery         ║ Burger   ║     1 ║
╚═══════════════╩══════════════════╩══════════╩═══════╝

A: Try following query:
select b.Supplier_Name,c.Supply_Type_Name,d.itemName  from db_supply a,lookup_supplier b,lookup_supply_type c,lookup_itm d where a.Supplier_ID=b.Supplier_ID and a.Supply_Type_ID=c.Supply_Type_ID and a.Itm_ID=d.Itm_ID and d.Itm_Name='Burger'


text:
Q: Execute shortcode in backend So I have a plugin that creates some images like a gallery. I add it to the page with shortcode:
add_shortcode('foo', 'foo_add_gallery');

I would like to create an option so that the gallery can be previewed in the wordpress admin area. I have managed to make it work like so:
1.
Normally I add my gallery scripts and styles to the frontend with
add_action('wp_enqueue_scripts', 'foo_enqueue_scripts');

Now I need to add them to the backend as well if I want to view the gallery, so I need to run
add_action('admin_enqueue_scripts', 'foo_admin_enqueue_scripts');

(This is where scripts and styles for plugin admin are already added, and I need to add my frontend script and styles in here as well)
2.
I run ajax when I want to preview the gallery and in there I call the same function shortcode would call:
var postData = [
        {name: 'action', value: 'foo_show_gallery_backend'},
        {name: 'gallery_id', value: gallery_id}
    ];

    $.ajax({
        url: foo_data.ajax_url,
        type: 'post',
        data: postData,
        dataType: 'json',
    }).done(function(response){
        console.log( response)

        $('#some-div').html(response)

    }).fail(function(jqXHR, textStatus, errorThrown) {
        console.log(jqXHR, textStatus, errorThrown);
    });

add_action('wp_ajax_foo_show_gallery_backend', 'foo_show_gallery_backend');

function foo_show_gallery_backend(){

   $data = foo_add_gallery($atts);

   echo json_encode($data);

   wp_die();

}

(My foo_add_gallery function creates some html and javascript and adds this to the page)
Then I add this response to the page in admin area in a div.


text:
Q: Which HTML5 offline storage solution should I use for storing user notes in my web app? I'm writing a Chrome app in which users can create and write notes(plain text), I'd like to the notes to be saved offline.
I've learned that there are several storage solutions from html5: localStorage, Web SQL DB, Application Cache. I'd like to know your advice on how to choose from them, considering the size they offer, the speed, and the convenience of use.

A: localStorage is by far the simplest solution and it's the one you should use for this task. It allows you to store strings, so as long as your data can be represented as strings - it will work (usual practice is to convert non-string data to json before saving, then parse is back).
WebDB is your normal database. If you need to run complicated queries on your data across multiple tables, then you can use it. For storing notes it would be an overkill.
Application cache is something completely different, I don't see how you can apply it here. It is for caching html pages and resources.

A: Local Storage
This is basically a key/value database, you could use this instead of cookies to store settings or other usecases you might use components like memcache on the server for. I would personally use this for data that needs to be cached.
Application Cache
I assume you mean caching by the means of a manifest file. This should complement your other uses of caching. This allows you to cache actual resources on the users device, such as images, javascript files and html files so they can work in your application when they are disconnected from the internet
Web SQL DB
This is a database in which you want to store user data, you might want to use it for data you would store in a sql database on the server too.

A: According to this: https://developer.chrome.com/apps/offline_apps#saving-locally

Packaged apps cannot use Web SQL Database or localStorage. The WebSQL
  specification has been deprecated for awhile now, and localStorage
  handles data synchronously (which means it can be slow). The Storage
  API handles data asynchronously.

IndexedDB is the recommended storage mechanism.


text:
Q: PHP foreach statement I am a student with PHP and I have a question from this course I am taking which I am able to produce my own solution which works, however the course uses some sort of "fill in the blank" testing method on their web page which means parts of the code cannot be edited.
Basically I have this right now:
<?php

$myArray = array(2,4,6,8);

foreach($myArray as $value)

    echo "Points are $value\n";

?>

But it prints "Points are 2 Points are 4 Points are 6 Points are 8"... It needs to print Points are 2 4 6 8 (so print a value with each loop with a space). I know that there is a method that measures the number of arrays against what is being printed before it stops, however I haven't been able to figure it out.
EDIT: Here is the actual question from the webpage of my school's course:
<?php

$numberstring = $_GET['numberstring'];
$numberarray = explode(',',$numberstring);

//your code here

echo "Points are $value\n";
?>

A: To put them together you can join them.
echo 'Points are ', implode(' ', $myArray), PHP_EOL;

Edit:
After you updated your question, use this as answer to the 2nd part:
$points is empty, so you can directly use implode on $numberrray.
echo 'Points are ', implode(' ', $numberarray), PHP_EOL;

A: Foreach loops do everything in the loop, every time. Easy mistake, you'll get used to it.
<?php

$myArray = array(2,4,6,8);

echo "Points are ";
foreach($myArray as $value)

    echo $value." ";

?>
echo "\n";

See Markus Zeller's answer for a better way to do this, if your predefined code templates allow it.


text:
Q: AS3 - unbalanced stack? I'm trying to create a board for a game, using a movie clip Block in my library. My code is in a linked actionscript file, and looks like this:
package {
import flash.display.*;

public class Plethora extends MovieClip {

        public function Plethora(): void {
        var m:uint=200;
        var n:uint=200;
        var boardArray:Array = [[0, 1, 0], [0, 1, 0], [1, 0, 1]];
        for (var i:uint=0; i < 3; i++) {
            for (var j:uint=0; j <3; j++) {
                if (boardArray[i,j] == 1){
                    var thisBlock: Block = new Block();
                    thisBlock.stop();
                    thisBlock.x = m;
                    thisBlock.y = n;
                    addChild(thisBlock);
                }
                m = m -50;
            }
            n = n - 50;
        }
    }
}
  }

When I test-run it, I get the following output:

          verify Plethora$iinit()
                        stack:
                        scope: [global Object$ flash.events::EventDispatcher$  flash.display::DisplayObject$ flash.display::InteractiveObject$ flash.display::DisplayObjectContainer$ flash.display::Sprite$ flash.display::MovieClip$ Plethora$]
                         locals: Plethora * * * * * *
  0:getlocal0
                        stack: Plethora
                        scope: [global Object$ flash.events::EventDispatcher$ flash.display::DisplayObject$ flash.display::InteractiveObject$ flash.display::DisplayObjectContainer$ flash.display::Sprite$ flash.display::MovieClip$ Plethora$]
                         locals: Plethora * * * * * *
  1:pushscope
                        stack:
                        scope: [global Object$ flash.events::EventDispatcher$ flash.display::DisplayObject$ flash.display::InteractiveObject$ flash.display::DisplayObjectContainer$ flash.display::Sprite$ flash.display::MovieClip$ Plethora$] Plethora

...

                         locals: Plethora? uint uint Array? uint uint Block
  136:findpropstrict addChild
                        stack: Array? Plethora
                        scope: [global Object$ flash.events::EventDispatcher$ flash.display::DisplayObject$ flash.display::InteractiveObject$ flash.display::DisplayObjectContainer$

I haven't the slightest idea what any of that could even begin to mean. I would appreciate some hints about how to start debugging this.

A: There may be something weird going on inside your Block MovieClip. Do you have any code in there? Also your 2D array syntax is incorrect:
boardArray[i, j]

Should be:
boardArray[i][j]

After making that change I copied your code on to wonderful and ran it - it seems to work fine. Have a look.


text:
Q: keydown controls for animation <html>
<header>
<link href='css.css' rel='stylesheet'>
<meta charset="UTF-8">
<title> moving box </title>

<script type= 'text/javascript'>

var rectangle = {
x: 100,
y: 100,
width: 100,
height: 100,
};

var mx = 4;
var my = 4;
var cheight = 700;
var cwidth = 700;
var e = event.keyCode;

function checkmx() {
if (rectangle.x + 100 > cwidth){
mx = -4;
}
if (rectangle.x < 0){
mx = 4;
}
}

function checkmy() {
if (rectangle.y + 100 > cheight){
my = -4;
}
if (rectangle.y < 0){
my = 4;
}
}
function keydowncontrol(){

if (e == 37){
mx = -1;
my = 0;
}
if (e == 38){
mx = 0;
my = -1;
}
if (e == 39){
mx = 1;
my = 0;
}
if (e == 40){
mx = 0;
my = 1;
}
//if (e == 35){
//mx = 0
//mx = 0
//}
}
function draw() {
checkmx();
checkmy();
keydowncontrol();

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var nextx = rectangle.x + mx;
var nexty = rectangle.y + my;

rectangle.x = nextx
rectangle.y = nexty
ctx.clearRect(0, 0, cwidth, cheight);

ctx.beginPath();
ctx.rect(rectangle.x, rectangle.y, rectangle.width, rectangle.height);
ctx.fillStyle = '#FF0000';
ctx.fill();
ctx.stroke();
}

function init() {

checkmx();
checkmy();
window.onkeydown = keydowncontrol();// how can does this notice the key pressed
draw();
}

</script>
</header>
<body onload='setInterval(init,10)'>
<canvas id="canvas" width="700" height="700"></canvas>
</body>
</html>

I am trying to animate a box. I'm not sure how the window.onkeydown and event.keycode work. My goal is to have the mx and my variables change depending on the keys pressed. Should keydowncontrol() be in the draw() function or init() function?

A: Try this:
<html>
<head>
    <link href='css.css' rel='stylesheet' />
    <meta charset="UTF-8" />
    <title>Moving box</title>
    <script type='text/javascript'>
        var rectangle = {
            x: 100,
            y: 100,
            width: 100,
            height: 100
        };

        var mx = 4;
        var my = 4;
        var cheight = 700;
        var cwidth = 700;
        var e = event.keyCode;

        function checkmx() {
            if (rectangle.x + 100 > cwidth) {
                mx = -4;
            }
            if (rectangle.x < 0) {
                mx = 4;
            }
        }

        function checkmy() {
            if (rectangle.y + 100 > cheight) {
                my = -4;
            }
            if (rectangle.y < 0) {
                my = 4;
            }
        }

        function keydowncontrol(e) {
            //alert(e);
            if (e.keyCode == 37) {
                mx = -1;
                my = 0;
            }
            if (e.keyCode == 38) {
                mx = 0;
                my = -1;
            }
            if (e.keyCode == 39) {
                mx = 1;
                my = 0;
            }
            if (e.keyCode == 40) {
                mx = 0;
                my = 1;
            }
            //if (e == 35){
            //mx = 0
            //mx = 0
            //}
        }

        function draw() {
            checkmx();
            checkmy();
            //keydowncontrol();

            var canvas = document.getElementById("canvas");
            var ctx = canvas.getContext("2d");
            var nextx = rectangle.x + mx;
            var nexty = rectangle.y + my;

            rectangle.x = nextx
            rectangle.y = nexty
            ctx.clearRect(0, 0, cwidth, cheight);

            ctx.beginPath();
            ctx.rect(rectangle.x, rectangle.y, rectangle.width, rectangle.height);
            ctx.fillStyle = '#FF0000';
            ctx.fill();
            ctx.stroke();
        }

        //document.attachEvent("onkeypress", keydowncontrol);
    </script>
</head>
<body onload='setInterval(draw, 10)' onkeydown="keydowncontrol(event)">
    <canvas id="canvas" width="700" height="700"></canvas>
</body>
</html>


text:
Q: Make one div inside two div and auto scale image subdiv

safsdghfghjghjkhkhjkhjkklhjkjh

How to make that image fit to div and text fit to div and make all responsive.THANK YOU

A: Set the image to be:
img {
 max-width: 100%;
 height: auto;
}

To make your div to resize with the parent, set the width to be relative to the parents using percentage:
 div {
    width: 100%;
    height: auto;
 }


text:
Q: Solution in Slick to Map a Future[Option] DB result to a value I'm doing this in play framework to get the relation between a command and a execution table using slick.
class ExecutionsTable(tag: Tag) extends BaseTable[Execution](tag, "executions") {
    def name = column[String]("name")
    def execution = column[String]("execution")
    def commandId = column[Long]("command_id")
    def * = (id, name, execution, commandId) <> (Execution.tupled, Execution.unapply)
    def command = foreignKey("commands", commandId, commandsTableQ)(_.id)

    implicit val CommandToLong = MappedColumnType.base[Long, Command] (
      id => {
        val cmd = Await.result(new CommandsDAO().findById(id), 1 second)
        cmd.get
      },
      cmd => cmd.id
    )

findById returns a Future[Option[Command]] I'm trying to use this method which I'm not sure is the best solution for this.
What would you recommend?

A: Do you want to handle errors? If you do, I suggest you use a flatMap and then pattern match again to see if you function actually returns something. Here you go, Something along these lines :
val x : Future[Option[String]] = Future(Option("1"))

val id = x.flatMap(optId => optId match {
  case Some(id) => id
  case None => throw new Exception("No ID.")
}


text:
Q: Playframework 2.1.x Database Error I try to add a database to my play framework app but I have several problems. I used the template (from Typesafe Activator) called "hello-play-2_3-scala". I always get an error if i try to insert 'import play.api.db._'. I looked at this instruction for the play database, but the main problem is I haven't any Build.scala file in my project folder. Also I cannot create once, just Java Files (I use Intellj Idea). I hope someone can help me.
Thanks!
Greetings Chryb.

A: You should add jdbc dependency inside build.sbt file. It should look like this:
name := """hello-play-2_3-scala"""

version := "1.0-SNAPSHOT"

libraryDependencies ++= Seq(
  PlayKeys.jdbc,
  "org.webjars" %% "webjars-play" % "2.3-M1",
  "org.webjars" % "bootstrap" % "2.3.1",
  "org.webjars" % "requirejs" % "2.1.11-1"
)

lazy val root = (project in file(".")).addPlugins(PlayScala)


text:
Q: Почему данный код выводит вместо размера файла одно и тоже число = названию директории (в численном виде)? int Dirka(char *DirectName)
{
    DIR *dir;
    struct dirent *dir_element;
    er = 1;
    if ((dir = opendir(DirectName)) == NULL)
    {
        return -1;
    }
    struct stat file;
    for (dir_elemnt = readdir(dir); dir_element != NULL; dir_element = readdir(dir))
    {
        if (strcmp(".", dir_element->d_name) && strcmp("..", dir_element->d_name))
        {
            lstat(dir_element->d_name, &file);
            if (file.st_mode == S_IFDIR)
            {
                fprintf(stdout, "%s\t<dir>\n", dir_element->d_name);
            }
            else
            {
                fprintf(stdout, "%s\t%ld\n", dir_element->d_name, file.st_size);
            }
        }
    }
    closedir(dir);
}

A: Ошибка в том, что вы вызываете lstat() с именем файла относительно current working directory (CWD), т.е. не учитывате значение DirectName
(и не проверяете результат вызова lstat()).
Правильный фрагмент кода вызова что-то вроде:
...
  char path[PATH_MAX];
  sprintf(path, "%s/%s", DirectName, dir_element->d_name);
  if (lstat(path ,&file))
    perror("Stat");
...

И еще одна ошибочка в проверке на тип файла.
Нужно писать:
...
  if ((file.st_mode & S_IFDIR) == S_IFDIR) {
     fprintf(stdout, "%s\t<dir>\n", dir_element->d_name);
...


text:
Q: Correct way to handle click event in single file Vue component What is the correct way to handle a click event inside a single file Vue component? Right now I have the code looking like below, but no luck.
<template>
    <button class="btn" @click="do_something">
        Delete
    </button>
</template>

<script>
    export default {
        methods: {
            do_something() {
                alert("Do something");
            }
        }
    }
</script>

I have the above file in a vile called TestComponent.vue and included in app.js like
Vue.component('test', require('./components/TestComponent.vue').default);

I am using the component inside Laravel, so I need to compile it to make it all work. When I run npm run dev compiling starts but at a certain moment I receive an error.
Module build failed (from ./node_modules/vue-loader/lib/loaders/templateLoader.js):
SyntaxError: Unexpected token (1:725)

A: Try using the v-on:click notation instead of the @click shorthand. So:
<button class="btn" v-on:click="do_something">

I'm not sure why the @click would not work in your case.

A: <div id="example">
  <button @click="greet">Greet</button>
</div>
<script>
var vm = new Vue({
  el: '#example',
  data: {
    name: 'Vue.js'
  },//say you have a variation of this
  methods: {
    greet(event) {
      alert('Hello ' + this.name + '!')
      alert(event.target.tagName)
    }
  }
})
</script>

this should work and it`s the same as your code so probably the error is an typo of yours.
show the whole page


text:
Q: how design a tree menu with an array of items in PHP?
I have an array like below (in PHP):
$menu = array(0 => array('id'=>1, 'name'=>'a', 'parent_id'=>''), 1 => array('id'=>2, 'name'=>'b', 'parent_id'=>''), 2 => array('id'=>3, 'name'=>'c', 'parent_id'=>'1'), 3 => array('id'=>4, 'name'=>'d', 'parent_id'=>''), 4 => array('id'=>5, 'name'=>'e', 'parent_id'=>''), 5 => array('id'=>6, 'name'=>'f', 'parent_id'=>'4'));

then I want to echo this array to something like this:
a
|-- c
b
d
|-- f
e

and if I push new item to array like this:
array_push ($menu, array('id'=>7, 'name'=>'g', 'parent_id'=>'6'));
it should be something like this:
a
|-- c
b
d
|-- f
|-- |-- g
e

do you have any solution for this?
thanks a lot
Reza

Hi again, I post my solution but there is something wrong. if I add something like this array_push ($menu, array('id'=>7, 'name'=>'g', 'parent_id'=>'6')); to my array, it will build above tree without any problem.but if I add this item to array array_push ($menu, array('id'=>7, 'name'=>'g', 'parent_id'=>'4')); it will hang because of infinity loop.I don't know why it will not exit from the "while" loop. can you please review my code and tell me what is wrong?thanks again.Reza

A: Try this one out, I guess it's pretty messy...
$menu = array(0 => array('id'=>1, 'name'=>'a', 'parent_id'=>''), 1 => array('id'=>2, 'name'=>'b', 'parent_id'=>''), 2 => array('id'=>3, 'name'=>'c', 'parent_id'=>'1'), 3 => array('id'=>4, 'name'=>'d', 'parent_id'=>''), 4 => array('id'=>5, 'name'=>'e', 'parent_id'=>''), 5 => array('id'=>6, 'name'=>'f', 'parent_id'=>'4'));
array_push ($menu, array('id'=>7, 'name'=>'g', 'parent_id'=>'6'));

$menu_arranged = array();

foreach ($menu as $k=>$v) {         // change array layout
    $id = $v['id'];
    unset($v['id']);
    $menu_arranged[$id] = $v;

}

$i = 0;
while($i < 5) {     // i put 5 as number of subtree levels since i can't find easy way to calculate it
    foreach ($menu_arranged as $k=>$v) {
        $parent = $v['parent_id'];
        if (!empty($parent)) {
            $menu_arranged[$parent][$k] = $menu_arranged[$k];
        }
    }
    $i++;
}

foreach ($menu_arranged as $k => $v) {
    if (!empty($v['parent_id'])) {
        unset($menu_arranged[$k]);
    }
}

echo "
";
print_r($menu_arranged);
echo "
";

A:     $menu = array(0 => array('id'=>1, 'name'=>'a', 'parent_id'=>''), 1 => array('id'=>2, 'name'=>'b', 'parent_id'=>''), 2 => array('id'=>3, 'name'=>'c', 'parent_id'=>'1'), 3 => array('id'=>4, 'name'=>'d', 'parent_id'=>''), 4 => array('id'=>5, 'name'=>'e', 'parent_id'=>''), 5 => array('id'=>6, 'name'=>'f', 'parent_id'=>'4'));
    array_push ($menu, array('id'=>7, 'name'=>'g', 'parent_id'=>'6'));

    public function sort_array_by_levels ($array)
 {
    $new = array();
    $i = 0;
    $sub_level = 1;
    $search_for_next_root = FALSE;
    $temp = array();
    $root_items_holder = array();

    while (count($array) > 0)
    {
        $set_i_to_zero = FALSE;
        //select first item without parent
        if (! $search_for_next_root)
        {
            foreach ($array as $key => $value)
            {
                if ($value['parent_id'] == 0 || $value['parent_id'] === 0 || $value['parent_id'] == '0')
                {
                    array_push($new, $array[$key]);
                    array_push($root_items_holder, $array[$key]);

                    $temp = $array[$key];
                    unset($array[$key]);
                    $array = array_values($array);
                    $search_for_next_root = TRUE;
                    $i = 0;
                    //break to find sub items for this "root item"
                    break;
                }
            }
        }

        //search for sub items
        //if (count($root_items_holder) > 0)
        if ($search_for_next_root)
        {
            //should search for all items in array
            if ($i < count($array))
            {
                if ($array[$i]['parent_id'] == $temp['id'])
                {
                    //next level sub item found
                    for($j=0; $j < $sub_level; $j++)
                    {
                        $array[$i]['name'] = "|-- " . $array[$i]['name'];
                    }

                    array_push($new, $array[$i]);
                    array_push($root_items_holder, $array[$i]);

                    $temp = $array[$i];
                    //set remove sub-item founded and re-index array again
                    unset($array[$i]);
                    $array = array_values($array);
                    //set $i to zero to search from first cell in array
                    $set_i_to_zero = TRUE;
                    $sub_level++;//to add "|-- " as how many as needed to the sub levels
                }
            } else
            {
                //seems that all of array searched and there is no item with last founded item as it's parent,
                //then we should find next "root item" and search for it's sub levels again.
                if (count($root_items_holder) > 0)
                {
                    array_pop($root_items_holder);

                    if (count($root_items_holder) > 0)
                    {
                        $temp = $root_items_holder[(count($root_items_holder)-1)];
                        $sub_level--;
                    } else
                    {
                        $search_for_next_root = FALSE;
                    }

                    $set_i_to_zero = TRUE;
                } else
                {
                    $search_for_next_root = FALSE;
                    $sub_level = 1;
                }
            }
        }

        if ($set_i_to_zero)
        {
            $i = 0;
        } else
        {
            $i++;
        }
    }

    return $new;
}

 $sorted = sort_array_by_levels ($menu);
 echo "
";
 print_r ($sorted);
 echo "
";


text:
Q: What is the difference between /* and /** pattern in Spring boot? I was trying to register certain URLs for a Filter when I noticed that there is a difference between /* and /** patterns.
    @Bean
    public FilterRegistrationBean tokenAuthenticationFilterBean() {
        FilterRegistrationBean registration = new FilterRegistrationBean(tokenAuthenticationFilter);
        registration.addUrlPatterns("/api/**","/ping","/api/*");
        return registration;
    }

What is the difference between these patterns?

A: there is no /** in registration.addUrlPatterns as we can see in
Source code
private static boolean matchFiltersURL(String testPath, String requestPath) {

    if (testPath == null)
        return false;

    // Case 1 - Exact Match
    if (testPath.equals(requestPath))
        return true;

    // Case 2 - Path Match ("/.../*")
    if (testPath.equals("/*"))
        return true;
    if (testPath.endsWith("/*")) {
        if (testPath.regionMatches(0, requestPath, 0,
                                   testPath.length() - 2)) {
            if (requestPath.length() == (testPath.length() - 2)) {
                return true;
            } else if ('/' == requestPath.charAt(testPath.length() - 2)) {
                return true;
            }
        }
        return false;
    }

    // Case 3 - Extension Match
    if (testPath.startsWith("*.")) {
        int slash = requestPath.lastIndexOf('/');
        int period = requestPath.lastIndexOf('.');
        if ((slash >= 0) && (period > slash)
            && (period != requestPath.length() - 1)
            && ((requestPath.length() - period)
                == (testPath.length() - 1))) {
            return testPath.regionMatches(2, requestPath, period + 1,
                                           testPath.length() - 2);
        }
    }

    // Case 4 - "Default" Match
    return false; // NOTE - Not relevant for selecting filters

}

A: Spring normally uses Ant-style path matching patterns for URLs. If you look at the Java docs for the AntPathMatcher you will see the explanation:

The mapping matches URLs using the following rules:

*

*? matches one character

** matches zero or more characters

*** matches zero or more directories in a path

*{spring:[a-z]+} matches the regexp [a-z]+ as a path variable named     "spring"

A: IMHO code worths 100 words in this case:
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import org.springframework.util.AntPathMatcher

class AntPathMatcherTests {
    @Test
    fun twoAsterisks() {
        val pattern = "/api/balance/**"

        val matcher = AntPathMatcher()
        val matching = { path: String -> matcher.match(pattern, path) }

        assertTrue(matching("/api/balance"))
        assertTrue(matching("/api/balance/"))
        assertTrue(matching("/api/balance/abc"))
        assertTrue(matching("/api/balance/abc/"))
        assertTrue(matching("/api/balance/abc/update"))

        assertFalse(matching("/api/bala"))
    }

    @Test
    fun oneAsterisk() {
        val pattern = "/api/balance/*"

        val matcher = AntPathMatcher()
        val matching = { path: String -> matcher.match(pattern, path) }

        assertTrue(matching("/api/balance/"))
        assertTrue(matching("/api/balance/abc"))

        assertFalse(matching("/api/bala"))
        assertFalse(matching("/api/balance"))
        assertFalse(matching("/api/balance/abc/"))
        assertFalse(matching("/api/balance/abc/update"))
    }
}


text:
Q: Can't run a shell script So I have this script:
#!/bin/bash
# Flips the screen (hopefully)

syntax_error=0
orientation=0

current_orientation="$(xrandr -q --verbose | grep 'connected' | egrep -o  '\) (normal|left|inverted|right) \(' | egrep -o '(normal|left|inverted|right)')"
case $current_orientation in
        normal)
                current_orientation=0
        ;;
        left)
                current_orientation=1
        ;;
        inverted)
                current_orientation=2
        ;;
        right)
                current_orientation=3
        ;;
esac

if [ $current_orientation -eq 0 ]; then
        orientation=2
fi

if [ $current_orientation -eq 2 ]; then
        orientation=0
fi
method=evdev

# LENOVO S10-3t CHANGE ==> Hard Coded my device number to 11!!!!!!!!

device=11

swap=0
invert_x=0
invert_y=0
real_topx=0
real_topy=0
real_bottomx=4020
real_bottomy=4020

case $orientation in
        0)
                swap=0
                invert_x=0
                invert_y=0
                topx=$real_topx
                topy=$real_topy
                bottomx=$real_bottomx
                bottomy=$real_bottomy
        ;;
        1)
                swap=1
                invert_x=1
                invert_y=0
                topx=$real_topx
                topy=$real_topy
                bottomx=$real_bottomy
                bottomy=$real_bottomx
        ;;
        2 )
                swap=0
                invert_x=1
                invert_y=1
                topx=$real_topx
                topy=$real_topy
                bottomx=$real_bottomx
                bottomy=$real_bottomy
        ;;
        3 )
                swap=1
                invert_x=0
                invert_y=1
                topx=$real_topx
                topy=$real_topy
                bottomx=$real_bottomy
                bottomy=$real_bottomx
        ;;
esac

if [ $method = "evdev" ]; then
        xinput set-prop "$device" "Evdev Axes Swap" $swap
        xinput set-prop "$device" "Evdev Axes Swap" $swap
        xinput set-prop "$device" "Evdev Axis Inversion" $invert_x $invert_y
        xinput set-prop "$device" "Evdev Axis Calibration" $topx $bottomx $topy $bottomy
        if [ $orientation = 2 ]; then
                xrandr -o inverted
        fi
        if [ $orientation = 0 ]; then
                xrandr -o normal
        fi
fi

#

It's for flipping screen in my Lenovo S10-3t. I copied it from the netbook's wiki page, and added the #!/bin/bash at the top. The filename is flipscreen.sh. How can I make it work?

A: Right click on the file, then choose "Properties".
From the dialog check the "Allow executing file as program" like in the picture below.
Then close the dialog and double-click on the file to execute.

A: First you need to make your file executable,
in directory type,
sudo chmod+x flipscreen.sh

sudo bash flipscreen.sh

A: OpenNingia's answer will work, but for those who will come googling later, you can also do through the commandline:
open terminal, and goto the folder where your script is located
chmod +x <yourScript>

then execute it as
./<yourScript>

A: Double click on the file. A dialogue box will ask you that the said file is executable what do you want to do. Click "run" and you should be good to go.


text:
Q: MVC3 HTML ActionLink not working I have a DashBoardController.cs here i have this code
public class DashBoardController : Controller
    {
        //
        // GET: /DashBoard/

        [Authorize]
        public ActionResult Index()
        {
            return View();
        }

        //
        // GET: /New Project/

        [Authorize]
        public ActionResult NewProject()
        {
            return View();
        }

        //
        // GET: /File Upload/

        public ActionResult UploadFile()
        {
            return View();
        }

        [HttpPost]
        public ActionResult UploadFile(HttpPostedFileBase file)
        {
            // Verify that the user selected a file
            if (file != null && file.ContentLength > 0)
            {
                // extract only the fielname
                var fileName = Path.GetFileName(file.FileName);
                // store the file inside ~/App_Data/uploads folder
                var path = Path.Combine(Server.MapPath("~/Uploads"), fileName);
                file.SaveAs(path);
            }
            // redirect back to the index action to show the form once again
            return RedirectToAction("Index", "Home");
        }

    }

I have another masterlayout file here i have this code

@Html.ActionLink("Dashboard","Index")

Project

@Html.ActionLink("New Project","NewProject")

Projects

Account

@Html.ActionLink("Change Password", "ChangePassword", "Account")

But If i goto Change Password action link then other link (New Project, Dashboard) not working. i try @Url.Action into a herf attr but not working :(
what should i do now ?

A: You need to include the controller name in your action link:
@Html.ActionLink("Dashboard","Index","DashBoard")

If you leave out the controllerName, then the links will be constructed with the current controller. Since you navigated to the AccountController, the link that was supposed to point to the DashboardController broke.
In shared areas (like navigation), you'll usually want to include the controller reference.

A: *

*LinkText: "Dashboard"

*ActionName: "index"

*ControllerName: "dashboard"
@Html.ActionLink("Dashboard", "index", "dashboard")
If you are using areas to group controllers into different areas you would need.
@Html.ActionLink("Dashboard", "index", "dashboard", new { area = "YourAreaName"})

A: Use this overload
@Html.ActionLink("New Project","NewProject","DashBoard")

this is the format
public static MvcHtmlString ActionLink(
    this HtmlHelper htmlHelper,
    string linkText,
    string actionName,
    string controllerName
)

A: Take a look closely, I think you did not put the controller for the "NewProject" and "Index" methods
try replacing
@Html.ActionLink("New Project","NewProject")

for
@Html.ActionLink("New Project","NewProject", "DashBoard")

and
@Html.ActionLink("Dashboard","Index")

for
@Html.ActionLink("Dashboard","Index", "DashBoard")


text:
Q: Hole Filling methods takes over 20 minutes When trying to fill holes in a mesh with a border that is highly complex, the application takes 20 minutes in the hole filling call.
It can be any of the calls shown here.
The code I'm using is this:
int main()
{
    std::ifstream input("V:/tobehealed2.off");
    Triangle_mesh mesh;
    input >> mesh;

    //////////////
    std::vector<std::vector<int>> indices(mesh.num_faces());
    std::vector<Point_3> vertices(mesh.num_vertices());

    int i = 0;
    for (auto& p : mesh.points()) {
        vertices[i++] = p;
    }

    i = 0;
    for (auto& f : mesh.faces()) {
        std::vector<int> triangle(3);
        int j = 0;
        for (auto v : mesh.vertices_around_face(mesh.halfedge(f))) {
            triangle[j++] = v;
        }

        indices[i++] = triangle;
    }

    mesh.clear();

    CGAL::Polygon_mesh_processing::repair_polygon_soup(vertices, indices);
    CGAL::Polygon_mesh_processing::orient_polygon_soup(vertices, indices);

    CGAL::Polygon_mesh_processing::polygon_soup_to_polygon_mesh(vertices, indices, mesh);

    CGAL::Polygon_mesh_processing::keep_largest_connected_components(mesh, 1);

    bool hasHoles = true;

    std::vector<face_descriptor> face_out;
    std::vector<vertex_descriptor> vertex_out;

    while (hasHoles) {
        hasHoles = false;

        for (auto& hh : mesh.halfedges()) {
            if (mesh.is_border(hh)) {
                hasHoles = true;
                CGAL::Polygon_mesh_processing::triangulate_and_refine_hole(mesh, hh, std::back_inserter(face_out), std::back_inserter(vertex_out));
                break;
            }
        }

        face_out.clear();
        vertex_out.clear();
    }

    CGAL::Polygon_mesh_processing::keep_largest_connected_components(mesh, 1);
    CGAL::Polygon_mesh_processing::remove_isolated_vertices(mesh);

    CGAL::Polygon_mesh_processing::remove_self_intersections(mesh);

    CGAL::Surface_mesh_simplification::Count_stop_predicate<Triangle_mesh> stop(60000);
    int r = CGAL::Surface_mesh_simplification::edge_collapse(mesh, stop);
    mesh.collect_garbage();

    std::ofstream out2("V:/healed.off");
    out2 << mesh;
}

Application takes over 20 minutes in the call to triangulate_and_refine_hole.
Tested model is available for download here:
https://drive.google.com/file/d/1t2dwJBs5vNpg2jLOVprHEY-8tCHvCErK/view?usp=sharing
My goal is just to be able to check beforehand if the model has a hole so complex the closing of it will take several minutes, so I can skip the hole filling attempt. Also, if there is a way to exit the function call after some threshold time it would be nice.
The size of the model doesn't matter so much. If I use a mesh 3 times larger, it can fill a not-so-complex-hole in just a few seconds.

A:
Also, if there is a way to exit the function call after some threshold time it would be nice.

What always works is to start the task in another thread and monitor that thread, killing it if necessary after some time.
Really wouldn't be a pretty solution though. CGAL is still a maintained library, so fairly sure you just povide it some incorrect data. Or are you sure at all that it actually hangs up?
36Mb is quite a solid size for a model and hole-fixing is a task that grows with model complexity if I recall right.
EDIT:
Ah well, if you can afford to wait in general for 20 mintes before having a repaired model, threading is the way to go. It will just run in the background.
if you cannot afford that it takes so long, well, then it is not so easy. Either you find some significantly better implementation (not that likely), or you will have to do some trade offs. Either simplifying the model or living with less correct hole fixes (assuming there are some heuristic algorithms for this task).


text:
Q: NullPointerException thrown on flush after upgrading to Hibernate 4.1.3 Final I have just completed an upgrade from Hibernate 3.6 to 4.1.3 Final and at first everything seemed to go fine. However, one of my colleagues recently tested this an in one scenario he gets a NullPointer being thrown from within Hibernate (and this exception was not being thrown before we upgraded for the exact same DB). It is an incredibly strange scenario. We have an entity called BlogPost that looks like the below and it extends some mapped superclasses (that I have also included):
@Entity
@Table(name = "blog_post")
public class BlogPost extends CommunityModelObject implements HasFeedPost {

    @Lob
    private String title;
    @Lob
    private String content;
    @Enumerated
    @Column(nullable = false)
    private CBlogPost.Status status = CBlogPost.Status.UNPUBLISHED;
    // Reference to the feed post that indicates that this blog post has been published
    @OneToOne
    @JoinColumn(name = "feed_post_id")
    private FeedPost feedPost;
    @ManyToOne
    @JoinColumn(name = "posted_by_employee_id")
    private Employee postedBy;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public CBlogPost.Status getStatus() {
        return status;
    }

    public void setStatus(CBlogPost.Status status) {
        this.status = status;
    }

    @Override
    public FeedPost getFeedPost() {
        return feedPost;
    }

    @Override
    public void setFeedPost(FeedPost feedPost) {
        this.feedPost = feedPost;
    }

    public Employee getPostedBy() {
        return postedBy;
    }

    public void setPostedBy(Employee postedBy) {
        this.postedBy = postedBy;
    }
}

@Filter(name = "tenantFilter", condition = "(tenant_id = :tenantId or tenant_id is null)")
@MappedSuperclass
public abstract class CommunityModelObject extends ModelObject {

    @IndexedEmbedded(prefix = "tenant", indexNullAs = IndexedEmbedded.DEFAULT_NULL_TOKEN)
    @ManyToOne
    @JoinColumn(name = "tenant_id")
    protected Tenant tenant;

    public Tenant getTenant() {
        return tenant;
    }

    public void setTenant(Tenant tenant) {
        this.tenant = tenant;
    }

    /**
     * If the Tenant is null then it can be accessed / viewed by the entire "community" / user base
     */
    public boolean isCommunityObject() {
        return tenant == null;
    }
}

@MappedSuperclass
public abstract class ModelObject extends BaseModelObject {

    @Id
    @GeneratedValue
    private Long id;

    @Override
    public long getId() {
        return (id == null ? 0 : id);
    }

    public void setId(long id) {
        this.id = (id == 0 ? null : id);
    }
}

@MappedSuperclass
public abstract class BaseModelObject implements java.io.Serializable {

    // This annotation ensures that a column is not associated with this member (simply omitting the @Column annotation is not enough since
    // that annotation is completely optional)
    @Transient
    private boolean doNotAutoUpdateDateUpdated = false;

    @Version
    protected int version;
    @Column(name = "date_created")
    protected Date dateCreated;
    @Column(name = "date_updated")
    protected Date dateUpdated;

    public abstract long getId();

    public int getVersion() {
        return version;
    }

    public void setVersion(int version) {
        this.version = version;
    }

    public Date getDateCreated() {
        return dateCreated;
    }

    public Date getDateUpdated() {
        return dateUpdated;
    }

    /**
     * This will set the dateUpdated to whatever is passed through and it will cause the auto update (pre-update) to NOT occur
     *
     * @param dateUpdated
     */
    public void setDateUpdated(Date dateUpdated) {
        doNotAutoUpdateDateUpdated = true;
        this.dateUpdated = dateUpdated;
    }

    public void touch() {
        // By setting date updated to null this triggers an update which results in onUpdate being called and the nett
        // result is dateUpdated = new Date()
        dateUpdated = null;
    }

    @PrePersist
    protected void onCreate() {
        dateCreated = new Date();
    }

    @PreUpdate
    protected void onUpdate() {
        if (!doNotAutoUpdateDateUpdated) {
            dateUpdated = new Date();
        }
    }

    @Override
    public boolean equals(Object obj) {
        long id = getId();

        if (id == 0) {
            return this == obj;
        }
        //Use Hibernate.getClass() because objects might be proxies
        return obj != null &&
                obj instanceof BaseModelObject &&
                Hibernate.getClass(this) == Hibernate.getClass(obj) &&
                getId() == ((BaseModelObject)obj).getId();
    }

    @Override
    public int hashCode() {
        Long id = getId();
        return id == 0 ? super.hashCode() : id.intValue();
    }

    @Override
    public String toString() {
        return getClass().getSimpleName() + "-" + getId();
    }
}

The strangest thing is happening when I query BlogPost in some scenarios. If I run the query below, for example, in isolation then it works fine but if I run it in amongst a bunch of other queries then I get the exception below:
select b from BlogPost b

java.lang.NullPointerException
   at org.hibernate.event.internal.DefaultFlushEntityEventListener.isUpdateNecessary(DefaultFlushEntityEventListener.java:240)
   at org.hibernate.event.internal.DefaultFlushEntityEventListener.onFlushEntity(DefaultFlushEntityEventListener.java:163)
   at org.hibernate.event.internal.AbstractFlushingEventListener.flushEntities(AbstractFlushingEventListener.java:225)
   at org.hibernate.event.internal.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:99)
   at org.hibernate.event.internal.DefaultAutoFlushEventListener.onAutoFlush(DefaultAutoFlushEventListener.java:55)
   at org.hibernate.internal.SessionImpl.autoFlushIfRequired(SessionImpl.java:1153)
   at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1208)
   at org.hibernate.internal.QueryImpl.list(QueryImpl.java:101)
   at org.hibernate.ejb.QueryImpl.getResultList(QueryImpl.java:256)

Now the kicker is that if I take all of the fields from all of the mapped superclasses that I listed above and put them directly into BlogPost and make BlogPost just extend nothing and implement java.io.Serializable then everything works perfectly. This leads me to believe that the bug is either related to mapped superclasses or the Hibernate filter that I am applying to CommunityModelObject.
Any ideas as to how to solve this? I am assuming that it is a newly introduced bug in Hibernate but I may be wrong. This is causing major issues for us since we need to upgrade asap in order to upgrade Hibernate Search which we need to do for a critical bug fix.
Also note that the DB we are using is MySQL with the following custom dialect that I wrote when doing this upgrade to handle our BIT columns:
public class MySQL5InnoDBDialectExt extends MySQL5InnoDBDialect {

    private static final String BIT_STRING = "bit";

    public MySQL5InnoDBDialectExt() {
        super();
        registerColumnType(Types.BOOLEAN, BIT_STRING);
    }
}

Thanks,
Brent

A: I sorted this issue out, found the problem by fluke. Here is the resolution as I posted it on the Hibernate forum:

I found the issue. It does not seem to be related to interceptors,
  rather to either caching or instrumentation. Basically our app
  automatically includes all entities within a very specific package in
  our caching scheme and the same classes in our instrumentation. We
  generally have all of our entities in this package, however this one
  which was causing the issue was the only one not included in this
  package. The previous version of EhCache / Hibernate that we were
  using seemed ok with this, but after upgrading it caused issues.
Anyway, the entity was in the incorrect package, when I refactored it
  and moved it into the correct package then everything worked! So it
  was not a bug in Hibernate, just an informative exception that made it
  difficult to track this issue down (I basically solved it by complete
  fluke).

A: Hope this helps somebody, but in my case it was a problem with a wrong instrumentation.
I have class 'A' and two child classes 'B' and 'C'. 'A' class has a lazy property and it is instrumented to make the lazy accessing works.
But the mistake was that I didn't instrument the child classes 'B' and 'C', therefore any access to the instrumented property from 'B' and 'C' caused the exception.
When I instrumented 'B' and 'C', the problem went away.