Q:

MDX replace null - get dimension ranges

Hi I have the following MDX query:
select NON EMPTY {[Measures].[count_X]} ON 0,
NON EMPTY {[DIM_DAYS].Children} ON 1
from [Cube]

With the following result set:
Axis #0:
{[DIM_S].[A], [DIM_LOCALIT].[X], [DIM_ANNO].[2013]}
Axis #1:
{[Measures].[count_X]}
Axis #2:
{[DIM_TEMPO_RILASCIO].[#null]}
{[DIM_TEMPO_RILASCIO].[0]}
{[DIM_TEMPO_RILASCIO].[1]}
{[DIM_TEMPO_RILASCIO].[2]}
{[DIM_TEMPO_RILASCIO].[3]}
{[DIM_TEMPO_RILASCIO].[4]}
{[DIM_TEMPO_RILASCIO].[5]}
{[DIM_TEMPO_RILASCIO].[6]}
{[DIM_TEMPO_RILASCIO].[7]}
{[DIM_TEMPO_RILASCIO].[8]}
{[DIM_TEMPO_RILASCIO].[9]}
{[DIM_TEMPO_RILASCIO].[10]}
Row #0: 468
Row #1: 69
Row #2: 70
Row #3: 53
Row #4: 90
Row #5: 77
Row #6: 78
Row #7: 119
Row #8: 159
Row #9: 155

I'd like to:
1) change the #null label with NOT SPECIFIED
2) make ranges for the days as [1 - 30] [31 - 60]
Could someone help me? THANKS

A:

with Member [DIM_TEMPO_RILASCIO].[NOT SPECIFIED] AS
            [DIM_TEMPO_RILASCIO].[#null]                       // just rename it
     Member [DIM_TEMPO_RILASCIO].[1-30] AS
            Aggregate( [DIM_TEMPO_RILASCIO].[1] : [DIM_TEMPO_RILASCIO].[30] )
     Member [DIM_TEMPO_RILASCIO].[31-60] AS
            Aggregate( [DIM_TEMPO_RILASCIO].[31] : [DIM_TEMPO_RILASCIO].[60] )
select NON EMPTY {[Measures].[count_X]} ON 0,
       NON EMPTY {
           [DIM_TEMPO_RILASCIO].[NOT SPECIFIED],
           [DIM_TEMPO_RILASCIO].[1-30],
           [DIM_TEMPO_RILASCIO].[31-60]
       } ON 1
  from [Cube]

should deliver what you stated in your question. However, I am not sure why you leave out [DIM_TEMPO_RILASCIO].[0].  And I am not suer about dimension and hierarchy names in detail, but maybe you can transfer my solution to your real situation.


Q:

How to deserialize datetime to local time?

I know dates should be stored in UTC Time and then be displayed based on client's configuration using libraries such as "moment-timezone". However, I'm writing software for a huge organization with a lot of legacy systems. It's not their culture storing dates as UTC. They have dozens of databases and thousands of tables, none uses UTC.
My Angular application sends data to my API as ISO format. My controllers receives date with the property Kind equals DateTimeKind.Utc.
I'm able to convert date to local time like this:
    public  static class DateTimeExtension
    {
        public static DateTime ToBrasiliaTime(this DateTime date)
        {
            if (date.Kind != DateTimeKind.Utc)
                return date;

            return TimeZoneInfo.ConvertTimeFromUtc(date, TimeZoneInfo.FindSystemTimeZoneById("E. South America Standard Time"));
        }
    }

I could then use
customer.bithrDate = customer.bithrDate.ToBrasiliaTime();....
product.assemblyDate = product.assemblyDate .ToBrasiliaTime();....
order.shippingDate = order.shippingDate .ToBrasiliaTime();....

But I don't want to call this extension all over and over... Is it possible to implement a Model Binder to deal with body data and apply my extension logic?
Again, I know dates should be stored in UTC Time, but that's not the point.

A:

Here is a Newtonsoft.Json solution using a custom JSON converter.  This assumes your date is sent as UTC.
public class LocalDateTimeConverter : JsonConverter
{
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.Value == null)
        {
            return null; // or DateTime.MinValue since its automatically converted anyway
        }

        var date = DateTime.Parse(reader.Value.ToString(), CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal);
        return TimeZoneInfo.ConvertTimeFromUtc(date, TimeZoneInfo.FindSystemTimeZoneById("E. South America Standard Time"));
    }

    public override bool CanConvert(Type objectType)
    {
        return true;
    }

    public override bool CanWrite
    {
        get { return true; }
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        serializer.Serialize(writer, value);
    }
}

Decorate the DateTime property in your model with the JsonConverter attribute.  It would look something like this:
public class SomeClass
{
    [JsonConverter(typeof(LocalDateTimeConverter))]
    public DateTime date { get; set; }
}

Even though the converter returns null when a null value is passed in, this method will still result in DateTime.MinValue when it's converted to a DateTime.  You'd need to change the type to nullable DateTime? if you actually want null instead.
Try it online


Q:

How to use bitwise shift operator in EL

I want to calculate a number use el expression.
<fmt:formatNumbers value="${num/1024}" pattern="0.00"/>

<fmt:formatNumbers value="${num >> 10}" pattern="0.00" />

A:

JSP EL doesn't support bitwise operators(only arithmetic, logical and relational operators).Its not implemented in EL.
If you want to do then, you need to encapsulate the operations within a java class, and expose that to the JSP.
For your reference please look in to given link,
http://www.informit.com/articles/article.aspx?p=30946&seqNum=4
** https://docs.oracle.com/javaee/6/tutorial/doc/gjddd.html**


Q:

Android: stretch layout above another

I create layout (ContentLayout) with wrap_content.
And I want to show loading layout (LoadingLayout) same size as ContentLayout above it.
Something like this:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    <LinearLayout.
            android:id="@+id/ContentLayout"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            ...

    </LinearLayout>

    <RelativeLayout
            android:id="@+id/LoadingLayout"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent">

            ...

    </RelativeLayout>

</RelativeLayout>

But when I want set LoadingLayout size in onMeasure, it will be set to right size only in second chance.
Works only something like this:
Activity
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) loadingLayout.getLayoutParams();
    params.height = getMeasuredHeight();
    loadingLayout.setLayoutParams(params);

    super.onMeasure(widthMeasureSpec, heightMeasureSpec); // android realignment hack
}

I think this is a hack. Do you have a better solution?

A:

If I understood correctly, you need LoadingLayout to keep width of ContentLayout
<RelativeLayout
    android:id="@+id/LoadingLayout"
    android:layout_alignLeft="@id/ContentLayout"
    android:layout_alignRight="@id/ContentLayout"
    ....>
....
</RelativeLayout>

Edit: Below is one way for the height
You can add a one time listener when global refresh happens. Then all sizes will be available.
// in your activity
@Override
protected void onCreate(Bundle state) {
    final View loading = findViewById(R.id.LoadingLayout);
    final View content = findViewById(R.id.ContentLayout);
    content.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            content.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            loading.getLayoutParams().height = content.getHeight();
            loading.onRequestLayout();
            loading.invalidate();
        }
    }
 }


Q:

UITableViewでのProgressBarの実装について

Swift3でのUITableView時のプログレスバーの振る舞いについて質問します。
データ取得中の真っ白な(何も表示されていない)tableViewの時にプログレスバーで、データ取得の進捗率を表示させたいのですが、下記のコードですと、tableViewにデータが表示された後にプログレスバーが表示されてしまいます。どのように修正したら良いでしょうか。
また、プログレスバーが終了後(.progressが1.0になった時)、プログレスバーをviewから消したいのですが、self.table.reloadData()の下にprogressView.removeFromSuperView()を書くとプログレスバーがそもそも表示されません。終了処理の書き方についてもアドバイスください。
override func viewDidLoad() {
    super.viewDidLoad()
    /* 諸々の設定(省略) */

    let navigationBarHeight = navigationController?.navigationBar.frame.size.height
    let statusBarHeight = UIApplication.shared.statusBarFrame.height

    progressView = UIProgressView(frame: CGRect(x: 0, y: navigationBarHeight! + statusBarHeight, width: self.view.frame.size.width, height: 5)) // プログレスバー
    progressView.progressViewStyle = .default
    progressView.progressTintColor = appleBlueColor
    progressView.trackTintColor = .white
    progressView.transform = CGAffineTransform(scaleX: 1.0, y: 2.0) // 長さと太さの設定

    self.view.addSubview(progressView)
}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    fetchData()
    self.table.reloadData()
}

func fetchData() {
    let request = URLRequest(url: rankUrl!)
    do {
        html = try String(contentsOf: request.url!, encoding: .utf8)
    }catch{
    }
    let jiDoc = Ji(htmlString: html)
    let parsedList = jiDoc?.xPath("//body/div/div/div/ul[@class='list']")?.first
    if parsedList != nil {
        for li in (parsedList?.enumerated())! {
            var item = [String]()
            let title = li.element.lastChild?.children.first?.content
            item.append(title!)
            let url = li.element.lastChild?.children.first?.children.first?.attributes["href"]
            item.append(url!)
            let site = li.element.lastChild?.children.last?.content
            item.append(site!)
            let newsDate = date_to_string(cellDate: Date())
            item.append(newsDate)

            self.items.append(item)
            progressView.setProgress(Float(self.items.count)/10, animated: true)
        }
    }

}

A:

やたらと長くなってしまったので、最初に結論を。
実際のアプリでは、ループ部分で(掲載のコードよりも)はるかに複雑な計算を行って、HTMLの受信よりもずーっと時間のかかる処理になるんだ、と言うのでない限り、UIProgressViewにはこだわらずUIActivityIndicatorViewなどを表示するだけで良いのではないでしょうか。
この結論に納得できない場合は、あちこちすっ飛ばしながらでも良いので以下の部分に目を通してみてください。
(コードはすべてこちらの環境でコンパイル・実行ができることを確認したものですので、わずかの修正が必要かもしれませんが、そちらでも試してみることができるはずです。)

まずは、UIProgressViewの基本をしっかり理解しておいてください。

進捗表示の対象となる処理は必ずバックグラウンドスレッドで実行する
進捗表示の契機となるごとにメインスレッド内でsetProgress(_:animated:)を呼ぶ

なぜ、こんな面倒なことになっているのかというと、そもそも 進捗表示が必要となるほど時間のかかる処理をメインスレッド(UIスレッド)内で行ってはならない と言うのがiOSの基本中の基本とも言える設計ポリシーだからです。(UIの更新に関する処理はメインスレッドで行う必要があるというのも別の「基本」ですね。)
(ちなみに、String(contentsOf:)は、 メインスレッドで使ってはいけない の代表メソッドの一つです。こちらも覚えておいてください。)

あなたのコードは以下の2点でUIProgressViewをうまく表示できないことになっています。

上記の UIProgressViewの基本 を踏まえたコードになっていない
実際の処理にかかる時間ではなく、取得したデータの処理に合わせて進捗を表示している

このうち2.については、実際のアクセス先(応答速度と取得するHTMLのサイズ)や使用している通信回線、その混み具合等に大きな影響を受けますので、もう少し情報がないとはっきりしたことはいえませんから、まずは1.についてのみ解決できるようにしてみます。
あなたのコードから無駄に見える部分を省いたこんなコードからスタートしてみます。
override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    fetchData()
    self.table.reloadData()
}

func fetchData() {
    //この`html`はローカル変数で良いはず
    let html: String
    do {
        //一度URLRequestを作って、その中からまたurlを取り出すのは無駄
        html = try String(contentsOf: rankUrl!, encoding: .utf8)
    } catch {
        //エラーを黙って無視するのは非常によくない
        fatalError("error=\(error)")
    }
    let jiDoc = Ji(htmlString: html)
    //条件付きバインディングが有効に使える場所
    if let parsedList = jiDoc?.xPath("//body/div/div/div/ul[@class='list']")?.first {
        //offsetを使わないのにenumerated()を使う意味がない
        for li in parsedList {
            var item: [String] = []
            //危険な`!`を使うより、`??`でデフォルト値を指定
            let title = li.lastChild?.firstChild?.content ?? ""
            item.append(title)
            let url = li.lastChild?.firstChild?.firstChild?.attributes["href"] ?? ""
            item.append(url)
            let site = li.lastChild?.lastChild?.content ?? ""
            item.append(site)
            let newsDate = date_to_string(cellDate: Date())
            item.append(newsDate)

            self.items.append(item)
            progressView.setProgress(Float(self.items.count)/Float(parsedList.children.count), animated: true)

            usleep(300_000) //<-本文参照
        }
    }
}

children.firstやchildren.lastはfirstChildやlastChildで良いように思われたので、そのように書き換えてあります。また危険な強制アンラップ(!)はできるだけ使わないように書き換えました。(rankUrl!だけは元がわからないので、そのまま使用していますが。)やりすぎで動きが変わってしまっている部分がありましたら、修正の上おためしください。
usleep(300_000) の行が追加されていると言うのが大きな変更点ですが、これは上の2.で述べた事柄が大きく影響することをご理解いただくためのものです。
上記のコード、ほぼあなたがご質問中に書かれたような挙動をします。

最初に書いた UIProgressViewの基本 に従って書き換えるなら、進捗表示の対象となるループ処理と、本来メインスレッドで実行してはいけないはずのString(contentsOf:)の両方を含むfetchData()自体をバックグラウンドスレッドで実行するというのが簡単でしょう。
デフォルトのバックグラウンドキューであるDispatchQueue.global()を使えば、大変なコードにはなりません。「UI更新はメインスレッドで」を実現する場合には、メインスレッドで管理されているDispatchQueue.mainを同様に使うだけです。
override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    //デフォルトのglobal()キューを使って処理をバックグラウンドで実行
    DispatchQueue.global().async {
        self.fetchData()
        DispatchQueue.main.async {
            self.table.reloadData()
            //reloadData()完了後に実行する処理をメインキューに登録
            DispatchQueue.main.async {
                self.progressView.removeFromSuperview()
                self.progressView = nil
            }
        }
    }
}

//このfetchData()は、必ずバックグラウンドで実行する
func fetchData() {
    let html: String
    do {
        html = try String(contentsOf: rankUrl!, encoding: .utf8)
    } catch {
        fatalError("error=\(error)")
    }
    let jiDoc = Ji(htmlString: html)
    if let parsedList = jiDoc?.xPath("//body/div/div/div/ul[@class='list']")?.first {
        for li in parsedList {
            var item: [String] = []
            let title = li.lastChild?.firstChild?.content ?? ""
            item.append(title)
            let url = li.lastChild?.firstChild?.firstChild?.attributes["href"] ?? ""
            item.append(url)
            let site = li.lastChild?.lastChild?.content ?? ""
            item.append(site)
            let newsDate = date_to_string(cellDate: Date())
            item.append(newsDate)

            //Jiライブラリーの要素は複数スレッドからアクセスすると不具合が出るようなので、バックグラウンド側で計算を済ませる
            let progressRatio = Float(self.items.count)/Float(parsedList.children.count)
            DispatchQueue.main.async {
                //SwiftのArrayはスレッドセーフではないので、こちらは必ずメインスレッド内で更新
                self.items.append(item)
                //`setProgress(_:animated:)`もメインスレッド内で呼ぶ
                self.progressView.setProgress(progressRatio, animated: true)
            }
            usleep(300_000)
        }
    }
}

こちらのコードをテスト環境(通信先のサーバはlocalhostのPHP、返すHTMLは上記のコードを試すのに必要最小限の内容)で実行したところ、progressViewが少しずつ(300_000μ秒ごと)伸びていきtableViewの表示とほぼ同時にprogressViewが消えると言うのがわかります。

さて、progressViewをはっきり見せるためにusleep(300_000)でユーザを余計に待たせるなんてことになっては本末転倒ですから、その行を削除してみましょう。htmlの複雑さにもよるので条件により大きく結果は異なるはずなのですが、こちらのテスト環境では全くprogressViewが見えなくなってしまいました。
先のfetchData()に処理時間を図るためのコードを埋め込んで実行してみました。
func fetchData() {
    var timeNow = Date()
    var timeLast = timeNow
    func showTime(_ label: String) {
        timeNow = Date()
        print(label, Int(timeNow.timeIntervalSince(timeLast) * 1_000_000), "μsec")
        timeLast = timeNow
    }

    let html: String
    do {
        html = try String(contentsOf: rankUrl!, encoding: .utf8)
    } catch {
        fatalError("error=\(error)")
    }
    showTime("A")
    let jiDoc = Ji(htmlString: html)
    showTime("B")
    if let parsedList = jiDoc?.xPath("//body/div/div/div/ul[@class='list']")?.first {
        showTime("C")
        for li in parsedList {
            var item: [String] = []
            let title = li.lastChild?.firstChild?.content ?? ""
            item.append(title)
            let url = li.lastChild?.firstChild?.firstChild?.attributes["href"] ?? ""
            item.append(url)
            let site = li.lastChild?.lastChild?.content ?? ""
            item.append(site)
            let newsDate = date_to_string(cellDate: Date())
            item.append(newsDate)

            //Jiライブラリーの要素は複数スレッドからアクセスすると不具合を発生するようなので、バックグラウンドで計算
            let progressRatio = Float(self.items.count)/Float(parsedList.children.count)
            DispatchQueue.main.async {
                //SwiftのArrayはスレッドセーフではないので、こちらは必ずメインスレッド内で更新
                self.items.append(item)
                //`setProgress(_:animated:)`もメインスレッド内で呼ぶ
                self.progressView.setProgress(progressRatio, animated: true)
            }
            showTime("D")
        }
    }
}

結果は実行するたびに大きく変動するんですが、傾向としては全く同じなので、ある1回分だけこちらのテスト環境での実行結果を載せておきます。

A 181083 μsec
B 3473 μsec
C 1659 μsec
D 2997 μsec
D 131 μsec
D 77 μsec
D 75 μsec
D 75 μsec
D 76 μsec
D 76 μsec
D 76 μsec
D 74 μsec
D 78 μsec

一番時間のかかっているAの部分(String(contentsOf:))は、次点のB(HTMLをパースしてJiインスタンスを作る部分)の50倍もかかっています。また進捗表示の対象としているループ処理は一番長い最初の1回でさえ、わずか3msecほど、2回目以降は100μsec程度ですから、この速度でprogressViewを更新しても人間の目に見えないどころか液晶表示の更新さえ追いつきません。
つまりここにあげたコードは、処理に必要な時間の95%以上が経過した後で、残りの一瞬を10回に分けて進捗表示しようとしている(それも10等分ではない)、と言うことになります。
実際のアプリではrankUrlは外部のサーバを表すわけですから、Aの部分にかかる処理時間ははるかに長くなります。その部分ではなにも進捗表示を行わないで、HTML取得後のループで0からprogressViewを表示しても、極めて不自然な表示(「全く見えない」を含む)にしかなりません。
さて、これ以上は「どこまで頑張ってどんな表示にしたいのか」がわからないとなんとも言えませんが、所要時間の予測できないネットワークからのデータ取得で、ユーザ目線から自然に見える進捗表示を行うのは極めて困難です。(ダウンロードに何十秒もかかる巨大なファイルの受信なら、時間ではなく、受信容量で進捗表示をする手もあるでしょうが。)多少大きなページでもHTMLそのものは大した大きさにはなりませんので、最初のレスポンスが返ってきてから進捗表示を行ってもあまり意味がないです。
と言うわけで最初の結論につながります。この部分はもうちょっと頑張りたい、だとか、(使うかどうかは別にして)この部分がよくわからない、などの点がありましたら、コメント等でお知らせください。

2つ目のコードに記載したこの部分:
    DispatchQueue.main.async {
        self.table.reloadData()
        //reloadData()完了後に実行する処理をメインキューに登録
        DispatchQueue.main.async {
            self.progressView.removeFromSuperview()
            self.progressView = nil
        }
    }

これはやはり説明なしでは少しわかりにくかったようです。なんせメインキュー(DispatchQueue.main)の中で実行されている処理で、またメインキューを指定していますから。
これをきちんと理解するためには一般的なキューベースのイベント処理がどのように実行されているのか、と言ったことがわかっていなくてはいけません。ここでは、その辺りのことをできるだけ直感的にご理解いただけるように努力して見ます。
その場合重要なのは、上の方の注にもあるこちらです:
UIの更新に関する処理はメインスレッドで行う必要がある
実はこれはあなたがアプリとして書くコードだけではなく、iOSが内側でなんらかの処理を行う際にも成り立つことなのです。例えばUITableViewのreloadData()のようなメソッドを呼ぶと、iOSはテーブル全体を再表示しないといけませんから、かなり膨大な内部処理が行われます。その中には(例えば新しいUITableViewCellの生成や内容の変更など)UIの更新を含むものもあるので、iOSは「後でメインスレッドでこの処理をやらないといけない」と言う処理の塊をメインキューに積んで行くのです。
そしてそのようにして積まれた処理が実行されるのは、現在メインキューで実行されている処理が終わってから、なのです。
単に:
    DispatchQueue.main.async {
        self.table.reloadData()
        self.progressView.removeFromSuperview()
        self.progressView = nil
    }

と書いてしまうと、そのようなreloadData()用にキューに積まれたシステム側の処理が走る前にremoveFromSuperview()が実行されてしまい、期待していた結果が得られなくなることもあるわけです。
なんらかのイベント処理の中でUI更新を含むメソッドを呼んだなら、その効果が現れるのは、そのイベント処理が終わった後になる、と言うのは覚えておいてもらったほうがいいでしょう。私が先に書いたコードでは、内側のDispatchQueue.main.async {...}により、「この処理はあとでやっといてくれ」と渡したら、すぐにイベント処理を終了しているのです。


Q:

How to keep order of collected database row the same as array passed to where clause

I am working on a project using Laravel 4.2 and I have a line that retrieves some rows from a table called Gifts
$theGifts = Gift::whereIn('id', $giftImages)->get();

This variable $giftImages is an array and values are ordered like this
Array
(
    [0] => 5
    [1] => 2
    [2] => 3
    [3] => 4
)

When I output this one however $theGifts the retrieved results are not in the same order as the array of ids is and I need it to be in the same order..
How can I insure that the order is the same? I am using the data from the object in the controller, not the view by the way.
The printout of the Gift::all() looks like this (in case someone needs to compare)..
Illuminate\Database\Eloquent\Collection Object
(
    [items:protected] => Array
        (
            [0] => Gift Object
                (
                    [table:protected] => gifts
                    [connection:protected] =>
                    [primaryKey:protected] => id
                    [perPage:protected] => 15
                    [incrementing] => 1
                    [timestamps] => 1
                    [attributes:protected] => Array
                        (
                            [id] => 2
                            [name] => Banana
                            [image] => bananas-icon.png
                            [value] => 10
                        )

                    [original:protected] => Array
                        (
                            [id] => 2
                            [name] => Banana
                            [image] => bananas-icon.png
                            [value] => 10
                        )

                    [relations:protected] => Array
                        (
                        )

                    [hidden:protected] => Array
                        (
                        )

                    [visible:protected] => Array
                        (
                        )

                    [appends:protected] => Array
                        (
                        )

                    [fillable:protected] => Array
                        (
                        )

                    [guarded:protected] => Array
                        (
                            [0] => *
                        )

                    [dates:protected] => Array
                        (
                        )

                    [touches:protected] => Array
                        (
                        )

                    [observables:protected] => Array
                        (
                        )

                    [with:protected] => Array
                        (
                        )

                    [morphClass:protected] =>
                    [exists] => 1
                )

            [1] => Gift Object
                (
                    [table:protected] => gifts
                    [connection:protected] =>
                    [primaryKey:protected] => id
                    [perPage:protected] => 15
                    [incrementing] => 1
                    [timestamps] => 1
                    [attributes:protected] => Array
                        (
                            [id] => 3
                            [name] => Cherry Cake
                            [image] => Cherry-Cake-icon.png
                            [value] => 15
                        )

                    [original:protected] => Array
                        (
                            [id] => 3
                            [name] => Cherry Cake
                            [image] => Cherry-Cake-icon.png
                            [value] => 15
                        )

                    [relations:protected] => Array
                        (
                        )

                    [hidden:protected] => Array
                        (
                        )

                    [visible:protected] => Array
                        (
                        )

                    [appends:protected] => Array
                        (
                        )

                    [fillable:protected] => Array
                        (
                        )

                    [guarded:protected] => Array
                        (
                            [0] => *
                        )

                    [dates:protected] => Array
                        (
                        )

                    [touches:protected] => Array
                        (
                        )

                    [observables:protected] => Array
                        (
                        )

                    [with:protected] => Array
                        (
                        )

                    [morphClass:protected] =>
                    [exists] => 1
                )

            [2] => Gift Object
                (
                    [table:protected] => gifts
                    [connection:protected] =>
                    [primaryKey:protected] => id
                    [perPage:protected] => 15
                    [incrementing] => 1
                    [timestamps] => 1
                    [attributes:protected] => Array
                        (
                            [id] => 4
                            [name] => Coconut
                            [image] => coconut-icon.png
                            [value] => 5
                        )

                    [original:protected] => Array
                        (
                            [id] => 4
                            [name] => Coconut
                            [image] => coconut-icon.png
                            [value] => 5
                        )

                    [relations:protected] => Array
                        (
                        )

                    [hidden:protected] => Array
                        (
                        )

                    [visible:protected] => Array
                        (
                        )

                    [appends:protected] => Array
                        (
                        )

                    [fillable:protected] => Array
                        (
                        )

                    [guarded:protected] => Array
                        (
                            [0] => *
                        )

                    [dates:protected] => Array
                        (
                        )

                    [touches:protected] => Array
                        (
                        )

                    [observables:protected] => Array
                        (
                        )

                    [with:protected] => Array
                        (
                        )

                    [morphClass:protected] =>
                    [exists] => 1
                )

            [3] => Gift Object
                (
                    [table:protected] => gifts
                    [connection:protected] =>
                    [primaryKey:protected] => id
                    [perPage:protected] => 15
                    [incrementing] => 1
                    [timestamps] => 1
                    [attributes:protected] => Array
                        (
                            [id] => 5
                            [name] => Lemon
                            [image] => lemon-icon.png
                            [value] => 3
                        )

                    [original:protected] => Array
                        (
                            [id] => 5
                            [name] => Lemon
                            [image] => lemon-icon.png
                            [value] => 3
                        )

                    [relations:protected] => Array
                        (
                        )

                    [hidden:protected] => Array
                        (
                        )

                    [visible:protected] => Array
                        (
                        )

                    [appends:protected] => Array
                        (
                        )

                    [fillable:protected] => Array
                        (
                        )

                    [guarded:protected] => Array
                        (
                            [0] => *
                        )

                    [dates:protected] => Array
                        (
                        )

                    [touches:protected] => Array
                        (
                        )

                    [observables:protected] => Array
                        (
                        )

                    [with:protected] => Array
                        (
                        )

                    [morphClass:protected] =>
                    [exists] => 1
                )

        )

)

A:

I believe this will do it for you:
Gift::whereIn('id', $giftImages)
    ->orderBy(DB::raw('FIELD(id, ' . implode(',', $giftImages) . ')'), 'ASC')
    ->get();

Taken from this question. You have to use DB::raw() since Laravel doesn't provide a native way to do this. Untested...


Q:

Hibernate session management with Spring and JAX-WS

I have an application that uses Hibernate for persistence and am attempting to implement a JAX-WS interface (exposing it using the Spring Framework).  I also have a service class (annotated with @WebService and @WebMethod) that calls methods in my persistence layer. I am getting exceptions (LazyInitializationException) when working with lazy loaded objects.
I ran into the same problem with Quartz jobs and was able to resolve it by wrapping my job bean with a org.springframework.aop.framework.ProxyFactoryBean and providing  org.springframework.orm.hibernate3.HibernateInterceptor.  I attempted to wrap my service bean with the ProxyFactoryBean, but received errors about the proxy not being an annotated web service.
Is there a way to do the same type of thing in this case, or what would be the best approach to managing my hibernate sessions to take in this scenario?

A:

So, it looks like one potential option is to split my implementation into two classes. One that will contain all of the business logic that calls the database persistence layer, and another that exposes the web service and calls the business logic.  The class containing the business logic can be wrapped with the Spring framework ProxyFactoryBean to utilize a HibernateInterceptor.
Java:
public class BusinessLogicClass implements MyInterface {
  public void doBusinessLogic() {
    //Perform Hibernate stuff here
  }
}

@WebService
public class WebServiceClass {
  BusinessLogicClass blc;

  public setBlc(BusinessLogicClass blc) {
    this.blc = blc;
  }

  @WebMethod
  public void doLogic() {
    blc.doBusinessLogic()
  }
}

Spring XML Configuration:
<bean id="transactionalService" class="BusinessLogicClass">
</bean>

<bean id="transactionalServiceProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
    <property name="target">
        <ref bean="transactionalMessageQueueService"/>
    </property>
    <property name="proxyInterfaces">
        <value>MyInterface</value>
    </property>
    <property name="interceptorNames">
        <value>hibernateInterceptor</value>
    </property>
</bean>

<bean id="webService" class="WebServiceClass">
    <property name="blc">
        <ref bean="transactionalServiceProxy"/>
    </property>
</bean>

This does solve my problem.  Though for my application it is a bit of annoyance to have two classes with basically the same methods just go get the persistence to work...
-- Update --
As an alternative (probably a better alternative) to using the proxy configuration in the Spring XML file annotation based translation management could be enabled and then each method in the BusinessLogicClass that needed to be within a transaction could be annotated with @Transactional. This is the approach I ultimately used.


Q:

How does Ubuntu One deal with files changed on more than one computer?

What happens if I edit a file on my desktop PC, and edit the same file on my synchronised laptop which is currently not connected to the internet?
Let's say I have a file called "jobs.todo" in "~/Ubuntu One" on my desktop, and this contains the following:
Job 1: description
Job 2: description
Job 3: description
As I have my laptop connected to the internet, this file will appear on both computers.
I disconnect my laptop, and take it away with me on a journey. While I'm away, I think of another job I have to get done and add it to the file, which will now read:
Job 1: description
Job 2: description
Job 3: description
Job 4: description
When I get home, I go back to my desktop and think of something else I need to get done, so I add this to the desktop computer's "jobs.todo" file, forgetting that I'd already altered this file on the laptop.
This file will read:
Job 1: description
Job 2: description
Job 3: description
Job 5: description
and the file will be synchronised with the cloud soon afterwards, because the desktop machine is connected to the internet.
Some while later, I start up my laptop, it connects itself to the internet wirelessly, and synchronisation with the cloud takes place.
I suspect that the desktop version (with Job 5 in it) will be copied from the cloud, and I will lose the file containing Job 4, because the datestamp on the cloud's version of the file will be later than that on the laptop

A:

What will happen is that when the laptop goes online, the server will tell it it has a new version of the file, and client (specifically syncdaemon) will notice it has a new version of the file also. This is called a conflict, and resolution is up to the client; what syncdaemon does is rename the locally-changed file to originalname.u1conflict, and download the file from the server to the original name. If .u1conflict already exists, it will try with .u1conflict.1, .u1conflict.2, and so on.
Right now nothing lets you know about the conflict; for 11.04 we'll be letting you know when they happen, and at some point (but not for 11.04) we'll be creating a little app that will help you resolve the conflicts. There isn't an automatic way of doing it, but we should be able to make it easy / userfriendly.


Q:

ngRepeat and directives execution order

When an Angular directive contains an ngRepeat element, the ngRepeat execution appears to to occur after the containing directive's link execution.
Is there a mechanism ($watch, $observe, etc) that I can use to wire up a response after the ngRepeat execution?
Here's an example of the behavior:
http://plnkr.co/edit/yBiSvveeSissU7Rik6Kp?p=preview
I want to operate in a state in the directive where the inputs are available.
My primary goal is to alter the elements of ngRepeat from the containing directive.

A:

The typical way to determine when ng-repeat has finished is to write a directive that checks to see if $last is true.  Then you can call a function (defined on a parent/ancestor scope) or emit an event, inside a $timeout callback or $evalAsync.
For more details and examples, see Calling a function when ng-repeat has finished


Q:

Multiple Ajax calls liferay portlets

I am having liferay portlet and I need to heavily depend upon the AJAX calls. So I need to make multiple calls to serveResource method. One way to do the same is that I can pass a parameter with the URL and then differentiate the request according to that parameter.
But in my case I have to call serveResource so many times due to which the method will be difficult to maintain.
Is there any framework to do so? Using which the code becomes maintainable.

A:

Use Spring MVC framework and call different method based on your business logic/user action in controller,
Try below code
in jsp
<portlet:resourceURL var="loadContents" id="loadContents"></portlet:resourceURL>
<portlet:resourceURL var="loadCategories" id="loadCategories"></portlet:resourceURL>

ajax call in jsp
AUI().ready(
        function(A) {
            A.use('aui-io-request',
                    function(aui) {
                    A.io.request("<%=loadContents%>", {
                        autoLoad : false,
                        cache : false,
                        dataType : 'json',
                        data:{},
                        method:'POST',
                        on : {
                            success : function(event, id, xhr) {
                                var response = this.get('responseData');
                                 // add logic here after response
                            }
                        }
                    }).start();
                });
        });

in controller/ java class
    @ResourceMapping("loadCategories")
    public void loadCategories(final ResourceRequest resourceRequest, final ResourceResponse resourceResponse)
    {
         // your business logic goes here
    }

    @ResourceMapping("loadContents")
    public void loadContents(final ResourceRequest resourceRequest, final ResourceResponse resourceResponse)
    {
         // your business logic goes here
    }

hope above code snippets will help you and you get what you were looking for!!!


Q:

Locating a memory leak/source of over-release crach

Can anyone help me figure out where I should be releasing exerciseArray? I get a crash in dealloc and when I release just before calling sortedArray. This code is called many times.
//Set exerciseArray
review.exerciseArray = [[workout assignedExercises] allObjects];

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    NSLog(@"viewWillAppear");
    NSString *workoutName =  [event.assignedWorkout valueForKey:@"name"];
    self.title = workoutName ;

    NSSortDescriptor *sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"index"
                                                                    ascending:YES] autorelease];
    NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
    [sortedArray release];
    sortedArray= [exerciseArray sortedArrayUsingDescriptors:sortDescriptors];
    NSLog(@"*****SORTEDARRAY****** %d",[sortedArray retainCount]);
    for (Exercise *ex in sortedArray){
        NSLog(@"%@ %@ %@",ex.name , ex.repCount, ex.weight);
    }
    NSLog(@"*********************");
    [sortedArray retain];
    [self.tableView reloadData];
}

 - (void)dealloc {
    [super dealloc];

    [managedObjectContext release];
    [event release];
}

A:

First things first: You should move the [super dealloc] call to the end of your dealloc method. Handle your custom variables first, and then the last thing you do is push the dealloc up to the superclass to handle the rest of the cleanup.

Now, I'm concerned about the [sortedArray release] and [sortedArray retain] in there. What you should be doing, to save you the semantics of implementing retain/release on your sortedArray ivar, is declaring a property for sortedArray like so:
// this goes in your @interface
@property (nonatomic, retain) NSArray *sortedArray;

// this goes in your @implementation
@synthesize sortedArray;

Now you can set sortedArray easily without worrying about retaining or releasing:
// note the use of self, this is required
self.sortedArray = [exerciseArray sortedArrayUsingDescriptors:sortDescriptors];

You can remove the release and retain calls now, as this is handled automatically. Make sure to add a line to your dealloc method to clean up the variable, too..
self.sortedArray = nil;

..which will call release on your array for you.
EDIT: This also applies to exerciseArray, which was your actual question. Wherever there's a Cocoa class involved, you can simplify memory management using @property (retain) and @synthesize. For NSInteger and other primitive types, or when you don't want to hold an owning reference to the object, use @property (assign) instead.


Q:

Strange template errors using vectors in C++

I right now am making a multithreading library for lua, and everything would compile if there weren't this strange problem. I have a container object for holding the thread object class I created. Here is the header for this object:
 #include "stdafx.h"
    ;

using namespace std;
class LuaThreadManager {
public:
    LuaThreadManager(int size);
    Thread& get(int id);
        int add(Thread& t);
void remove(int id);
protected:
     vector <Thread&> T;
     int numoccupied;
}

When I compile, I get three errors from this header(I will note that they are all at the line where I declare my header):
Line 12: error C2143: syntax error : missing ';' before '<'
Line 12: error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
Line (12): error C2238: unexpected token(s) preceding ';'
And here is my question: what the heck am I doing wrong? (Also, you will see the identifier Thread in the vector declaration; it is my thread object I created)
EDIT: All of the answers I have been given haven't worked. It isn't because I didn't include the vector library(I DID include it via including it in stdafx.h_, or because I am using references for the vector (fixed that, didn't fix my errors).

A:

You're not including the <vector> header. :)
(Stylistically, another thing you're doing wrong is putting using namespace std in a header file. Don't do that)

A:

std::vector cannot be specialized for reference types. The elements of a vector need to be assignable, which references are not.
The nearest equivalent may be a std::vector<std::reference_wrapper<Thread>>, depending on whether that suits your design.


Q:

Probability of each outcome from dice notation

In the "dice notation", XdY means you rolls X number of Y-sided dices, and adds the results together to get the final outcome.
For example, on 3d3 distribution, you can get number from 3 to 9, and the probability of each number can be calculated as:
$P(X=3) = P(X=9) = \frac{1}{27}$
$P(X=4) = P(X=8) = \frac{1}{9}$
$P(X=5) = P(X=7) = \frac{2}{9}$
$P(X=6) = \frac{7}{27}$.
For other examples, on 1d4 distribution, you can get number from 1 to 4 equally likely, and on 4d1 distribution, you always get 4.
Can I get the explicit formula that gives the probability of each outcome (namely, Z) from XdY distribution? I want the function $f(X,Y,Z)$ that exactly returns the probability that we get outcome $Z$ from XdY distribution.
I know when $X$ becomes large, this approaches the normal distribution, but when $X$ is not that large (like 15~20), I need exact value here..

A:

Let r.v. $S$ be the sum of $n$ dice, each with $m$ faces $1,...,m.$ The generating function for $S$ is
$$\sum_{j=1}^{nm} P(S=j)x^j = \left[\frac xm+\frac {x^2}m+...+\frac{x^m}m  \right]^n $$
$$ =\frac{x^n}{m^n}(1-x^m)^n(1-x)^{-n}  $$
Binomial expansions:
$$(1-x^m)^n=\sum_{k=0}^{nm}{n \choose k}(-1)^kx^{km}$$
$$ (1-x)^{-n}=\sum_{i=0}^{\infty} {-n \choose i}(-1)^ix^i= \sum_{i=0}^{\infty}{n+i-1 \choose i}x^i  $$
For a fixed integer $j\ge n$ we need to find the coefficient of $x^{j-n}$ in the product of these two sums in order to find $P(S=j).$ If we multiply term $k$ of the first sum and term $i$ of the second, then this gives $x^{km+i}.$ So we need to require $km+i=j-n.$ For given $k$ I can solve for  $i=j-n-km.$ So now $k$ is the only index variable:
$$P(S=j)=\frac {1}{m^n}\sum_{k=0}^{n} {j-1-km \choose j-n-km} {n \choose k}(-1)^k  $$
example: $ n=3,m=3,j=6$
$$ P(S=6)=\frac{1}{3^3}\left[ {5 \choose 3}{3 \choose 0}-{2\choose 0}{3 \choose 1} \right]=\frac{7}{27}  $$


Q:

jQuery when using renderWith method error regarding accessing an element id from a jQuery click event

I have a problem regarding accessing an element id from a jQuery click event when the actual element is part of template rendered with the method renderWith(). I cannot figure out whats wrong and could surely need some wise input.

A:

If your element is rendered (AKA: created dynamically) try like:
$(document).on('click', "#yourElementId", function(){
   alert( this.id ); // Test
});

if that's the case the question is a dupe of Click event doesn't work on dynamically generated elements (Pending Close)


Q:

Dealing with mods with poor reading comprehension?

My flag:

Not an Answer flag declined, with reason that it is a wrong answer or technically innacurate. The answer is actually RIGHT and ACCURATE, however, it does not answer the question asked. Therefore the flag "does not attempt to answer the question" applies. This is exactly what the Not an Answer flag is for. Please coach the moderator on this. – AaronLS Oct 22 at 22:26

Moderator Response:

declined - flags should not be used to indicate technical inaccuracies, or an altogether wrong answer

This mod clearly can't see that no one has claimed the answer is inaccurate or wrong.  In fact, the answer is completely accurate and factual, however is in no way relevant to the question asked.  It's akin to answering the question "Is peanut butter good for you?" with an answer of "Peanut butter is brownish color"
I flagged an item to clarify a flag, however it was declined again with the same reason, as if completely ignoring the fact that I made it absolutely clear I was not flagging it because I believed it was wrong or inaccurate.  I understand that an answer that is wrong or inaccurate should simply be downvoted. The answer given is an accurate statement, but is not relevant to the question.
The reason for the decline doesn't apply to this answer.  I've made this clear in my flag, but they didn't address this.
I imagine some will give alternative reasons that the "Not an Answer" flag does not apply here, but the point is that if the mod is incapable of articulating this themselves then they are unqualified to be a moderator.  If there is a legitimate reason to decline the flag, then so be it, but a moderator should be capable of articulating that.
The answer:
https://stackoverflow.com/a/31346669/84206

A:

Not an Answer (NAA) flags are there to indicate that someone misused the Answer button to post a question, or similarly something that is not an answer to anything. Wether or not an actual answer (like this is) is relevant to the post is not the moderator's job to decide and thus you should not flag those posts as NAA. Downvote them if you deem it necessary and leave a comment.
By the way, implying that mods have poor reading comprehension because you do not understand the meaning of the NAA flag is a little rude.

A:

Moderators aren't there to do anything about the accuracy of a post.  They're not to be regarded as subject-matter experts, since it very may well be a moderator handling your flag that doesn't know about this particular software's intricacies.
If you feel that an answer does not satisfy, you may comment and downvote to that effect.  Mod flags are only useful in situations when a post is actively harmful or can't be acted upon by someone like yourself in the community; namely, the post is spammy or offensive.

A:

This would be a proper "not an answer":

I have the same problem plz halp send solution to pekka5000@gmail.com

or

I make $8,000 a month from home using Google! Want to find out how?

If an answer is clearly attempting to answer the question, it is not "Not an answer" even though the author may have gotten something so completely wrong that they're actually not answering the question at all.
By our definition, that still is an incorrect answer, not none at all.


Q:

iOS NSMutableArray to NSString and then save to device >>> out of memory

i have a NSMutableArray filled with a lot of lines like this (GPS data, 3600 lines in one hour)
51.040987|12.379154|183|599|0.0|0.0|2014-05-23T17:48:02Z|321.4

In a loop i combine these values to a xml string.
like so
xmlExport = [NSString stringWithFormat:@"%@\t\t<trackpoint>\n\t\t\t<latitude>%@</latitude>\n\t\t\t<longitude>%@</longitude>\n\t\t\t<altitudemeter>%@</altitudemeter>\n\t\t\t<altitudefeet>%@</altitudefeet>\n\t\t\t<speedkmh>%@</speedkmh>\n\t\t\t<speedmph>%@</speedmph>\n\t\t\t<datetime>%@</datetime>\n\t\t\t<degree>%@</degree>\n\t\t</trackpoint>\n", xmlExport,[CoordsArray objectAtIndex: 0], [CoordsArray objectAtIndex: 1], [CoordsArray objectAtIndex: 2], [CoordsArray objectAtIndex: 3], [CoordsArray objectAtIndex: 4], [CoordsArray objectAtIndex: 5], [CoordsArray objectAtIndex: 6], [CoordsArray objectAtIndex: 7]];

and than i want to save this data on device as an xml file, like so
NSString *fileNameCSV = [NSString stringWithFormat:@"%@/export_%@.csv", documentsDirectory, date2];
success = [csvExport writeToFile:fileNameCSV atomically:YES encoding:NSUTF8StringEncoding error:&error];

With fewer data all works fine but when i have about/over 1500 lines i get a memory problem and the app crashes, in simulator all works fine.
The problem is not to save the file, I think more it is in the for loop when combining the xml string.
Is there an other way to save the data to device?
Here my code with autoreleasepool
    for (NSString *line in coords) {

    @autoreleasepool {

        NSArray* CoordsArray = [line componentsSeparatedByString:@"|"];

        if(ExportType2==2){
            xmlExport = [NSString stringWithFormat:@"%@\t\t<trackpoint>\n\t\t\t<latitude>%@</latitude>\n\t\t\t<longitude>%@</longitude>\n\t\t\t<altitudemeter>%@</altitudemeter>\n\t\t\t<altitudefeet>%@</altitudefeet>\n\t\t\t<speedkmh>%@</speedkmh>\n\t\t\t<speedmph>%@</speedmph>\n\t\t\t<datetime>%@</datetime>\n\t\t\t<degree>%@</degree>\n\t\t</trackpoint>\n", xmlExport,[CoordsArray objectAtIndex: 0], [CoordsArray objectAtIndex: 1], [CoordsArray objectAtIndex: 2], [CoordsArray objectAtIndex: 3], [CoordsArray objectAtIndex: 4], [CoordsArray objectAtIndex: 5], [CoordsArray objectAtIndex: 6], [CoordsArray objectAtIndex: 7]];
        }

        if(ExportType2==3){
            kmlExport = [NSString stringWithFormat:@"%@,%@,%@,%@", kmlExport,[CoordsArray objectAtIndex: 1], [CoordsArray objectAtIndex: 0], [CoordsArray objectAtIndex: 2]];
        }

        if(ExportType2==4){
            gpxExport = [NSString stringWithFormat:@"%@\t\t<trkpt lat=\"%@\" lon=\"%@\">\n\t\t\t<ele>%@</ele>\n\t\t\t<time>%@</time>\n\t\t\t<magvar>%@</magvar>\n\t\t</trkpt>\n", gpxExport,[CoordsArray objectAtIndex: 0], [CoordsArray objectAtIndex: 1], [CoordsArray objectAtIndex: 2], [CoordsArray objectAtIndex: 6], [CoordsArray objectAtIndex: 7]];
        }

        //NSLog([NSString stringWithFormat:@"line: %@", line]);
        //NSLog([NSString stringWithFormat:@"gpxExport: %@", gpxExport]);

    }
}

now the app crashes also with few data
self    Class   MailBuilder 0x00115f58
coords  __NSArrayM *    @"29 objects"   0x15e5e960
line    __NSCFString *  @"51.041037|12.379055|0|0|0.0|0.0|2014-05-23T18:29:17Z|297.6"   0x15e497f0
CoordsArray __NSArrayM *    @"8 objects"    0x17dde2a0
xmlExport   NSString *  0x17d39a00  0x17d39a00

A:

Wrap the inside of the loop in autoreleasepool, like this:
for (...) { // or however you are looping
    @autoreleasepool {
        // .... everything else
    }
}

This will cause one loop and 1500 loops to use the same amount of memory.


Q:

NetBeans can SELECT all columns except Primary Key field

This is related to this question, the solution for which did not work for me.
I'm using NetBeans to connect to a MySQL database (all running locally, all latest versions, latest JDBC driver).  I have created a simple table and populated it with a few rows of data:
CREATE TABLE STUDENTS(
    STUDENTID INTEGER not null primary key AUTO_INCREMENT,
    FIRSTNAME VARCHAR(30),
    LASTNAME VARCHAR(30),
    EMAIL VARCHAR(60)
);

INSERT INTO STUDENTS values ( null, 'Joe', 'Shmoe', 'joeshmoe@email.com' );

Using the MySQL command line, I can verify that the data made it into the database (SELECT *).  However, when I issue that same SELECT command in NetBeans, I get this weird error:
In NetBeans

    SELECT * FROM Students;

    Error code 1064, SQL state 42000: You have an error in your SQL syntax;
    check the manual that corresponds to your MySQL server version for the right
    syntax to use near 'OPTION SQL_SELECT_LIMIT=DEFAULT' at line 1
    Line 12, column 1

I also tried issuing the statement long form, which throws the error.  However, when I omit the primary key field from the long form statement, it returns data:
In NetBeans

SELECT STUDENTID, FIRSTNAME, LASTNAME, EMAIL FROM STUDENTS; <-- THROWS 1064 ERROR
SELECT FIRSTNAME, LASTNAME, EMAIL FROM STUDENTS;            <-- WORKS???

I don't have any idea what this error means.  Forum posts on the internet point to an old bug that has since been fixed, so I don't believe it has anything to do with NetBeans (maybe I'm wrong?).  Can anybody offer any insight into what I'm doing wrong?

A:

Problem solved.  It turns out that this bug has been corrected in the latest mysql jdbc driver.
http://dev.mysql.com/downloads/connector/j/


Q:

Dark Tower universe inconsistent maps

Refer to the answer in the question Dark Tower world map and the wiki article Can_Calyx
After giving a look at Dark Tower's world maps and reading "Wizard and Glass" I wonder:
Are the maps official (Stephen King approved)?
Because if you read "Wizard and Glass" you will see all people referring Mejis toward WEST. When Jonas catches Roland, he said Jonas was banned to WEST, lives and will die there. But in all maps Mejis is at EAST (or SOUTH in some others).

Just after set CIT-GO on fire, is some reference to smoke, wind and direction too.

(EDIT: Reference point is GILEAD. Sorry.)

A:

Roland passes his test and is sent East to Mejis as a gunslinger with Alain and Cuthbert; not West.
As @Magno C quotes in the comments:

She closed her eyes as if struck, drew in a breath, let it out, opened her eyes again. "Bad," she said, "yet maybe not as bad as I thought. And if thee doesn't come back? Sheemie and I go west, as thee said before?"

...

"Aye, to Gilead. There'll be a place of safety and respect for you there, dear, no matter what . . . but it's especially important that you go if you don't hear the tankers explode. Thee knows that, doesn't thee?"

You are correct Jonas was "sent West" for failing his test; but that doesn't mean he has to stay in the West.
I think you are taking the "sent West" and "sent East" too literally. They are phrases referring to the orientation of the courtyard where the "gunslinger test" takes place. The apprentice enters from the West end of the courtyard and the teacher enters from the East end of the courtyard.
If the apprentice fails his test, he is "sent West" out of the courtyard the same way he came in. If he passes, he is "sent East" and allowed to exit the East end as a gunslinger.

A:

TL;DR - no, those maps are not correct, and are not "official".
There isn't a comprehensive canonical map of All-World, but the closest we can get may be Bev Vincent's map from his book The Dark Tower Companion:

However, Vincent admits that even this map is partially unreliable:

NOTES CONCERNING THE MAP OF MID-WORLD:
This map assembles the known geography of Mid-World. Few distances are known, so the scale is arbitrary and probably wildly different in different parts of the map.
The biggest problem is this: if there is a Beam that goes due north, there cannot be a Beam that goes southwest. Since the Beams are arranged like the hours on a clock, that means there are two in the northwest quadrant. One runs from the eleven o’clock position south-southeast toward the Dark Tower, and the other runs from the ten o’clock position east-southeast.2
For a long time, the relative placement of Gilead was unknown, but in The Wind Through the Keyhole we learn that Tree is on or near the Beam of the Lion that ends in the north, and that Tree is north of Gilead.
After Roland saves the Beams, he believes that Shardik’s Beam has snapped into an eastward direction, which might lead one to assume it was the one that begins in the ten o’clock position. However, we also learn that the Western Rail Line used to run from Gilead through Debaria all the way to the Mohaine Desert. This is possible only if the Mohaine, which is south of Shardik’s Beam, is relatively far north. Closer to eleven o’clock than ten o’clock, in other words. This also means that Roland crossed only one Path of the Beam before reaching Tull, and not two. How he ended up near the Western Sea without reaching it before he visited Pricetown is another mystery.
There are other issues. According to Roland, the Western Sea used to be only a thousand miles from Gilead. We have only his word on this point, and there’s a lot about Mid-World that he doesn’t know. The distance from Lud to Topeka is around eight thousand miles, and this is only a segment of Shardik’s Beam. Mid-World has expanded a great deal if both pieces of data are accepted as fact.
We also know that the Arc of the Callas extends all the way to the region where the snow falls. That means Roland must have crossed it at some point. Perhaps the Callas are widely spaced and he went between them.
Garlan’s position on this map is arbitrary. It is to the west of Gilead and Debaria. But how far? No one knows. Presumably not near the Callas.
Here’s the bottom line: if you ever find yourself in Mid-World, you probably shouldn’t stake your life on this map, even if directions and distances are no longer drifting.
  -  The Dark Tower Companion: A Guide to Stephen King's Epic Fantasy

Still, this map does have a lot going for it:  Vincent is probably the world's third greatest Dark Tower expert (after Stephen King and Robin Furth);  Vincent interviewed King for his analyses of the Dark Tower;  Vincent had the help of Robin Furth (King's research assistant, the author of the *Dark Tower comics, and the author of Dark Tower:  The Complete Concordance) and Marsha DeFilippo (King's personal assistant); and so on.  None of this means that Vincent's map is canonical or official, but it does mean that it is very likely to be the best anyone can do.

The map linked in your other question:
In the map you added in a link in an edit on your other question, there are many problems - for starters, it calls the entire place "Mid-World", when in fact, Mid-World is a region of All-World.  Gilead, where Roland was born, is in "In-World".  The Dark Tower books follow a course through Mid-World into "End-World".  Also, Gilead, Mejis, Hambry, and several other locations are in the wrong places.


Q:

How to disable buttons in GTK3

Windows API has a function called EnableWindow that disables controls so user can't interact with them any more.
Is there an equivalent for GTK3 or GTK3++?

A:

gtk_widget_set_sensitive (widget, FALSE);

Note that if you need to check whether a widget is sensitive,  gtk_widget_get_sensitive() returns the value set with the above function and gtk_widget_is_sensitive() will tell you whether the widget really is sensitive -- this is affected by parent widgets sensitivity as well.


Q:

asp.net MVC - Default route doesn't appear to be working

I have  setup some routes and they work so if i put localhost/MyWebApp/Reservas ...... it works.
I have setup up a default route that if somebody enter localhost/MyWebApp it should go directly to the Reservas route ... but it doesn't..
I have installed a route debugger and it appears nothing matches the request.. am i doing something wrong?
Can you help? ... here is my routes .. notice the last route is the DEFAULT route that i preusume should kick in and send me via the Reservas route
  routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "Reservas", // Route name
            "Reservas/{action}/{jsonData}", // URL with parameters
            new {controller = "Reservation", action = "Index", jsonData="" } // Parameter defaults
            );

            routes.MapRoute(
            "Default",                                              // Route name
            "Reservas/{action}/{jsonData}",                           // URL with parameters
            new { controller = "Reservation", action = "Index", jsonData = "" }  // Parameter defaults
            );

A:

Your current default route will only match when the URL looks something like /MyWebApp/Reservas. You should change it to look something like this:
routes.MapRoute(
    "Default",
    "{controller}/{action}/{jsonData}",
    new { controller = "Reservation", action = "Index", jsonData = "" });


Q:

How do I add a reverse field value into the django serializer data set Part 2

I previously asked a similar question:
How do I add a reverse field value into the django serializer data set
But oddly, what worked for the first model doesn't work for the second.  Here are my models:
class ae(models.Model):
    opp_own = models.CharField(max_length = 50)

class statement_line(models.Model):
    ae = models.ForeignKey(ae, on_delete=models.PROTECT)
    pay_date = models.DateField(null=True)
    approve_date = models.DateField()
    opp_name = models.CharField(max_length = 50)
    type = models.CharField(max_length = 10)
    document_number = models.CharField(null=True,max_length = 50,)
    ct_id = models.CharField(max_length = 50,validators=[
        RegexValidator(regex='^CT',
                       message='this didn\'t come from salesforce'
                       )])
    amt = models.FloatField()
    cur = models.CharField(default='USD',max_length = 3)

class draws(models.Model):
    ae = models.ForeignKey(ae, on_delete=models.PROTECT)
    draw_type = models.CharField(choices=[('incentive pay','incentive pay'),('recoverable draw','recoverable draw')], max_length = 50)
    amt = models.FloatField()
    usd_amt = models.FloatField()
    cur = models.CharField(choices=[('USD','USD'),('EUR','EUR'),('AUD','AUD'),('IND','IND'),('GBP','GBP')],default='USD', max_length = 3)
    owe_date = models.DateField()
    sl = models.ForeignKey(statement_line, on_delete=models.PROTECT, null = True)

This works fine:
class drawsSerializer2(serializers.ModelSerializer):
    opp_own = serializers.SerializerMethodField()

    class Meta:
        model = draws
        fields = ['id','ae_id', 'ae','owe_date','draw_type','usd_amt','amt', 'opp_own']
        extra_kwargs = {
            'ae': {'write_only': True}
        }

    def get_opp_own(self, obj):
        return obj.ae.opp_own
goods = draws.objects.filter(sl_id__isnull=True).order_by('-owe_date')
serializer = drawsSerializer2(goods,many=True)
serializer.data

But inexplicably, this doesn't:
class statement_lineSerializer2(serializers.ModelSerializer):
    opp_own = serializers.SerializerMethodField()

    class Meta:
        model = statement_line
        fields = ['id','ae_id','ae','pay_date','opp_name','type','document_number','ct_id','amt','cur','opp_own']
        extra_kwargs = {
            'ae': {'write_only': True}
        }

    def get_opp_own(self, obj):
        return obj.ae.opp_own

goods2 = statement_line.objects.filter(pay_date__isnull=True).order_by('-approve_date')
sl = ae_statement_lineSerializer2(goods2,many=True)
sl.data

Instead I get this:
AttributeError: Got AttributeError when attempting to get a value for field opp_own on serializer ae_statement_lineSerializer2.
The serializer field might be named incorrectly and not match any attribute or key on the statement_line instance.
Original exception text was: 'statement_line' object has no attribute 'opp_own'.
I don't know what the background magic is actually doing and probably have to swim through the code to figure it out.  It must be something stupidly obvious.  Is it something stupidly obvious?  And now its memorialized on the internet for all to see.  serializerMethodFields, nested serializers; Everytime I have to look up a value from a foreign table in django I have a panic attack.

A:

I don't know if it's the only problem, but this line is causing you trouble:
ae = models.ForeignKey(ae, on_delete=models.PROTECT)

That's creating a class variable ae, so it can't see the module-level class ae. That's one reason we usually name classes with mixed case, like StatementLine, and name variables in snake case, like statement_line. See PEP8 for the standard guidelines.
However you do it, just make sure that the class name and the field name aren't the same.


Q:

Problem with kubernetes dicovery client in gateway microservice

I'm working on a microservices architecture just on spring and kubernetes. Right now I'm working on the gateway microservice. During the startup of the microservice I have the following error at runtime:

Blockquote

2020-01-15 11:00:57.312 ERROR 1 --- [      elastic-4] reactor.core.scheduler.Schedulers        : Scheduler worker in group main failed with an uncaught exception

reactor.core.Exceptions$ErrorCallbackNotImplemented: java.lang.IllegalStateException
Caused by: java.lang.IllegalStateException: null
    at java.util.Optional.orElseThrow(Optional.java:290) ~[na:1.8.0_212]
    at org.springframework.cloud.kubernetes.discovery.KubernetesDiscoveryClient.findEndpointPort(KubernetesDiscoveryClient.java:218) ~[spring-cloud-kubernetes-discovery-1.1.1.RELEASE.jar!/:1.1.1.RELEASE]
    at org.springframework.cloud.kubernetes.discovery.KubernetesDiscoveryClient.getNamespaceServiceInstances(KubernetesDiscoveryClient.java:161) ~[spring-cloud-kubernetes-discovery-1.1.1.RELEASE.jar!/:1.1.1.RELEASE]
    at org.springframework.cloud.kubernetes.discovery.KubernetesDiscoveryClient.getInstances(KubernetesDiscoveryClient.java:118) ~[spring-cloud-kubernetes-discovery-1.1.1.RELEASE.jar!/:1.1.1.RELEASE]
    at org.springframework.cloud.kubernetes.discovery.reactive.KubernetesReactiveDiscoveryClient.lambda$getInstances$0(KubernetesReactiveDiscoveryClient.java:58) ~[spring-cloud-kubernetes-discovery-1.1.1.RELEASE.jar!/:1.1.1.RELEASE]
    at reactor.core.publisher.FluxDefer.subscribe(FluxDefer.java:46) ~[reactor-core-3.3.2.RELEASE.jar!/:3.3.2.RELEASE]
    at reactor.core.publisher.FluxSubscribeOn$SubscribeOnSubscriber.run(FluxSubscribeOn.java:194) ~[reactor-core-3.3.2.RELEASE.jar!/:3.3.2.RELEASE]
    at reactor.core.scheduler.WorkerTask.call(WorkerTask.java:84) ~[reactor-core-3.3.2.RELEASE.jar!/:3.3.2.RELEASE]
    at reactor.core.scheduler.WorkerTask.call(WorkerTask.java:37) ~[reactor-core-3.3.2.RELEASE.jar!/:3.3.2.RELEASE]
    at java.util.concurrent.FutureTask.run(FutureTask.java:266) ~[na:1.8.0_212]
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180) ~[na:1.8.0_212]
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293) ~[na:1.8.0_212]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) ~[na:1.8.0_212]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) ~[na:1.8.0_212]
    at java.lang.Thread.run(Thread.java:748) ~[na:1.8.0_212]

2020-01-15 11:00:57.481  INFO 1 --- [           main] o.s.b.web.embedded.netty.NettyWebServer  : Netty started on port(s): 9080
2020-01-15 11:00:57.485  INFO 1 --- [           main] i.m.gateway.GatewayApplication           : Started GatewayApplication in 7.941 seconds (JVM running for 8.67)

Blockquote

The problem appeared with the move to kubernetes service discovery by adding the spring-cloud-starter-kubernetes dependency. By using another service discovery such as eureka or consul the gateway works correctly. Below is the pom:
<project>
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.2.RELEASE</version>
        <relativePath/>
    </parent>
    <groupId>it.milionaires</groupId>
    <artifactId>gateway</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>gateway</name>
    <description>Gateway service</description>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Hoxton.SR1</spring-cloud.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
        </dependency>
        <!--Dipendenza per gateway spring-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-loadbalancer</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>io.projectreactor</groupId>
            <artifactId>reactor-core</artifactId>
            <version>3.3.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-kubernetes</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.cloud</groupId>
                    <artifactId>spring-cloud-netflix-hystrix</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.springframework.cloud</groupId>
                    <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-config-client</artifactId>
        </dependency>
    </dependencies>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>com.spotify</groupId>
                <artifactId>dockerfile-maven-plugin</artifactId>
                <version>1.4.13</version>
                <executions>
                    <execution>
                        <id>tag-latest</id>
                        <goals>
                            <goal>build</goal>
                            <goal>tag</goal>
                            <goal>push</goal>
                        </goals>
                        <configuration>
                            <repository>gateway</repository>
                            <tag>latest</tag>
                        </configuration>
                    </execution>
                    <execution>
                        <id>tag-version</id>
                        <goals>
                            <goal>build</goal>
                            <goal>tag</goal>
                            <goal>push</goal>
                        </goals>
                        <configuration>
                            <repository>gateway</repository>
                            <tag>${project.version}</tag>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

Has anyone encountered this problem or know how to fix it? Thanks in advance
This is my deployment.yml :
apiVersion: apps/v1
kind: Deployment
metadata:
  name: gateway-deployment
  labels:
    app: gateway
spec:
  replicas: 1
  selector:
    matchLabels:
      app: gateway
  template:
    metadata:
      labels:
        app: gateway
    spec:
      containers:
        - name: gateway
          image: liviucornel/gateway
          ports:
            - containerPort: 9080
---
apiVersion: v1
kind: Service
metadata:
  name: gateway
spec:
  selector:
    app: gateway
  ports:
    - port: 9080
      targetPort: 9080
#      nodePort: 30010
  type: ClusterIP

This is the property file :
server:
  port: 9080

spring:
  application:
    name: gateway
  profiles:
    active: zone2
  cloud:
    loadbalancer:
      ribbon:
        enabled: false
    config:
      uri: http://configuration-server
      failFast: false
      discovery:
        service-id: configuration-server
        enabled: true
      retry:
        maxAttempts: 20
      enabled: true
      request-connect-timeout: 500
      request-read-timeout: 500
    kubernetes:
      discovery:
        service-name: gateway
        primary-port-name: 9080
        enabled: true
        all-namespaces: true

    gateway:
      routes:
        - id : servizio1
          uri : lb://servizio1
          predicates :
            - Path=/servizio1/**
          filters :
            - RewritePath=/servizio1/servizio1/(?<path>.*), /$\{path}
#            - name : ServiceGatewayPreFilter
#            - name : ServiceGatewayPostFilter
        - id: servizio2
          uri: lb://servizio2
          predicates:
            - Path=/servizio2/**
          filters:
            - RewritePath=/servizio2/servizio2/(?<path>.*), /$\{path}
      default-filters:
        - name : ServiceGatewayGlobalFilter
      discovery:
        locator:
          enabled: true

This is the docker file :
FROM openjdk:8-jdk-alpine

MAINTAINER Liviu <liviucornelciobanu91@gmail.com>

# Add a volume pointing to /tmp
VOLUME /tmp

# Make port 9080 available to the world outside this container
EXPOSE 9080

# The application's jar file
ARG JAR_FILE=target/gateway-0.0.1-SNAPSHOT.jar

# Add the application's jar to the container
ADD ${JAR_FILE} gateway.jar

# Run the jar file
ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/gateway.jar"]

A:

I have found the solution for my problem.
The problem was with the DiscoveryClient Route Definition Locator on spring-cloud-gateway.
I saw in the documentation that:
"The Gateway can be configured to create routes based on services registered with a DiscoveryClient compatible service registry.
To enable this, set spring.cloud.gateway.discovery.locator.enabled=true and make sure a DiscoveryClient implementation is on the classpath and enabled (such as Netflix Eureka, Consul or Zookeeper)."
This properties doesn't work with Kubernate configuration Service Discovery.
I have changed it to False and it worked!!
Greetings


Q:

Android GCM encryption

I'm starting my way with Android GCM Framework..
It's actually pretty nice and easy to implement but one important question:
The data i'm transferring is not sensitive, but yet i don't want it be available from everyone..
Is this encrypted some how ? or should i encrypt my messages ?
I know that in basic its a notification service - but i'm sending short messages so its important to me to understand how these messages are passing by Google,
Thanks !

A:

Is this encrypted some how ?

Google uses encryption over the air, between your server and theirs (SSL) and between their server and the device. Hence, the only systems that have access to the GCM message data are:

your server
your subscriber's device
Google

should i encrypt my messages ?

That would depend upon whether or not you trust Google, and what the nature of your message payload is. For example, if the message payload cannot be directly used by Google (e.g., it is simply a flag telling your app to sync using your normal Web service protocol), then encryption is perhaps not necessary.


Q:

Increase Message Size Service Fabric

I have hosted a Web API in Service Fabric and Posting data on it. Currently My object size is around 10 MB but default limit is 4 MB. I know its not a good practice to post such large objects but as per my need I have to do so.
Please help to increase the default message size limit.

A:

While creating Service Listener, add this as a parameter to increase message size to be accepted by microservice in service-fabric.
    return new[]
    {
      new ServiceReplicaListener(con=> new
      FabricTransporServiceRemotingListener(con,this,remotingListenerSettings: new
      FabricTransportremotingListenerSettings(){
      MaxMessageSize = int.MaxValue;
      },serializationProvider: new ServiceRemotingSerializationProvider())),
    };

This honors the message size to be increased which bypasses the default message size.


Q:

SQL export to ListView using C#

I have a query that selects 3 columns from a SQL table, I need to export the resulting query into a listview.  I don't need any help with the SQL setup, just how to format it into the listview.  There is where I am stuck.  Any help is appreciated.  Thanks!
string sql = "select distinct pro,ds,date from dbo.Sge where date IN (select max(date) from dbo.Storage) order by project";
SqlConnection con = new SqlConnection("Data Source= ;Initial Catalog= ;Integrated Security= SSPI");
con.Open();
DataSet ds = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(sql,con);
adapter.Fill(ds);
foreach (DataRow row in ds.Tables[0].Rows)
{
    for(int i=0; i< ds.Tables[0].Columns.Count; i++))
}

Edit: Sorry guys, i mentioned ListBox originally and i meant ListView. My ListView is detailed and had a column for each of my columns in my select, i just simply need the SQL export to go to the right column.
This is what I have come up with, but it doesn't add to each column, just to the first column
foreach (DataRow row in poplb6ds.Tables[0].Rows)
{
    listView1.Items.Add(row["Pro"].ToString());
    listView1.Items.Add(row["size"].ToString());
    listView1.Items.Add(row["Date"].ToString());
}

A:

The following assumes that your ListView has columns in the order |Pro|Size|Date|
foreach (DataRow row in poplb6ds.Tables[0].Rows) {
    ListViewItem item = new ListViewItem(row["Pro"].ToString());
    item.SubItems.Add(row["size"].ToString());
    item.SubItems.Add(row["Date"].ToString());
    listView1.Items.Add(item);
}


Q:

How to detect a redirected URL?

I'm working on an app that takes URLs from RSS feeds and opens them in a video player. It works if the URL is directly to the mp4/whatever file, but if I have a redirected URL (e.g. This one which redirects here) my player crashes and fails.
Is there any way to detect if its redirecting, and to which URL?
Thanks in advance :)

A:

for redirected url you may try this
try {
    HttpResponse response = client.execute(getRequest);
    final int statusCode = response.getStatusLine().getStatusCode();
    if(statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY){
        String location = response.getHeaders("Location")[0].toString();
        String redirecturl = location.replace("Location: ", "");
    }
}


Q:

How to get Packet Processing(packet_in, flow_match, output) time in OVS switch?

I'm trying to evaluate a routing technique implemented by me with Mininet, Open vSwitch and Ryu controller. But currently I'm unable to figure out the measurement techniques of packet processing time within switch. I can measure probe message processing time as packet_in occurs for those and reports back to controller program. But how to measure processing time for packets whose presence will not be reported back to the controller by switch(packet_in will not occur)? Probably ovs-ofctl command has some options that can report me the time. But still not sure how to do that. Please help me in this circumstance. I have not got enough resources over the internet. Thanks in advance for your help.

A:

As long as you're using the kernel datapath of Open vSwitch, you should be able to retrieve the processing delay for each packet using the usual Linux tracing toolkits.
Below is an example using the BPF infrastructure (requires Linux v4.4+) and the bcc toolkit (I have version 0.5.0-1). Note, however, that for high packet rates, the overhead from running this tool may be significant. Another way to measure the overhead your modifications add is to measure the maximum throughput the switch can achieve with and without your modifications.
#!/usr/bin/env python
from bcc import BPF
import sys
import ctypes as ct

prog = """
#include <uapi/linux/ptrace.h>
#include <linux/openvswitch.h>

struct vport;

enum action_t {
    DROP = 0,
    OUTPUT,
};

struct proc_record_t {
    u64 delay;
    enum action_t action;
};

BPF_HASH(pkts, struct sk_buff *, u64, 1024);
BPF_PERF_OUTPUT(events);

// Take a timestamp at packet reception by Open vSwitch.
int
kprobe__ovs_vport_receive(struct pt_regs *ctx, struct vport *port, struct sk_buff *skb) {
    u64 ts = bpf_ktime_get_ns();
    pkts.update(&skb, &ts);
    return 0;
}

// Once the packet has been processed by the switch, measure the processing delay and send to userspace using perf_submit.
static inline void
end_processing(struct pt_regs *ctx, struct sk_buff *skb, enum action_t action) {
    u64 *tsp = pkts.lookup(&skb);
    if (tsp) {
        u64 ts = bpf_ktime_get_ns();
        struct proc_record_t record = {};
        record.delay = ts - *tsp;
        record.action = action;
        events.perf_submit(ctx, &record, sizeof(record));
        pkts.delete(&skb);
    }
}

// Called when packets are dropped by Open vSwitch.
int
kprobe__consume_skb(struct pt_regs *ctx, struct sk_buff *skb) {
    end_processing(ctx, skb, DROP);
    return 0;
}

// Called when packets are outputted by Open vSwitch.
int
kprobe__ovs_vport_send(struct pt_regs *ctx, struct vport *vport, struct sk_buff *skb) {
    end_processing(ctx, skb, OUTPUT);
    return 0;
}
"""

b = BPF(text=prog)

class Data(ct.Structure):
    _fields_ = [("delay", ct.c_ulonglong),
                ("action", ct.c_int)]
actions = ["drop", "output"]

print("%-18s %s" % ("DELAY(ns)", "ACTION"))

# Callback function to display information from kernel
def print_event(cpu, data, size):
    event = ct.cast(data, ct.POINTER(Data)).contents
    print("%-18d %s" % (event.delay, actions[event.action]))

b["events"].open_perf_buffer(print_event)
while True:
    b.kprobe_poll()

You'll need to install bcc to execute this script. Then, it's as simple as:
$ sudo python trace_processing_time.py
DELAY(ns)          ACTION
97385              drop
55630              drop
38768              drop
61113              drop
10382              output
14795              output

See the bcc documentation for details on how this script works. You will need to change it if you want to support more OpenFlow actions (only drop and output currently).


Q:

How does the next code for passing a string from fragment_1 to fragment_2 works?

i've been development a android project, i had the necesity of pass information from one fragment to another and i found this code, but i've been having problems understanding how it works.
The next code pass information from fragment_1 to fragment_2 using interfaces,
I not particularly understand the part when the object mCallbacks gets the Activity. (mCallbacks = (Callbacks)getActivity();)
And how the object mCallbacks that Fragment_1 has, calls the interface on MainActivity.

Note: im going to put all the code, maybe it helps someone.

private Callbacks mCallbacks = null;

public class frament_1 extends Fragment{

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mCallbacks = (Callbacks)getActivity();//****************************
    }

   Public interface Callbacks{

    public void callMethodOnMainActivity(String folio);

  }

  Public void passInformationToFragment2(){
   mCallbacks.callMethodOnMainActivity("This String is passed using interfaces"); //****************************+
  }

}

This is the MainActivity that implements the interface that frament_1 has.
public class MainActivity extends Activity implements fragment_1.Callbacks{

 @Override
    public void callMethodOnMainActivity(String folio) {//*********************
        //here you call the fragment_2 and pass the String has parameter.
        // no problem wthis part
    FragmentManager fragmentManager = getSupportFragmentManager();
    Fragment module = fragment_2.newInstance(this, folio);
    fragmentManager.beginTransaction().replace(R.id.MainContent, module).commit();

    }

}

Fragment_2
public class Fragment_2 extends Fragment{

   public static Fragment_2 newInstance (Context c, String folio){
      //folio has the String passed
     Fragment_2 fragment = new Fragment_2();
     Bundle args = new Bundle();
        args.putString(ARG_PARAM1, folio);
        fragment.setArguments(args);

        parent = c;

        return fragment;

}

}

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getArguments() != null) {
            //Here you get the parameter that ARG_PARAM1
            String folio = getArguments().getString(ARG_PARAM1);
        }

        mCallbacks = (Callbacks) this.getActivity();
    }

A:

The first step in understanding how a block of code works is to read it, and in order to read it you must adhere to the standards of the language; some of the things your code is missing is the following:
Indentation
Class names should not use underscores(_)
Class names are typically not in plural (Callback not Callbacks)
Class names must be capitalized (Fragment1 not fragment1)
Fields must be defined inside the class (mCallback)
Interfaces must not specify the member access qualifier (i.e. no private, public, protected declarations)
Let's see how your code will look now:
public class Fragment1 extends Fragment {
    private MyCallback mCallback = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mCallback = (MyCallback) getActivity();
    }

    public interface MyCallback{
       void callMethodOnMainActivity(String folio);
    }

    public void passInformationToFragment2(){
       mCallback.callMethodOnMainActivity("This String is passed using interfaces");
    }

}

public class Fragment2 extends Fragment {

    public static final String ARG_PARAM_FOLIO = "param_folio";

    public static Fragment2 newInstance(String folio) {
        Fragment2 fragment = new Fragment2();
        Bundle args = new Bundle()
        args.putString(ARG_PARAM_FOLIO, folio);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
             String folio = getArguments().getString(ARG_PARAM_FOLIO);
        }
    }
}

Important notes:
There is no need to store the context in a parent field; you can always access the parent context by using the getActivity() method.
I'm removing the mCallback in Fragment2 because if you want to communicate back to the MainActivity you must specify its own interface in Fragment2 (i.e. each fragment will have its own interface to communicate back to the activity).
The best practice is to initialize the mCallback in the onAttach(Context context) method by casting the context to a callback type, and setting the callback to null on onDetach() in the following way:
@Override
public void onAttach(Context context) {
    super(context);
    try {
        mCallback = (MyCallback) context;
    } catch (ClassCastException e) {
        throw new IllegalArgumentException(this.getClassName() + " must implement MyCallback";
    }

}

@Override
public void onDetach() {
    super();
    mCallback = null;
}

Now, let's take a look at the MainActivity code and see what's actually doing:
public class MainActivity extends Activity implements Fragment1.MyCallback {
    @Override
    public void callMethodOnMainActivity(String folio) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        Fragment fragment = Fragment2.newInstance(this, folio);
        fragmentManager.beginTransaction().replace(R.id.MainContent, fragment).commit();
    }
}

The callMethodOnMainActivity(String folio) is basically replacing the current fragment on screen (Fragment1) with a Fragment2 in which we pass a folio as parameter. So, nothing magic about that; but how is it triggered? Well, the Fragment2 has a field mCallback of type MyCallback that is initialized to be the MainActivity. So, when you call mCallback.callMethodOfMainActivity(String folio) on the Fragment1 you're, in a way, telling the program to execute the method callMethodOfMainActivity defined in the MainActivity.
It might be useful to get more familiar with the Observable/Observer pattern (you can google this or look at the book by the Gang of Four.


Q:

Match an HTML attribute using Regex/jQuery (for a search)

I'm trying to initiate a search (or rather filter) on keypress for an image library. The user starts typing in the name of an image, and any image name that doesn't match the search term gets hidden:

So if a user starts typing in "ab", then: $('#xyz').hide();
How can I do this?  Can I use regex on an attribute?

A:

//bind an event handler to the text input for the keyup event (so the value will have changed by the time this event fires)
$('input[type="text"]').on('keyup', function (event) {

    //convert the value of the text box to lowercase
    this.value = this.value.toLowerCase();

    //cache the elements that match the search
    var good_to_go = $('[data-imgName*=' + $(this).val() + ']').show();

    //hide all the elements that do not match the search
    $('[data-imgName]').not(good_to_go).hide();
});

There is probably a way to do this that performs better but this takes the value of the text input and finds all the elements with the data-imgName attribute that contains the value of the text input. It then finds all the elements with the data-imgName attribute and hides all of the elements that have not been found already.
If you have a parent element to all of the searched elements, you should start all the selectors with it to avoid searching the entire DOM:
var $container = $('#container-id');
$('input[type="text"]').on('keyup', function (event) {
    this.value = this.value.toLowerCase();
    if (this.value == '') {
        $container.children().show();
    } else {
        var good_to_go = $container.find('[data-imgName*="' + this.value + '"]').show();
        $container.find('[data-imgName]').not(good_to_go).hide();
    }
});

Notice that this example also checks if the value of the text box is nothing, if so then it shows all of the searched elements.
Here are docs for the *= (contains) selector: http://api.jquery.com/attribute-contains-selector/
Here are docs for the .not() function: http://api.jquery.com/not
Here is a working demo: http://jsfiddle.net/HRjHV/3/


Q:

POST larger than 400 Kilobytes payload to a container in Kubernetes fails

I'm using EKS (Kubernetes) in AWS and I have problems with posting a payload at around 400 Kilobytes to any web server that runs in a container in that Kubernetes. I hit some kind of limit but it's not a limit in size, it seems at around 400 Kilobytes many times works but sometimes I get (testing with Python requests)
requests.exceptions.ChunkedEncodingError: ("Connection broken: ConnectionResetError(104, 'Connection reset by peer')", ConnectionResetError(104, 'Connection reset by peer'))

I test this with different containers (python web server on Alpine, Tomcat server on CentOS, nginx, etc).
The more I increase the size over 400 Kilobytes, the more consistent I get: Connection reset by peer.
Any ideas?

A:

Thanks for your answers and comments, helped me get closer to the source of the problem. I did upgrade the AWS cluster from 1.11 to 1.12 and that cleared this error when accessing from service to service within Kubernetes. However, the error still persisted when accessing from outside the Kubernetes cluster using a public dns, thus the load balancer.
So after testing some more I found out that now the problem lies in the ALB or the ALB controller for Kubernetes: https://kubernetes-sigs.github.io/aws-alb-ingress-controller/
So I switched back to a Kubernetes service that generates an older-generation ELB and the problem was fixed. The ELB is not ideal, but it's a good work-around for the moment, until the ALB controller gets fixed or I have the right button to press to fix it.


Q:

Is there a neater way to do this? Java IF

public void moveRowItemToBottomIfAllowed(int r, int f) {
    int i = rows[r].peek().getType();
    int j = 0;
    if (bottom[f].isEmpty()) {
        for (int k = 0; k < 4; k++) {
            if ((k == f) || (bottom[k].isEmpty()) || (bottom[k].peek().getType() != i)) {
                continue;
            }
            j = 1;
        }
        if (j == 0) {
            bottom[f].push(rows[r].pop());
        }
    } else if ((!bottom[f].isEmpty()) && (rankTrueFalse(rows[r].peek(), bottom[f].peek())) && (rows[r].peek().getType() == bottom[f].peek().getType())) {
        bottom[f].push(rows[r].pop());
    }
}

As I'm still learning java I've been putting together some rules for a game, I went through how to do it logically and came up with the above code which works correctly but it looks like a bit of a mess - is there any neater way or a more efficient way of writing this code? any pointers are much appreciated.

A:

I would extract methods to make the code more readable. At first sight I would extract

the for loop, or probably the whole contents of the if block,
the expression from the 2nd long else if

Use descriptive names for your new methods (and for your variables too, for that matter). This makes a huge difference in readability.


Q:

try-catch doesn't catch IOException

In the following code, I get the Unreachable catch block for IOException. This exception is never thrown from the try statement body error(underlined) with the IOException in } catch (IOException e){ what am I doing wrong?
class driver {

  public static void main(String[] args) {
    // TODO Auto-generated method stub
    Customer forrest = new Customer("Forrest Gump", 1,
        "42 New Street, New York, New York");
    Customer random = new Customer("Random Name", 2,
        "44 New Street, New York, New York");
    Customer customer[] = { null, forrest, random };
    int whichOption = 1;
    int id = 0;
    char action = ' ';
    char accSrc = ' ';
    char accDest = ' ';
    double amount = 0;
    BankAccount src = null;
    do {

      try{
        // process JOptionPane input information
        String input = JOptionPane
            .showInputDialog("Please enter your transaction information: ");
        Scanner s = new Scanner(input);
        id = Integer.parseInt(s.next());
        action = Character.toUpperCase((s.next().charAt(0)));

        if (action == 'T') {
          amount = s.nextDouble();
          accSrc = s.next().charAt(0);
          accDest = s.next().charAt(0);
        } else if (action == 'G' || action == 'I') {
          accSrc = s.next().charAt(0);
        } else {
          // if D,W
          amount = s.nextDouble();
          accSrc = s.next().charAt(0);
        }

      } catch (IOException e){

      }
      // taking action accordingly (T)ransfer, (D)eposit, (W)ithdraw, (I)nterest
      if (action == 'T') {

        (customer[id].getAccount(accSrc)).transfer(amount,
            customer[id].getAccount(accDest));
      } else if (action == 'G') {
        System.out.println("The current balance on your " + accSrc
            + " account is "
            + customer[id].getAccount(accSrc).getBalance() + "\n");
      } else if (action == 'D') {
        (customer[id].getAccount(accSrc)).deposit(amount);
      } else if (action == 'W') {
        (customer[id].getAccount(accSrc)).withdraw(amount);
      } else if (action == 'I') {
        (customer[id].getAccount(accSrc)).computeInterest();
      }
      whichOption = JOptionPane
          .showConfirmDialog(null , "Do you want to continue?");

      System.out.println("The balance on " + customer[id].getName()
          + " auto account is " + customer[id].A.balance);
      System.out.println("The balance on " + customer[id].getName()
          + " savings account is " + customer[id].S.balance);
      System.out.println("The balance on " + customer[id].getName()
          + " checkings account is " + customer[id].C.balance);
      System.out.println("The balance on " + customer[id].getName()
          + " loan account is " + customer[id].L.balance + "\n");

    } while (whichOption == 0);

  }
}

A:

It is because none of the operations you perform inside try/catch throws IOException.
As per Scanner javadoc
Most of the Scanner class methods throws either FileNotFoundException (Which is not applicable in your case because not reading from file) (or) IllegalArgumentException (or) IllegalStateException
You need to change IOException to either of above exceptions (or) remove try/catch.

A:

You can remove the IOException and the try catch since none of the statements inside the try catch is throwing this exception

A:

Seems like nothing you are doing in that try block is throwing the IOException


Q:

zerodivisionerror-Float division error

ctr=0.0
i=0
pc=0.0
pi=0.0
nc=0.0
ni=0.0

for line in fileinput.input(['/pro/file1']):
    line = line.replace("\n", "")
    if (i < len(revs)):
        if('pos' in revs[i]):
            if(float(line) > 0):
                ctr=ctr+1
                pc=pc+1

            else:
                                pi=pi+1

        elif('neg' in revs[i]):
            if(float(line) < 0):
                ctr=ctr+1
                nc=nc+1

            else:
                                ni=ni+1

    i=i+1
precision = pc/(pc+pi)
recall = pc/(ni+pc)

This code is about sentiment analysis.I am getting ZeroDivisionError:Float division by zero when I try to find accuracy and recall.how to fix it??

A:

With no idea if this is a good idea for your case, one way of solving this is to do something like
precision = pc/(pc+pi) if (pc+pi) else 0
recall = pc/(ni+pc) if (ni+pc) else 0

which will give a zero in the case that there is nothing to divide by. May be what you need, may be horribly hiding a real error.
Edit: If your data makes you take the "neg" branch every time, pc and pi will be zero, so you'll get a div/0 error at
precision = pc/(pc+pi)

...so that is the cause.


Q:

Connected components of subspaces vs. space

If $Y$ is a subspace of $X$, and $C$ is a connected component of $Y$, then C need not be a connected component of $X$ (take for instance two disjoint open discs in $\mathbb{R}^2$).
But I read that, under the same hypothesis, $C$ need not even be connected in $X$. Could you please provide me with an example, or point me towards one?
Thank you.
SOURCE http://www.filedropper.com/manifolds2 Page 129, paragraph following formula (A.7.16).

A:

Isn't it just false? The image of a connected subspace by the injection $Y\longrightarrow X$ is connected...


Q:

model.matrix generates fewer rows than original data.frame

Why doesn't a model matrix necessarily have the same number of rows as the data frame?
mergem = model.matrix(as.formula(paste(response, '~ .')), data=mergef)
dim(mergef)
# [1] 115562     71
dim(mergem)
# [1] 66786   973

I tried looking for hints in the documentation but couldn't find anything.  Thanks in advance.

A:

Well, if a row has NAs in it, that row is (by default) removed:
d <- data.frame(x=c(1,1,2), y=c(2,2,4), z=c(4,NA,8))
m <- model.matrix(x ~ ., data=d)

nrow(d) # 3
nrow(m) # 2

This behavior is controlled by the option "na.action":
options(na.action="na.fail")
m <- model.matrix(x ~ ., data=d) # Error: missing values in object