Getting exceptions in dialog box having endless adapter implementation for its listview

This is my Demo Adapter.

public class DemoAdapter extends EndlessAdapter {

    private RotateAnimation rotate = null;
    private View pendingView = null;
    private ArrayList<ShipTo> next;
    private static ArrayList<ShipTo> list;
    private int pageFrom = 1;
    private static Activity act;

    DemoAdapter(Context ctxt, ArrayList<ShipTo> list) {
        super(new Adapater());
            act = (Activity) ctxt;
        DemoAdapter.list = list;
        rotate = new RotateAnimation(0f, 360f, Animation.RELATIVE_TO_SELF,
                0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        rotate.setDuration(600);
        rotate.setRepeatMode(Animation.RESTART);
        rotate.setRepeatCount(Animation.INFINITE);
    }

    @Override
    protected View getPendingView(ViewGroup parent) {
        View row = LayoutInflater.from(parent.getContext()).inflate(
                R.layout.row, null);

        pendingView = row.findViewById(android.R.id.text1);
        pendingView.setVisibility(View.GONE);
        pendingView = row.findViewById(R.id.throbber);
        pendingView.setVisibility(View.VISIBLE);
        startProgressAnimation();

        return (row);
    }

    @Override
    protected boolean cacheInBackground() {
        // SystemClock.sleep(1000); // pretend to do work
        pageFrom += 10;
        next = ItemController.getInstance().getShipTo(pageFrom + "", "10", "0");
        return (ItemController.moreShipTo.equalsIgnoreCase("1")) ? true : false;
    }

    @Override
    protected void appendCachedData() {
                if (next != null)
            list.addAll(next);
        if (!(ItemController.moreShipTo.equalsIgnoreCase("1")) ? true : false)
            Toast.makeText(act, "No More Category found", Toast.LENGTH_SHORT)
                    .show();

    }

    void startProgressAnimation() {
        if (pendingView != null) {
            pendingView.startAnimation(rotate);
        }
    }

    private static class Adapater extends BaseAdapter {

        private class ViewHolder {
            private TextView tv;
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public ShipTo getItem(int arg0) {
            return null;
        }

        @Override
        public long getItemId(int arg0) {
            return 0;
        }

        @Override
        public View getView(int arg0, View arg1, ViewGroup arg2) {

            try {
                ViewHolder viewHolder = null;
                ShipTo shipTo = list.get(arg0);
                LayoutInflater lf = (LayoutInflater) act
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                // if (arg1 == null) {
                viewHolder = new ViewHolder();
                arg1 = lf.inflate(R.layout.category_spinner_textview, null);
                viewHolder.tv = (TextView) arg1
                        .findViewById(R.id.textView1_cat_spinner);

                arg1.setTag(viewHolder);
                /*
                 * } else { viewHolder = (ViewHolder) arg1.getTag(); }
                 */

                viewHolder.tv.setText(shipTo.getName());
                arg1.setTag(R.layout.category_spinner_textview, shipTo);
                viewHolder.tv.setPadding(5, 10, 0, 10);

            } catch (Exception e) {
                e.printStackTrace();

            }
            return arg1;
        }
    }
}

This is my activity for showing listview using endless adapter in Dialog box.

public class EndlessAdapterDemo extends Activity {
    public ArrayList<ShipTo> shipToList;

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);
        Button button = (Button) findViewById(R.id.button1);

        button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        shipToList = ItemController.getInstance().getShipTo(
                                "1", "10", "0");

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                showCategoryList();
                            }
                        });
                    }
                }).start();

            }
        });

    }

    private void showCategoryList() {
        final Dialog categoryDialog = new Dialog(this);
        categoryDialog.setTitle("Select Category");
        categoryDialog.setContentView(R.layout.custumdialoglstview);
        ListView lv = (ListView) categoryDialog.findViewById(R.id.listView1);

        DemoAdapter adapter = null;

        if (adapter == null) {
            adapter = new DemoAdapter(EndlessAdapterDemo.this, shipToList);
        }
        lv.setAdapter(adapter);
        lv.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                    long arg3) {
                System.out.println(arg1.getTag().getClass().getName());
                ShipTo temp = (ShipTo) arg1
                        .getTag(R.layout.category_spinner_textview);
                categoryDialog.dismiss();

            }
        });
        categoryDialog.show();

        }

    }

When I run the above code it throws illegal state exception or null pointer exception.

Following is my logcat details

11-17 09:40:08.532: D/AndroidRuntime(331): Shutting down VM
11-17 09:40:08.532: W/dalvikvm(331): threadid=1: thread exiting with uncaught exception (group=0x40015560)
11-17 09:40:08.541: E/AndroidRuntime(331): FATAL EXCEPTION: main
11-17 09:40:08.541: E/AndroidRuntime(331): java.lang.NullPointerException
11-17 09:40:08.541: E/AndroidRuntime(331):  at android.widget.ListView.measureScrapChild(ListView.java:1135)
11-17 09:40:08.541: E/AndroidRuntime(331):  at android.widget.ListView.measureHeightOfChildren(ListView.java:1218)
11-17 09:40:08.541: E/AndroidRuntime(331):  at android.widget.ListView.onMeasure(ListView.java:1127)
11-17 09:40:08.541: E/AndroidRuntime(331):  at android.view.View.measure(View.java:8313)
11-17 09:40:08.541: E/AndroidRuntime(331):  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3138)
11-17 09:40:08.541: E/AndroidRuntime(331):  at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1017)
11-17 09:40:08.541: E/AndroidRuntime(331):  at android.widget.LinearLayout.measureVertical(LinearLayout.java:386)
11-17 09:40:08.541: E/AndroidRuntime(331):  at android.widget.LinearLayout.onMeasure(LinearLayout.java:309)
11-17 09:40:08.541: E/AndroidRuntime(331):  at android.view.View.measure(View.java:8313)
11-17 09:40:08.541: E/AndroidRuntime(331):  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3138)
11-17 09:40:08.541: E/AndroidRuntime(331):  at android.widget.FrameLayout.onMeasure(FrameLayout.java:250)
11-17 09:40:08.541: E/AndroidRuntime(331):  at android.view.View.measure(View.java:8313)
11-17 09:40:08.541: E/AndroidRuntime(331):  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3138)
11-17 09:40:08.541: E/AndroidRuntime(331):  at android.widget.FrameLayout.onMeasure(FrameLayout.java:250)
11-17 09:40:08.541: E/AndroidRuntime(331):  at android.view.View.measure(View.java:8313)
11-17 09:40:08.541: E/AndroidRuntime(331):  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3138)
11-17 09:40:08.541: E/AndroidRuntime(331):  at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1017)
11-17 09:40:08.541: E/AndroidRuntime(331):  at android.widget.LinearLayout.measureVertical(LinearLayout.java:386)
11-17 09:40:08.541: E/AndroidRuntime(331):  at android.widget.LinearLayout.onMeasure(LinearLayout.java:309)
11-17 09:40:08.541: E/AndroidRuntime(331):  at android.view.View.measure(View.java:8313)
11-17 09:40:08.541: E/AndroidRuntime(331):  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3138)
11-17 09:40:08.541: E/AndroidRuntime(331):  at android.widget.FrameLayout.onMeasure(FrameLayout.java:250)
11-17 09:40:08.541: E/AndroidRuntime(331):  at android.view.View.measure(View.java:8313)
11-17 09:40:08.541: E/AndroidRuntime(331):  at android.view.ViewRoot.performTraversals(ViewRoot.java:839)
11-17 09:40:08.541: E/AndroidRuntime(331):  at android.view.ViewRoot.handleMessage(ViewRoot.java:1859)
11-17 09:40:08.541: E/AndroidRuntime(331):  at android.os.Handler.dispatchMessage(Handler.java:99)
11-17 09:40:08.541: E/AndroidRuntime(331):  at android.os.Looper.loop(Looper.java:123)
11-17 09:40:08.541: E/AndroidRuntime(331):  at android.app.ActivityThread.main(ActivityThread.java:3683)
11-17 09:40:08.541: E/AndroidRuntime(331):  at java.lang.reflect.Method.invokeNative(Native Method)
11-17 09:40:08.541: E/AndroidRuntime(331):  at java.lang.reflect.Method.invoke(Method.java:507)
11-17 09:40:08.541: E/AndroidRuntime(331):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
11-17 09:40:08.541: E/AndroidRuntime(331):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
11-17 09:40:08.541: E/AndroidRuntime(331):  at dalvik.system.NativeStart.main(Native Method)

What might be the problem?


Vb.net get username that is running process

I'm making a program that looks for processes and can see which user is using them. I've got the scanning code, but not the username code. The username has to be a string. For example: I have 2 people running some processes and the processes will show in the listview. The first column is for processes and the second is for the username. I want it to be like:

(process here) (username here)

(process here) (username here)....

You get the point I think and there's much more processes than that running on the computer. The question is: How do you get the username for someone using the process?

Edit: The code. This is my code.

For Each pr As Process In Process.GetProcesses
Dim lvi As ListViewItem = ListView1.Items.Add(CStr(pr.ProcessName))
'Now I need something to put for the username
Next

This is the other one that is most common.

Public Function GetProcessOwner(processId As Integer) As String
        Dim query As String = "Select * From Win32_Process Where ProcessID = " + processId
        Dim searcher As New ManagementObjectSearcher(query)
        Dim processList As ManagementObjectCollection = searcher.[Get]()

        For Each obj As ManagementObject In processList
            Dim argList As String() = New String() {String.Empty, String.Empty}
            Dim returnVal As Integer = Convert.ToInt32(obj.InvokeMethod("GetOwner", argList))
            If returnVal = 0 Then
                ' argList(0) == User
                ' argList(1) == DOMAIN
                Return argList(0)
            End If
        Next

        Return "NO OWNER"
End Function


sencha app build package gives me a java.lang.NullPointerException

I use sencha architect to build an app.

Then I copy the project files such as app, packages, resources, touch, app.js, index,html to a empty app built by sencha cmd. Then I use sencha app build package to build a package, but the error comes. The cmd window are as the follow picture, can anyone help me?

I use win7+sencha cmd4.0+cordova+touch-2.4.1


Unable to set product's category by code

According to

Mage::app()->getWebsite(true)->getDefaultStore()->getRootCategoryId();

ID of the default product category is '2' but:

public function initProduct(Varien_Event_Observer $observer)
// catalog_product_new_action event
{
    $product = $observer->getEvent()->getProduct();
    (...)

    $productCatalog = Mage::getModel('catalog/product')->load($product->getId());
    $productCatalog->setCategoryIds(array("2"));
    $productCatalog->save();
    $product->save();
    (...)

doesn't change product's category at all. It's either wrong ID or wrong way of changing the category.


WebView drawn to Android Bitmap from java to Qt C++

I'm trying to generate a webview in Java (Android) and return an Android Bitmap back to Qt C++. So far I am getting an invalid object.

The static java funtion: (in android/src/com/parity/jni/JniExtras.java)

package com.parity.jni;

import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.webkit.WebView;

public class JniExtras {
    public static Bitmap htmlToBitmap(String html, float scale, int w, int h, int r, int g, int b, int a) {
        int color = (r << 24) | (g << 16) | (b << 8) | a;

        WebView web = new WebView(null);
        web.loadData(html, "text/html", "UTF-8");
        web.layout(0, 0, (int)((float)w / scale), (int)((float)h / scale));

        Bitmap bitmap = Bitmap.createBitmap(w, h, Config.ARGB_8888);

        Canvas canvas = new Canvas(bitmap);

        Paint paint = new Paint();
        paint.setColor(color);

        canvas.drawPaint(paint);
        canvas.scale(scale, scale);

        web.draw(canvas);

        return bitmap;
    }
}

And I'm trying to fetch the Bitmap in QT with:

QAndroidJniObject jni_html = QAndroidJniObject::fromString(html);
QAndroidJniObject bitmap = QAndroidJniObject::callStaticObjectMethod(
            "com/parity/jni/JniExtras",
            "htmlToBitmap",
            "(Ljava/lang/String;FIIIIII)Ljava/lang/Object;",
            jni_html.object<jstring>(),
            scale,
            w, h,
            r, g, b, a);

if (!bitmap.isValid()) {
    qDebug("Java call failed to get android bitmap");
}

Can anybody tell me what it is I am doing wrong?

Edit 1:

In the meantime I am trying to get the WebView to draw to a Bitmap in an Android Studio project. Here's what I've got so far:

package com.parity.webviewtest;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    String tag = "WLGfx";

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

        int wid = 1000;
        int hgt = 1000;

        String html = "<div align=\"center\"><font face=\"FreeMono\"><b><font color=\"#FF0000\"><font size=\"6\">Title of report</font></font></b></font><br></div><font face=\"FreeSerif\" color=\"#0000FF\">Now as we enter a new era of stuff to do some really amazing and weird things, we notice that our distractions are seemingly taking our focus away from the smaller and more important things that we should be thoroughly immersed in. Either way, this will test out a formatted paragraph.</font><font face=\"FreeSerif\"><br></font><ol><li><font face=\"FreeSerif\" color=\"#008000\">Throw away old bins</font></li><li><font face=\"FreeSerif\" color=\"#008000\">Buy new bins</font></li><li><font face=\"FreeSerif\" color=\"#008000\">Fill the new bins</font></li></ol><div align=\"center\"><font face=\"FreeSerif\" color=\"#993300\"><i>The quick brown fox does stuff</i></font><br></div>";
        //String html = "Some line of text to test out...";

        Log.d(tag, html);

        Context context = this.getApplicationContext();

        WebView web = new WebView(context);
        web.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        web.layout(0,0,wid,hgt);
        web.loadData(html, "text/html", "UTF-8");
        web.buildDrawingCache();

        Paint paint = new Paint();
        paint.setColor(0xffffffff);

        Bitmap bitmap = Bitmap.createBitmap(wid, hgt, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);

        web.draw(canvas);

        ImageView img = (ImageView)findViewById(R.id.imageView);
        img.setImageBitmap(bitmap);
    }

}

Still I am getting a blank bitmap.

Edit 2:

As suggested in comments, I've tried both capturePicture() and getDrawingCache() and neither are working in the Android Studio test project:

Context context = getApplicationContext();

WebView web = new WebView(context);
web.setEnabled(true);
//web.loadUrl(html);
web.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
web.layout(0,0,wid,hgt);
web.loadData(html, "text/html", "UTF-8");

web.setDrawingCacheEnabled(true);
web.buildDrawingCache();

Picture picture = web.capturePicture();
Bitmap bitmap = Bitmap.createBitmap(picture.getWidth(), picture.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
//picture.draw(canvas);
canvas.drawPicture(picture);

Log.d(tag, "Picture: " + picture.getWidth() + "x" + picture.getHeight());

//Bitmap bitmap = Bitmap.createBitmap(web.getDrawingCache());
//web.setDrawingCacheEnabled(false);

//Paint paint = new Paint();
//paint.setColor(0xffffffff);

//Bitmap bitmap = Bitmap.createBitmap(wid, hgt, Bitmap.Config.ARGB_8888);
//Canvas canvas = new Canvas(bitmap);
//web.draw(canvas);

ImageView img = (ImageView)findViewById(R.id.imageView);
img.setImageBitmap(bitmap);

The main reason I want to render html to a bitmap is so I only have to transfer simple html strings across the network to devices and not have the server render the images and send them.


Equivalent to ASP.NET WebForms URL Authorization in MVC

We're considering making the move from WebForms to MVC for our (quite substantial) intranet application.

The intranet app currently uses Windows authentication. Authorization to particular folders is controlled by web.config files inside each folder. The app also uses a Menu control which picks all this up and only shows users menu links to pages they are authorised to view. All this functionality comes out of the box with WebForms.

In terms of the conversion to MVC, I think that replacing this functionality is going to be one of the key challenges.

Can anyone tell me what tools are available in MVC to:

restrict users' access to certain
pages / views whatever based on
their Active Directory group
membership

generate markup for a
menu which is aware of the users'
authorisation to certain pages /
views

That would be mighty helpful.


How does DelegatingVehicleTracker (p. 65 Goetz) return a "live" view?

On page 65 and 66 of Java Concurrency in Practice Brian Goetz lists the following code:

@ThreadSafe
public class DelegatingVehicleTracker {
private final ConcurrentMap<String, Point> locations;
private final Map<String, Point> unmodifiableMap;

public DelegatingVehicleTracker(Map<String, Point> points) {
    locations = new ConcurrentHashMap<String, Point>(points);
    unmodifiableMap = Collections.unmodifiableMap(locations);
}

public Map<String, Point> getLocations() {
    return unmodifiableMap;
}

public Point getLocation(String id) {
    return locations.get(id);
}

public void setLocation(String id, int x, int y) {
    if (locations.replace(id, new Point(x, y)) == null)
        throw new IllegalArgumentException("invalid vehicle name: " + id);
}

// Alternate version of getLocations (Listing 4.8)
public Map<String, Point> getLocationsAsStatic() {
    return Collections.unmodifiableMap(
            new HashMap<String, Point>(locations));
}
}

About this class Goetz writes:

"...the delegating version [the code above] returns an unmodifiable but
  'live' view of the vehicle locations. This means that if thread A calls
  getLocations() and thread B later modifies the location of some of the
  points, those changes are reflected in the map returned to thread A."

In what sense would Thread A's unmodifiableMap be "live"? I do not see how changes made by Thread B via calls to setLocation() would be reflected in Thread A's unmodifiableMap. This would seem the case only if Thread A constructed a new instance of DelegatingVehicleTracker. But were Thread A to hold a reference to this class, I do not see how this is possible.

Goetz goes on to say that getLocationsAsStatic() could be called were an "unchanging view of the fleet required." I am confused. It seems to me that precisely the opposite is the case, that a call to getLocationsAsStatic() would indeed return the "live" view, and a call to getLocations(), were the class not constructed anew, would return the static, unchanging view of the fleet of cars.

What am I missing here in this example?

Any thoughts or perspectives are appreciated!


How to deploy google firebase functions using cmd?

I have a problem with a web hosting project. I created a new proyect in google firebase, and I executed the following commands:

C:\myproject>firebase init functions

C:\myproject>firebase deploy --only functions

But the site says this:

Site Not Found

  Why am I seeing this?

  There are a few potential reasons:

You haven't deployed an app yet.

You may have deployed an empty directory.

This is a custom domain, but we haven't finished setting it up yet.

How can I deploy my first app?

  Refer to our hosting documentation to get started.

What could I do for show, at least, some text when an user go to my project url?


Android location accuracy

I have the following code implemented to retrieve location values on Android:

mLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);

On Android 2.3 and 4.1 this works great and returns updates at 180 samples per hour with a resolution down to 100m or less.

However, on Android 4.3 something has changed so this only provides updates at 5 samples per hour and a resolution at 2km. I haven't tested on later versions.

What has changed? Is it possible to return to the old accuracy levels again? I don't want to force GPS for power reasons. The app has ACCESS_COARSE_LOCATION permissions.

I have been testing this on a Samsung S3 if it makes a difference.


Lucene.NET and searching on multiple fields with specific values

I've created an index with various bits of data for each document I've added, each document can differ in it field name.

Later on, when I come to search the index I need to query it with exact field/ values - for example:

FieldName1 = X AND FieldName2 = Y AND FieldName3 = Z

What's the best way of constructing the following using Lucene .NET:

What analyser is best to use for this exact match type?

Upon retrieving a match, I only need one specific field to be returned (which I add to each document) - should this be the only one stored?

Later on I'll need to support keyword searching (so a field can have a list of values and I'll need to do a partial match).

The fields and values come from a Dictionary<string, string>. It's not user input, it's constructed from code.

Thanks,

Kieron


Ignore some files in IPython tab completion in linux

When I am working in IPython 5.0, sometimes I want to run a script with run script.py, but the tab completion will show me options run script.py and run script.py~, that is, Emacs backup files. How can I set to ignore these and other files like one does with FIGNORE in bash?


Sum based on chart of Account Name

I'm trying to create a Report Dimension (Income Statement Report) in my Cube and would like to perform calculation (Sum or Divide) based on Report Action attribute.  The Dimension table looks like below

Could you kindly let me know if I could achieve this by MDX script?  Thanks a lot for your help!


Can not fetch value from REST service in AngularJS

I'm trying fetch data by calling Java REST service from AngularJS web portal. I'm using ngResource.

Call From Angular Service :

BankingModule.factory('UserFactory', function ($resource) {
    return $resource('http://localhost:8080/demoApp/service/users', {}, {
        show: { method: 'GET', isArray: true },
        update: { method: 'PUT', params: {id: '@id'} },
        delete: { method: 'DELETE', params: {id: '@id'} }
    })
});

It is calling Service perfectly and even I can get the result if I put the URL directly at the browser :

URL :   http://localhost:8080/demoApp/service/users

RESULT :   [{"id":1,"firstName":"Jayanta","lastName":"Pramanik"}]

But Angular-JS controller I can not get any result !!

For your understanding -
Here is my Service method definition -

@GET
@Produces(MediaType.APPLICATION_JSON)
public List<User> getAllUsersInJSON() {
    /* ------ Some Hard coded values are set into an ArrayList ------*/
    List<User> userList = new ArrayList<User>();
    User usr1 = new User();
    usr1.setId(1);
    usr1.setFirstName("Jayanta");
    usr1.setLastName("Pramanik");

    userList.add(usr1);

    return userList;
}

Any idea please !

Thanks in advance -

Jayanta P.


SQL how to count census points occurring between date records

I’m using MS-SQL-2008 R2 trying to write a script that calculates the Number of Hospital Beds occupied on any given day, at 2 census points: midnight, and 09:00.

I’m working from a data set of patient Ward Stays. Basically, each row in the table is a record of an individual patient's stay on a single ward, and records the date/time the patient is admitted onto the ward, and the date/time the patient leaves the ward.

A sample of this table is below:

Ward_Stay_Primary_Key |   Ward_Start_Date_Time  |   Ward_End_Date_Time
          1           | 2017-09-03 15:04:00.000 | 2017-09-27 16:55:00.000
          2           | 2017-09-04 18:08:00.000 | 2017-09-06 18:00:00.000
          3           | 2017-09-04 13:00:00.000 | 2017-09-04 22:00:00.000
          4           | 2017-09-04 20:54:00.000 | 2017-09-08 14:30:00.000
          5           | 2017-09-04 20:52:00.000 | 2017-09-13 11:50:00.000
          6           | 2017-09-05 13:32:00.000 | 2017-09-11 14:49:00.000
          7           | 2017-09-05 13:17:00.000 | 2017-09-12 21:00:00.000
          8           | 2017-09-05 23:11:00.000 | 2017-09-06 17:38:00.000
          9           | 2017-09-05 11:35:00.000 | 2017-09-14 16:12:00.000
          10          | 2017-09-05 14:05:00.000 | 2017-09-11 16:30:00.000

The key thing to note here is that a patient’s Ward Stay can span any length of time, from a few hours to many days.

The following code enables me to calculate the number of beds at both census points for any given day, by specifying the date in the case statement:

SELECT
     '05/09/2017' [Date]
    ,SUM(case when Ward_Start_Date_Time <= '05/09/2017 00:00:00.000' AND (Ward_End_Date_Time >= '05/09/2017 00:00:00.000' OR Ward_End_Date_Time IS NULL)then 1 else 0 end)[No. Beds Occupied at 00:00]
    ,SUM(case when Ward_Start_Date_Time <= '05/09/2017 09:00:00.000' AND (Ward_End_Date_Time >= '05/09/2017 09:00:00.000' OR Ward_End_Date_Time IS NULL)then 1 else 0 end)[No. Beds Occupied at 09:00]

FROM
    WardStaysTable

And, based on the sample 10 records above, generates this output:

   Date     | No. Beds Occupied at 00:00 | No. Beds Occupied at 09:00
05/09/2017  |             4              |             4

To perform this for any number of days is obviously onerous, so what I’m looking to create is a query where I can specify a start/end date parameter (e.g. 1st-5th Sept), and for the query to then evaluate the Ward_Start_Date_Time and Ward_End_Date_Time variables for each record, and – grouping by the dates defined in the date parameter – count each time the 00:00:00.000 and 09:00:00.000 census points fall between these 2 variables, to give an output something along these lines (based on the above 10 records):

   Date    | No. Beds Occupied at 00:00 | No. Beds Occupied at 09:00
01/09/2017 |             0              |            0
02/09/2017 |             0              |            0
03/09/2017 |             0              |            0
04/09/2017 |             1              |            1
05/09/2017 |             4              |            4

I’ve approached this (perhaps naively) thinking that if I use a cte to create a table of dates (defined by the input parameters), along with associated midnight and 9am census date/time points, then I could use these variables to group and evaluate the dataset.

So, this code generates the grouping dates and census date/time points:

DECLARE
  @StartDate DATE = '01/09/2017'
 ,@EndDate DATE = '05/09/2017'
 ,@0900 INT = 540

SELECT
     DATEADD(DAY, nbr - 1, @StartDate) [Date]
    ,CONVERT(DATETIME,(DATEADD(DAY, nbr - 1, @StartDate))) [MidnightDate]
    ,DATEADD(mi, @0900,(CONVERT(DATETIME,(DATEADD(DAY, nbr - 1, @StartDate))))) [0900Date]

FROM
(
SELECT
ROW_NUMBER() OVER ( ORDER BY c.object_id ) AS nbr
FROM      sys.columns c
) nbrs

WHERE   nbr - 1 <= DATEDIFF(DAY, @StartDate, @EndDate)

The stumbling block I’ve hit is how to join the cte to the WardStays dataset, because there’s no appropriate key… I’ve tried a few iterations of using a subquery to make this work, but either I’m taking the wrong approach or I’m getting my syntax in a mess.

In simple terms, the logic I’m trying to create to get the output is something like:

SELECT
[Date]
,SUM (case when  WST.Ward_Start_Date_Time <= [MidnightDate] AND (WST.Ward_End_Date_Time >= [MidnightDate] OR WST.Ward_End_Date_Time IS NULL then 1 else 0 end) [No. Beds Occupied at 00:00]
,SUM (case when  WST.Ward_Start_Date_Time <= [0900Date] AND (WST.Ward_End_Date_Time >= [0900Date] OR WST.Ward_End_Date_Time IS NULL then 1 else 0 end) [No. Beds Occupied at 09:00]

FROM WardStaysTable WST

GROUP BY [Date]

Is the above somehow possible, or am I barking up the wrong tree and need to take a different approach altogether? Appreciate any advice.


Regular Expression for Removing (nested) Parentheses

I am using DOM to get a Wikipedia article as a NSString and then using NSString stringByReplacingOccurrencesOfString:withString:options:range: to remove unneeded things. I'm using regular expressions, which I don't have much experience with. From reading Apple's documentation and just trying things I was able to make this

"\\[[\\w]+\\]"

regular expression which removes the brackets from the Wikipedia article. This works perfectly fine because brackets aren't nested.

Now I am trying to remove parentheses (including everything inside them (and nested ones)) from the NSString. I'm having problems with the nesting part. With this

\\s+\\([^\\)]*+\\)

regular expression I was able to remove a set of parentheses including the space before it (so I don't end up with duplicate spaces after is removed). What regular expression could I use to do this same thing but also remove nested parentheses instead?

My current implementation will change this

The quick brown (slightly reddish) fox jumped over the lazy (he was old (26 years) and exhausted) dog.

into this

The quick brown fox jumped over the lazy and exhausted) dog.

while the desired result is this

The quick brown fox jumped over the lazy dog.


How can I draw simple lines (flows) between arcs in D3.js?

This is my circle. I want to draw flow lines between the circle arcs. How can I do it in D3.js.

FYI I know about https://bl.ocks.org/mbostock/4062006. What I want is instead of those wide chords I want simple lines like so.

var arcGenerator = d3.arc()
  .innerRadius(80)
  .outerRadius(100)
  .padAngle(.02)
  .padRadius(100)
  .cornerRadius(4);

var arcData = [
  {startAngle: 0, endAngle: 1.3},
  {startAngle: 1.3, endAngle: 2.6},
  {startAngle: 2.6, endAngle: 3},
  {startAngle: 3, endAngle: 4},
  {startAngle: 4, endAngle: 2* Math.PI}
];

d3.select('g')
  .selectAll('path')
  .data(arcData)
  .enter()
  .append('path')
  .attr('d', arcGenerator);

Here is a simple codepen:
    http://codepen.io/ioan-ungurean/pen/aJNWMM


Best way for images css

Oops, wrong snippet– had to change it back. Creating new question now


How to use fields in Comfortable Mexican Sofa?

I have seen in documentation that fields are not rendered in the view, and instead it can be used in helpers, partials etc. but I can't find a way how they are used.
The documentation says to use it like this:

{{ cms:field:some_label }}

But I am courios how can I use that? I wanted to be able to define some text in the snippet and then, use that field in my partial or in my helper function to form some data that will be used in the view. Can somebody tell me how can I use fields in this CMS?


Transparent colors Tkinter

Is it possible to change the color of a frame background or any other widget to transparent light blue or any other transparent color?


jQuery: Pause or delay a function

So here's the situation:

I have a recursive, asynchronous AJAX call which is pulling data from the server. This recursive call happens only once when the user logs in.
I have another page which requires AJAX calls in order to navigate (basically a lazy-loaded tree). While the first AJAX call is happening, these other calls are taking a while to go through, and since the first could make as many as 2,000 requests, this delay can sometimes be fairly long.

Basically what I would like to achieve is to "pause" the recursive call when the other call is made. Pseudo code:

function recursiveAjax(){
    $.ajax( {
        async : true,
        url : 'someurl',
        dataType : 'json',
        beforeSend : function(xhr) {
            // do stuff
        },
        error : function(xhr, ajaxOptions, thrownError) {
            // handle errors
        },
        success : function(data) {
            //conditions
            recursiveAjax();
        }
    });
}

function navigationAjax(){
    $.ajax( {
        async : true,
        url : 'someurl',
        dataType : 'json',
        beforeSend : function(xhr) {
            // pause recursiveAjax();
        },
        error : function(xhr, ajaxOptions, thrownError) {
            // handle errors
        },
        success : function(data) {
            //conditions
            // resume recursiveAjax();
        }
    });
}


HtmlService.createTemplateFromFile does not output

I am not a software engineer but wrote quite some Google Apps scripts. However I've got virtually no experience on the GUI side, but now I implemented a script for seat reservations which requires an input dialog (working) and a confirmation page (the problem).

The entire script works, but the resulting confirmation page remains empty.

The relevant code snipplet (all used variables are properly defined):

// Make a web page
var template = HtmlService.createTemplateFromFile('thank_you.html');
template.msg = 'Eine Buchung erscheint demnächst in Ihrem <a target="_blank" href="https://www.google.com/calendar/">persönlichen Kalender</a>.';
template.email = email;
template.header = title;
Logger.log(template.getCodeWithComments());
return template.evaluate().setTitle('Vielen Dank für Ihre Buchung');

And the getCSS() function:

function getCSS(){
  var template = HtmlService.createTemplateFromFile('css.html');
  return template.getRawContent();
}

I am am using the same approach to create the input form which is working,but this simple confirmation page remains emppty.
I tried many different approaches for hours but I do not see the problem! What am I missing?

The resulting execution log does not show any problem, as far as I can see it, at least I can see, that values are assigned:

[17-11-23 11:36:33:447 PST]
  HtmlService.createTemplateFromFile([thank_you.html]) [0.001 seconds]
  [17-11-23 11:36:33:451 PST] Function.apply([[]]) [0.004 seconds]
  [17-11-23 11:36:33:452 PST] Logger.log([(function() { return eval('var
  output = HtmlService.initTemplate(); output._ =  \'\n\';\n' +
  //    'output._ =  \'\n\' +\n' +

  , []]...) [0 seconds] [17-11-23 11:36:33:453 PST] Function.apply([[]])
  [0 seconds] [17-11-23 11:36:33:453 PST] HtmlService.createHtmlOutput()
  [0 seconds] [17-11-23 11:36:33:454 PST] HtmlOutput.append([ ])
  [0 seconds] [17-11-23 11:36:33:455 PST] HtmlOutput.append([
      ]) [0 seconds] [17-11-23 11:36:33:457 PST] HtmlService.createTemplateFromFile([css.html]) [0.001 seconds]
  [17-11-23 11:36:33:457 PST] Function.apply([[]]) [0 seconds] [17-11-23
  11:36:33:458 PST] HtmlOutput.append([

page{

  font-family: Arial, Helvetica, sans-serif;
  margin-top:50px;
  padding-top:260px;
  text-align: left;
  font-size: 1.3em;
  background: no-repeat 0px 0px;  ]...) [0 seconds] [17-11-23 11:36:33:458 PST] HtmlOutput.append([   </head> ]) [0 seconds]

[17-11-23 11:36:33:459 PST] HtmlOutput.append([

    <h3>]) [0 seconds] [17-11-23 11:36:33:459 PST] HtmlOutput.appendUntrusted([Buchung Scheibe 1]) [0 seconds] [17-11-23

11:36:33:460 PST] HtmlOutput.append([ ]) [0 seconds] [17-11-23
  11:36:33:460 PST] HtmlOutput.append([

          ]) [0 seconds] [17-11-23 11:36:33:460 PST] HtmlOutput.appendUntrusted([heinz.ruffieux@ondemandmanagement.net]) [0
  seconds] [17-11-23 11:36:33:461 PST] HtmlOutput.append([

  ]) [0 seconds] [17-11-23 11:36:33:461 PST] HtmlOutput.append([

   <p>]) [0 seconds] [17-11-23 11:36:33:462 PST] HtmlOutput.append([Eine Buchung erscheint demnächst in Ihrem <a

target="_blank" href="https://www.google.com/calendar/">persönlichen
  Kalender.]) [0 seconds] [17-11-23 11:36:33:462 PST]
  HtmlOutput.append([
 ]) [0 seconds] [17-11-23 11:36:33:463 PST]
  HtmlOutput.append([

 </div>
 </body> </html> ]) [0 seconds] [17-11-23 11:36:33:463 PST] HtmlOutput.append([]) [0 seconds] [17-11-23 11:36:33:464 PST]

HtmlOutput.setTitle([Vielen Dank für Ihre Buchung]) [0 seconds]
  [17-11-23 11:36:33:549 PST] HtmlOutput.getContent() [0 seconds]
  [17-11-23 11:36:33:549 PST] HtmlOutput.getTitle() [0 seconds]
  [17-11-23 11:36:33:551 PST] Execution succeeded [0.506 seconds total
  runtime]

However, the Logger.log(template.getCodeWithComments()); then shows the following, empty output:

doPost()
(function() { return eval('var output = HtmlService.initTemplate(); output._ =  \'<html>\\n\';\n' +  // <html>
  'output._ =  \'<head>\\n\' +\n' +                                                                  // <head>
  '  \'    \'; output._ =  getCSS(); \n' +                                                           //     <?!= getCSS()?>
  'output._ =  \'   </head>\\n\';\n' +                                                               //    </head>
  'output._ =  \'   \\n\' +\n' +                                                                     //
  '  \'   <body>\\n\' +\n' +                                                                         //    <body>
  '  \'     <div id=\\\"page\\\" >\\n\' +\n' +                                                       //      <div id="page" >
  '  \' \\n\' +\n' +                                                                                //
  '  \'        <h3>\'; output._$ =  header ; output._ =  \'</h3>\\n\';\n' +                          //         <h3><?= header ?></h3>
  'output._ =  \'        \\n\' +\n' +                                                                //
  '  \'        <p>\\n\' +\n' +                                                                       //         <p>
  '  \'        \'; output._$ =  email; \n' +                                                         //         <?= email?>
  'output._ =  \'        </p>\\n\';\n' +                                                             //         </p>
  'output._ =  \'           \\n\' +\n' +                                                             //
  '  \'       <p>\'; output._ =  msg ; output._ =  \'</p>\\n\';\n' +                                 //        <p><?!= msg ?></p>
  'output._ =  \'       \\n\' +\n' +                                                                 //
  '  \'     \\n\' +\n' +                                                                             //
  '  \'\\n\' +\n' +                                                                                //
  '  \'       \\n\' +\n' +                                                                           //
  '  \'     </div>\\n\' +\n' +                                                                       //      </div>
  '  \' \\n\' +\n' +                                                                                //
  '  \' \\n\' +\n' +                                                                                //
  '  \' </body>\\n\' +\n' +                                                                          //  </body>
  '  \'</html>\\n\';\n' +                                                                            // </html>
  '\n' +                                                                                //
  '/* End of user code */\n' +
  'output.$out.append(\'\');');
})();

The thank_you.html file:

<html> <head>
<?!= getCSS()?>    </head>
   <body>
 <div id="page" >

    <h3><?= header ?></h3>

    <p>
    <?= email?>
    </p>

   <p><?!= msg ?></p>

 </div>

The css file (used in the working form as well):

    <style>

#page{
      font-family: Arial, Helvetica, sans-serif;
      margin-top:50px;
      padding-top:260px;
      text-align: left;
      font-size: 1.3em;
      background: no-repeat 0px 0px;
      width:600px;
      margin-left:auto;
      margin-right:auto;
      border:1px solid #DDD;
      padding-bottom:20px;
      padding-left:20px;
    }

    input#email{
    font-size:1.1em;
    }

    input#submit{
      -webkit-appearance: button;
       margin-top:10px;
       height: 50px;
       font-size:1.7em;

    }

  .submitbutton {
      -webkit-appearance: button;
      font-size:30px;
     }

   .small{
      font-size:12px;
  }
</style>

Is there anyone who sees the problem?

Thanks a lot for your help.

Heinz


Why is the entire HorizontalFieldManager clickable?

I have added buttons on my setStatus method in the MainScreen. Now the entire HFM is clickable I don't know why? Please guide. Here's the code:

 setStatus(setFooter());
    ...
    public Field setFooter() {

            HorizontalFieldManager hfm1 = new HorizontalFieldManager(USE_ALL_WIDTH|Manager.NO_HORIZONTAL_SCROLL|Manager.NO_HORIZONTAL_SCROLLBAR);

            Bitmap bm;
            bm = Bitmap.getBitmapResource("statusImage.PNG");
            Background bg = BackgroundFactory.createBitmapBackground(bm, Background.POSITION_X_LEFT, Background.POSITION_Y_BOTTOM, Background.REPEAT_SCALE_TO_FIT);
            hfm1.setBackground(bg);
            hfm1.add(new DummyField(bm.getHeight()));
            hfm1.add(backButton);
            hfm1.add(nextButton);

            return hfm1;
            }

The dummy field:

class DummyField extends Field {
    private int logoHeight;

    public DummyField(int height) {
        logoHeight = height;
    }

    protected void layout(int width, int height) {
        setExtent(1, logoHeight);
    }

    protected void paint(Graphics graphics) {
    }
}

I have also overridden these methods(lionscribe implementation) to avoid HFM from being clickable but it doesn't work:

protected boolean touchEvent(TouchEvent message)
    {
     int event = message.getEvent();
     if (event == TouchEvent.CLICK || event == TouchEvent.UNCLICK)
     {
      // Ignore clcik events that happen outside any fields
      if (getFieldAtLocation(message.getX(1), message.getY(1)) == -1)
       return true;    // kill the event
     }
     return super.touchEvent(message);
    }

    // The regular getFieldAtLocation returns wrong values in open spaces in complex managers, so we override it
    public int getFieldAtLocation(int x, int y)
    {
     XYRect rect = new XYRect();
     int index = getFieldCount() -1;
     while (index >= 0)
     {
      getField(index).getExtent(rect);
      if (rect.contains(x, y))
       break;
      --index;
     }
     return index;
    }


Optimizing query with left outer join and comma-separated-string

I have tables in my db called Items, which are in a relationships with ItemParents table. One item can have one parent, one parent can have multiple items (something like file-folder tree structure). I have a third table called ParentPermissions and in this table I have the permissions if a user depending on its role can view the parent. If he can view the parent, he can view the item too. In this table we save the relationships between the parent and the userroles that CAN NOT view the parent.

For example, for parentId = 1, if there is no data in the table ParentPermissions for this parent, all users can see it. If there is data with values "5,6" in ParentPermissions for parentId = 1, then the users with roles 5 and6 can't see this folder. Users with role 4 can see it.

This is my query:

SELECT count(*)
FROM Items item
INNER JOIN ItemParents parent ON parent.id = item.parentId
LEFT OUTER JOIN ParentPermissions permissions ON permissions.folderId = parent.id
WHERE permissions.view IS NULL OR (permissions.view != CONVERT(VARCHAR(5), @userRole + ',%') AND permissions.view != CONVERT(VARCHAR(5), @userRole) AND permissions.view != CONVERT(VARCHAR(5), '%,' +  @userRole))

I want to somehow optimize this query because it is called a lot of times. How do I do that?


Moq basic questions

I made the following test for my class:

var mock = new Mock<IRandomNumberGenerator>();
mock.Setup(framework => framework.Generate(0, 50))
    .Returns(7.0);

var rnac = new RandomNumberAverageCounter(mock.Object, 1, 100);
rnac.Run();
double result = rnac.GetAverage();
Assert.AreEqual(result, 7.0, 0.1);

The problem here was that I changed my mind about what range of values Generate(int min, int max) would use. So in Mock.Setup() I defined the range as from 0 to 50 while later I actually called the Generate() method with a range from 1 to 100.

I ran the test and it failed. I know that that is what it's supposed to happen but I was left wondering if isn't there a way to launch an exception or throw in a message when trying to run the method with wrong params.

Also, if I want to run this Generate() method 10 times with different values (let's say, from 1 to 10), will I have to make 10 mock setups or something, or is there a special method for it? The best I could think of is this (which isn't bad, I'm just asking if there is other better way):

for (int i = 1; i < 10; ++i) {
    mock.Setup(framework => framework.Generate(1, 100))
        .Returns((double)i);
}


What architecture do VoIP applications use, P2P or Client-Server?

Please let me know what architecture do VoIP applications use, P2P or Client-Server?

Thank you.


How do I divide my Rust code between two source files?

Updated in response to "possible duplicate"

Yes, the indicated question, "Can't understand Rust module system" solved my problem, for which my thanks.

However, as part of my question, I also asked for pointers into the documentation "where I missed this"; it would be nice to have an answer to that, too, even if the answer is "it's not explained simply". (which is OK - I appreciate there's lots of work done and to do.)

I'm starting to learn Rust, from a background of z/Assembler, Python, Go, and some C; but no C++ or Java.

I've successfully built and executed the "Hello World!" example, and a couple of other monolithic main.rs. For one of these, I've tried to separate my utility functions into a separate source file, but I can't get it to build, and I confess I find the documentation a bit incomprehensible. (All due respect to the authors; I'm sure it's me.)

So for a minimum non-working example, I went back to hallo world.

In my src/ directory, I have two files:

say.rs:

mod say {
    pub fn say() {
        println!("Hello, world!");
    }
}

main.rs:

pub mod say;
fn main() {
    say();
}

cargo build gives me this error message:

D:\Development\Rust\hw\src>cargo build
   Compiling hw v0.1.0 (file:///D:/Development/Rust/hw)
main.rs:3:5: 3:8 error: unresolved name `say` [E0425]
main.rs:3     say();
              ^~~

etc. I've also tried calling as say::say(), but with the same answer.

I've come to the conclusion that I'm missing something pretty fundamental here. Could someone please explain where I've gone wrong, and, hopefully, give a pointer into the book where I should have seen this?


What mutation-testing frameworks exist?

In another question I asked if mutation-testing is useful in practice. As I didn't get any answers that satisfy me, I want to check the current tools myself. So I need an overview about current existing mutation-test-frameworks. Which of them are most usable and why?

I program in Java, so I would prefer Java-tools, but I would risk a look at interesting frameworks for different languages.

I want to integrate in an automatic build-process, so I would prefer tools that can be executed through command-line.


Converting varchar values to decimal while handling NULLs and EMPTY strings as 0

I have a column of varchar datatype populated with a mix of values such as 1.2, 5.33 while also having NULLs and EMPTY strings.
I want to convert all the values to decimal while treating NULLs and EMPTY strings as 0.

I can change the NULLs or EMPTY strings using the CONVERT function like below. Like this I replace the NULLs and EMPTY strings with a varhcar 0.

CASE WHEN Column1 = '' OR Column1= NULL THEN '0' ELSE Column1 END AS 'NewColumn1'

However what I want to do is to be able to then convert this data (output of NewColumn1) into decimal but when I place the CASE statement into a CONVERT or a CAST function I will have errors.

I also tried the following.
CONVERT(DECIMAL(10,4), ISNULL(Column1, '0')) however it fails since here I am not handling the EMPTY strings.

Any ideas how can I solve this problem.


How to trigger the java agent from xpage button click event?

I'd like to test java agent to clear all the documents in a view by triggering the button click event on my xpage. I have no errors in java agent, but it is not working. Could you help me out to get through this stage?

Button click event:

var serverName=session.getCurrentDatabase().getServer();
//@WarningMessage("current one");
//@WarningMessage("server=" + serverName);
//var db:NotesDatabase = session.getDatabase(session.getCurrentDatabase().getServer(), "\ProTexII.nsf");
var db:NotesDatabase=session.getCurrentDatabase();
@WarningMessage("db=" + db);

var agent:NotesAgent = db.getAgent("SnapShotUpdate");
@WarningMessage("agent" + agent);

if (agent!=null){

 agent.run();
 @WarningMessage("view is fired!");

}

Java agent:

package javaPkg;
import java.io.PrintWriter;

import lotus.domino.*;

public class SnapShotUpdate extends AgentBase{

 public void NotesMain() {
       try {

         //String p = session.getPlatform();
           //PrintWriter out=getAgentOutput();

          System.out.println("Hello i never give it up!!");

          Session session = getSession();
          AgentContext agentContext =session.getAgentContext();
          Database db=session.getCurrentDatabase();

          //**clear view "vActualSalesFromSD" before copying documents into it

          DocumentCollection dc= db.createDocumentCollection();
          View view= db.getView("vActualSalesFromSD");
          Document docToBeCleared= view.getFirstDocument();

          while (docToBeCleared != null) {

             {
                dc.addDocument(docToBeCleared);
             }

                docToBeCleared = view.getNextDocument(docToBeCleared);
          }

          dc.removeAll(true);
       } catch(Exception e) {
         e.printStackTrace();
       }
     }

}


Spring Quartz entries missing in some tables

In Spring 4.x and Quartz 2.3.x, the creation of new jobs in the database is failing due to Deadlock found when trying to get lock; try restarting transaction.

And I have a similar process running on a different set of Quartz Mysql database tables, which doesn't have this issue. The number of jobs in these tables are almost 3 times the other table.

So I don't understand why the it is happening on tables with low volume.

Also even with deadlock the entries are made into jobs table, but not into simple triggers and triggers table. Why would this happen ?

Below is detailed stack trace.

org.quartz.JobPersistenceException: Couldn't store trigger 'SDTriggerGroup.SDTrigger__10416434' for 'SDJobGroup.SDJob__10416434' job:Deadlock found when trying to get lock; try restarting transaction [See nested exception: com.mysql.jdbc.exceptions.jdbc4.MySQLTransactionRollbackException: Deadlock found when trying to get lock; try restarting transaction] at org.quartz.impl.jdbcjobstore.JobStoreSupport.storeTrigger(JobStoreSupport.java:1223) at org.quartz.impl.jdbcjobstore.JobStoreSupport$2.executeVoid(JobStoreSupport.java:1063) at org.quartz.impl.jdbcjobstore.JobStoreSupport$VoidTransactionCallback.execute(JobStoreSupport.java:3719) at org.quartz.impl.jdbcjobstore.JobStoreSupport$VoidTransactionCallback.execute(JobStoreSupport.java:3717) at org.quartz.impl.jdbcjobstore.JobStoreCMT.executeInLock(JobStoreCMT.java:245) at org.quartz.impl.jdbcjobstore.JobStoreSupport.storeJobAndTrigger(JobStoreSupport.java:1058) at org.quartz.core.QuartzScheduler.scheduleJob(QuartzScheduler.java:886) at org.quartz.impl.StdScheduler.scheduleJob(StdScheduler.java:249)

Any clues on how to handle this gracefully ?


makefile with categories

Imagine I have files that are categorized in my mind but cannot be distinguished by any kind of naming scheme, and they reside in the same directory:

apple cherry celery onion

I have two rules, one recipe for pie and one for soup.

If I implement these recipes as implicit rules:

fruits:= apple cherry
vegetables:= celery onion

%.soup : %
        @echo "making soup"
        cp $< $@

%.pie : %
        @echo "making pie"
        cp $< $@

Then I allow terrible meals to be constructed:

> touch celery
> make celery.pie
making pie
cp celery celery.pie #bleech this should not be allowed

But if I use explicit rules:

fruits:= apple cherry
vegetables:= celery onion

pies:=$(addsuffix .pie,$(fruits))
soups:=$(addsuffix .soup,$(vegetables))

$(pies) : $(fruits)
        @echo "making pie"
        cp $< $@

$(soups) : $(vegetables)
        @echo "making soup"
        cp $< $@

I am forced to establish dependencies that don't exist in reality:

> touch apple
> make apple.pie
make: *** No rule to make target `cherry', needed by `apple.pie'.  Stop.

How can I tell Make about file categories?


declared variable doesn't seem global

I declared my variable first - then have my jquery :

var cimg = '';
jQuery(function($) {
    $(".trigger").click(function() {
  var cimg = event.target.id;
  clickedimage();
  loadPopup();
});
});

Then the script outside the jquery :

function clickedimage()
  {
    var xmargin  = $(cimg).width()/2;
    var ymargin = $(cimg).height()/2;
    $("#popupimage").css('margin-left',-xmargin+'px')
    $("#popupimage").css('margin-top',-ymargin+'px')
    var Clicked = cimg.src;
    $('#popupimage').attr('src',Clicked);
  }

It doesn't seem to want to take on the cimg value supplied from the .trigger clicked event

What am I doing wrong here?


Highlight Text in TextView or WebView

Is it possible to Highlight text in a TextView or WebView?

I see it is possible in a EditText

Highligh text in a EditText

I'd like to do the same in TextView or WebView.

Thats Possible?


Create a iOS6 Maps MKUserTrackingBarButtonItem button

I want to create a MKUserTrackingBarButtonItem the same way iOS6 have it. Like a floating UIBarButtonItem. ( http://cl.ly/image/1Q1K2S1A1H3N )

Can you give some advice in how to achieve this?

Thx!


UITableView won't present

I have a very strange situation in my app and i can't explain or locate the bug.
I have a UIViewController with a tableView in it.
In the table view I have 3 prototype cells, also i have 2 section that are divided like so:

first section: row 0 (cell ID: episodeScrollersCell)
second section: row 0 (cell ID: addCommentsCell)
              : row 1+ (cell ID: commentCell)

The required methods in the protocol are listed below.

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger rowNum;
    if(section == 0){
        rowNum = 1;
    }else{
        rowNum = 1; // here is the problem. If i change the number of row to above 1
    }
    return rowNum;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier;
    if(indexPath.section == 0){
        cellIdentifier = episodeScrollersCell;
    }else if (indexPath.section == 1 && indexPath.row == 0){
        cellIdentifier = addCommentsCell;
    }else{
        cellIdentifier = commentCell;
    }
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    return cell;
}

Now the problem arises when I want to have 2 rows or above in the second section (i.e to have 2 prototype cells in one section), the view Controller won't show. I've logged the cellForRowAtIndexPath: method to see if the cells gets loaded and they do.

Any advice?
Thanks,


Extending the Android application certificate past its expiration

Recently I saw this:

In the unlikelihood any of my apps survive (and I survive and everything else dependent survives) until 2037, will my apps have to be re-released with a new package name because of needing a new certificate?

Is there no way to extend a certificate?


Apache(2.2.22) not starting after enabling SSL on windows7

Installed Apache on win 7 and previously(without enabling SSL) its worked successfully. After Configuring SSL on httpd.conf,while trying to restart through monitor(stop then start) its prompting below error. please help me otu of this issue.

  The Request Operation has failed

while trying start apache through services getting below error

"Windows couldn't start Apache 2.2 on local PC. For more information check system events log. If it's not a windows service contact service provider and reference the code:1"

Apache Verion is

c:\Program Files (x86)\Apache Software Foundation\Apache2.2\bin>httpd.exe -v
Server version: Apache/2.2.22 (Win32)
Server built:   Jan 28 2012 11:16:39

while executing httpd.exe -e debug,

c:\Program Files (x86)\Apache Software Foundation\Apache2.2\bin>httpd.exe -e debug
[Fri Jan 15 15:06:51 2016] [debug] mod_so.c(246): loaded module actions_module
[Fri Jan 15 15:06:51 2016] [debug] mod_so.c(246): loaded module alias_module
[Fri Jan 15 15:06:51 2016] [debug] mod_so.c(246): loaded module asis_module
[Fri Jan 15 15:06:51 2016] [debug] mod_so.c(246): loaded module auth_basic_module
[Fri Jan 15 15:06:51 2016] [debug] mod_so.c(246): loaded module authn_default_module
[Fri Jan 15 15:06:51 2016] [debug] mod_so.c(246): loaded module authn_file_module
[Fri Jan 15 15:06:51 2016] [debug] mod_so.c(246): loaded module authz_default_module
[Fri Jan 15 15:06:51 2016] [debug] mod_so.c(246): loaded module authz_groupfile_module
[Fri Jan 15 15:06:51 2016] [debug] mod_so.c(246): loaded module authz_host_module
[Fri Jan 15 15:06:51 2016] [debug] mod_so.c(246): loaded module authz_user_module
[Fri Jan 15 15:06:51 2016] [debug] mod_so.c(246): loaded module autoindex_module
[Fri Jan 15 15:06:51 2016] [debug] mod_so.c(246): loaded module cgi_module
[Fri Jan 15 15:06:51 2016] [debug] mod_so.c(246): loaded module dir_module
[Fri Jan 15 15:06:51 2016] [debug] mod_so.c(246): loaded module env_module
[Fri Jan 15 15:06:51 2016] [debug] mod_so.c(246): loaded module imagemap_module
[Fri Jan 15 15:06:51 2016] [debug] mod_so.c(246): loaded module include_module
[Fri Jan 15 15:06:51 2016] [debug] mod_so.c(246): loaded module isapi_module
[Fri Jan 15 15:06:51 2016] [debug] mod_so.c(246): loaded module log_config_module
[Fri Jan 15 15:06:51 2016] [debug] mod_so.c(246): loaded module mime_module
[Fri Jan 15 15:06:51 2016] [debug] mod_so.c(246): loaded module negotiation_module
[Fri Jan 15 15:06:51 2016] [debug] mod_so.c(246): loaded module setenvif_module
[Fri Jan 15 15:06:51 2016] [debug] mod_so.c(246): loaded module userdir_module

in httpd.con file,updated the below entries

Listen <ipadress>:81
ServerAdmin admin@www.d235y.com => www.d235y.com->domain name created after executing "openssl" command=> openssl req -new -out server.csr
    # Secure (SSL/TLS) connections
Include conf/extra/httpd-ssl.conf

in httpd-ssl.conf file,

Listen 10.94.2.44:8443
<VirtualHost _default_:443>
#   General setup for the virtual host
DocumentRoot "C:/Program Files (x86)/Apache Software Foundation/Apache2.2/htdocs"
ServerName www.d235y.com:443
ServerAlias d235y.com:443
ServerAdmin admin@www.d235y.com
ErrorLog "C:/Program Files (x86)/Apache Software Foundation/Apache2.2/logs/error.log"
TransferLog "C:/Program Files (x86)/Apache Software Foundation/Apache2.2/logs/access.log"

certificates file entries are as follows

SSLCertificateFile "C:/Program Files (x86)/Apache Software Foundation/Apache2.2/conf/server.cert"
SSLCertificateKeyFile "C:/Program Files (x86)/Apache Software Foundation/Apache2.2/conf/server.key"


How to create context menus that modify the Current Control?

In my application, a RichTextBox is dynamically created when a certain form is opened.  Currently, clicking on the box opens up an OpenFileDialog, where the user selects a file, and then the file location is put into the RichTextBox.

My end user told me yesterday that he instead wants the following:

Left-clicking the RichTextBox should open the specified file in explorer

Right-clicking should open up a ContextMenuStrip, with one of the options in the strip being "Select File".

My revised code is contained in the following Gists:

My openFileDialog sub, which handle the .Click event for the ToolStripMenuItem

Sub openFileDialog(ByVal sender As System.Windows.Forms.ToolStripMenuItem, ByVal e As System.EventArgs)
    Dim myOpenFileDialog As New OpenFileDialog()

    If Not sender.GetCurrentParent().Parent.Text = "" Then
        myOpenFileDialog.InitialDirectory = sender.GetCurrentParent().Parent.Text
    Else
        myOpenFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
    End If

    myOpenFileDialog.Filter = "All files (*.*)|*.*"
    myOpenFileDialog.FilterIndex = 1
    myOpenFileDialog.RestoreDirectory = True

    If myOpenFileDialog.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
        sender.GetCurrentParent().Parent.Text = myOpenFileDialog.FileName
    End If
End Sub

My fileControlRightClicked sub, which handle the right-clicking of the RichTextBox

Sub fileControlRightClicked(ByVal sender As System.Windows.Forms.RichTextBox, ByVal e As System.Windows.Forms.MouseEventArgs)
    If e.Button <> Windows.Forms.MouseButtons.Right Then Return

    Dim cms = New ContextMenuStrip
        'cms.Parent = sender
        Dim item1 = cms.Items.Add("Select File")
        item1.Tag = 1
        AddHandler item1.Click, AddressOf openFileDialog
        cms.Show(sender, e.Location)
End Sub

Other than those two pieces of code, then only relevant code I can think of is

AddHandler .MouseUp, AddressOf fileControlRightClicked

Which is used when the RichTextBox is declared.

How do I reference the specific instance of RichTextBox that is clicked?

Clearly, using sender.GetCurrentParent().Parent does not work, and neither does sender.GetCurrentParent.SourceControl.  (These can be seen in the openFileDialog gist above)

If I left out any relevant information or code, or was unclear about the problem I am having, please comment, and I will correct/add any necessary information.


Why should we override a method?

Recently I was asked this question "why should one override a method? "

I replied, if I have a class with 10 methods and I want to use all of its functionality except one method, then I will override that method to have my own functionality.

Then the interviewer replied in that case why cant we write a new method with a different name and use that method instead.

Yes this is also right. Now I am confused. What is the real objective in overriding a method?

Can anyone please tell me?  Thank you all in advance.


Finding an element in a javascript array and returning the position of the matched element

I'm plucking my brain away at this but was hoping someone could help after several failed attempts.

I have an HTML list like this:

<ul>
<li><span class="current"></span></li>
<li><span class="normal"></span></li>
</ul>

I'm trying to figure out a way to find the li element in this list which has the span with the class current with the number it is at in the ul. So, in this case, it would be 1.

I tried using different jquery functions but I seem to be getting nowhere. This is what it looks like right now:

var list = $('ul li');
$.each(list, function(key, value) {
    if( $(this).find('.current') ) {
        alert(key);
    }
});

This just alerts 0, and 1, essentially meaning that it doesn't work. Does anyone have any idea what is wrong with what I'm doing?


Removing strings from another string in java

Lets say I have this list of words:

 String[] stopWords = new String[]{"i","a","and","about","an","are","as","at","be","by","com","for","from","how","in","is","it","not","of","on","or","that","the","this","to","was","what","when","where","who","will","with","the","www"};

Than I have text

 String text = "I would like to do a nice novel about nature AND people"

Is there method that matches the stopWords and removes them while ignoring case; like this somewhere out there?:

 String noStopWordsText = remove(text, stopWords);

Result:

 " would like do nice novel nature people"

If you know about regex that wold work great but I would really prefer something like commons solution that is bit more performance oriented.

BTW, right now I'm using this commons method which is lacking proper insensitive case handling:

 private static final String[] stopWords = new String[]{"i", "a", "and", "about", "an", "are", "as", "at", "be", "by", "com", "for", "from", "how", "in", "is", "it", "not", "of", "on", "or", "that", "the", "this", "to", "was", "what", "when", "where", "who", "will", "with", "the", "www", "I", "A", "AND", "ABOUT", "AN", "ARE", "AS", "AT", "BE", "BY", "COM", "FOR", "FROM", "HOW", "IN", "IS", "IT", "NOT", "OF", "ON", "OR", "THAT", "THE", "THIS", "TO", "WAS", "WHAT", "WHEN", "WHERE", "WHO", "WILL", "WITH", "THE", "WWW"};
 private static final String[] blanksForStopWords = new String[]{"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""};

 noStopWordsText = StringUtils.replaceEach(text, stopWords, blanksForStopWords);


Java Criteria API and operations on java.util.Date columns

Is there a way to convert java.util.Date column to unix time and perform operations on that instead.

I've tried

CriteriaBuilder cb = entityManager.getCriteriaBuilder();
Root<Trip> table = cq.from(Trip.class);
table.get(Trip_.endTime).as(Long.class)

but it doesn't seem to work (endTime is of type java.util.Date (DATETIME in database))

OR

Is there a way to get number of seconds between two java.util.Date columns

Thanks


Embed content from a different server

I have a landing page (mainly CSS and HTML) that I want to add content to. The issue is that the server that deploys the page is outdated and I'd rather run my content from another server. The content I want to add is a cgi script written in Python. Is it possible to run this script from within another server on the landing page. Ultimately, the page will load content from two different servers.


Intertistitial ADMOB and external/chromium/net/disk_cache/backend_impl.cc

I've installed a Interstitial on my first app. It's my first time and error rains from the aindroid sky... I've solved a lot of them thanks to StackOverflow, but this is a strange error, maybe someone could help me:

06-26 09:48:56.221      604-629/com.armadillo.sh5 E/chromium﹕ external/chromium/net/disk_cache/backend_impl.cc:1097: [0626/094856:ERROR:backend_impl.cc(1097)] Critical error found -8
06-26 09:48:56.531      604-629/com.armadillo.sh5 W/chromium﹕ external/chromium/net/disk_cache/storage_block-inl.h:119: [0626/094856:WARNING:storage_block-inl.h(119)] Failed data load.
06-26 09:48:56.544      604-629/com.armadillo.sh5 W/chromium﹕ external/chromium/net/disk_cache/storage_block-inl.h:119: [0626/094856:WARNING:storage_block-inl.h(119)] Failed data load.
06-26 09:48:56.544      604-629/com.armadillo.sh5 W/chromium﹕ external/chromium/net/disk_cache/storage_block-inl.h:119: [0626/094856:WARNING:storage_block-inl.h(119)] Failed data load.
06-26 09:48:56.571      604-629/com.armadillo.sh5 W/chromium﹕ external/chromium/net/disk_cache/storage_block-inl.h:119: [0626/094856:WARNING:storage_block-inl.h(119)] Failed data load.
06-26 09:48:56.601      604-629/com.armadillo.sh5 E/chromium﹕ external/chromium/net/disk_cache/entry_impl.cc:830: [0626/094856:ERROR:entry_impl.cc(830)] Failed to save user data
06-26 09:48:56.601      604-629/com.armadillo.sh5 E/chromium﹕ external/chromium/net/disk_cache/entry_impl.cc:830: [0626/094856:ERROR:entry_impl.cc(830)] Failed to save user data
06-26 09:49:01.051      604-604/com.armadillo.sh5 I/Ads﹕ Ad finished loading.

Software is running anyway but no ADS appear. What could be the problem? Seems android cannot download (or save after download) the interstitial image from internet... I'm right?
I'm working on Android Studio. Thanks for any help!


Convert image to byte array without using SwingFXUtils

In the answer of the question getPublicStorage(“Pictures”) lists no files we have tried solution 1 and 2 but in the byte array process seems the array does not represent the actual image.

Used code:
Services.get(PicturesService.class).ifPresent(service -> {
            service.takePhoto(false).ifPresent(image -> {
                imageView.setImage(image);

                PixelReader pixelReader = image.getPixelReader();
                int width = (int) image.getWidth();
                int height = (int) image.getHeight();
                byte[] buffer = new byte[width * height * 4];
                pixelReader.getPixels(0, 0, width, height, PixelFormat.getByteBgraInstance(), buffer, 0, width * 4);

                //Test
                ByteArrayInputStream in = new ByteArrayInputStream(buffer);
                Image image2 = new Image(in);

                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                imageView.setImage(image2);
                //Test

                proceedImage(buffer);
            });
        });

private void proceedImage(byte[] arrayImage) {
        this.arrayImage = arrayImage;

        enableZoom(true);

        apply = true;
    }

Exception:
W/System.err(15096): com.sun.javafx.iio.ImageStorageException: No loader for image data
W/System.err(15096):    at com.sun.javafx.iio.ImageStorage.loadAll(ImageStorage.java:276)
W/System.err(15096):    at com.sun.javafx.tk.quantum.PrismImageLoader2.loadAll(PrismImageLoader2.java:142)
W/System.err(15096):    at com.sun.javafx.tk.quantum.PrismImageLoader2.<init>(PrismImageLoader2.java:77)
W/System.err(15096):    at com.sun.javafx.tk.quantum.QuantumToolkit.loadImage(QuantumToolkit.java:740)
W/System.err(15096):    at javafx.scene.image.Image.loadImage(Image.java:1073)
W/System.err(15096):    at javafx.scene.image.Image.initialize(Image.java:804)
W/System.err(15096):    at javafx.scene.image.Image.<init>(Image.java:707)
W/System.err(15096):    at org.openjanela.dialog.ImageViewDialog.lambda$null$5(ImageViewDialog.java:260)

Any idea for a fix \ tweak \ workaround would be much appreciated.


How can I tell if a user clicked "Don't allow" on a <fb:login-button> initiated dialog?

I have a FB login button on my site. I'd like to analyze how many people click the button, but do not proceed with the login process (i.e. close the dialog, or click "Don't Allow").

Any ideas?


Undefined reference in C++ but classes are included

I have the following C++ code, which uses the PointCloud Library, and i want to extract some narf features. I use the CMAKE compiler as explained in the tutorial http://pointclouds.org/documentation/tutorials/narf_keypoint_extraction.php#narf-keypoint-extraction
I would like to keep it in the same way, as I am not so familiar with C++.

#include <iostream>

#include <pcl/io/ply_io.h>
#include <boost/thread/thread.hpp>
#include <pcl/range_image/range_image.h>
#include <pcl/point_cloud.h>
#include <pcl/io/pcd_io.h>
#include <pcl/visualization/range_image_visualizer.h>
#include <pcl/visualization/pcl_visualizer.h>
#include <pcl/features/range_image_border_extractor.h>
#include <pcl/keypoints/narf_keypoint.h>
#include <pcl/console/parse.h>

int main(int argc, char** argv) {
// Fetch point cloud filename in arguments | Works with PCD and PLY files
std::vector<int> filenames;
bool file_is_pcd = false;

filenames = pcl::console::parse_file_extension_argument(argc, argv, ".ply");

if (filenames.size() != 1) {
    filenames = pcl::console::parse_file_extension_argument(argc, argv,
            ".pcd");

    if (filenames.size() != 1) {
        return -1;
    } else {
        file_is_pcd = true;
    }
}

// Load file | Works with PCD and PLY files
pcl::PointCloud<pcl::PointXYZ>::Ptr source_cloud(
        new pcl::PointCloud<pcl::PointXYZ>());

if (file_is_pcd) {
    if (pcl::io::loadPCDFile(argv[filenames[0]], *source_cloud) < 0) {
        std::cout << "Error loading point cloud " << argv[filenames[0]]
                << std::endl << std::endl;
        return -1;
    }
} else {
    if (pcl::io::loadPLYFile(argv[filenames[0]], *source_cloud) < 0) {
        std::cout << "Error loading point cloud " << argv[filenames[0]]
                << std::endl << std::endl;
        return -1;
    }
}

if (pcl::console::find_argument(argc, argv, "-m") >= 0) {
    bool setUnseenToMaxRange = true;
    std::cout
            << "Setting unseen values in range image to maximum range readings.\n";
}
int tmp_coordinate_frame;
if (pcl::console::parse(argc, argv, "-c", tmp_coordinate_frame) >= 0) {
    int coordinate_frame = pcl::RangeImage::CoordinateFrame(
            tmp_coordinate_frame);
    std::cout << "Using coordinate frame " << (int) coordinate_frame
            << ".\n";
}
float angular_resolution = 0.5f;
float support_size = 0.2f;
pcl::RangeImage::CoordinateFrame coordinate_frame =
        pcl::RangeImage::CAMERA_FRAME;
bool setUnseenToMaxRange = false;

// --------------------------------
// -----Extract NARF keypoints-----
// --------------------------------
pcl::RangeImageBorderExtractor range_image_border_extractor;
pcl::NarfKeypoint narf_keypoint_detector(&range_image_border_extractor);
narf_keypoint_detector.getParameters().support_size = support_size;
//narf_keypoint_detector.getParameters ().add_points_on_straight_edges = true;
//narf_keypoint_detector.getParameters ().distance_for_additional_points = 0.5;

pcl::PointCloud<int> keypoint_indices;
narf_keypoint_detector.compute(keypoint_indices);
std::cout << "Found " << keypoint_indices.points.size() << " key points.\n";

return 0;
}

The thing is that when I run "make" in my /build folder I get this output:

adrian@Jarvis:~/PointCloudComparator/build$ make
Scanning dependencies of target visua
[ 50%] Building CXX object CMakeFiles/visua.dir/src/visua.cpp.o
[100%] Linking CXX executable visua
CMakeFiles/visua.dir/src/visua.cpp.o: En la función `main':
visua.cpp:(.text+0x4ea): referencia a `pcl::RangeImageBorderExtractor::RangeImageBorderExtractor(pcl::RangeImage const*)' sin definir
visua.cpp:(.text+0x50b): referencia a `pcl::NarfKeypoint::NarfKeypoint(pcl::RangeImageBorderExtractor*, float)' sin definir
visua.cpp:(.text+0x54d): referencia a `pcl::NarfKeypoint::compute(pcl::PointCloud<int>&)' sin definir
visua.cpp:(.text+0x5ad): referencia a `pcl::NarfKeypoint::~NarfKeypoint()' sin definir
visua.cpp:(.text+0x5bc): referencia a `pcl::RangeImageBorderExtractor::~RangeImageBorderExtractor()' sin definir
visua.cpp:(.text+0x6e8): referencia a `pcl::NarfKeypoint::~NarfKeypoint()' sin definir
visua.cpp:(.text+0x6fc): referencia a `pcl::RangeImageBorderExtractor::~RangeImageBorderExtractor()' sin definir
collect2: error: ld returned 1 exit status
make[2]: *** [visua] Error 1
make[1]: *** [CMakeFiles/visua.dir/all] Error 2
make: *** [all] Error 2

But, as you can see, everything is imported. I thought that maybe it is a problem of compilation or cmake, I do not know. Here is also my CMakeLists:

cmake_minimum_required(VERSION 2.6 FATAL_ERROR)

project(PointCloudComparator)

find_package(PCL 1.8 REQUIRED COMPONENTS common io)

include_directories(${PCL_INCLUDE_DIRS})
link_directories(${PCL_LIBRARY_DIRS})
add_definitions(${PCL_DEFINITIONS})

add_executable (visua src/visua.cpp)
target_link_libraries (visua ${PCL_LIBRARIES})

How can i make this work?

Cheers


Regex correct pattern matching conditions in java jdbc

I want to match with strings which is alphanumeric as well as which has special characters -, / and also white spaces

For example: If the string is Motorola C168/CC168i-1 , it should match

But when I am using following regular expression, its not matching it right. So, what is the correct condition?

if (line.matches("[A-Za-z0-9 \\/\\-]+$") {
    .....
}


Initializing object of derived class using initializer-list

I got a struct B that is derived from a struct A.

struct A{
  int a;
};

struct B : public A{
    int b;
};

Is there a straight way to initialize an object of type B without providing a constructor, let's say using initializer-list?

Some more insight:

I got two structs that I use to pass data between threads; the second one holds the same data as the first one, with the addition of some synchronization variable. I could make the first struct a data member of the second one, or just duplicate the declaration of data members in the second struct, to easily use the initializer-list; but I think that in this particular application it would be logically more correct that the second struct extends the first one.


Saving an image from picture box to png C#

Good Day!
I am trying to save an image from PictureBox, however, it is giving me an error.

        pictureBox1.ImageLocation = @"C:\emo\hairs\Hair-01.png";
        this.pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
        pictureBox1.Image.Save(@"C:\Coke\res1.png", System.Drawing.Imaging.ImageFormat.Png);

This is the error:

An unhandled exception of type 'System.NullReferenceException' occurred in Emo.exe
  Additional information: Object reference not set to an instance of an object.

Please help me identify my answer.


Posting Images to mongodb using multer MEAN stack

Hello I am trying to upload images from angular to my mongodb. I am using multer on my server side and my api looks like that and it works when i insert to it static data :

app.post('/api/photo', function(req, res) {
    var newItem = new ItemSchema();
    // THIS WILL COME FROM ANGULAR FORM
    // newItem.img.data = fs.readFileSync(req.files.userPhoto.path)
    newItem.img.data = fs.readFileSync('/Users/heshamelmasry/Desktop/FerreroRocher.jpg')
    newItem.img.contentType = 'image/png';

    console.log(req.body);

    newItem.save();
    res.status(200);

});

I am trying on the client side to make a function to post image to the data base and use http to call my api. So in my controller for angular i tried to write a code like that :

postImages() {

    var vm = this;

    function(this, $upload) {
      this.onFileSelect = function($files) {
        //$files: an array of files selected, each file has name, size, and type.
        for (var i = 0; i < $files.length; i++) {
          var file = $files[i];
          this.upload = $upload.upload({
            url: 'http://localhost:5000/api/photo', //upload.php script, node.js route, or servlet url
            data: {
              myObj: this.myModelObj
            },
            file: file,
          }).progress(function(evt) {
            console.log('percent: ' + parseInt(100.0 * evt.loaded / evt.total));
          }).success(function(data, status, headers, config) {
            // file is uploaded successfully
            console.log(data);
          });
        }
      };
    }

  }

and my main i have this

  <input type="file" ngf-select="onFileSelect($files)" multiple>

Actually this is not right IN MY client side

in my schema on the server side i need to pass two things buffer and content type

img: {
        data: Buffer,
        contentType: String
    }

which is like that if i am passing it statically in my server

newItem.img.data = fs.readFileSync('/Users/heshamelmasry/Desktop/FerreroRocher.jpg')
    newItem.img.contentType = 'image/png';

so it is the url and the content type

my question how i can handle this on the client side to get this url and content type from my form calling my function and the function in my controller


WP meta_query passing an array for an IN comparison

I have a string that I want to separate into an array and then pass to the value of a meta_query and then pass with the IN operator.

For example:

$my_string = "San Francisco, CA 94111";

And then I was thinking I would do this:

$my_string = (explode(',',$my_string));

And then in my meta_query:

'meta_query'        => array(
    array(
        'key' => 'login_email',
        'value' => $my_string,
        'compare' => 'IN'
    )

This doesn't seem to work. And I wonder if it is how the array is written with keys and passed to the value operator.

For example:

Array ( [0] => san francisco [1] => ca 94111 )

vs

In the Wordpress documentation it wants something like:

array( 3, 4 ),

Beyond what I am working on now, I thing it would be useful to be able to do something like this for a meta_query.  Any ideas? Thanks


Android Default Browser creates Horizontal Scroll Bar for Responsive Design

Android's default browser, shows my-site wider and creates horizontal scroll bar.

Here the screenshots of the problem: (Chrome vs default browser)

My viewport is:

<meta name="viewport" content="width=device-width, initial-scale=1">

What should I do?


Different Object of same type

I have a class

CartIndexViewModel

in my project SportsStore. I am making calls to WCF service so I want to pass an Object of CartIndexViewModel so I copied the required .dll files in the WCF Project but its conflicting as it says there is a type mismatch.

SportsStore.WebUI.ServiceReference.CartIndexViewModel
  SportsStore.WebUI.Models.CartIndexViewModel

both the classes are same, have same properties and methods but in different project how can i pass an object from sending side i.e SportsStore.WebUI.Models.CartIndexViewModel and the receiving end
i.e. SportsStore.WebUI.ServiceReference.CartIndexViewModel receive the object.
I dont have much knowledge i tried doing a lot of homework on this but couldn't get a solution.
Please help. Thank you.


Winphone project type is not supported in Visual studio 2017

I have an existing xamarin native project and It has

myproj.iOS

myproj.Droid

myproj.WinPhone

I uninstalled my visual studio 2015 and installed Visual studio 2017

Now in the solution explorer I can see it clearly says myproj.WinPhone (incompatible)

I am aware Microsoft is pushing for UWP but I still want to do as I was doing earlier like supporting windows 8.1 etc..

Is it possible to downgrade this to 2015 so that I can still do myproj.WinPhone ?

Or is there anyother way that will solve this problem

FYI:

I tried creating a new xamarin native project but that doesn't have winphone project but it has for iOS and Android though


What is the best way to manipulate a css file using a java servlet filter?

I need to convert relative image path (inside some css files) to absolute on the fly, using a java servlet filter.

What is the best way?


What is difference between escape sequence in Single quotes and Double quotes in Ruby

I have the following string and want to replace \n with < br>

string = "Subject: [Information] \n Hi there, \n...\n\n\n\\ud83d\\ude00\n--\n"
string.gsub('\n','<br>')  #don't work

Than I tried

string.gsub("\n",'<br>')

It works, can explain this to me. String in double quotes are different from string in single quotes or it has to do with escape sequence.

Thanks


Perl multiline search replace

I want to find and corresponding block and uncomment the second line in text file using perl one-liner. Im fairly new to using complex regex, so your help is very much appreciated! Also is there a way to debug one-liners?

Here is what I have so far, which does not work even though I tested it using a interactive regex tester:

perl -p -i.bak -e 's/#[\s]*label2[\n]#(.*)/${1}/gi;' file.txt

The text file looks like the following

#   label1
#variable=foobar1

#   label2
#variable=foobar2


Import jest object when not using jest runner

What do I need to import/require in order to access the magic jest object that contains jest.fn when not running my code with jest?


I have a Adapter in my application which inflates posts and shows them in a ListView. Each post has an image, so it uses LruCache to store images.

The app works well completely, but it crashed two or three times and I couldn't realize what was the problem. Only last time, I could get this log from LogCat:

E/AndroidRuntime(2407): Caused by: java.lang.NullPointerException: key
  == null || value == null

The crashes happen only when app is recently installed (When I delete the app from the device and install it again)! When I open the app for the first time and start scrolling up and down so fast, sometimes it crashes. (It won't happen all the time, it's completely random!)

And after that, it won't crash anymore... :/

I think it has something to do with LruCache and empty cache. I saw this question, but that wasn't my problem! I did check for null cache in my code:

if (MainActivity.thumbnailsCache.get(postID) != null)
        {
            imageViewThumbnail.setImageBitmap(MainActivity.thumbnailsCache.get(postID));
        } else {
            new DownloadAndSetImageTask(thumbnailURL).execute();
        }

Any suggestion?

P.S.: I know my question doesn't have enough details, but that's all the information I have!


Jenkins: how to limit checkouts to a few projects only (not the entire SVN)?

I am a complete newbie to Jenkins - so bear with me! I am sure that info sits somewhere out there, but I am currently still a bit swamped with Jenkins info...

Our project's SVN root contains many more projects than what is actually needed to build the release that I am supposed to create. Jenkins by default seems to check out the HEAD version of ALL projects found under the supplied repository URL. How/where can I specify that it needs to checkout (and later monitor) about 10 relevant projects only (and not all that are found in our SVN)?

I tried to specify that using Configure => Source Code Management => Advanced => Included Regions but apparently that's a different pair of shoes.


Swift: Setting SCNMaterial works for SCNBox but not for SCNGeometry loaded from Wings3D DAE

This code excerpt (scene, camera, light, etc. cut out of the code) works in Swift on an iOS simulator:

    let boxNode = SCNNode()

    // Create a box
    boxNode.geometry = SCNBox(width: 1, height: 1, length: 1, chamferRadius: 0.1)
    let numFaces = 6

    scene.rootNode.addChildNode(boxNode)

    // create and configure a material for each face
    var materials: [SCNMaterial] = Array()

    for i in 1...numFaces
    {
        let material = SCNMaterial()
        material.diffuse.contents = UIImage(named: "texture")
        materials += material
    }

    // set the material to the 3d object geometry
    boxNode.geometry.materials = materials

It generates a box with each face being the checkered image.

Trying the same thing with a simple stock geometry created in Wings3D, saved to a DAE, and loaded in the app gives me an appropriate shape, but no shading and image on the faces:

    let boxNode = SCNNode()

    // Load the geometry
    let urlToColladaFile = NSBundle.mainBundle().URLForResource("Objects", withExtension:"dae")
    let sceneSource = SCNSceneSource(URL:urlToColladaFile, options:nil)

    boxNode.geometry = sceneSource.entryWithIdentifier("dodecahedron3-0", withClass:SCNGeometry.self) as SCNGeometry
    let numFaces = 10

    scene.rootNode.addChildNode(boxNode)

    // create and configure a material for each face
    var materials: [SCNMaterial] = Array()

    for i in 1...numFaces
    {
        let material = SCNMaterial()
        material.diffuse.contents = UIImage(named: "texture")
        materials += material
    }

    // set the material to the 3d object geometry
    boxNode.geometry.materials = materials

What am I missing?


topics in distributed systems

what do you think is an interesting topic in distributed systems.

i should pic a topic and present it on monday. at first i chose to talk about Wuala, but after reading about it, i don't think its that interesting.

so what is an interesting (new) topic in distributed systems that i can research about.

sorry if this is the wrong place to post.


Android Custom Preference changing Override

My custom preference class helps color picking.

The custom-preference calls GridView Intent it's include 9 colors.

But My custom class can't refresh color which user-selected on gridview

When I finish the preference intent, then re-launch preference,

The Color showing up me as I selected.

onBindView() Method, I overried. It's perfect.

But I don't know what method I must override to refresh color.

public class ConfigImage extends Preference
{
    Context mContext;

    public ConfigImage(Context context, AttributeSet attrs)
    {
        this(context, attrs, 0);
        this.mContext = context;
    }

    public ConfigImage(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
        this.mContext = context;
        setLayoutResource(R.layout.preference_image);
    }

    @Override
    public void onBindView(View view)
    {
        super.onBindView(view);
        ImageView imageView = (ImageView) view.findViewById(R.id.preference_image_iv_color);
        if (imageView != null)
        {
            SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(mContext);
            int colorIndex = sharedPref.getInt("setting_color_default", 3);
            imageView.setBackgroundColor(Color.parseColor(ColorStorage.colors[colorIndex]));
        }
    }
}

<PreferenceCategory
    android:key="setting_color_info"
    android:title="색상" >

    <com.pack.ConfigImage
        android:id="@+id/setting_color_default"
        android:key="setting_color_default"
        android:selectable="true"
        android:summary="Choose default color"
        android:title="Default Color"
        settings:background="#FFFFFFFF" />
</PreferenceCategory>


Code breaks when anchors overlap KineticJS

Code breaks when anchors overlap. I have anchors for resizing draggable groups of shapes as given in below tutorial. I also have the functionality to delete the selected group. The delete functionality breaks the code when anchors (of two different groups) overlap and overlapping anchor is selected (mousedown).

       if (layer !== null && e.keyCode == 46) {  //Delete Key = 46
                SelectedShape.remove();
                layer.batchDraw();
            }
        });

        //Selecting on mousedown
        layer.on('mousedown', function (evt) {
            SelectedShape = evt.targetNode.getParent();
        });

Error message: Cannot get parent of a null or undefined reference.

http://www.html5canvastutorials.com/labs/html5-canvas-drag-and-drop-resize-and-invert-images/

Sample code

    var SelectedShape = null;

    function update(activeAnchor) {
    var group = activeAnchor.getParent();
    var topLeft = group.get('.topLeft')[0];
    var topRight = group.get('.topRight')[0];
        var bottomRight = group.get('.bottomRight')[0];
        var bottomLeft = group.get('.bottomLeft')[0];
        var rect = group.get('.rect')[0];

        var anchorX = activeAnchor.getX();
        var anchorY = activeAnchor.getY();

        // update anchor positions
        switch (activeAnchor.getName()) {
            case 'topLeft':
                topRight.setY(anchorY);
                bottomLeft.setX(anchorX);
                break;
            case 'topRight':
                topLeft.setY(anchorY);
                bottomRight.setX(anchorX);
                break;
            case 'bottomRight':
                bottomLeft.setY(anchorY);
                topRight.setX(anchorX);
                break;
            case 'bottomLeft':
                bottomRight.setY(anchorY);
                topLeft.setX(anchorX);
                break;
        }

        rect.setPosition(topLeft.getPosition());

        var width = topRight.getX() - topLeft.getX();
        var height = bottomLeft.getY() - topLeft.getY();
        if (width && height) {
            rect.setSize(width, height);
        }
    }
    function addAnchor(group, x, y, name) {
        var stage = group.getStage();
        var layer = group.getLayer();

        var anchor = new Kinetic.Circle({
            x: x,
            y: y,
            stroke: '#666',
            fill: '#ddd',
            strokeWidth: 2,
            radius: 8,
            name: name,
            draggable: true,
            dragOnTop: false
        });

        anchor.on('dragmove', function () {
            update(this);
            layer.draw();
        });
        anchor.on('mousedown touchstart', function () {
            group.setDraggable(false);
            this.moveToTop();
        });
        anchor.on('dragend', function () {
            group.setDraggable(true);
            layer.draw();
        });
        group.add(anchor);
    }

        var stage = new Kinetic.Stage({
            container: 'container',
            width: 578,
            height: 400
        });
        var darthVaderGroup = new Kinetic.Group({
            x: 270,
            y: 100,
            draggable: true
        });
        var yodaGroup = new Kinetic.Group({
            x: 100,
            y: 110,
            draggable: true
        });

        var Group3 = new Kinetic.Group({
            x: 100,
            y: 300,
            draggable: true
        });
        var layer = new Kinetic.Layer();

        /* add the groups to the layer and the layer to the stage*/
        layer.add(darthVaderGroup);
        layer.add(yodaGroup);
        layer.add(Group3);
        stage.add(layer);

        // darth vader
        var darthVaderImg = new Kinetic.Rect({
            x: 0,
            y: 0,
            width: 200,
            height: 138,
            fill: 'green',
            stroke: 'black',
            strokeWidth: 4,
            name: 'rect'
        });

        darthVaderGroup.add(darthVaderImg);
        addAnchor(darthVaderGroup, 0, 0, 'topLeft');
        addAnchor(darthVaderGroup, 200, 0, 'topRight');
        addAnchor(darthVaderGroup, 200, 138, 'bottomRight');
        addAnchor(darthVaderGroup, 0, 138, 'bottomLeft');

        darthVaderGroup.on('dragstart', function () {
            this.moveToTop();
        });
        // yoda
        var yodaImg = new Kinetic.Rect({
            x: 0,
            y: 0,
            width: 93,
            height: 104,
            fill: 'red',
            stroke: 'black',
            strokeWidth: 4,
            name: 'rect'
        });

        yodaGroup.add(yodaImg);
        addAnchor(yodaGroup, 0, 0, 'topLeft');
        addAnchor(yodaGroup, 93, 0, 'topRight');
        addAnchor(yodaGroup, 93, 104, 'bottomRight');
        addAnchor(yodaGroup, 0, 104, 'bottomLeft');

        yodaGroup.on('dragstart', function () {
            this.moveToTop();
        });

        var rect3 = new Kinetic.Rect({
            x: 0,
            y: 0,
            width: 93,
            height: 104,
            fill: 'blue',
            stroke: 'black',
            strokeWidth: 4,
            name: 'rect'
        });

        Group3.add(rect3);
        addAnchor(Group3, 0, 0, 'topLeft');
        addAnchor(Group3, 93, 0, 'topRight');
        addAnchor(Group3, 93, 104, 'bottomRight');
        addAnchor(Group3, 0, 104, 'bottomLeft');

        Group3.on('dragstart', function () {
            this.moveToTop();
        });

        stage.draw();

        //Deleting selected shape
        window.addEventListener('keydown', function (e) {
            if (layer !== null && e.keyCode == 46) {  //Delete Key = 46
                SelectedShape.remove();
                layer.batchDraw();
            }
        });

        //Selecting on mousedown
        layer.on('mousedown', function (evt) {
            SelectedShape = evt.targetNode.getParent();
        });
</script>


grep and regex : Print lines that contain character N times in unknown combinations

I have a file containing strings like

xxxbbxxxbxbx
xxxbxxxxbxxx
xxbxxxbxxbxx
bbbbxxxxxxxx
bxxxxxxxxxxx
xxxxbxxxxxxx
xxxxbbxxbbxx
xxxxbbbbxxxx
xxxxbbbbbxxx

In reality the file x is really a variety of uninteresting alphabetical characters. I want to use grep to print out all the lines where b occurs exactly four times.

If I use grep -e "[^b]b[^b]\{0,4\}b[^b]\{0,4\}b[^b]\{0,4\}b[^b]\{1,4\}" test.txt it excludes the last line (I want), but also excludes line 4 (I don't want) where the line starts with b.

If I use grep -e "b[^b]\{0,4\}b[^b]\{0,4\}b[^b]\{0,4\}b[^b]\{1,4\}" test.txt, it catches line 4 (I want) but also the last line (I don't want).


I have four buttons directing to a single activity, how to findout which button caused the activity to open?

Button novice = (Button) findViewById(R.id.novice);

novice.setOnClickListener(new OnClickListener(){

    public void onClick(View v) {
        Intent nov = new Intent(getApplicationContext(), gameface.class);
        startActivity(nov);
        nov.putExtra("lvl", "1");
    }
});

Button easy1 = (Button) findViewById(R.id.easy);
easy1.setOnClickListener(new OnClickListener(){
    public void onClick(View v) {
        Intent eas = new Intent(getApplicationContext(), gameface.class);
        startActivity(eas);
        eas.putExtra("lvl", "2");
    }
});

THis is my code so i tried sending data with the button press and thought of using
this

Intent g = getIntent();
String x = g.getStringExtra("lvl");

on the new activity to capture which button it was but it doesnt work.

can someone tell me whats up?


NSTextField lags when changing frame

I am building my first application for osx and have run into trouble when i try to change the frame of a NSTextField.

I am trying to change the frame of the text field inside an animation (so close to 60 fps) and it works when my window is really small and the textfield is empty. But when i enter a lot of text into the text field or just make it much bigger the animation will lagg horribly. This can also be seen when i resize the window containing the text field.

Resizing the window in the TextEdit application works at close to 60 fps so i would like some help to achieve similar performance.

Currently i do something similar to below on every frame of the animation.

NSRect rect = NSMakeRect(0, 0, width, height);
self.textField.frame = rect;