View inside toast

I want to make a toast in which I have put EditText and a button ..but I can't type anything inside EditText neither I can click the button how to write inside EditText that viewed by the toast..

public class MainActivity extends Activity
{
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button New=(Button)findViewById(R.id.button1);
        Button save=(Button)findViewById(R.id.button3);
        EditText ed1=(EditText)findViewById(R.id.editText1);

        final Toast t=new Toast(getApplicationContext());
        New.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub

            ListView l=new ListView(getApplication());
            l.setAdapter(new badp(getApplicationContext()));

            t.setGravity(Gravity.CENTER_VERTICAL, 0, 0);

            t.setView(l);
            t.setDuration(Toast.LENGTH_LONG);
            t.show();
            }
        });

    }
    public class badp extends BaseAdapter
    {

        Context context;
        private badp(Context context) {
            // TODO Auto-generated constructor stub
            this.context=context;
        }

        public int getCount() {
            // TODO Auto-generated method stub
            return 1;
        }

        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return null;
        }

        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return 0;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            LinearLayout l=new LinearLayout(context);
            Button b1=new Button(context);
            b1.setText("Save");
            EditText ed=new EditText(context);
            ed.setGravity(Gravity.CENTER);
         //   LayoutParams lparams = new LayoutParams();
           //     ed.setLayoutParams(lparams);
                ed.setWidth(5);
                ed.setEms(10);

            l.addView(ed);
            l.addView(b1);

            return l;
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

}


Source tree .gitignore to ignore everything but specific directories/files

I've seen many examples and they pretty much say the same but for some reason I cannot get it to work using SourceTree.
My folder structure shown below, i want to ignore everything except for folder3 and all it's content, folder2_3_2_1, all it's content and the .ignore file.

folder1
folder2
   folder2_1
   folder2_2
   folder2_3
     folder2_3_1
     folder2_3_2
          folder2_3_2_1
             someOtherFile1.php
             someOtherFile12php
             someNewFolder
     folder2_3_3
   folder2_4
folder3
.ignore
somefile.php
somefile2.php

in my .ignore I have the following

# Ignore everything
/*

#except for
!.gitignore
!folder3/
!folder2/folder2_3/folder2_3_2/

Strange thing is, if I don't ignore anything and I'm able to see all my files in my unstaged files panel, if I right click and ignore someOtherFile.php and select the option to ignore everything beneath, it does the opposite, sourceTree ignores it's folder (i.e. folder2_3_2_1) and everything within!

SourceTree V 2.3.1.0

Thank you in advance


Change variable type mysql with existing data

Hi I've got a variable 'text' within my MYSQL database that gathers something like a status update. I believe this variable has a limit of 200?

Is this something that is already set?

If so what variable would be
suitable for both a quick 150 character updates as well as something
as long as a 1500 word article if a user wanted to elaborate?

How do
i change it within phpmyadmin to the desired new variable if data is
currently present within the present form?


Printing a dynamic array after increasing its size

I'm currently making a code on the MU game using dynamic arrays, and I've got a problem with printing a sequence.

Rule: If the first character is denoted by the character M, and the rest of the sequence is denoted by R, then the new sequence is MRR.

Examples include:

Current sequence: MIUI

New sequence: MIUIIUI

Current sequence: MUM

New sequence: MUMUM

Current sequence: MU

New sequence: MUU

Here are snippets of my code:

IN MAIN:

if (userchoice == 2)
{
    if (rule2valid == false)
    {
        cout << "This rule may not be applied to your input." << endl;
        return 0;
    }
    int newsize = size + size - 1;
    char *resultant = new char[newsize];
    resultant = applyRule2(userinput, size);
    printarray (resultant, newsize);
}

In the function which applies the rule:

char *applyRule2(char* sequence, int size)
{
int newsize = size + size - 1;
int j = 1;

char* applyRule = new char[newsize];
for (int i = 0; i < size; i++)
    applyRule[i] = sequence[i];
for (int i = size; i < newsize; i++)
{
    applyRule[i] == sequence[j];
}
return applyRule;
}

and the function for printing:

void printarray(char* sequence, int size)
{
for (int i = 0; i < size; i++){
cout << sequence[i] << "\t";
}
cout << "The length of this array is : " << size;
cout << endl;
}

The problem is that when I run the program, my output is as such:

Input: M U M

Output: M U M, The length of this string is 5. (supposed to be M U M U M)

Input: M I U I

Output: M I U I, the length of this string is 7. (supposed to be M I U I I U I)

What I have done so far is that I allocated a new dynamic array with the new size, and added values into the array accordingly. I am, however, at a loss as to whether the problem lies in the applyRule2 function or in the printarray function.

It would be greatly appreciated if someone could point me out in the right direction.


Priority of learning programming craft and other suggestions

As I am in my starting career year in software development (C++ & C#) I now see my flaws and what I miss in this sphere. Because of that I came into some conclusions and made myself a plan to fill those gaps and increase my knowledge in software development. But the question I stumbled upon after making a tasks which I need to do has not quite obvious answer to me. What is the priority of those tasks? Here are these tasks and my priority by numbering:

Learning:

Functional programming (Scala)

Data structures & Algorithms (Cormen book to the rescue + TopCoder/ProjectEuler/etc)

Design patterns (GOF or Head First)

Do you agree with this tasks and priorities? Or do I miss something here? Any suggestions are welcome!


What is the technique of presenting again form which contains error?

Using Flask + Flask-Classy + WTForms, I am trying to implement a route, such that, when user having error in their input form, application will presented again that form to the user, complete with what user already filled. This way, user didn't have to worried of typing again all the form input : (s)he can correct the errors.

These are code from my class UserView(FlaskView) which is a flask-classy class :

def post(self):
    form = forms.UserForm(request.form)
    if form.validate():
        if form.id.data=='':
            user = models.Users()
            form.populate_obj(user)
            user.id = None
            db.session.add(user)
        else:
            user = models.Users.query.get(form.id.data)
            form.populate_obj(user)

        db.session.commit()
        return redirect(url_for('UserView:index'))
    else:
       return redirect(url_for('UserView:validation_error', error_form=form))

def validation_error(self, error_form):
    return render_template('users/form.html', form=error_form)

You can see that in this attempt, I try to create another method : validation_error, with argument --that in my expectation-- should contain all the form data. But, turns out I got Jinja2 exception, UndefinedError: 'unicode object' has no attribute 'hidden_tag'. As I inspect it, after having been in validation_error, that form object is somewhat changed from UserForm into somekind of unicode object.

Any suggestion? Or, is it that I try to solve this problem in a wrong direction?

EDIT 1 : Elaborate more on how to display the error

As @Rawrgulmuffins added an answer on how to display the error inline (which I think is the best way, as the page will not get jumpy), here I pasted the code in my layout.html that list all the errors. It may not as good as an inline error display, but I think it's the easiest way there is. First I do an if for the form object, as this code is also exist for all page (I maybe refactored it even more)

 {% if form %}
                {% for error in form.errors %}
                <div class="alert alert-error">
                    <a class="close" data-dismiss="alert">×</a>
                    <strong>{{ form[error].label }} {{form.errors[error][0] }}</strong>
                </div>
 {% endfor %}
 {% endif %}

Screenshot given :


Can 1330316 AJAX requests crash my server?

I'm building a small PHP/Javascript app which will do some processing for all cities in all US states. This rounds up to a total of (52 x 25583) = 1330316 or less items that will need to be processed.

The processing of each item will take about 2-3 seconds, so its possible that the user could have to stare at this page for 1-2 hours (or at least keep it minimized while he did other stuff).

In order to give the user the maximum feedback, I was thinking of controlling the processing of the page via javascript, basically something like this:

var current = 1;
var max = userItems.length; // 1330316 or less

process();

function process()
{
  if (current >= max)
  {
     alert('done');
     return;
  }

  $.post("http://example.com/process", {id: current}, function()
     {
        $("#current").html(current);
        current ++;
        process();
     }
  );
}

In the html i will have the following status message which will be updated whenever the process() function is called:

<div id="progress">
   Please wait while items are processed.
   <span id="current">0</span> / <span id="max">1330316</span> items have been processed.
</div>

Hopefully you can all see how I want this to work.

My only concern is that, if those 1330316 requests are made simultaneously to the server, is there a possibility that this crashes/brings down the server? If so, if I put in an extra wait of 2 seconds per request using sleep(3); in the server-side PHP code, will that make things better?

Or is there a different mechanism for showing the user the rapid feedback such as polling which doesn't require me to mess with apache or the server?


What is the better way for update table 2 with table 1 php mysqli?

What is the better way for update table 2 with table 1 php mysqli ?

for me, use while loop and update row

<?PHP
session_start();
include("connect.php");
$query = "SELECT * FROM table_1";
$result = mysqli_query($db_mysqli, $query);
while($row = mysqli_fetch_assoc($result))
{
    $id = $row['id'];
    $money = $row['money'];
    $db_mysqli->query("Update table_2 Set money = '$money' WHERE id = '$id'");
}
?>

I want to know php have code that process in 1 step for update table 2 with table 1 ?


Textarea in chrome only shows one line

Hi I have a form with a text area for comments. The problem is my code below should produce a textbox 3 rows high but when it is displayed in Chrome it only ever appears as one line , Can anyone suggest what I am doing wrong please?

<tr>
    <td >&nbsp;</td>
    <td ><strong>Approver Comments</strong></td>
    <td colspan="3" >
    <textarea name="approvecom" cols="100" rows="5" autocomplete="OFF"></textarea>
    </td>
    <td >&nbsp;</td>
</tr>


Comparison operators not working?

I have never stumbled upon this issue before. What is wrown with the following comparison:

$longest_side = 2.9;
if ($longest_side > 2.9) echo 'Too long'; // Returns true, incorrect

Some debugging:

var_dump($longest_side, 2.9) // Displays float(2.9) float(2.9)

The only way to make it work was to stringify the values

if ((string)$longest_side > (string)2.9) echo 'Too long'; // Returns false, OK

Is this a PHP bug or as constructed?


Expand the grouping automatically in begin in ui-grid

I have followed the steps in th tutorial to construct my grouping.

What i want to have is expanding certain (or all) rows in begin automatically. In tutorial they used: $scope.gridApi.treeBase.toggleRowTreeState($scope.gridApi.grid.renderContainers.body.visibleRowCache[rowNum]);
and: $scope.gridApi.treeBase.expandAllRows();

They are working after my grid is ready but; my grid is not initialized in begin in my app and just after some required actions the grid will be shown and initialized. Therefore, i don't know how to use them to expand the rows automatically.

Thus i believe i need some callback like onReady. Any idea?


how to get facebook albumName

i have problem with get facebook album name.i use this code:

private void LoadAlbumName()
    {

        dynamic albums = new FacebookMediaObject();
        albums = _fb.Get("me/albums/");
        foreach (dynamic albumInfo in albums.data)
        {
            Dispatcher.BeginInvoke(new MethodInvoker(
                () =>
                {
                    dynamic albumsPhotos = _fb.Get(albumInfo.id + "/photos");
                }));
        }
    }

when i run i get null


http to https redirection based on subdomain name

We have 3 sub domains pointed to a apache webserver,all the subdomains are for different web applications, we have got ssl against the sub domains,ssl certificates were installed, but we are not able to redirect the http requests to https.. we have to write manually https://subdomain.domain-name.com to access our applications...

We are using zend server 6 . please help us to know so that all the http request can be redirected to  https.

we have written this on our httpd.conf file

    RewriteEngine On
     RewriteCond %{HTTP_HOST} ^(.*?)\.domain-name.com$
      RewriteCond %{HTTPS} !=on
        RewriteRule ^(.*?)$ https://%{HTTP_HOST} [nc]

we are really new to this.we will be highly grateful.


How to batch update Box enterpise users

I have successfully pulled back a list of enterprise users using the Box API:
http://developers.box.com/docs/

I now want to batch update a group of users, setting the group to Inactive.

In the API, I see that you can update a single user like this: PUT /users/{id}

I believe I can just loop through a list of users from a .csv file and individually set each of them to "inactive" via the method above. The problem is that I don't know the ID of each user to include in the .csv file. If I export the users via the Box Admin Console's "Bulk Edit" feature, I get a .csv file of the users, but it only contains the following columns: Name, Email, Groups, and Storage.

So, my first thought is that there may be some way to update the user through the API using the email address.
As in, first search for the user via the email address, then get the ID from the results, and finally use the returned ID to update the user account. Is this possible or can you suggest another way to solve this problem?


Server side validation with custom DataAnnotationsModelValidatorProvider

I have setup a custom provider to allow setting validation attributes from a data store instead of in static code.  Works great with the client side validation in my .NET MVC 4 project, but I am unable to get the server side validation to work.

CustomModelValidatorProvider .cs:

    public class CustomModelValidatorProvider : DataAnnotationsModelValidatorProvider
    {
        protected override IEnumerable GetValidators(ModelMetadata metadata, ControllerContext context, IEnumerable attributes)
        {
            // set attributes from datastore here

            return base.GetValidators(metadata, context, attributes);
        }
    }

In my Global.asax.cs I have:

    protected void Application_Start()
    {
        ModelValidatorProviders.Providers.Clear();
        ModelValidatorProviders.Providers.Add(new CustomModelValidatorProvider());
    }

And in a Web API method I have:

    var validationResultList = new List();
    bool valid = Validator.TryValidateObject(myModelObject, new ValidationContext(myModelObject, null, null), validationResultList, true);

Here, valid is always true. Even when the Jquery client side validation displays an error.  On the server side my custom provider is not being used to apply the data annotations. When I set a breakpoint in GetValidators() it's called when the View is created and correctly displays the client side validators, but does not get called again when the model is bound to the controller.

Have I missed a step? Any help is greatly appreciated!

UPDATE

The custom validator works correctly when the object is posted to a Controller, but does not get fired when posted to an ApiController.


NHibernate mapping without keys

I have these two classes

[DataServiceKey("Id")]
public class EmailMessage
{
    [DataMember]
    public virtual long Id { get; set; }

    [DataMember]
    public virtual string Scope { get; set; }

    [DataMember]
    public virtual long ScopeId { get; set; }

    ...

    [DataMember]
    public virtual IList<BinaryDataView> Attachments { get; set; }
}

and

public class BinaryDataView
{
    [DataMember]
    public virtual long BinaryId { get; set; }

    [DataMember]
    public virtual string ExternalLink { get; set; }
}

I am trying to create a propher nhibernate mapping for them but, data base are old enough and I can't use forenkeys. Both data bases (tEmail and tBinaryData) contains fields Scope and ScopeId and I need to use them to get BinaryData.

So this is how my classes in hbm.xml looks like:

 <class name="EmailMessage" table="tEmail">
    <id name="Id">
      <column name="EmailId" sql-type="bigint"/>
      <generator class="native" />
    </id>
    <property name="DataOwnerId" />
    <property name="Scope"/>
    <property name="ScopeId"/>
    <property name="From" column="[From]"/>
    <property name="To" column="[To]"/>
    <property name="Subject"/>
    <property name="Body"/>
    <bag name="Attachments" lazy="false" fetch="join" generic="true">
      <key>
        <column name="Scope" />
        <column name="ScopeId" />
      </key>
      <one-to-many class="Entities.BinaryDataView,Entities" not-found="ignore"/>
    </bag>
  </class>

and

  <class name="BinaryDataView" table="tBinaryData" >
    <id name="BinaryId">
      <column name="BinaryId" sql-type="bigint"/>
      <generator class="native" />
    </id>
    <property name="ExternalLink"/>
  </class>

Right now I'm getting the: Foreign key (FK66731BD76FED2100:tBinaryData [Scope, ScopeId])) must have same number of columns as the referenced primary key (tEmail [EmailId]) error.
So, there is my question: Where am I wrong and what I'm doing wrong? How can I create this mapping without using forenkeys  for Scope and ScopeId?

And sorry for my bad English.

Update:
Managed to create mapping. At least right now its working:

  <class name="EmailMessage" table="tEmail">
    <id name="Id">
      <column name="EmailId" sql-type="bigint"/>
      <generator class="native" />
    </id>
    <property name="DataOwnerId" />
    <property name="Scope" />
    <property name="ScopeId" />
    <properties name="ScopeInfo">
      <property name="Scope" column="Scope"/>
      <property name="ScopeId" column="ScopeId"/>
    </properties>
    <property name="From" column="[From]"/>
    <property name="To" column="[To]"/>
    <property name="Subject"/>
    <property name="Body"/>
    <bag name="Attachments" lazy="false" fetch="join" generic="true">
      <key property-ref="ScopeInfo" foreign-key="none">
        <column name="Scope" />
        <column name="ScopeId" />
      </key>
      <one-to-many class="Entities.BinaryDataView,Entities" not-found="ignore"/>
    </bag>
  </class>


Caption uncentering its image

I have a problem that might be a simple one, but can't find a solution.

I am managing my self-hosted wordpress, and am often adding pictures to articles I post, and like to have them centered. However, I noticed that when adding a caption to the centered pictures, they ended up aligned left. You can see an example here (first and second pictures).

The "no caption & aligned" picture code is:

<p style="text-align: center;">
    <a rel="attachment wp-att-1949" href="http://themikal.com/?attachment_id=1949">
        <img class=" size-large wp-image-1949 aligncenter" title="hildolfr1" src="http://themikal.com/wp-content/uploads/2011/05/hildolfr1-566x400.jpg"alt="" width="391" height="276" />
    </a>
</p>

Whereas the "caption and disaligned" picture code would be:

[caption id="attachment_1949" align="aligncenter" width="391" caption="Hildolfr"]
    <a rel="attachment wp-att-1949" href="http://themikal.com/?attachment_id=1949">
        <img class=" size-large wp-image-1949 aligncenter  " title="hildolfr1" src="http://themikal.com/wp-content/uploads/2011/05/hildolfr1-566x400.jpg" alt="" width="391" height="276" />
    </a>
[/caption]

I tried adding <p style="text-align: center;"></p> to the captioned picture code, either outside the caption brackets or inside, but without results.

Would someone have an idea about why it reacts like that? wordpress.stackexchange decided it was a css-related issue, and so was more relevant here.

I am a total beginner regarding CSS, and am using a predesigned code that I then heavily modified. But I can give more info about some info in the CSS if someone points where it is located.

Thanks a lot!


Current state of drd and helgrind support for std::thread

As I transition my code to C++11, I would very much like to convert my pthread code to std::thread.  However, I seem to be getting false race conditions on very simple programs in drd and in helgrind.

#include <thread>

int main(int argc, char** argv)
{
    std::thread t( []() { } );
    t.join();
    return 0;
}

Helgrind output snippet - I also get similar errors in drd, using gcc 4.6.1, valgrind 3.7.0 on Ubuntu 11.11 amd64.

My questions are:

sanity check: Am I doing anything wrong?  Are others getting similar false reports on simple std::thread programs?

What are current users of std::thread using to detect race-conditions?

I am reluctant to port a ton of code from pthread to std::thread until some crucial tools like helgrind/drd have caught up.

==19347== ---Thread-Announcement------------------------------------------
==19347==
==19347== Thread #1 is the program's root thread
==19347==
==19347== ---Thread-Announcement------------------------------------------
==19347==
==19347== Thread #2 was created
==19347==    at 0x564C85E: clone (clone.S:77)
==19347==    by 0x4E37E7F: do_clone.constprop.3 (createthread.c:75)
==19347==    by 0x4E39604: pthread_create@@GLIBC_2.2.5 (createthread.c:256)
==19347==    by 0x4C2B3DA: pthread_create_WRK (hg_intercepts.c:255)
==19347==    by 0x4C2B55E: pthread_create@* (hg_intercepts.c:286)
==19347==    by 0x50BED02: std::thread::_M_start_thread(std::shared_ptr<std::thread::_Impl_base>) (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.16)
==19347==    by 0x400D51: _ZNSt6threadC1IZ4mainEUlvE_IEEEOT_DpOT0_ (in /mnt/home/kfeng/dev/robolab/cpp/sbx/sandbox)
==19347==    by 0x400C60: main (in /mnt/home/kfeng/dev/robolab/cpp/sbx/sandbox)
==19347==
==19347== ----------------------------------------------------------------
==19347==
==19347== Possible data race during write of size 8 at 0x5B8E060 by thread #1
==19347== Locks held: none
==19347==    at 0x40165E: _ZNSt6thread5_ImplISt12_Bind_resultIvFZ4mainEUlvE_vEEED1Ev (in /mnt/home/kfeng/dev/robolab/cpp/sbx/sandbox)
==19347==    by 0x401895: _ZNKSt19_Sp_destroy_inplaceINSt6thread5_ImplISt12_Bind_resultIvFZ4mainEUlvE_vEEEEEclEPS6_ (in /mnt/home/kfeng/dev/robolab/cpp/sbx/sandbox)
==19347==    by 0x4016D8: _ZNSt19_Sp_counted_deleterIPNSt6thread5_ImplISt12_Bind_resultIvFZ4mainEUlvE_vEEEESt19_Sp_destroy_inplaceIS6_ESaIS6_ELN9__gnu_cxx12_Lock_policyE2EE10_M_disposeEv (in /mnt/home/kfeng/dev/robolab/cpp/sbx/sandbox)
==19347==    by 0x401B83: std::_Sp_counted_base<(__gnu_cxx::_Lock_policy)2>::_M_release() (in /mnt/home/kfeng/dev/robolab/cpp/sbx/sandbox)
==19347==    by 0x401B3E: std::__shared_count<(__gnu_cxx::_Lock_policy)2>::~__shared_count() (in /mnt/home/kfeng/dev/robolab/cpp/sbx/sandbox)
==19347==    by 0x401A93: std::__shared_ptr<std::thread::_Impl_base, (__gnu_cxx::_Lock_policy)2>::~__shared_ptr() (in /mnt/home/kfeng/dev/robolab/cpp/sbx/sandbox)
==19347==    by 0x401AAD: std::shared_ptr<std::thread::_Impl_base>::~shared_ptr() (in /mnt/home/kfeng/dev/robolab/cpp/sbx/sandbox)
==19347==    by 0x400D5D: _ZNSt6threadC1IZ4mainEUlvE_IEEEOT_DpOT0_ (in /mnt/home/kfeng/dev/robolab/cpp/sbx/sandbox)
==19347==    by 0x400C60: main (in /mnt/home/kfeng/dev/robolab/cpp/sbx/sandbox)
==19347==
==19347== This conflicts with a previous read of size 8 by thread #2
==19347== Locks held: none
==19347==    at 0x50BEABE: ??? (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.16)
==19347==    by 0x4C2B547: mythread_wrapper (hg_intercepts.c:219)
==19347==    by 0x4E38EFB: start_thread (pthread_create.c:304)
==19347==    by 0x564C89C: clone (clone.S:112)
==19347==
==19347== Address 0x5B8E060 is 32 bytes inside a block of size 64 alloc'd
==19347==    at 0x4C29059: operator new(unsigned long) (vg_replace_malloc.c:287)
==19347==    by 0x4012E9: _ZN9__gnu_cxx13new_allocatorISt23_Sp_counted_ptr_inplaceINSt6thread5_ImplISt12_Bind_resultIvFZ4mainEUlvE_vEEEESaIS8_ELNS_12_Lock_policyE2EEE8allocateEmPKv (in /mnt/home/kfeng/dev/robolab/cpp/sbx/sandbox)
==19347==    by 0x40117C: _ZNSt14__shared_countILN9__gnu_cxx12_Lock_policyE2EEC1INSt6thread5_ImplISt12_Bind_resultIvFZ4mainEUlvE_vEEEESaISA_EIS9_EEESt19_Sp_make_shared_tagPT_RKT0_DpOT1_ (in /mnt/home/kfeng/dev/robolab/cpp/sbx/sandbox)
==19347==    by 0x4010B9: _ZNSt12__shared_ptrINSt6thread5_ImplISt12_Bind_resultIvFZ4mainEUlvE_vEEEELN9__gnu_cxx12_Lock_policyE2EEC1ISaIS6_EIS5_EEESt19_Sp_make_shared_tagRKT_DpOT0_ (in /mnt/home/kfeng/dev/robolab/cpp/sbx/sandbox)
==19347==    by 0x401063: _ZNSt10shared_ptrINSt6thread5_ImplISt12_Bind_resultIvFZ4mainEUlvE_vEEEEEC1ISaIS6_EIS5_EEESt19_Sp_make_shared_tagRKT_DpOT0_ (in /mnt/home/kfeng/dev/robolab/cpp/sbx/sandbox)
==19347==    by 0x401009: _ZSt15allocate_sharedINSt6thread5_ImplISt12_Bind_resultIvFZ4mainEUlvE_vEEEESaIS6_EIS5_EESt10shared_ptrIT_ERKT0_DpOT1_ (in /mnt/home/kfeng/dev/robolab/cpp/sbx/sandbox)
==19347==    by 0x400EF7: _ZSt11make_sharedINSt6thread5_ImplISt12_Bind_resultIvFZ4mainEUlvE_vEEEEIS5_EESt10shared_ptrIT_EDpOT0_ (in /mnt/home/kfeng/dev/robolab/cpp/sbx/sandbox)
==19347==    by 0x400E17: _ZNSt6thread15_M_make_routineISt12_Bind_resultIvFZ4mainEUlvE_vEEEESt10shared_ptrINS_5_ImplIT_EEEOS7_ (in /mnt/home/kfeng/dev/robolab/cpp/sbx/sandbox)
==19347==    by 0x400D2B: _ZNSt6threadC1IZ4mainEUlvE_IEEEOT_DpOT0_ (in /mnt/home/kfeng/dev/robolab/cpp/sbx/sandbox)
==19347==    by 0x400C60: main (in /mnt/home/kfeng/dev/robolab/cpp/sbx/sandbox)
==19347==
==19347== ----------------------------------------------------------------
==19347==


How to return a specific view based on user input in ASP.NET MVC

I am fairly new to MVC, but not web programming and I am having an issue with passing data values from a View to a Controller where the data values are not associated with a Model.

Scenario: I have two types of users: Student and Faculty; Basically I am trying to determine which view to return when users register on the site.

EX:

    public ActionResult Preregister(bool fac, bool stud)
    {

        if (stud == true)
        {
            return StudentRegister();
        }
        else if(fac == true)
        {
            return FacultyRegister();
        }
        else
        {
            return Index();
        }
    }

So, I want this ActionMethod called from this form:

@{
ViewBag.Title = "Preregister";
}

<h2>Registration</h2>
<p>Please indicate whether you are a student or faculty.</p>
@{
    bool chkValFac = false;
    bool chkValStud = false;
}
@using (Html.BeginForm("Preregister, Account"))
{
    <div class="pre-reg-container">
    <div class="checkbox-container">
        <div class="item">
            <label for="Student" style="width:70px;">Student</label>
            @Html.CheckBox("Student", chkValStud)
        </div>
        <div class="item">
            <label for="Faculty" style="width:70px;">Faculty</label>
            @Html.CheckBox("Faculty", chkValFac)
        </div>
    </div>
    <input name="continue" type="submit" id="continue" value="Continue" />
</div>
}

In debugging, I get this error:

The parameters dictionary contains a null entry for parameter 'stud' of non-nullable type 'System.Boolean' for method 'System.Web.Mvc.ActionResult Preregister(Boolean)' in 'Room_Booking_System.Controllers.AccountController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
Parameter name: parameters

I don't understand how I can get the data from this view into the controller without posting back. I want a simple redirect based on the response. Please Help.

Thank you all!


Backbone Route parameter not working without hash

I have problem routing my app to a route like :

"list/:id": 'list'

My webpage goes to, eg list/subpage and I have a blank page.
It is well redirected when I use an hash, like #list/subpage

My Backbone start :

Backbone.history.start({ pushState: true });

My .htaccess :

<ifModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule !\.(js|ico|gif|jpg|png|css)$ index.php [L]
</ifModule>

What could be wrong ? Tell me if you need more code


OpenGL project with Codeblocks compilation issue

I'm using Codeblocks (in Ubuntu with GCC) and have apt-gotten the necessary files for OpenGL and am now going through a tutorial on the basics of OpenGL:

My (tutorial based) code:

#include <GL/glu.h>
#include <GL/freeglut.h>

//#include <GL/gl.h>
#include <GL/glut.h>

void display(void)
{
    /* clear window */

     glClear(GL_COLOR_BUFFER_BIT);

    /* draw unit square polygon */

    glBegin(GL_POLYGON);
        glVertex2f(-0.5, -0.5);
        glVertex2f(-0.5, 0.5);
        glVertex2f(0.5, 0.5);
        glVertex2f(0.5, -0.5);
    glEnd();

    /* flush GL buffers */

    glFlush();

}

void init()
{

    /* set clear color to black */

    /*  glClearColor (0.0, 0.0, 0.0, 0.0); */
    /* set fill  color to white */

    /*  glColor3f(1.0, 1.0, 1.0); */

    /* set up standard orthogonal view with clipping */
    /* box as cube of side 2 centered at origin */
    /* This is default view and these statement could be removed */

    /* glMatrixMode (GL_PROJECTION);
    glLoadIdentity ();
    glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);  */
}

int main(int argc, char** argv)
{

    /* Initialize mode and open a window in upper left corner of screen */
    /* Window title is name of program (arg[0]) */

    /* You must call glutInit before any other OpenGL/GLUT calls */
    glutInit(&argc,argv);
    glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
    glutInitWindowSize(500,500);
    glutInitWindowPosition(0,0);
    glutCreateWindow("simple");
    glutDisplayFunc(display);
    init();
    glutMainLoop();

}

When I try to run this in Codeblocks (with GCC set in the build settings) I get the following error:

error: undefined reference to glClear error:

undefined reference to glBegin ...

After trying for hours to change build settings, I decided to just call GCC from the command line:
gcc -o main main.c -lGL -lGLU -lglut

This compiles without problem and I can even run it. So I'm not sure what the problem is.
(Also, in Codeblocks I did add "-lGL -lGLU -lglut" to the build options.)

Why can command line GCC compile this but codeblocks can't?

Note: In Codeblocks I turned off all compiler flags in build settings.
Linker Settings is empty. The only thing I have added are the above-mentioned compiler options.


Does the size of the constructor matter if you're using Inversion of Control?

So I've got maybe 10 objects each of which has 1-3 dependencies (which I think is ok as far as loose coupling is concerned) but also some settings that can be used to define behavior (timeout, window size, etc).

Now before I started using an Inversion of Control container I would have created a factory and maybe even a simple ObjectSettings object for each of the objects that requires more than 1 setting to keep the size of the constructor to the recommended "less than 4" parameter size.  I am now using an inversion of control container and I just don't see all that much of a point to it.  Sure I might get a constructor with 7 parameters, but who cares?  It's all being filled out by the IoC anyways.

Am I missing something here or is this basically correct?


Blank page after login of user created by Prestashop Webservice

I face strange problem after I create remotely customer via Prestashop  1.6 Webservice and try to login (to Prestashop frontend) with his email and password.

Customer is logged in correctly but page is displayed without content, just empty layout divs. No menu, footer, hooks... Only the logo:

When I replace URL to get into "My account", it works, but no header/footer is displayed.

Other users that were created in standard way can log in correctly and all the content is displayed.

What could be the problem? Did I forget to fill some of the madatory fields for customer when using webservice?

I created customer with these fields filled:

lastname
firstname
email
passwd
active
note

PS: I also found out, that last visit of this user in Prestashop admin remains blank after login...

Thank you :)


SQL order by 0 first and then descend number/values

I have a weird situation where i need to order 0 first and then descends a column.

Let's say i have column that looks like this

Status
------
3
4
0
5
1
2
4
0
2

And Now i need to order it by

Status
------
0
0
5
4
4
3
2
2
1

Is this possible for SQL? I've been trying to test for 2 days now but i am stuck.


How do I to get a ul list od divs to display inline?

I've got a ul that I want to be inline horizontally. See what it currently looks like here. I need the pink, orange & blue boxes to display inline. Can anybody help?

Here's the HTML:

<div id="header-li">
    <ul class="header-i">
        <li>
            <div class="quick-i1"></div>
        </li>
        <li>
            <div class="quick-i2"></div
        </li>
        <li>
            <div class="quick-i3"></div>
        </li>
    </ul>
</div>

And here's the CSS code:

#header-li {
    display: inline-block;
    height: 60px;
    width: 500px;
    border: 1px solid #000000;
    margin: 10px;
    padding: 0;
    position: relative;
    vertical-align: middle;
}
.quick-i {
    height:70px;
    width: 166px;
    border: 1px solid #000000;
    display: inline-block;
    vertical-align: middle;
    position: relative;
    margin: 0 0 0 0;
    padding: 0px;
}
ul.header-i {
    display: inline-block;
    list-style-type: none !important;
    padding: 0;
    list-style-type: none;
}
.quick-i1 {
    height: 50px;
    width: 100px;
    border: 2px solid orange;
    position: relative;
    margin-top: 4px;
    display: inline-block;
}
.quick-i2 {
    height: 50px;
    width: 100px;
    border: 2px solid yellow;
    position: relative;
    margin-top: 4px;
    display: inline-block;
}
.quick-i3 {
    height: 50px;
    width: 231px;
    border: 2px solid blue;
    position: relative;
    margin-top: 4px;
    display: inline-block;
}


python3 exception invalid syntax error

I recently started learning python3, and I am trying to write an exception.
I have this line, which is a list of words.
I want to match the word create to the list, sometimes it's there sometimes its not. When it's not there I get this error:

Traceback (most recent call last):
File "sub_process.py", line 17, in <module>
if (line.index("create")):
ValueError: 'create' is not in list

and I am fine with that. This is expected. So I thought if I wrote an exception to it the script could just continue on and keep doing stuff. So I an exception below and all its suppose to do is nothing. Catch the error and continue on.

line = line.split()

if line.index("create"):
    print("basd");
except ValueError:
    print("123");

But everytime i try to compile this I get syntax error at "except" and I am not sure why. It looks perfectly normal compared against all the tutorials that I could find.


INNER JOIN from the same table

I need to make a inner join of two queries in a mysql same table "ride":

id| appointment_address|arrival_city| arrival_country|departure_city|departure_country|end_date|nb_places|price|start_date|travel_id|rank

The first query :

SELECT DISTINCT travel_id FROM ride  WHERE departure_city LIKE <value> AND start_date > <value> OR departure_country LIKE <value> AND start_date > <value>;

The second one

SELECT DISTINCT travel_id FROM ride  WHERE arrival_city LIKE <value2> AND start_date > <value> OR departure_country LIKE <value2> AND start_date > <value>;

Thanks for any help.


How to find the correct OpenSSL EVP key length for DES3 encryption

I'm trying to implement a hybrid cryptosystem (RSA for key envelope, and DES3 (with two-key option) for data envelope). Thus, I'm trying first to implement DES3 with Openssl's EVP functions. Because it seems I can easily use EVP to combine RSA and DES3 encryption.

I've got this example code (changed data types to fix gcc warnings and put snippets in one file) from the Openssl book:

#include <stdio.h>
#include <openssl/ssl.h>
#include <openssl/evp.h>
#include <openssl/rand.h>

unsigned char *encrypt_example(EVP_CIPHER_CTX *ctx, unsigned char *data, int inl, int *rb);
unsigned char *decrypt_example(EVP_CIPHER_CTX *ctx, unsigned char *ct, int inl);
void select_random_key(unsigned char *key, int b);
void select_random_iv(unsigned char *iv, int b);
int seed_prng(int bytes);

int main(int argc, char *argv[])
{
    EVP_CIPHER_CTX ctx;
    EVP_CIPHER_CTX_init(&ctx);

    unsigned char key[EVP_MAX_KEY_LENGTH];
    unsigned char iv[EVP_MAX_IV_LENGTH];
    unsigned char *ct, *out;
    unsigned char final[EVP_MAX_BLOCK_LENGTH];
    unsigned char str[] = "123456789abcdef";
    int i = 0;

    if (!seed_prng(16))
    {
        printf("Fatal Error! Unable to seed the PRNG!\n");
        abort();
    }

    select_random_key(key, EVP_MAX_KEY_LENGTH);
    select_random_iv(iv, EVP_MAX_IV_LENGTH);

    /* EVP_des_ede3()       :three-key DES3 with ECB
     * EVP_des_ede()        :two-key DES3 with ECB
     * EVP_des_ede_cbc()    :two-key DES3 with CBC
     * EVP_des_ede3_cbc()   :three-key DES3 with CBC */

    EVP_EncryptInit(&ctx, EVP_des_ede_cbc(), key, NULL);
    ct = encrypt_example(&ctx, str, strlen((const char*)str), &i);
    printf("Ciphertext is %d bytes.\n", i);

    EVP_DecryptInit(&ctx, EVP_des_ede_cbc(), key, NULL);
    out = decrypt_example(&ctx, ct, 8);
    printf("Decrypted: >>%s<<\n", out);
    out = decrypt_example(&ctx, ct + 8, 8);
    printf("Decrypted: >>%s<<\n", out);

    if (!EVP_DecryptFinal(&ctx, final, &i))
    {
        printf("Padding incorrect.\n");
        abort();
    }

    final[i] = 0;
    printf("Decrypted: >>%s<<\n", final);
    return 0;
}

int seed_prng(int bytes)
{
    if (!RAND_load_file("/dev/random", bytes))
        return 0;
    return 1;
}

void select_random_key(unsigned char *key, int b)
{
    int i;

    RAND_bytes(key, b);
    for (i = 0; i < b - 1; i++)
        printf("%02X:",key[i]);
    printf("%02X\n\n", key[b - 1]);
}

void select_random_iv (unsigned char *iv, int b)
{
    RAND_pseudo_bytes (iv, b);
}

unsigned char *encrypt_example(EVP_CIPHER_CTX *ctx, unsigned char *data, int inl, int *rb)
{
    unsigned char *ret = (unsigned char *)malloc(inl + EVP_CIPHER_CTX_block_size(ctx));
    int i, tmp, ol;

    ol = 0;
    for (i = 0; i < inl /100; i++)
    {
        EVP_EncryptUpdate(ctx, &ret[ol], &tmp, &data[ol], 100);
        ol += tmp;
    }

    if (inl % 100)
    {
        EVP_EncryptUpdate(ctx, &ret[ol], &tmp, &data[ol], inl%100);
        ol += tmp;
    }

    EVP_EncryptFinal(ctx, &ret[ol], &tmp);
    *rb = ol + tmp;
    return ret;
}

unsigned char *decrypt_example(EVP_CIPHER_CTX *ctx, unsigned char *ct, int inl)
{

    /* We're going to null-terminate the plaintext under the assumption it's
     * non-null terminated ASCII text. The null can be ignored otherwise.
     */
    unsigned char *pt = (unsigned char *)malloc(inl + EVP_CIPHER_CTX_block_size(ctx) + 1);
    int ol;

    EVP_DecryptUpdate(ctx, pt, &ol, ct, inl);
    if (!ol) /* there's no block to decrypt */
    {
        free(pt);
        return NULL;
    }

    pt[ol] = 0;
    return pt;
}

I'm compiling it with this

gcc -g -O0 -Wall evp_encrypt_decrypt.c  -o evp_encrypt_decrypt -lssl -lcrypto

Now if I execute this i get this output:

13:98:EB:64:D5:8B:1E:0A:70:1D:28:9D:25:3A:13:40:FE:C1:81:3C:C5:8F:4B:F6:66:1A:07:F8:17:D6:10:B6:4E:BC:45:96:00:A1:9F:59:44:A0:43:D9:9D:DD:C8:A9:0B:22:EC:7B:F2:5F:78:01:D1:58:6D:0B:B4:CB:5F:CD

Ciphertext is 16 bytes.
Decrypted: >>(null)<<
Decrypted: >>12345678<<
Decrypted: >>9abcdef<<

Here it says that the the chipertext is 16 bytes (which is ok). But the key itself(hex code printed above) is 64 bytes long!

However, DES3 with two-key options should have key length with 128 bits (including parity bits). However the EVP_MAX_KEY_LENGTH definition is by default 64. Also I've tried to print  the chiper key length, the size of variable key and the ctx key size as seen below:

printf("Key length DES3: %d\n", EVP_CIPHER_key_length(EVP_des_ede3_cbc()));
printf("Key size: %d\n", sizeof(key));
printf("Cipher CTX key length: %d\n\n", EVP_CIPHER_CTX_key_length(&ctx));

This will output:

Key length DES3: 24
Key size: 64
Cipher CTX key length: 16

I'm a little bit confused here. Shouldn't be the DES3(two-key) key size 128 bits? Why is the length of DES3 key printed as 24(is this bit,byte,etc..)? Why are all these key lengths and sizes different?


Node hierarchy and inheritance

I made a scene graph hierarchy where each node has a parent and possibly children. I created this BaseNode class

class BaseNode
{
public:
    BaseNode(const char *nodeName, BaseNode *parent);
    ~BaseNode();

    BaseNode* addChildSceneNode(const char *name);
    void deleteChildSceneNode(const char *name);
    void deleteAllChildSceneNodes();

    BaseNode* findFirstSceneNode(const char *name);
    BaseNode* getChildSceneNode(const char *name);
    BaseNode* getChildSceneNode(unsigned int index);

    void setName(const char *name);
    void setTranformation(const glm::mat4 &transformation);

    unsigned int getNumChildren() const { return _children.size(); }
    const char *name() const { return _name.c_str(); }
    BaseNode* parent() const { return _parent; }
    const glm::mat4& transformation() const { return _transformation; }
    const glm::mat4& toRootTransformation() const { return _toRoot; }

protected:
    std::string _name;

    glm::mat4 _transformation;
    glm::mat4 _toRoot;

    BaseNode *_parent;
    std::vector<BaseNode*> _children;
};

and I have this SceneNode class that inherits from BaseNode

class SceneNode : public BaseNode
{
public:
    SceneNode(const char *nodeName, SceneNode *parent);
    ~SceneNode();

    void attachRenderMeshData(RenderMeshData *renderMeshData);

    const std::vector<RenderMeshData*>* renderMeshDatas() { return &_meshDatas; }

private:
    std::vector<RenderMeshData*> _meshDatas;
};

Now my question is about all the member functions that include a BaseNode* parameter.

At the moment, when working with SceneNode objects, I have to explicitly cast BaseNode* to SceneNode* as follows

SceneNode *mySceneNode = new SceneNode("root", nullptr);
mySceneNode->addChildSceneNode("my child");
SceneNode *child = reinterpret_cast<SceneNode*>(mySceneNode->getChildSceneNode("my child")); //i thought this should be dynamic_cast but the compiler throws an error.. weird

My goal is to have "many types" of BaseNode, so I won't have to rewrite its parent/children functionality every time.

Any idea how I can do this better?


Cloning Git repository into existing Xcode project

I am a complete newbie in using GitHub and I want to use the SWXMLHash library found here: https://github.com/drmohundro/swxmlhash . There is a part where author talks about "manual" installation which I don't understand. I have already made my project with some code. I would be very greatful if someone would make a step-by-step list of what to do to use this library in my project. Thank you!


How to Call this Method from OnCreate - Android C# Xamarin

I am wondering how I am meant to Call public static async Task CopyAssetAsync(Activity activity) from the OnCreate method.

  public static async Task CopyAssetAsync(Activity activity)
    {
        {
            var notesPath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "NotesData.txt");

            if (!File.Exists(notesPath))
            {
                try
                {

UPDATE 1:

protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);
            ActionBar.Hide();

            btnAdd = FindViewById<Button>(Resource.Id.btnAdd);
            //Notes
            notesList = FindViewById<ListView>(Resource.Id.lvNotes);

            //Where I am trying to call the method...
            CopyAssetAsync();

UPDATE 2:


WordPress Timing Out

Currently I am receiving the following error whenever I attempt to bulk update posts. This is even happening with just 5 posts at once and with little or no ouside server requests. Any ideas on how to resolve?

"The server is temporarily unable to service your request due to maintenance downtime or capacity problems."

Server: Digital Ocean

2GB Ram 40GB SSD Disk CentOS 7 x64

PHP 5.4.16 / Memory Limit is 128M.


For the Image element, the transformation is not happening

My Input xml is:

<Body>
<p><img src="https://tneb.com"/></p>
<h1>Taking</h1>
<p>Your records.</p>
<h2>Blood Pressure?</h2>
<p>second.</p>
</Body>

XSL I used as:

    <xsl:template match="Body">
          <xsl:for-each-group select="*" group-starting-with="h1">
             <topic>
                <xsl:attribute name="id">topic_<xsl:number count="h1 | h2"/></xsl:attribute>
                <title>
                   <xsl:apply-templates select="node()"/>
                </title>

                <xsl:for-each-group select="current-group() except ." group-starting-with="h2">
                   <xsl:choose>
                      <xsl:when test="self::h2">
                         <topic>
                            <xsl:attribute name="id">topic_<xsl:number count="h1 | h2"/></xsl:attribute>
                            <title>
                               <xsl:apply-templates select="node()"/>
                            </title>
                            <body><xsl:apply-templates select="current-group() except ."/></body>
                         </topic>
                      </xsl:when>
                      <xsl:otherwise>
                         <body><xsl:apply-templates select="current-group()"/></body>
                      </xsl:otherwise>
                   </xsl:choose>
                </xsl:for-each-group>
                </topic>
          </xsl:for-each-group>
       </xsl:template>

       <xsl:template match="p">
       <p><xsl:apply-templates/></p>
       </xsl:template>

       <xsl:template match="img">
      <xsl:element name="image">
            <xsl:if test="@src">
               <xsl:attribute name="href"><xsl:apply-templates select="@src"/></xsl:attribute>
            </xsl:if>
       </xsl:element>
   </xsl:template>

I'm getting output as:

<topic id="topic_">
   <title>
      <image href="https://tneb.com"/>
   </title>
</topic>
<topic id="topic_1">
   <title>Taking</title>
   <body>
      <p>Your records.</p>
   </body>
   <topic id="topic_2">
      <title>Blood Pressure?</title>
      <body>
         <p>second.</p>
      </body>
   </topic>
</topic>

Expected output would be:

<topic id="topic_1">
   <title>Taking</title>
   <body>
      <p><image href="https://tneb.com"/></p>
      <p>Your records.</p>
   </body>
   <topic id="topic_2">
      <title>Blood Pressure?</title>
      <body>
         <p>second.</p>
      </body>
   </topic>
</topic>

While using the image, its coming as seperate topic. But i need to come by para tag inside the h1 topic. Please provide the suggestion codes. Thanks in advance


How to have angular controller respond to a variable's value change event

I am building an application where I have several controllers controlling various parts of the page. I would like for them to respond to specific model change events. For example when $scope.Variable has a change of value, I would like for controller A to run a certain method etc.

How do I respond to model change events with controllers in angular?


SQL calculated column based on other calculated column

I have a table with a list of invoices, In one query I calculate the invoice due date based on the terms of the invoice (7days/30 days etc)

I have following layout:

InvoiceNr | InvoiceDate | InvoiceDueDate

I want to add now an extra column to put the invoice in an ageing bucket based on the current date. for example:

InvoiceNr | InvoiceDate | InvoiceDueDate | ageing

But it seems that I cannot create that extra column based on the InvoiceDueDate column because thats already a combined column. So question how can I create a query which can and calculate the duedate, and calculate the ageing of that invoice.

The base invoice table looks likes this:

Customer    Name    InvoiceTerms Description        Invoice        InvoiceDate  Value   InvoiceBal1
    0000    CASH A/C        00  CASH ONLY ACCOUNT   000000000050033 2015-11-06  0.00    0.00
    0000    CASH A/C        00  CASH ONLY ACCOUNT   000000000050034 2015-11-06  550.00  0.00
    0000    CASH A/C        00  CASH ONLY ACCOUNT   000000000050037 2015-11-09  362.18  0.00

With following query, I add the invoice due dates

    SELECT     dbo.ArInvoice.Customer, dbo.ArCustomer.Name, dbo.ArCustomer.CustomerOnHold, dbo.ArCustomer.CreditStatus, dbo.ArCustomer.TermsCode AS CustomerTerms,
                      dbo.ArInvoice.TermsCode AS InvoiceTerms, dbo.TblArTerms.Description, dbo.ArInvoice.Invoice, CAST(dbo.ArInvoice.InvoiceDate AS date) AS InvoiceDate,
                      CAST(CASE ArInvoice.TermsCode WHEN '00' THEN CAST(dbo.ArInvoice.InvoiceDate AS date) WHEN '22' THEN dateadd(month, datediff(month, 0, DateAdd(month, MONTH(InvoiceDate), DateAdd(Year,
                       YEAR(InvoiceDate) - 1900, 0) + 1)), 0) - 1 WHEN '24' THEN dateadd(month, datediff(month, 0, DateAdd(month, MONTH(InvoiceDate) + 1, DateAdd(Year, YEAR(InvoiceDate) - 1900, 0) + 1)), 0)
                      - 1 WHEN '28' THEN dateadd(month, datediff(month, 0, DateAdd(month, MONTH(InvoiceDate) + 2, DateAdd(Year, YEAR(InvoiceDate) - 1900, 0) + 1)), 0)
                      - 1 ELSE InvoiceDate + TblArTerms.DueDays + TblArTerms.InvDayOfMonth END AS date) AS InvoiceDueDate, dbo.ArInvoice.CurrencyValue, dbo.ArInvoice.InvoiceBal1
FROM         dbo.ArCustomer INNER JOIN
                      dbo.ArInvoice ON dbo.ArCustomer.Customer = dbo.ArInvoice.Customer INNER JOIN
                      dbo.TblArTerms ON dbo.ArInvoice.TermsCode = dbo.TblArTerms.TermsCode

Which gives me

Customer    Name    InvoiceTerms Description        Invoice        InvoiceDate DueDate    Value   InvoiceBal1
    0000    CASH A/C        00  CASH ONLY ACCOUNT   000000000050033 2015-11-06  2015-11-06  0.00    0.00
    0000    CASH A/C        00  CASH ONLY ACCOUNT   000000000050034 2015-11-06  2015-11-06  550.00  0.00
    0000    CASH A/C        00  CASH ONLY ACCOUNT   000000000050037 2015-11-09  2015-11-09  362.18  0.00

So what I now need is an extra column which takes the invoiceDueDate,
checks if the difference between getdate() and the invoice days is bigger then 30 then it should say overdue.

For example:

Customer    Name    InvoiceTerms Description        Invoice        InvoiceDate DueDate    Value   InvoiceBal1   Ageing
    0000    CASH A/C        00  CASH ONLY ACCOUNT   000000000050033 2015-11-06  2015-11-06  0.00    0.00      OVERDUE
    0000    CASH A/C        00  CASH ONLY ACCOUNT   000000000050034 2015-11-06  2015-11-06  550.00  0.00      OVERDUE
    0000    CASH A/C        00  CASH ONLY ACCOUNT   000000000050037 2015-11-09  2015-11-09  362.18  0.00      OVERDUE

Currently the only way I can find is creating two views.
First one with the invoiceduedate and then a second one with the ageing.
but that feels a bit overkill? So trying to find a way to do it all in one query?


QtWidgets.QFileDialog.getOpenFileName returns a Tuple

I've recently updated to the new version of Qt5 for Python. In doing so, I've been having to alter my code in accordance to some of the notable changes that have occurred. I wanted to get some insight into this line of code that I've created. It feels like a dirty way of solving the problem of getting a string instead of a tuple from the function. (Note the [0] at the end of the line)

filename = QtWidgets.QFileDialog.getOpenFileName(None, "Open " + key + " Data File", '.', "(*.csv)")[0]

I want filename = {str}'C:/.././.../format.csv'

not filename = <class 'tuple'>: ('C:/.././.../format.csv', '(*.csv)')


Uniqueness Validation on has_many association records via accepts_nested_attributes_for

Here are my Models:

class User < ApplicationRecord
  has_many :cities_users, inverse_of: :user
  has_many :cities, through: :cities_users

  accepts_nested_attributes_for :cities_users
end

class CitiesUser < ApplicationRecord
  belongs_to :user
  belongs_to :city

  validates :user_id, uniqueness: { scope: :city_id, message: "already specified that they have lived in this city"}
end

class City < ApplicationRecord
  has_many :cities_users
  has_many :users, through: :cities_users
end

While creating a new user record: The user can dynamically add cities that they have lived in (via the nested_form_fields gem ). This ultimately creates records on the join table of cities_users.

After clicking the 'Add a city you have lived in' button:

User then goes and clicks the button again to add another city:

That situation above is where I want a validation error to trigger when the user clicks the Create User button.  When creating a new user record: a user should NOT specify that they lived in the same city more than one time.

So above: without a validation: two cities_users records would be created with the same user_id and city_id.  This is no good, so I want to re-render the form, highlight the two offending cities_users nested_fields and have an error message say something like "You cannot specify that the user has lived in the same city more than once".

Clearly this requires a validation either on the user model or the cities_user model.  I do not know where the validation should go, and I do not know how to code the validation so that it catches this error.  The current uniqueness validation I have on the CitiesUser model does not catch this situation.

Extra setup information just in case someone wants to recreate the scenario

This was how I set up the nested_fields within the user _form.html.erb:

<%= f.nested_fields_for :cities_users do |ff| %>

<div>
  <%= ff.label :city_id %>
  <%= ff.collection_select(:city_id, City.all, :id, :name) %>
</div>

<% end %>

<br>

<div><%= f.add_nested_fields_link :cities_users, "Add a City You have lived in" %></div>

The users_controller#create action is standard, generated from the scaffold command.  I did add to the strong params in order to allow for the nested attributes:

def user_params
  params.require(:user).permit(:name, cities_users_attributes: [:id, :city_id, :user_id])
end


Uncaught TypeError: Cannot use 'in' operator to search for '0' in (jQuery)

I feel like this has to do with the AJAX call. Not really sure what is going on. The error is technically being thrown within the jQuery file at line 584 which defines the isArraylike(obj) function.

jQuery(document).ready(function(){
  var width_of_grams = $(window).width();
  var new_pic_height = (width_of_grams /7);
  $("img.gram_photo").css('height', (width_of_grams) / 7);
  $("#instafeed").css('height', 2*new_pic_height);

  $(window).resize(function() {
    var width_of_grams = $(window).width();
    var new_pic_height = (width_of_grams /7);
    $("img.gram_photo").css('height', (width_of_grams) / 7);
    $("#instafeed").css('height', 2*new_pic_height);
  });

  $("#school_application_fls_center_name").change(function(){
    var center_name = document.getElementById("school_application_fls_center_name").value;
    var formdata = {center: center_name};
    $.ajax({
        url: "/application/get_programs_for_center",
        type: "POST",
        data: formdata,
        success: function(response){
          var options = $("#school_application_program_name");
          console.log(response);
          $.each(response, function(i,item) {
            options.append($("<option />").val(response[i].id).text(response[i].name));
          });
        }
    });
  });
});

Here is the jQuery library code that throws the error:

function isArraylike( obj ) {
  var length = obj.length,
    type = jQuery.type( obj );

    if ( type === "function" || jQuery.isWindow( obj ) ) {
        return false;
    }

    if ( obj.nodeType === 1 && length ) {
        return true;
    }

    return type === "array" || length === 0 ||
        typeof length === "number" && length > 0 && ( length - 1 ) in obj; //THIS LINE THROWS ERROR
}

N.B. When I remove all of the callback function in the success part of the AJAX request,
   and just put a console.log to confirm I am making it to the callback successfully it prints
    my log message and does not throw the error.


Outlook auto replacing links with anchor

In my email template I have an import to use a web font:

@import url("http://fonts.googleapis.com/css?family=Open+Sans+Condensed:300");

Outlook is replacing the url content with a anchor:

@import url("<a href="http: //fonts.googleapis.com/css?family=Open+Sans+Condensed:300" class="">http://fonts.googleapis.com/css?family=Open+Sans+Condensed:300</a>");

I tried  instead but same result, what is missing?

Thanks


How to rewrite my url?

Hy!

I'm developing a web site and have a small problem with .htaccess.

Problem:
how to rewrite urls?

From: http://www.mysite.com/index.php?page=about
To:   http://www.mysite.com/about/

and

From: http://www.mysite.com/index.php?page=stuff&catId=1
To:   http://www.mysite.com/stuff/1/

and

From: http://www.mysite.com/index.php?page=stuff&catId=1#someAnchor
To:   http://www.mysite.com/stuff/1/#someAnchor

Currently I'm doing this but it doesn't work! :(

<IfModule mod_rewrite.c>
Options +FollowSymlinks
RewriteEngine on
RewriteRule ^page/([^/\.]+)/?$ index.php?page=$1 [L]
RewriteRule ^page/([^/.]+)/([^/.]+)/?$ index.php?page=$1&catId=$2 [L]
</IfModule>

Please help.
Thanks in advance, Silvano.


WPF Itemscontrol datatemplate property changing

I'm currently using the following itemscontrol and datatemplate:

<UserControl.Resources>
    <DataTemplate x:Key="OrdersTemplate">
        <dxlc:LayoutItem Label="CustomerReference" LabelPosition="Top" MaxWidth="300" HorizontalAlignment="Left" Width="300">
            <dxe:TextEdit IsEnabled="True" Text="{Binding Path=CustomerReference}" />
        </dxlc:LayoutItem>
    </DataTemplate>
</UserControl.Resources>

<HeaderedContentControl Header="Steps">
    <ItemsControl ItemsSource="{Binding Orders}" ItemTemplate="{StaticResource OrdersTemplate}"/>
</HeaderedContentControl>

The source is just a list with entities.

The problem is that the "CustomerReference" of every object from my source changes when I change it in the textbox. Whats missing here?

Greets


Too many cartesian products, making query to run slower

Consider I have two tables DETAILS AND RATE with following columns:

DETAILS table:

CREATE TABLE DETAILS(
LONG ID PRIMARY KEY AUTO_INCREMENT,
DOUBLE PRICE1,
DOUBLE PRICE2,
DOUBLE PRICE3,
VARCHAR(25) CURRENCY,
DATE CREATED_DATE,
VARCHAT(50) COMPLETED
..................
Few more columns
);

RATE TABLE:

CREATE TABLE RATE(
LONG ID PRIMARY KEY AUTO_INCREMENT,
DOUBLE RATE,
VARCHAR(25) CURRENCY,
DATE CREATED_DATE
..................
Few more columns
);

And I have a update query for DETAILS table as shown bellow.

UPDATE DETAILS D, RATE R
SET D.PRICE1=D.PRICE1*R.RATE,
D.PRICE2=D.PRICE2*R.RATE,
D.PRICE3=D.PRICE3*R.RATE
WHERE
D.CURRENCY=R.CURRENCY AND
DATE(D.CREATED_DATE) = DATE(R.CREATED_DATE) AND
D.COMPLETED IS NULL OR DO.COMPLETED='ABC' AND
D.CURRENCY!='RUPEE';

Before the query was working fine but as table grown this query is started taking more time and it is giving cartesion product in terms of billions.

Is there any way I can optimise this query?
Any help will be greatly appriciated.


Haskell: Algebraic types error (Suffix trees: recursion)

Working on a function that given a SuffixTree as input, outputs the list of integers in that suffix tree. For example. getIndices tree1 = [2,4,1,3,5,0] . The order of the list of integers does not matter. I am getting the error, on the second last line of the function: "Couldn't match expected type 'SuffixTree' with actual type '[SuffixTree]'". I have thought about this for a long time now and have had no luck. Any help would be greatly appreciated.

data SuffixTree = Leaf Int | Node [ ( String, SuffixTree ) ]
            deriving (Eq,Ord,Show)

text1 :: String
text1 = "banana"

tree1 :: SuffixTree
tree1 = Node [("banana",Leaf 0),
              ("a",Node [("",Leaf 5),
                         ("na",Node [("",Leaf 3),
                                     ("na",Leaf 1)])]),
              ("na",Node [("",Leaf 4),
                          ("na",Leaf 2)])]

------------------------------------------------------------------

getIndices :: SuffixTree -> [ Int ]
getIndices sufTree = getIndices' sufTree []
  where getIndices' :: SuffixTree -> [Int] -> [Int]
        getIndices' (Node ((_, Node xs):ys)) c
          | Node xs == Node [] = c
          | otherwise = getIndices' ((Node xs):([Node ys])) c
        getIndices' (Node ((_,Leaf i):xs)) c = getIndices' (Node xs) (i:c)


Left Associativity vs Left Recursion

I'm trying to write a compiler for C (simpler grammar though).

There is something that I've been stuck on for a while. If I understated correctly, all binary operations are left associative. So if we have we "x+y+z", x+y occurs first and then followed by plus z.

However, doesn't enforcing left associativity causes infinite left recursion?

So far all solutions that I've checked are either left associative or don't have left recursion, but not both. Is it possible to have a grammar that have both of these properties. Is it even possible?

Example:

Left Associative:

Expr = Term | Expr + Term
Term = Element | Term ∗ Element
Element = x|y|z|(Expr)

Left Recursion Eliminated:

Expr = Term ExprTail
ExprTail = epsilon | + Term ExprTail

Term = Element TermTail
TermTail = epsilon | * Element TermTail

Element = x|y|z|(Expr)

Any ideas?


LDAP how to modify attribute _name_

I need to update for some thousand entries the name of an LDAP attribute, eg.
cn=myentry,ou=people,o=mycompany has an attribute like surname and it shall be renamed to lastname and preserve the value.

Any clue how to achieve this with ldiff-commands?
Just to be clear I don't want to rename the rdn but the attribute name.


Adding an array of UIButtons to navigationItem.rightBarButtonItem results in NSInvalidArgumentException

I am trying to add an array of 2 buttons to the right of a navigation bar, but I get a exception when I run the code.

'NSInvalidArgumentException', reason: '-[UIButton isSystemItem]: unrecognized selector sent to instance

My code is pretty simple really:

   UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(0,0,100,45)];
   label.backgroundColor=[UIColor clearColor];
   label.text = @"Test 2 Buttons";

   UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
   button1.frame = CGRectMake(00.0f, 0.0f, 32.0f, 32.0f);

   UIButton *button2 = [UIButton buttonWithType:UIButtonTypeCustom];
   button2.frame = CGRectMake(00.0f, 0.0f, 32.0f, 32.0f);

   NSArray *rightBarButtons = [[NSArray alloc] initWithObjects:button2, button1, nil];

   UINavigationItem* navItem = self.navigationItem;
   navItem.titleView = label;
   navItem.rightBarButtonItems = rightBarButtons;
   [rightBarButtons release];
   [label release];

I am running it on the iPhone 5.0 simulator.
Any idea??
Thanks in advance.
Al


Telerik RadControls + JetBrains Resharper = VERY SLOW, Can anyone help?

Anyone know of a way to speed up the Visual Studio IDE when you have Telerik RadControls (either windows or web) and JetBrains ReSharper installed?  If I disable ReSharper it runs rocking fast, but I love ReSharper a bit too much to drop it.  I know it would perform better without the RadControls.  Anyone know a way to speed it up?


double for loops in python

I am trying to get a list of file names in order. Something like

files-1-loop-21
files-1-loop-22
files-1-loop-23
files-1-loop-24
files-2-loop-21
files-2-loop-22
files-2-loop-23
.
.
.
and so on

As for testing I have written python code as below:

code sample_1:

for md in range(1,5):
   for pico in range(21,25):
      print md, pico

It gives me pair of number such as:

  `1 21
   1 22
   1 23
   1 24
   2 21
   2 22
   2 23
   2 24
   3 21
   3 22
   3 23
   3 24
   4 21
   4 22
   4 23
   4 24

`

if I use:

code sample_2:

 for md in range(1,5):
   for pico in range(21,25):
  print "file-md-loop-pico"

I get

  files-md-loop-pico
  files-md-loop-pico
  files-md-loop-pico
  files-md-loop-pico
  files-md-loop-pico
  files-md-loop-pico
  files-md-loop-pico

How (code sample_2) should be altered to get the file lists as I wanted (as shown in the beginning of this post) in python?

Thanks in advance.

Regards


inmobi landscape interstitial ads for android

Does anybody know how to make inmobi interstitial ads only landscape orientation for Android?
I tried to send post request with parameter "d-orientation", but nothing happened.

Map<String, String> map = new HashMap<String, String>();
map.put("d-orientation", "3");
request.setRequestParams(map);


Creating Wifi links between APs and the server on ns-3

Say I want to have 3 APs serving 60 users, and these APs are in turn wirelessly (Using Wifi) connected to the server. How would I create such a topology?

At this moment, I was thinking that 'wifiStaNodes' can represent the users, 'wifiApNodes' can represent the APs. How do I make these APs relay information to the server through Wifi? This is my attempt: I have created 'wifiServer', which is the server node.

//Topology
// ------> denotes a Wifi Link

u0 u1 u2 .....   ------> AP1
..............
..............   ------> AP2  -----> Server
..............
...u58 u59 u60   ------> AP3

int nWifi = 60;
int nAP = 3;

NodeContainer allNodes;

NodeContainer wifiStaNodes; //User Nodes
wifiStaNodes.Create (nWifi);
allNodes.Add (wifiStaNodes);

NodeContainer wifiApNodes ; //Access Points
wifiApNodes.Create (nAP);
allNodes.Add (wifiApNodes);

NodeContainer wifiServer; //Server
wifiServer.Create (1);
allNodes.Add(wifiServer.Get(0));

YansWifiChannelHelper channel = YansWifiChannelHelper::Default ();
YansWifiPhyHelper phy = YansWifiPhyHelper::Default ();
WifiHelper wifi;
wifi.SetRemoteStationManager ("ns3::ConstantRateWifiManager","DataMode", StringValue("VhtMcs9"), "ControlMode", StringValue("VhtMcs9"));
wifi.SetStandard (WIFI_PHY_STANDARD_80211af);
channel.AddPropagationLoss("ns3::TwoRayGroundPropagationLossModel","Frequency",DoubleValue(300e+06));

//Setting Physical layer parameters for the User Nodes
phy.Set("TxPowerStart",DoubleValue(20)); // 40mW = 16.02dBm
phy.Set("TxPowerEnd",DoubleValue(20));
phy.Set("TxPowerLevels", UintegerValue(1));
phy.Set("TxGain",DoubleValue(0));
phy.Set("RxGain",DoubleValue(-3));
phy.Set("EnergyDetectionThreshold",DoubleValue(-88));
phy.SetChannel (channel.Create ());

WifiMacHelper mac;
Ssid ssid = Ssid ("ns-3-ssid");

NetDeviceContainer staDevices;
mac.SetType ("ns3::StaWifiMac","Ssid", SsidValue (ssid),"ActiveProbing", BooleanValue (false));
staDevices = wifi.Install (phy, mac, wifiStaNodes);

//Setting Physical Layer parameters for Access Points and Server
phy.Set("TxPowerStart",DoubleValue(20)); // 40mW = 16.02dBm
phy.Set("TxPowerEnd",DoubleValue(20));
phy.Set("TxPowerLevels", UintegerValue(1));
phy.Set("TxGain",DoubleValue(30));
phy.Set("RxGain",DoubleValue(0));
phy.Set("EnergyDetectionThreshold",DoubleValue(-78));

NetDeviceContainer apDevices,serverDevice;
mac.SetType ("ns3::ApWifiMac","Ssid", SsidValue (ssid));
apDevices  = wifi.Install (phy, mac, wifiApNodes);
serverDevice = wifi.Install (phy, mac, wifiServer);

Ptr<BasicEnergySource> energySource = CreateObject<BasicEnergySource>();
Ptr<SimpleDeviceEnergyModel> energyModel = CreateObject<SimpleDeviceEnergyModel>();

energySource->SetInitialEnergy (100);
energyModel->SetEnergySource (energySource);
energySource->AppendDeviceEnergyModel (energyModel);
energyModel->SetCurrentA (20);

// aggregate energy source to node
wifiServer.Get(0)->AggregateObject (energySource);

// Install internet stack
InternetStackHelper stack;
stack.Install (allNodes);

// Install Ipv4 addresses
Ipv4AddressHelper address;
address.SetBase ("10.1.0.0", "255.255.192.0");
address.Assign (staDevices);
address.Assign (apDevices);
address.SetBase ("10.2.0.0", "255.255.192.0");
Ipv4InterfaceContainer serverInterface;
serverInterface = address.Assign (serverDevice);
address.Assign (apDevices);

// Install applications

UdpEchoServerHelper echoServer (9);
ApplicationContainer serverApps = echoServer.Install (wifiServer.Get(0));
serverApps.Start (Seconds (1.0));
serverApps.Stop (Seconds (5.0));
UdpEchoClientHelper echoClient (serverInterface.GetAddress(0), 9);
echoClient.SetAttribute ("MaxPackets", UintegerValue (10));
echoClient.SetAttribute ("Interval", TimeValue (Seconds (3)));
echoClient.SetAttribute ("PacketSize", UintegerValue (1024));
ApplicationContainer clientApps = echoClient.Install (wifiStaNodes);
clientApps.Start (Seconds (2.0));
clientApps.Stop (Seconds (5.0));

Ipv4GlobalRoutingHelper::PopulateRoutingTables ();
Simulator::Stop (Seconds (4.0));

MobilityHelper mobility;
mobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel");
mobility.Install (wifiStaNodes);
mobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel");
mobility.Install (wifiApNodes);

I receive the following error:

aborted. cond="!(networkHere == networkThere)", msg="GlobalRouter::ProcessSingleBroadcastLink(): Network number confusion", file=../src/internet/model/global-router-interface.cc, line=852


Python: MemoryError in generating a array

I am using anaconda2 with python 2.7 in 64-bit wind10 with RAM of 4G. My codes are as follows:

number_of_documents = 21578
document_max_num_words = 100
num_features = 500
X = np.zeros(shape=(number_of_documents, document_max_num_words, num_features)).astype('float32')

In generating x, the memory error occurs.


iOS - push notifications not determined

is there any workaround to find out if user has been ever asked for push notifications permissions?
Calling isRegisteredForRemoteNotifications directly is not sufficient for me.
I have a screen that changes based on whether it is a first launch of app or not.

If it is it says that app can send push notifications and when prompted please tap Allow. Then user click Got it button and and VC with push notifications prompt is displayed.

However if user signup up again on another account (push notifications are remembered) I want to display info that he needs to go Settings to allow push notifications (if they are disabled) or just simply skip notifications prompt screen (if user allowed them).

So in other words i need to know not if user has allowed push notification but if he was ever asked for them.

I've tried to save some data in keychain after user was asked but when app is deleted and installed again (after one day or more so push notifications settings are reseted) user is not asked (I only check if there is my flag in keychain).

Thanks for help

Edit #1 I added image that presents my problem

Actually screens with OK and Go to settings buttons are not seperate View Controllers but it really doesn't matter.


SQL server user session time out?

i use window application and i want to fire trigger after user session time out So ,

How to detect if user abort or his session timeout using SQ L server 2008 ?


restric access json data with grape and rails 3

I have a json data in this address:

http://localhost:3000/api/v1/apisearch

These json data are generated with grape gem https://github.com/intridea/grape:

class API_v1 < Grape::API
  version 'v1', :using => :path, :vendor => 'myapp', :format => :json
    get :apisearch do
      Object.search({query: "*#{params[:q]}*"}).map{ |object| {id: object.title, text: object.description } }
    end
 end

I have a search engine that get data from this address with select2

This is my coffescript file:

jQuery ->
  $('#query_txt').select2
    width: 'resolve'
    allowClear: true
    minimumInputLength: 2
    ajax:
      url: "api/v1/apisearch"
      dataType: 'json'
      data: (term, page) -> {q: term}
      results: (data, page) ->
        results: data

The script is working very fine, but I would like protect this address of external requests.

I don't want to allow a user if type http://localhost:3000/api/v1/apisearch can access to these data. Only can access to these data my internal search engine from my own application.

How can I restric access data only to my own application from grape?

Thank you


Combining 2 queries into 1 query

How would I combine the results of the first query with the second query where the EMPLID column for both the Z_EMP_YAN table and the Z_OPRDEFN table match up?

select b.OPRID
from Z_EMP_BENFT a, PSOPRDEFN b
WHERE a.EMPLID = b.EMPLID
AND A.Z_PEND_COVER = 'Y'
AND OPRID LIKE 'ZZ%'

select EMPLID from z_emp_yan where z_yan_action_id = 1


What am I doing wrong: Structure cannot be indexed because it has no default property (WITH CLAUSE)

Am getting: "Structure cannot be indexed because it has no default property". What am I doing wrong?

With grid.Rows(10).Cells
    Dim note As New Note With {.ID = "Blah", _
                               .Date = "1/1/2011", _
                               .Message = "AAA", _
                               .Type = "ABC", _
                               .SubType = "DEF", _
                               .ReferenceKey = !SetRefNum.Value}
End With

And Note looks like:

Public Structure Note
    Public Property ID As String
    Public Property [Date] As Date
    Public Property Message As String

    Public Property Type As String
    Public Property SubType As String
    Public Property ReferenceKey As String
 End Structure


overloading class operator new with dependency

How does one provide a dependency to a class for use in operator new, without using a global?

If I understand correctly, if I want to customize the behavior every time someone creates an instance of my type, then I have to overload operator new as a class method. That class method is static, whether I declare it static or not.

If I have a class:

class ComplexNumber
{
public:

    ComplexNumber(double realPart, double complexPart);
    ComplexNumber(const ComplexNumber & rhs);
    virtual ~ComplexNumber();

    void * operator new  (std::size_t count);
    void * operator new[](std::size_t count);

protected:

    double m_realPart;
    double m_complexPart;
};

and I want to use an custom memory manager that I created to do the allocation:

void * ComplexNumber::operator new  (std::size_t count)
{
     // I want to use an call IMemoryManager::allocate(size, align);
}

void * ComplexNumber::operator new[](std::size_t count)
{
    // I want to use an call IMemoryManager::allocate(size, align);
}

How do I make an instance of IMemoryManager available to the class without using a global?

It does not seem possible to me, and therefore forces bad design where the class is tightly coupled to a particular global instance.


how can I remove multiple new line and space(white char) from a string?

A String looks like this : "   I am   seal \n\n  \t   where are we? ". and the printed version

   I am  seal

      where are we?

I want to make the string like : "I am seal\nwhere are we?"

I am seal
where are we?

I am removing the new line with "[\r\n]+", "\n" this regex but the problem is when I am trying to remove the white space it also remove the newline. I have used StringUtils from Apache-common.

update

Also white space from the beginning of a line also be removed. It should not be consecutive.

How can I achieve this in Java ?

Thank you.


Bootstrap 3 - Different grid sizes with different alignments

I use bootstrap 3 and my site has 2 cols. The left content is left align and the right content is right align. On smaller display I will work with 1 col. So the right col is under the left col. That works fine.

But I want that on smaller displays both cols have left alignment. Is this possible?

Here my current code:

<div class="row">
   <div class="col-lg-6 col-md-6 col-xm-12 col-xs-12 text-left">
      content a
   </div>
   <div class="col-lg-6 col-md-6 col-xm-12 col-xs-12 text-right">
      content b
   </div>
</div>


should autoboxing be avoided in Java

I want to ask if autoboxing should be avoided in Java. As there are instances where a method expects a primitive type 'double' and you pass a 'Double' object as a parameter, should this be avoided as compiler unboxes your passed object and could be heavy?


How bad is it to launch many small kernels in CUDA?

I have a grid of rectangles. Each of these rectangles consists of a rectangular grid of points. All points inside the rectangle can be treated by exactly the same instruction sequence in a kernel. I will be able to launch a kernel with 10000s of points to handle, where each thread would handle about 10-50 points. The points on the edges and on the corners of the rectangles however will lead to a large set of different instruction sequences.

From a design point of view, it would be easier to launch a kernel for each set of points with the same instruction sequence. This would mean that some kernel launches would only treat very few points, probably less than 10.

So I would have maybe 4 kernel launches with 10000s of points to handle (10-50 points for each thread), and maybe 30-100 kernel launches with only a few points each (1 point per thread normally).

I have absolutely no idea whether this is acceptable or whether it will completely destroy my performance. I would be glad if you could give me a rough estimate or at least some hints, what to consider to get an estimate.


Are there predefined functions in scipy/numpy to shift/rotate an image that use sinc-interpolation instead of spline interpolation?

The question title summarizes it well I hope. I have a large batch of images which I want to register. For this purpose I need to shift/rotate the images. So far I have used scipy.ndimage.rotate and scipy.ndimage.shift for this task. However, some of the images have sharp intensity features for which the higher order spline interpolation fails (i.e. produces ringing artefacts). Lower order (0 or 1) splines are not preserving the image data well enough.

Is there a build in task in scipy/numpy (or any other package in principle) that uses sinc interpolation (http://en.wikipedia.org/wiki/Whittaker%E2%80%93Shannon_interpolation_formula)?

I have searched around for quiet a while myself but have not come up with any easy solutions, if I have missed something obvious please point me in the right direction.


Get data from iframe

I am doing this first time. I have created an iframe on my page and I want the text from the iframe through jquery.
Here is my code :

<html>
  <head><script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>

    <script type="text/javascript">
    function copyIframeContent(iframe){
        var iframeContent = $(iframe).contents(); //alert(iframeContent);
        //$("#result").text("Hello World");
        $("#result").html(iframeContent.find('body').html);alert(iframeContent.find('body').html());
    }
    </script>
  </head>
  <body>
    <iframe id="myIframe" onload="copyIframeContent(this);" name="myIframe" src="text.php"></iframe><br />
    Result:<br />
    <textarea id='result'></textarea>
    <input type="button" value="click" id="btn" onclick="aa()">
    <script type="text/javascript">
         function aa(){  alert("Fdf");
            alert(document.getElementById('myIframe').contentWindow.document.body.innerHTML);
    }
    </script>
  </body>
</html>

text.php:

text to change

I tried a lot in all browsers but still this is not working.
Can anyone help me to get this content?


Selecting nodes with different classes in XPath in PHP

I'm attempting to use XPath to select nodes that have different classes. Only two, in this case. One is "msg_head" and the other is "msg_sub_head".

The following is currently the string I'm running with after many hours of Googling and searching here on Stack Overflow. I feel I'm close, but not quite there.

//*[contains(concat(' ',@class,' '),' msg_head') and (contains(concat(' ',@class,' '),' msg_sub_head'))]


Taking specific order of differences of elements in a vector, MATLAB

I have the following vector:

A = [1 2 3 4 5 6]

I want to take the the difference between the third element and the first (A(3)-A(1))

and then fourth and second element (A(4)-A(2)) and so on.

How do I do this?

Thank you!


set dropdown box and display last selected item in php

i need to populate a select box with values and
i need to select box to display last selected item(from db).The goal is to let the user update the details.
And i have more than 30 items in the select box.i am new to php ..help me


django login popup

I've been trying to figure out how to do a modal login in django and have been having some trouble. Is this possible? It seems like it should be. I imagine the solution involves writing a view that takes a POST request and returns some JSON.

Are there any examples out there of how to do this in a clean way?


jQuery based Splitter plugin

I need to create a layout as below;

Now as you can see, I want resizable cells around Cell-center i.e for cell-left and cell-right

I was using the jQuery plugin at http://methvin.com/splitter/3csplitter.html
to achieve the same.

But I also needed to create 4 portlets (as you can see for cell-center) . I used jQuery UI for the same and for some reasons, the 2 are not going very well (3cSplitter and jQuery UI Portlets)...the layout gets broken completely...not sure if it has to do with absolute positioning...

But my question is, can I use jQuery UI to acheive similar kind of splitter. The  one that I saw under http://jqueryui.com/resizable/
does not seem to be very good for what I want as http://methvin.com/splitter/3csplitter.html
If both are jQuery UI based, I guess the integration issues would not be much...


node.js monitoring for when a file is created

I am writing a node.js program that needs to do something as soon as a file with a certain name is created in a specific directory. I could do this by doing repeated calls to fs.readdir until I see the name of the file, but I'd rather do something more efficient. Does anyone know of a way to do this?


Angular 2 submodule routing with AOT and Rollup

What is the correct way to configure a submodule in Angular 2 so that it will work after AOT and rollup? I'm not concerned about lazy loading and will be happy for all submodules to be bundled together, but loadChildren is the cleanest way of referencing a submodule and having it use the correct <router-outlet>, and although I've tried various methods, none will work in both development and production.

I followed the instructions in the AOT cookbook to prepare my app for deployment. My module structure is root > account > admin, and I want the admin routes to load in the outlet defined by the account component.

Here's the router config for the account module:

import { NgModule } from '@angular/core';
import { AdminModule }   from './admin/admin.module';

const accountRoutes: Routes = [{
    path: 'account',
    component: AccountComponent,
    children: [
        { path: 'setup', component: SetupComponent },
        { path: 'admin', loadChildren: () => AdminModule }
    ]
}];

This works in development, but NGC compilation fails with Error: Error encountered resolving symbol values statically. Reference to a local (non-exported) symbol 'accountRoutes'.

I added an export to accountRoutes but this also fails to compile with Error: Error encountered resolving symbol values statically. Function calls are not supported..

One suggestion was to use a string instead of a function so that NGC can compile the code:

loadChildren: 'app/account/admin/admin.module#AdminModule'

This works in development and compiles successfully but the compiled app will not run, because SystemJS is unavailable. The error is:

ERROR Error: Uncaught (in promise): TypeError: System.import is not a function
TypeError: System.import is not a function
at t.loadFactory (build.js:6)
at t.load (build.js:6)
at t.loadModuleFactory (build.js:12)

I tried including SystemJS in the production build but it could not find the separate module file app/account/admin/admin.module.ngfactory - after rollup everything is in one build.js. There may be a way to have separate rollups build each submodule, but that's a lot of work.

I found the suggestion of referring to an exported function:

export function loadAdminModule() {
    return AdminModule;
}

loadChildren: loadAdminModule

This works in development, but in production the runtime compiler is unavailable so it logs build.js:1 ERROR Error: Uncaught (in promise): Error: Runtime compiler is not loaded.

The helper function can be modified so it works in production by referencing the NgFactory instead, but this won't work in development.

import { AdminModuleNgFactory }   from '../../../aot/src/app/account/admin/admin.module.ngfactory';

export function loadAdminModule() {
    return AdminModuleNgFactory;
}

loadChildren: loadAdminModule

Is there a supported way of using loadChildren so that it will work with the instructions in the AOT cookbook? Is it better to use webpack instead?


Avoiding parallel arrays with Objective-C and C++

Some context: I am writing a 2D Destructible terrain library for Cocos2D/Box2D which involves a hybrid of C++ and Objective-C. I recently encountered a situation that has stumped me where I can't think of a solution that doesn't involve parallel arrays.

In order for the physics boundaries to be defined around the terrain, an initial trace must be made of the terrain border. I make a function call to trace all isolated bodies of pixels within a texture and cache them. This creates the following data structures

An NSMutableDictionary "borderPixels" with the key being equal to an CGPoint wrapped in an NSValue which is equal to the pixel's unique location. This holds all traced pixels.

A circular linked lists with TerPixels pointing to their next neighbor pixel

An NSMutableArray "traceBodyPoints" which holds a single TerPixel representing a 'start' point of a terrain body. I only store TerPixel *'s here where I need to trace a physics body. So, if a terrain body has been modified, I insert any individual TerPixel * from the modified body into this array. I can then reference each of these and traverse the linked list to trace the physics body.

Here is some code to help paint a better picture of the situation:

-(void)traverseBoundaryPoints:(CGPoint)startPt {

if (!borderPixels) borderPixels = [[NSMutableDictionary alloc] init]; // Temp
if (!traceBodyPoints) traceBodyPoints = [[NSMutableArray alloc] init]; // Temp

TerPixel * start = [[TerPixel alloc] initWithCoords:startPt.x ypt:startPt.y prevx:-1 prevy:0];
TerPixel * next = start;
//CCLOG(@"Start of traverseBoundary next.x and next.y %d, %d", next.x, next.y);
TerPixel * old;

while (true) {

    old = next;
    next = [self findNextBoundaryPixel:next];
    [next setNSP:[old subTerPixel:next]];
    old.nextBorderPixel = next;

    if (next.x == start.x && next.y == start.y) {
        CCLOG(@"SUCCESS :: start = next");
        next.nextBorderPixel = start; // Make the linked list circular
        NSValue * pixLocVal = [next getAsValueWithPoint];
        [borderPixels setObject:next forKey:pixLocVal];
        // Add the pixel to the tracePoints array to be traversed/traced later
        [traceBodyPoints addObject:start];
        break;
    } // end if

    // Connect the linked list components

    NSValue * pixLocVal = [next getAsValueWithPoint];
    [borderPixels setObject:next forKey:pixLocVal];

} // end while
} // end traverse function

Here is where I can't find a solution. I need to relate each TerPixel * in the traceBodyPoints array to a Box2D b2Body which will be created and added to the physics world. In my library, each isolated body of pixels within a texture corresponds to a Box2D body. So, when an event happens that destroys a chunk of the terrain, I need to destroy the body associated the the destroyed pixels and retrace ONLY the altered bodies. This means I need a way to associate any given TerPixel * to a Box2D body *.

In Objective-C with ARC, to my knowledge, I cannot include C++ objects/pointers in Objective-C containers without bridge casting to void *'s. Problem is these operations need to be incredibly performant and engaging in bridge casting is very costly. Also, I don't want to include a pointer to a Box2D body in every single TerPixel. This would be a nightmare to ensure there are no dangling pointers and require pointless iteration to nil pointers out.

Here is my logic for creating physics boundaries

-(void)createPhysicsBoundaries {

if ([self->traceBodyPoints count] == 0)  {
    CCLOG(@"createPhysicsBoundaries-> No bodies to trace");
    return;
}

// NEED LOGIC HERE TO DELETE ALTERED BODIES
// NEED TO DELETE EXISTING BOX2D BODY AND RE-TRACE A NEW ONE

// For each body that has been altered, traverse linked list to trace the body
for (TerPixel * startPixel in self->traceBodyPoints) {
    TerPixel * tracePixel = startPixel.nextBorderPixel;

    b2BodyDef tDef;
    tDef.position.Set(0, 0);
    b2Body * b = self->world->CreateBody(&tDef);
    self->groundBodies->push_back(b);
    b->SetUserData((__bridge void*) self);
    b2EdgeShape edgeShape;

    CCLOG(@"StartPixel %d, %d", startPixel.x, startPixel.y);
    while (tracePixel != startPixel) {
        b2Vec2 start = b2Vec2(tracePixel.x/PTM_RATIO, tracePixel.y/PTM_RATIO);
        //CCLOG(@"TracePixel BEFORE %d, %d", tracePixel.x, tracePixel.y);
        tracePixel = tracePixel.nextBorderPixel;
        //CCLOG(@"TracePixel AFTER %d, %d", tracePixel.x, tracePixel.y);
        b2Vec2 end = b2Vec2(tracePixel.x/PTM_RATIO, tracePixel.y/PTM_RATIO);
        edgeShape.Set(start,end);
        b->CreateFixture(&edgeShape, 0);
    } // end while

} // end for
} // end createPhysicsBoundaries

Hopefully this makes sense. If you need a visual of what is happening, here is a video. http://www.youtube.com/watch?v=IUsgjYLr6e0&feature=youtu.be where the green boundaries are physics boundaries.


Asp.Net MVC RequireHttpsAttribute or Response Redirect doesn't work in IIS6

I am using RequireHttps attribute to redirect Http to Https. It works fine in my dev machine which has IIS7.5 installed. However, it doesn't work in IIS 6 in Windows Server 2003. Thus, I have got Http error 403.4.
I have tried to use Response.Redirect(), it doesn't work either. So it seems that redirection doesn't work properly in II6.
I am using .Net 4, MVC 3, and QA machine is Windows server 2003 with IIS6.
Does anyone know how to solve this problem?

Thanks!
huang


How to maintain both debug and appstore release version in test device?

I have an iPhone application released at App Store. In development of next version, I want to maintain these two versions on test device(iPhone).

But when I tried to run the next version for debug on the test device, it overwrites the release version downloaded from the App Store. At the first, I guessed it can be done by changing the version number in xcode target setting > summary > iOS Application Target, but it's not. I have changed the both 'Version' and 'Build' number in iOS Application Target.

App Store version number is 1.1 and debug version number is 1.2

So, how can I get this work?


iOS 1 point view showing up blurred

i have a view that is supposed to emulate the separator in a table view.  it is one point in height, calculated by

#define kViewHeight 1.0
CGFloat height = kViewHeight / [[UIScreen mainScreen] scale];

but the view comes across with something like an etched look depending on where it is displayed on the screen.  for example, the same view will be a clear one pixel in height, but when the view is scrolled it changes.  a few examples below of the same 3 separator views before and after scrolling.  the views are the same, just had to move to the right to avoid text, so the chevrons are now in the picture.  in the first, the top view is blurry, the bottom two are fine, in the second it's the opposite.


Why is my print function printing the () and the "" along with the statement?

This is my code for a challenge in Python Programming for the Absolute Beginner

    food = input("What is your favorite entree? ")

    dessert = input("What is your favorite dessert? ")

    print("\nI am going to assume that your favorite meal is" , food +   dessert)

Instead of printing

I am going to assume that your favorite meal is

It is printing

('\nI am going to assume that your favorite meal is', 'steakcookies')

What do I need to change?


C++ header include conflict

I am working on a traffic simulation program for school. My Simulation class reads in a list of vehicles from an XML file, so I have included Vehicle.h in my Simulation class. I want my vehicle to be able to hold a pointer to the simulation object so that it can use the simulation's searchRoads function. So I included Simulation.h in my Vehicle class.

When I did this, I got over 100 errors when I tried to compile. I'm pretty iffy on my C++ so if I committed some sort of cardinal sin, please let me know how to rectify this.


mciSendString randomly stops working

My code

    char MusicLoc [50][200];
    char Music [50][50];
    int MusicBox(int IndexMusic)
    {
    std::string rawloc = ((std::string)"open \""+MusicLoc[IndexMusic]+Music[IndexMusic]+"\"type mpegvideo alias "+Music[IndexMusic]);`
    mciSendString(rawloc.c_str(), NULL, 0, 0);
    mciSendString(((std::string)"play "+Music[IndexMusic]).c_str(), NULL, 0, 0);
    return 0;
    }

MusicLoc contains the path and Music contains the filename, so MusicLoc[1]+Music[1] would be C:\etc\etc\etc\audio.mp3 , it worked fine at first but then it randomly stopped working , I have tried everything and it doesn't work so I am gonna guess using mciSendString isn't recomended, so does anyone knows about a good and lightweight audio library?

Edit:
The first mciSendString returns 266, and the second one return 275, if its of any use, but I really haven't found good documentation about them.

Also GetLastError says there is no error...


I want to access the MS SQL Server and have the select query. I have installed the dll files and am using the sqlsrv_query. The connection has been successful but I get:

[Microsoft][SQL Server Native Client 11.0][SQL Server]Invalid object
  name as error

I am using PHP version 5.3.1

After the connection I have this code

$sql = "SELECT id, latitude, longitude from job ";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false) {
    die( print_r( sqlsrv_errors(), true) );
}

while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
      echo $row['latitude'].", ".$row['longitude']."<br />";
}
sqlsrv_free_stmt( $stmt);


How to programmatically post like and comment an URL on facebook?

This is confusing. So just to clarify:

REQ #1: To fetch basic stats for a URL, you send GET request to:

http://graph.facebook.com/?ids=http://some.com

(alternatively, FQL can be used to fetch stats for a URL, but that doesn't return the OpenGraph Object)

REQ #2: To fetch comments for a URL, you do a GET:

http://graph.facebook.com/comments/?ids=http://some.com

REQ #3: To fetch likes for a URL, you GET:

http://graph.facebook.com/likes/?ids=http://some.com

But how do you comment on / like a URL programmatically?

I guess, likes can be created using Open Graph API, right?

https://graph.facebook.com/me/og.likes?object=1234

where 1234 is the OpenGraph Object ID of an article (as returned by REQ #1).
But this requires an approval process, the like action has to be approved by Facebook.

Is there a better way to do this? Can I use for example the Graph API for all these things?

My goal:

Currently I'm using the Facebook like button and comments plugin to create likes and comments. But these use the JS SDK, which is huge, and they generate a lot of external requests. I wanna get rid of them and just send an AJAX request to my server, which would then asynchronously talk to Facebook, and it would post the Like / Comment.

Is this possible?

Thanks in advance!


I am getting below error while using ui-grid in angular js

var app = angular.module("finApp", ["ui.grid"]);
app.controller(
  "finController",
  function($scope, $http) {
    $http.get("url", "data")
      .then(function(response) {
        $scope.gridOptions.data = response.data;

      }, function(errorResponse) {});
  });

<link href="https://cdn.rawgit.com/angular-ui/bower-ui-grid/main/ui-grid.min.css" rel="stylesheet"/>
<script src="https://cdn.rawgit.com/angular-ui/bower-ui-grid/main/ui-grid.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ui-grid="gridOptions" class="grid"></div>

While executing above code I am getting below error:

angular.min.js:122 TypeError: Cannot read property 'data' of undefined

              at new  (ui-grid.js:3330)

              at Object.invoke (angular.min.js:43)

              at Q.instance (angular.min.js:93)


How to close JOptionPane

I have a JoptionPane like below. However, when I select a value and hit 'OK' it does return the value, but the frame still remains as is. Only after 'cancel' or 'X' mark on the top, it closes. How to fix this.

 JOptionPane.showInputDialog(
                null,
                "Select the user",
                "Users",
                JOptionPane.INFORMATION_MESSAGE,
                null,
                userNames,
                userNames[0]);