Q: Unity shadows ignoring shader's transparency but only in build I've made a custom shader that adds a pass to the surface shader to achieve an outline around the object.  The object is a quad with the characters sprite on it to achieve a 2d character in a 3d game.  The object should be casting a shadow in the same shape as its sprite.
In the editor's play mode the shadows work perfectly:

However when I build the game in either windows or android platform the shadows completely ignore the object's transparency and only show the shadow of the quad.

I'm not sure if the problem is caused by my shader or something in the settings.  I've reset the quality settings to the default values and still have the problem even when it is set to ultra quality.  The only light in the scene is a directional light with soft shadows turned on.
This is the code in my shader.
Shader "Custom/MultiPassOutlineShader" {
    Properties {
        _Color ("Color", Color) = (1,1,1,1)
        _MainTex ("Albedo (RGB)", 2D) = "white" {}
        _Glossiness ("Smoothness", Range(0,1)) = 0.5
        _Metallic ("Metallic", Range(0,1)) = 0.0
        _OutlineColor ("Outline Color",Color) = (1,1,1,1)
        _OutlineThickness ("Outline Thickness",float) = 0.05
    }
    SubShader {

        Tags {"RenderType"="Transparent" "Queue"="Transparent" "IgnoreProjector"="True"}
        LOD 100

        Pass
        {
            ZWrite Off
            Blend SrcAlpha OneMinusSrcAlpha
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag alpha
            // make fog work
            #pragma multi_compile_fog

            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                float2 uv : TEXCOORD0;
                UNITY_FOG_COORDS(1)
                float4 vertex : SV_POSITION;
            };

            sampler2D _MainTex;

            float4 _MainTex_ST;
            float _OutlineThickness;
            fixed4 _OutlineColor;

            v2f vert (appdata v)
            {
                v2f o;
                v.vertex = normalize(v.vertex) * _OutlineThickness + v.vertex;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = TRANSFORM_TEX(v.uv, _MainTex);
                UNITY_TRANSFER_FOG(o,o.vertex);
                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {

                UNITY_APPLY_FOG(i.fogCoord, col);
                fixed4 c = tex2D (_MainTex, i.uv);
                fixed4 col = _OutlineColor;
                col.a *= c.a;
                clip(c.a-0.1);
                return col;
            }
            ENDCG
        }

        ZWrite On
        Blend Off
        CGPROGRAM
        #pragma surface surf Standard fullforwardshadows alpha
        #pragma target 3.0

        sampler2D _MainTex;

        struct Input {
            float2 uv_MainTex;
        };

        half _Glossiness;
        half _Metallic;
        fixed4 _Color;

        // Add instancing support for this shader. You need to check 'Enable Instancing' on materials that use the shader.
        // See https://docs.unity3d.com/Manual/GPUInstancing.html for more information about instancing.
         #pragma instancing_options assumeuniformscaling
        UNITY_INSTANCING_CBUFFER_START(Props)
            // put more per-instance properties here
        UNITY_INSTANCING_CBUFFER_END

        void surf (Input IN, inout SurfaceOutputStandard o) {
            fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * _Color;
            clip(c.a - 0.9);
            o.Albedo = c.rgb;
            o.Metallic = _Metallic;
            o.Smoothness = _Glossiness;
            o.Alpha = c.a;
        }
        ENDCG
    }
    FallBack "Standard"
}

A: I fixed the problem by adding a shadow casting pass.  (for some reason unity has no documentation on these.)  I also changed the fallback to "VertexLit" but I don't know if that had any effect.  I still don't know why the shadow shapes were different in the editor than in the build though.
    //From https://answers.unity.com/questions/1003169/shadow-caster-shader.html
    Pass{
        Name "ShadowCaster"
        Tags { "LightMode" = "ShadowCaster" }

        Fog {Mode Off}
        ZWrite On ZTest Less Cull Off
        Offset 1, 1

        CGPROGRAM

        #pragma vertex vert
        #pragma fragment frag
        #pragma fragmentoption ARB_precision_hint_fastest
        #pragma multi_compile_shadowcaster
        #include "UnityCG.cginc"

        sampler2D _MainTex;

        struct v2f
        {
            V2F_SHADOW_CASTER;
            float2 uv : TEXCOORD1;
        };

        v2f vert(appdata_full v )
        {
            v2f o;
            o.uv = v.texcoord;
            TRANSFER_SHADOW_CASTER(o)

        return o;
        }

        float4 frag( v2f i ) : COLOR
        {
            fixed4 c = tex2D (_MainTex, i.uv);
            clip(c.a - 0.9);
            SHADOW_CASTER_FRAGMENT(i)
        }
        ENDCG
    }


Q: What is the difference between doc_values and fielddata.doc_values mapping settings? Question is about Elasticsearch 1.x
The documentation says that setting "doc_values": true should suffice to use disk-based fielddata. Like this:
"string_field": {
  "doc_values": true,
  "type": "string",
  "index": "not_analyzed"
}
However, there is also a possibility to set doc_values as a fielddata format:
"string_field": {
  "type": "string",
  "index": "not_analyzed",
  "fielddata": {
    "format": "doc_values"
  }
}
So my questions are:
Are these two approaches essentially the same thing?
If not, what is the difference and should they be used together at the same time (I checked, they can, but I don't know if there is any actual benefit from that)?

A: "fields don't need to be indexed to enable doc values" means you can have "index": "no", for example:
"my_field": {
  "type": "string",
  "index": "no",
  "fielddata": {
    "format": "doc_values"
  }
}

If you want to change format to doc_values, you need to update mapping and reindex your data.


Q: Using Different elements for Laptop and Mobile? Framework: Meteor
I am using Handlebars to send information to the client.
I have this layout defined named post.html:

            {{title}}

            {{title}}

{{body}}

Notice the Card layout.
Now this is responsive and works and I dont have a problem that How to make it responsive? It works.
I want to completely change this layout, and use other elements in the layout.
I know this can be done using JS by manipulating the DOM, and appending HTML, but can that be attained without JS?
Like maybe, the JS is only used to find the screen size, or something, and if it is, it renders layout number 1, otherwise, it renders layout number 2.
[ Think of it as Media Queries, but for HTML/JS]
You could also think about how Fragments work in Android.

A: You can do this using window.matchMedia(), which is basically media queries in javascript. And if it matches your condition load your templates accordingly.
https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia


Q: Select value from text based Postgres field I would like to extract some information that store in one field.
for example :
{"Dtl":"{\"title\"campaignId\":\"12345\",\"offerId\":\"67789\"}
I need the information of campaignid and also offerid
the expected result should be : 12345 and 67789
is there any way to extract that information?

A: SELECT '{"Dtl": {"campaignId":"12345","offerId":"67789"}}' :: jsonb #> '{Dtl,campaignId}' => "12345"

SELECT '{"Dtl": {"campaignId":"12345","offerId":"67789"}}' :: jsonb #> '{Dtl,offerId}' => "67789"

see test result in dbfiddle


Q: How to change color of specific cell's label in collection view from array of labels in swift I'm pretty new to Swift and I have a question, I have a collection view, with a cell inside, and a label inside of this cell. I created an array and returned it, so I have multiple cells with labels. My question is, how to change a color of specific labels, for example if I want the labels "2", "7", "13"(from the image) and etc to be not green, but other color. THANK YOU
screen of simulator

A: Implement method below and set desired colour.
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
    // Access label of cell object and set desired colour
}

Tells the delegate that the specified cell is about to be displayed in
  the collection view.

https://developer.apple.com/reference/uikit/uicollectionviewdelegate/1618087-collectionview


Q: How should I detect an observable is idle and inject data every minute? I have an observable returning data sporadically. If there is no data for one minute, I need to repeat the last data, every minute until it generates data again. How can I achieve this?
Thank you.

A: Here's a one liner to do what you want. I've tested it and it seems to be correct.
var results = source
    .Publish(xs =>
        xs
            .Select(x =>
                Observable
                    .Interval(TimeSpan.FromMinutes(1.0))
                    .Select(_ => x)
                    .StartWith(x))
            .Switch());

Let me know if this does the trick.

A: I would wrap the observable in an observable that is guaranteed to return a value at least once per minute. The wrapper could do this by running a timer that is restarted whenever the wrapped observable returns a value.
Thus, the wrapper returns data whenever the wrapped observable returns data or when a minute has passed after the last event.
The rest of the application conveniently just observes the wrapper.

A: Here's a (non-threadsafe, in case your source is multithreaded) implementation of a RepeatAfterTimeout operator:
EDIT Updated as Timeout didn't work as I expected
// Repeats the last value emitted after a timeout
public static IObservable<TSource> RepeatAfterTimeout<TSource>(
    this IObservable<TSource> source, TimeSpan timeout, IScheduler scheduler)
{
    return Observable.CreateWithDisposable<TSource>(observer =>
    {
        var timer = new MutableDisposable();
        var subscription = new MutableDisposable();

        bool hasValue = false;
        TSource lastValue = default(TSource);

        timer.Disposable = scheduler.Schedule(recurse =>
        {
            if (hasValue)
            {
                observer.OnNext(lastValue);
            }

            recurse();
        });

        subscription.Disposable = source
            .Do(value => { lastValue = value; hasValue = true; })
            .Subscribe(observer);

        return new CompositeDisposable(timer, subscription);
    });
}

public static IObservable<TSource> RepeatAfterTimeout<TSource>(
    this IObservable<TSource> source, TimeSpan timeout)
{
    return source.RepeatAfterTimeout(timeout, Scheduler.TaskPool);
}

A: I had the exact same requirement once.  I chose to include a default value to use if no value triggers before the first timeout.  Here's the C# version:
public static IObservable<T>
AtLeastEvery<T>(this IObservable<T> source, TimeSpan timeout,
                T defaultValue, IScheduler scheduler)
{
    if (source == null) throw new ArgumentNullException("source");
    if (scheduler == null) throw new ArgumentNullException("scheduler");
    return Observable.Create<T>(obs =>
        {
            ulong id = 0;
            var gate = new Object();
            var timer = new SerialDisposable();
            T lastValue = defaultValue;

            Action createTimer = () =>
                {
                    ulong startId = id;
                    timer.Disposable = scheduler.Schedule(timeout,
                          self =>
                          {
                              bool noChange;
                              lock (gate)
                              {
                                  noChange = (id == startId);
                                  if (noChange) obs.OnNext(lastValue);
                              }
                              //only restart if no change, otherwise
                              //the change restarted the timeout
                              if (noChange) self(timeout);
                          });
                };
            //start the first timeout
            createTimer();
            var subscription = source.Subscribe(
                v =>
                {
                    lock (gate)
                    {
                        id += 1;
                        lastValue = v;
                    }
                    obs.OnNext(v);
                    createTimer(); //reset the timeout
                },
                ex =>
                {
                    lock (gate)
                    {
                        id += 1; //'cancel' timeout
                    }
                    obs.OnError(ex);
                    //do not reset the timeout, because the sequence has ended
                },
                () =>
                {
                    lock (gate)
                    {
                        id += 1; //'cancel' timeout
                    }
                    obs.OnCompleted();
                    //do not reset the timeout, because the sequence has ended
                });

            return new CompositeDisposable(timer, subscription);
        });
}

If you don't want to have to pass a scheduler every time, just make an overload that picks a default one and delegates to this method.  I used Scheduler.ThreadPool.
This code works by using the behavior of SerialDisposable to "cancel" the previous timeout call when a new value from the source comes in.  There is also a counter I use in case the timer has already elapsed (in which case Disposing the return from Schedule will not help) but the method has not yet actually run.
I investigated the possibilities of changing timeouts but did not need them for the problem I was working on.  I recall that it was possible but don't have any of that code handy.

A: I think this should work the Rx way (no recursion but still involving a side effect):
    public static IObservable<TSource> RepeatLastValueWhenIdle<TSource>(
        this IObservable<TSource> source,
        TimeSpan idleTime,
        TSource defaultValue = default(TSource))
    {
        TSource lastValue = defaultValue;

        return source
            // memorize the last value on each new
            .Do(ev => lastValue = ev)
            // re-publish the last value on timeout
            .Timeout(idleTime,  Observable.Return(lastValue))
            // restart waiting for a new value
            .Repeat();
    }


Q: How to use each method to put result in view Instead of creating a foreach loop I want to iterate over the results and
I am using the each() method:
$collection = Comment::all();

$comment =  $collection->each(function ($comment){
    dd($comment->comment);
});

when I dd() I get:

"Hatter; 'so I should think."

But when I pass to view:
 return view('welcome')->with('comment',$comment);

I get
[{"id":1,"post_id":5,"comment":"Hatter; 'so I should think.","created_at":"2018-04-05 15:23:20","updated_at":"2018-04-05 15:23:20"},

{"id":2,"post_id":5,"comment":"Alice gently remarked;.","created_at":"2018-04-05 15:23:20","updated_at":"2018-04-05 15:23:20"},

and so on..
This is the view:
{{$comment}}

I want to iterate through the collection and put data into $comment and then show it in the view.

A: It is quite simple like this.
Iterate then -> following the property name
 @foreach($comment as $row)

{{ $row->id }}

{{ $row->post_id}}

    //AND SO ON
 @endforeach


Q: Not overloading operator Good day, I'm doing some Codeforces exercises in my free time, and I had a problem to test if the user was a boy or a girl, well, my problem isn't that, i have just demonstrated the code.
While compiling my code in my computer ( I'm using  version 3.0.4 for i386 ) i get no error, but codeforces gives me this error
program.pas(15,16) Error: Operator is not overloaded: "freq(Char;AnsiString):LongInt;" + "ShortInt"
program.pas(46,4) Fatal: There were 1 errors compiling module, stopping

The error wasn't clear enough to me, as the same script was perfectly compiled with my version.
The platform is using ( version 3.0.2 i386-Win32 ).
program A236;
uses wincrt, sysutils;

var
    username : String;

function freq(char: char; username : String): Integer;
var
   i: Integer;
begin
    freq:= 0;
    for i:= 1 to length(username) do
        if char = username[i] then
            freq:= freq + 1;
            //writeln(freq);
end;

function OddUserName(username : String): Boolean;
var
    i, counter: Integer;

begin
    OddUserName:= false; // even
    counter:= 0;
    for i:= 1 to length(username) do
        if freq(username[i], username) <> 1 then
            delete(username, i, 1)
        else
            counter:= counter + 1;
    if counter mod 2 <> 0 then
        OddUserName:= true; // odd
    //writeln(counter);
    //writeln(OddUserName);
end;

begin
    readln(username);
    if not OddUserName(username) then
        writeln('CHAT WITH HER!')
    else
        writeln('IGNORE HIM!');

    //readkey();
end.

The error is supposed to be at this line probably  :
function freq(character: char; username : String): Integer;

Thanks for everyone who helps.

A: Inside of a function, the function's name can be used as a substitute for using an explicit local variable or Result. freq() and OddUserName() are both doing that, but only freq() is using the function name as an operand on the right-hand side of an assignment.  freq := freq + 1; should be a legal statement in modern Pascal compilers, see Why i can use function name in pascal as variable name without definition?.
However, it would seem the error message is suggesting that the failing compiler is treating freq in the statement freg + 1 as a function type and not as a local variable. That would explain why it is complaining about not being able to add a ShortInt with a function type.
So, you will have to use an explicit local variable instead, (or the special Result variable, if your compiler provides that), eg:
function freq(charToFind: char; username : String): Integer;
var
  i, f: Integer;
begin
  f := 0;
  for i := 1 to Length(username) do
    if charToFind = username[i] then
      f := f + 1;
      //writeln(f);
  freq := f;
end;

function freq(charToFind: char; username : String): Integer;
var
  i: Integer;
begin
  Result := 0;
  for i := 1 to Length(username) do
    if charToFind = username[i] then
      Result := Result + 1;
      //writeln(f);
end;


Q: Insert IoT message array as multiple rows in DynamoDB I'm starting a new project that involves some IoT devices sending every 5 minutes their status and other info to AWS IoT.
The structure of the message is the following:

{
    "SNC":"C_SN_15263217541",
    "STATUS":"enable",
    "PLANT":{
        "PNAME":"nomeimpianto",
        "DVS":{
            "SD":[{
                    "SDSN":"LD_SN_15263987543",
                    "TT":"30/11/17 4:37 PM",
                    "STATUS":"Enable",
                    "TON":"3sec",
                    "TOFF":"6min",
                    "QTAC":"125",
                    "ALCODE":"201",
                    "ALDESC":"assenza scarico"
                },
                {
                    "SDSN":"LD_SN_15263987543",
                    "TT":"30/11/17 4:39 PM",
                    "STATUS":"Enable",
                    "TON":"3sec",
                    "TOFF":"6min",
                    "QTAC":"125",
                    "ALCODE":"201",
                    "ALDESC":"assenza scarico"
                },
                {
                    "SDSN":"LD_SN_15263997545",
                    "TT":"30/11/17 4:37 PM",
                    "STATUS":"Enable",
                    "TON":"3sec",
                    "TOFF":"6min",
                    "QTAC":"125"
                },
                {
                    "SDSN":"LD_SN_15263997545",
                    "TT":"30/11/17 4:39 PM",
                    "STATUS":"Enable",
                    "TON":"3sec",
                    "TOFF":"6min",
                    "QTAC":"125"
                },
                {
                    "SDSN":"LD_SN_15123987543",
                    "TT":"30/11/17 4:37 PM",
                    "STATUS":"Enable",
                    "TON":"3sec",
                    "TOFF":"6min",
                    "QTAC":"125"
                },
                {
                    "SDSN":"LD_SN_15123987543",
                    "TT":"30/11/17 4:39 PM",
                    "STATUS":"Enable",
                    "TON":"3sec",
                    "TOFF":"6min",
                    "QTAC":"125"
                }
            ]
        }
    }
}

I created a rule that inserts the message on DynamoDB, and it's working nicely, but I'd need to create, for each message received, one row for each item in PLANT.DVS.SD.
My DynamoDB table has as hashkey the field PLANT.DVS.SD[x].SDSN and as sort field PLANT.DVS.SD[x].TT.
I tried with a DynamoDBv2 rule and I managed only to create one row per message with the whole array, but it's not what I'm looking for.
So basically the problem is that I don't know how to structure the SQL statement in the rule definition.
I know that PLANT.DVS.SD's max length is 12, so the only idea that I've got is to create 12 IoT rules that insert on DynamoDB only the element at a specific position. Although if there is a better way to solve this problem dynamically, it'd be appreciated!


Q: WSS 3.0: change parent type for a content type I have created a hierarchy of content types. The root of my hierarchy has the content type "Document" as a parent. There are about 20 other content types derived from my root.
Now, I want to change the parent from "Document" to something else. Is it possible? Either in the web interface or in code? Can the definition of content types be dumped to a text file and then recreated? Or any other trick?

A: If you can create a feature that contains all your custom content types, you will be able to change the XML that defines each content type and it's columns.
This will give you the ability to change the content types for your site by removing the feature and installing it again with the changes (using a Solution is best).
Note that any content using the older content types will still use them after updating the feature (content types are stored at the site level, list level and on the actual item).


Q: Migrating from XML + dataset to SQL + Entity Framework Migrating XML + .xsd dataset version to SQL + Entity Framework.
I'm a novice to SQL databases now I have to.
Current scenario: my project has many XML files (40,000+) which can be loaded to one of .xsd dataset schema(~30). There are a lot of XML separation made to quickly choose one of the dataset and load data into it. Later the dataset is loaded into the UI but going on we expect maintainability and performance issues.
So now we want to migrate to SQL + Entity Framework.
How can I best utilize the existing code to migrate?
My main concern is how can I leverage existing code to create tables and load data to those created tables in SQL server.
How can existing XML files or dataset (.xsd) be used to develop tables and data in a SQL database?
Any other suggestions in order achieve my goal will help me a lot.


Q: jQuery failed: parsererror with error thrown: SyntaxError: Unexpected end of JSON input I have a contact form which is passed to a PHP script through ajax. Once the form is processed, The ajax will perform some actions depending on the response received from json_encode() function in the PHP script. The problem is I get the following error message:

parsererror  SyntaxError: Unexpected end of JSON input
readyState:4 responseText:"" status:200 statusText:"OK"

When the dataType is text in the ajax call and the PHP script simply echos a text message, then code works fine, but with json, I get the above error.
I have tried header("Content-Type: application/json")and JSON.parse() with no success. I have added charset="UTF-8" in the header and tried encode_utf8() function on the array passed to json_encode too, but nothing seems to work for me.
I am posting the code for the relevant files below. Any help to resolve this problem will be highly appreciated.
contact.php
<form action="" method="post" name="contactForm" id="contactForm">

            Order Number
            <input type="text" name="orderNumber" id="orderNumber" value="<?php echo ($_POST['orderNumber']); ?>" />

          Comment *
          <textarea name="message" id="comment" maxlength="2000" rows="5"><?php echo ($_POST['comment']); ?></textarea>

            Title *
            <select name="title" id="title">
                <option value="" <?php if ($_POST['title'] == "") {echo "selected='selected'";} ?>>Select a title...</option>
                <option value="ms" <?php if ($_POST['title'] =="ms") {echo "selected='selected'";} ?>>Ms</option>
                <option value="miss" <?php if ($_POST['title'] == "miss") {echo "selected='selected'";} ?>>Miss</option>
                <option value="mrs" <?php if ($_POST['title'] == "mrs") {echo "selected='selected'";} ?>>Mrs</option>
                <option value="mr" <?php if ($_POST['title'] == "mr") {echo "selected='selected'";} ?>>Mr</option>
                <option value="other" <?php if ($_POST['title'] == "other") {echo "selected='selected'";} ?>>Other</option>
            </select>

            First Name *
            <input type="text" name="firstName" id="firstName" value="<?php echo ($_POST['firstName']); ?>" />

            Surname *
            <input type="text" name="surname" id="surname" value="<?php echo ($_POST['surname']); ?>" />

            Email Address *
            <input type="text" name="email" id="email" value="<?php echo ($_POST['email']); ?>" />

            <input type="submit" name="submitContactForm" id="submitContactForm" value="Submit" class="btn" />

</form>

jsCode.js
// process contact form
$("#contactForm").submit(function(e) {

    e.preventDefault();

    // some jQuery validation goes here...

    $.ajax({
        type:"POST",
        url: "functions.php",
        dataType: "json",
        data: new FormData(this),
        //data: $('form').serialize(),
        processData: false,
        contentType: false,
        success:function(response) {
            if(response.status === "OK") {
                $("#contactFormResponse").html("

");
                $("#message").html(response.message).fadeIn("100");
                $("#contactForm")[0].reset();
                $(window).scrollTop(0);
            } else if (response.status === "error") {
                $("#contactFormResponse").html("

");
                $("#message").html(response.message).fadeIn("100");
                $(window).scrollTop(0);
            }
       },
       error:function(jqXHR, textStatus, errorThrown) {
           console.log("JQuery failed: " + textStatus + " with error thrown: " + errorThrown);
           console.log(jqXHR);

         }
    });
});

functions.php
// send email
function sendMessage() {

    if (isset($_POST["submitContactForm"])) {
        if (!$_POST["comment"]) {
            $error .= "
Comment is required.";
        }

        if (!$_POST["firstName"]) {
            $error .= "
First name is required.";
        }

        // validation for other form fields goes here...

        if ($error) {
            echo json_encode(array("status" => "error", "message" => "There were error(s)in your form: " . $error));

        } else {

            $to            = "email@domain.com";
            $subject       = "Message from the website";
            $order_number  = $_POST["orderNumber"];
            $comment       = $_POST["comment"];
            $title         = $_POST["title"];
            $first_name    = $_POST["firstName"];
            $surname       = $_POST["surname"];
            $email_address = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
            $headers       = "From: " . $title  . " "  . $first_name . " " . $surname . " <" . $email_address . " >";
            $message       = "Order Number: " . $order_number . "/r/n" . "Topic: " . $topic . "/r/n" . "Comment: " . $comment;

            $result = mail($to, $subject, $message, $headers);

            if (!$result) {

                echo json_encode(array("status" => "error", "message" => "Message failed."));

            } else {

               echo json_encode(array("status" => "OK", "message" => "Message sent."));

            }
        }
    }
}

A: you are not parsing the json response in your success function,you need to use $.parseJSON(response) like below
    success:function(res) {
var response=$.parseJSON(res);
                if(response.status === "OK") {
                    $("#contactFormResponse").html("

");
                    $("#message").html(response.message).fadeIn("100");
                    $("#contactForm")[0].reset();
                    $(window).scrollTop(0);
                } else if (response.status === "error") {
                    $("#contactFormResponse").html("

");
                    $("#message").html(response.message).fadeIn("100");
                    $(window).scrollTop(0);
                }
           },


Q: Scraping source view image link with SwiftSoup I'm trying to grab faveIcon image from a website using SwiftSoup
 if rel == "icon", try element.attr("type") == "image/x-icon", element.hasAttr("href") {
    favIconUrl = try element.absUrl("href")
 }

The issue is, in href, there is no any direct url, and it looks like an hyperlink (not so expert on HTML), it's href="/favicon.ico" , which favicon.ico is clickable and it will open the url. My question is, how I can access to the link inside the favicon.ico? Your help would be appreciated.
Many thanks


Q: Accessing hadoop from remote machine I have hadoop set up (pseudo distributed) on a server VM and I'm trying
to use the Java API to access the HDFS.
The fs.default.name on my server is hdfs://0.0.0.0:9000 (as with localhost:9000 it wouldn't accept requests from remote sites).
I can connect to the server on port 9000
$ telnet srv-lab 9000
Trying 1*0.*.30.95...
Connected to srv-lab
Escape character is '^]'.
^C

which indicates to me that connection should work fine. The Java code I'm using is:
try {
        Path pt = new Path(
                "hdfs://srv-lab:9000/test.txt");
        Configuration conf = new Configuration();
        conf.set("fs.default.name", "hdfs://srv-lab:9000");
        FileSystem fs = FileSystem.get(conf);
        BufferedReader br = new BufferedReader(new InputStreamReader(
                fs.open(pt)));
        String line;
        line = br.readLine();
        while (line != null) {
            System.out.println(line);
            line = br.readLine();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

but what I get is:
java.net.ConnectException: Call From clt-lab/1*0.*.2*2.205 to srv-lab:9000 failed on connection exception: java.net.ConnectException: Connection refused; For more details see:  http://wiki.apache.org/hadoop/ConnectionRefused

Thus, any hints on why the connection is refused even though connecting through telnet works fine?

A: Your hdfs entry is wrong. fs.default.name has to be set as hdfs://srv-lab:9000. Set this and restart your cluster. that will fix the issue


Q: error when using cronTrigger with an expression that contains a year value I'm observing a strange behavior scheduling a job in Quartz using a CronTrigger that contains a year value.
Here is how I am creating a trigger and scheduling a job with it:
CronTrigger trigger =  cronJobTriggerFactory.getObject();
trigger.setName(triggerName);
trigger.setGroup(triggerGroupName);
trigger.setCronExpression(cronSchedule);
trigger.setVolatility(false);

JobDetail job = schedulableJobFactory.getObject();
job.setName(jobName);
job.setGroup(jobGroupName);
job.setVolatility(false);
job.setDurability(true);
Date scheduleTime1 = scheduler.scheduleJob(job, trigger);
logger.info(job.getKey() + " will run at: " + scheduleTime1);

and then in my unit test I determines the "now" date, add 5 minutes to it, calculate cron expression for this date/time and call my main class schedule a job with this schedule. Here is the out put of the unit test that shows which cron expression is passed :
NotificationSchedulerTest - Today is: 9 May 2012 05:32 PM
NotificationSchedulerTest - 5 min later is: 9 May 2012 05:37 PM
NotificationSchedulerTest - cron schedule is: 0 37 17 * 4 ? 2012

However, when trying to schedule a job with this cron expression - I'm getting the following error:
org.quartz.SchedulerException: Based on configured schedule, the given trigger will never fire.

As you can see, the date is in the future relative to the date/time I am running the test... So, it should not be a problem with trying to schedule a job to run at a time in the past.
Now the next strange thing: notice that I do specify the year value in my cron expression: " 0 37 17 * 4 ? 2012".
If I modify generation of the cron expression and leave the year field as unspecified (since it is optional): " 0 37 17 * 4 ?"
Then the scheduling DOES succeed, however, the scheduler shows that the next time the job will fire is in the year 2013! (one year later.... - and of course I cannot wait that long to verify it is fired...):
NotificationSchedulerTest - Today is: 9 May 2012 06:11 PM
NotificationSchedulerTest - 5 min later is: 9 May 2012 06:16 PM
NotificationSchedulerTest - cron schedule is: 0 16 18 * 4 ?
...
NotificationScheduler - myJobKey will run at: Mon Apr 01 18:16:00 EDT 2013

Am I missing something in these cron expressions?

A: Months in cron expressions are 1-based. That's why 0 37 17 * 4 ? 2012 is never executed: today is 10th of May and you want it to run on every day of April. When you remove the year it prints next scheduled date in 2013, but in April! myJobKey will run at: Mon Apr 01 18:16:00 EDT 2013.
Obviously your expression should be:
0 37 17 * 5 ? 2012

or to avoid confusion in the future:
0 37 17 * May ? 2012


Q: Ipad app with two UIWebViews I have an iPad app with two UIWebviews, one on top of the other. Is there a way to have all the links that are clicked in one, open in only the other view?

A: Use this in the delegate for your first UIWebView:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    if (navigationType == UIWebViewNavigationTypeLinkClicked) {
        [otherWebView loadRequest:request];

        return NO;
    }

    return YES;
}


Q: Optimize Kruskal Wallis Test Spotfire On spotfire i had created several Kruskal Wallis test. First i had created a pivot table and after i did a data relationship (Kruskal Wallis). Then i reflate my tests with a button (script python).
That is my code :
kruskal = Document.Calculations[0]
settings = Document.Calculations[0].CalculationSettings

settings.XColumns.Clear()
settings.YColumns.Clear()

for col in EWSWAFER.Columns:
  if "HB" in col.ToString():
    settings.YColumns.Add(col)
  if col.ToString() == "SPLIT":
    settings.XColumns.Add(col)

kruskal.Execute(CalculationExecutionPromptMode.Never)

I would like to know if it possible to optimize my code so that the test takes less time. Because sometimes my datatable has 1500 columns and 500 rows.
Thanks for your help and your ideas.
Regards, Laurent


Q: What's the difference between printf and printf_s in C? I just want to know the difference and I've already tried search on google.
printf()
printf_s()

A: I learned something new today.  I've never used the _s functions and always assumed they were vendor-supplied extensions, but they are actually defined in the language standard under Annex K, "Bounds-checking Interfaces".  With respect to printf_s:

K.3.5.3.3 The printf_s function
Synopsis
1 #define _ _STDC_WANT_LIB_EXT1_ _ 1
  #include <stdio.h>
  int printf_s(const char * restrict format, ...);
Runtime-constraints
2 format shall not be a null pointer. The %n specifier394) (modified or not by flags, field
width, or precision) shall not appear in the string pointed to by format. Any argument
to printf_s corresponding to a %s specifier shall not be a null pointer.
3 If there is a runtime-constraint violation, the printf_s function does not attempt to
produce further output, and it is unspecified to what extent printf_s produced output
before discovering the runtime-constraint violation.
Description
4 The printf_s function is equivalent to the printf function except for the explicit
runtime-constraints listed above.
Returns
5 The printf_s function returns the number of characters transmitted, or a negative
value if an output error, encoding error, or runtime-constraint violation occurred.

394) It is not a runtime-constraint violation for the characters %n to appear in sequence in the string pointed
at by format when those characters are not a interpreted as a %n specifier. For example, if the entire
format string was %%n.

C 2011 Online Draft
To summarize, printf_s performs additional runtime validation of its arguments not done by printf, and will not attempt to continue if any of those runtime validations fail.
The _s functions are optional, and the compiler is not required to support them.  If they are supported, the macro __STDC_WANT_LIB_EXT1__ will be defined to 1, so if you want to use them you'll need to so something like
#if __STDC_WANT_LIB_EXT1__ == 1
    printf_s( "%s", "This is a test\n" );
#else
    printf( "%s", "This is a test\n" );
#endif


Q: REACT : How to render component inside a div with specific classname? I'm not sure what is the best method to do this but - I have outputted list of divs. When I click on one of them, it gets given a class active. I need to show a component I made (to render) inside this particular class once the div has been clicked on. I am using next.js with react and having been using CSS modules.
Currently I tried: ReactDOM.render( <InnerDisc/>, document.getElementsByClassName(styles.active) );
but I get an error Error: Target container is not a DOM element.
Child (InnerDisc) Component
const InnerDisc = (props) => {
   const active = props.active;

   if (active) {
      return (

            <Image className={styles.pic} src="https://picsum.photos/200/300" width={200} height={200}/>
            <Image className={styles.pic} src="https://picsum.photos/200/300" width={200} height={200}/>
            <Image className={styles.pic} src="https://picsum.photos/200/300" width={200} height={200}/>
            <Image className={styles.pic} src="https://picsum.photos/200/300" width={200} height={200}/>
            <Image className={styles.pic} src="https://picsum.photos/200/300" width={200} height={200}/>
            <Image className={styles.pic} src="https://picsum.photos/200/300" width={200} height={200}/>
            <Image className={styles.pic} src="https://picsum.photos/200/300" width={200} height={200}/>
            <Image className={styles.pic} src="https://picsum.photos/200/300" width={200} height={200}/>

       );
   }

}

export default InnerDisc;
Main App Component
export default function Home() {
   const [discs, setDiscs] = useState([
      { id: 1, top: 100 },
      { id: 2, top: 200 },
      { id: 3, top: 300 },
      { id: 4, top: 400 },
      { id: 5, top: 500 },
      { id: 6, top: 600 },
      { id: 7, top: 700 },
      { id: 8, top: 800 },
      { id: 9, top: 900 },
      { id: 10, top: 1000 },
      { id: 11, top: 1100 },
      { id: 12, top: 1200 }
   ])

   function enlargeDisc(e, num) {
      let t = e.target
      if (t.classList.contains(styles.active)) {
         t.classList.remove(styles.active)
         discRender()
      } else {
         t.classList.add(styles.active)
         discRender()
      }
   }

   function discRender() {
      ReactDOM.render(
         <InnerDisc/>, document.getElementsByClassName(styles.active)
      );
    }

return (

                     {discs.map((item) => (

                         enlargeDisc(e, item.id)}>

                         ))}

)
}

A:
First, you're not using "num" at the function, so it can be like this:
function enlargeDisc(e) {

      let t = e.target
      if (t.classList.contains(styles.active)) {
         t.classList.remove(styles.active)
         discRender()
      } else {
         t.classList.add(styles.active)
         discRender()
      }
   }

Now that you only have the event has parameter, you could just put the onClick like:

 {discs.map((item) => (

Test what is reciving "enlargeDisc" event with a console.log inside the function, if there is the e.target, you could handle better using const clsList = e.target.classList, so you just need if(classList."property").

Also, you can instead using ReactDOM.render(), make a component Disc and use a State to handle when the class property gonna change or remove.


Q: React navigation not showing the right screen I have created a navigation setup for my application that should start off with a welcome screen on the welcome screen you find two buttons, one for registering and the other for logging in.
When the user registers or logs in he get sent to other screens. I have created a stack navigator between the log in and register screen and put them in a loginFlow constant and another between the welcome screen and the loginFlow constant and the navigation between these screens works, but for some reason the welcome screen doesn't get shown first instead I get the sign up screen (register screen).
Why is that the case and how can i make the welcomeScreen get shown first
import React from "react";
import { View } from "react-native";
import WeclomeScreen from "./app/screens/WelcomeScreen";
import MainScreen from "./app/screens/MainScreen";
import AccountScreen from "./app/screens/AccountScreen";
import { Provider as AuthProvider } from "./app/context/AuthContext";
import { createMaterialBottomTabNavigator } from "react-navigation-material-bottom-tabs";
import SignupScreen from "./app/screens/SignupScreen";
import { createAppContainer, createSwitchNavigator } from "react-navigation";
import { createStackNavigator } from "react-navigation-stack";
import ResultShowScreen from "./app/screens/ResultShowScreen";
import ResolveAuthScreen from "./app/screens/ResolveAuthScreen";
import SigninScreen from "./app/screens/SigninScreen";
import ArticleSaveScreen from "./app/screens/ArticleSaveScreen";
import { setNavigator } from "./app/navigationRef";

const articleListFlow = createStackNavigator({
  Main: MainScreen, // screen with diffrent articles categories
  ResultsShow: ResultShowScreen, // article details screen
});
const loginFlow = createStackNavigator({
  Signup: SignupScreen,
  Signin: SigninScreen,
});
loginFlow.navigationOptions = () => {
  return {
    headerShown: false,
  };
};

articleListFlow.navigationOptions = {
  title: "News Feed",
  tabBarIcon: ({ tintColor }) => (
    <View>
      <Icon style={[{ color: tintColor }]} size={25} name={"ios-cart"} />
    </View>
  ),
  activeColor: "#ffffff",
  inactiveColor: "#ebaabd",
  barStyle: { backgroundColor: "#d13560" },
};
const switchNavigator = createSwitchNavigator({
  ResolveAuth: ResolveAuthScreen,
  MainloginFlow: createStackNavigator({
    WelcomeScreen: WeclomeScreen,
    loginFlow: loginFlow,
  }),

  mainFlow: createMaterialBottomTabNavigator(
    {
      articleListFlow: articleListFlow,
      ArticleSave: ArticleSaveScreen, // we dont need this one
      Account: AccountScreen,
    },
    {
      activeColor: "#ffffff",
      inactiveColor: "#bda1f7",
      barStyle: { backgroundColor: "#6948f4" },
    }
  ),
});
const App = createAppContainer(switchNavigator);
export default () => {
  return (
    <AuthProvider>
      <App
        ref={(navigator) => {
          setNavigator(navigator);
        }}
      />
    </AuthProvider>
  );
};

here is the content of ResolveAuthscreen :

import React, { useEffect, useContext } from "react";
import { Context as AuthContext } from "../context/AuthContext";

const ResolveAuthScreen = () => {
  const { tryLocalSignin } = useContext(AuthContext);

  useEffect(() => {
    tryLocalSignin();
  }, []);

  // not returning anything since just waiting to check the token
  // will transition to signin or signup very quickly
  return null;
};

export default ResolveAuthScreen;

A: As you have mentioned in your comments, you have an issue in your tryLocalSignin method. In that method, if there is no any token, you are navigating the user to the Signup screen. Instead of navigating to the Signup screen, navigate to the WelcomeScreen screen like:
const tryLocalSignin = (dispatch) => async () => {
    const token = await AsyncStorage.getItem("token");
    if (token) {
        dispatch({ type: "signin", payload: token });
        navigate("Main");
    } else {
        navigate("WelcomeScreen");
    }
};


Q: Defining own CONTROL exception The subject says it all: can I define own control exception which would handled by the CONTROL block? Applying the X::Control role is useless:
 class CX::Whatever does X::Control {
     method message { "<whatever control exception>" }
 }

 do {
     CX::Whatever.new.throw;
     CONTROL {
         say "CONTROL!!!";
         default {
             say "CONTROL: ", $_.WHAT;
         }
     }
 }

By looking into the core sources I could guess that only a predefined set of exceptions is considered suitable for CONTROL, but not sure I didn't miss a thing.

A: This hasn't been possible in the past, however you're far from the first person to ask for it. Custom control exceptions would provide a way for framework-style things to do internal control flow without CATCH/default in user code accidentally swallowing the exceptions.
Bleeding edge Rakudo now contains an initial implementation of taking X::Control as an indication of a control exception, meaning that the code as you wrote it now does as you expect. This will, objections aside, appear in the 2019.01 Rakudo release, however should be taken as a draft feature until it also appears in a language specification release.
Further, a proposed specification test has been added, so unless there are objections then this feature will be specified in a future Perl 6 language release.


Q: How to handle c# WPF thread in MVVM view model I am having a bear of a time figuring out how to handle a Thread from a class outside my ViewModel.
The Thread originates from a Track class. Here is the ResponseEventHandler code in Track:
public delegate void ResponseEventHandler(AbstractResponse response);
public event ResponseEventHandler OnResponseEvent;

When a "command" method is processed from within my Track object, the following code runs the OnResponseEvent, which sends a message in a Thread back to my ViewModel:
if (OnResponseEvent != null)
{
    OnResponseEvent(GetResponseFromCurrentBuffer());
}

GetResponseFromCurrentBuffer() merely returns a message type which is a pre-defined type within the Track.
My MainWindowViewModel constructor creates an event handler for the OnResponseEvent from the Track:
public MainWindowViewModel()
{
    Track _Track = new Track();

    _Track.OnResponseEvent +=
        new Track.ResponseEventHandler(UpdateTrackResponseWindow);
}

So, the idea is that every time I have a new message coming from the OnResponseEvent Thread, I run the UpdateTrackResponseWindow() method.  This method will append a new message string to an ObservableCollection<string> list property called TrackResponseMessage:
private void UpdateTrackResponseWindow(AbstractResponse message)
{
    TrackResponseMessage.Add(FormatMessageResponseToString(message));
}

The FormatMessageResponseToString() method merely compares the message with all pre-defined message types within the Track, and does some nifty string formatting.
The main problem is:  The UI disappears when TrackResponseMessage.Add() is run. The executable is still running in the background, and the only way to end the task is to shut down Visual Studio 2010.
TrackResponseMessage is a public property within my ViewModel:
public ObservableCollection<String> TrackResponseMessage
{
    get { return _trackResponseMessage; }
    set
    {
        _trackResponseMessage = value;
        RaisePropertyChanged("TrackResponseMessage");
    }
}

Is there a need for me to marshal the Thread coming from the Track object to my ViewModel? Any example code would be very appreciated!

A:
Is there a need for me to marshall the thread comming from the Track.cs object to my viewmodel? Any example code would be very appreciated!

Yes.  Unfortunately, while INotifyPropertyChanged will handle events from other threads, INotifyCollectionChanged does not (ie: ObservableCollection<T>).  As such, you need to marshal back to the VM.
If the VM is being create from the View (View-First MVVM) or is known to be created on the UI thread, there's a good option using .NET 4 tasks:
TaskScheduler uiScheduler;
public MainWindowViewModel()
{
    uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
    Track _Track = new Track();
    _Track.OnResponseEvent += new Track.ResponseEventHandler(UpdateTrackResponseWindow);
}

Then, later, your event handler can do:
private void UpdateTrackResponseWindow(AbstractResponse message)
{
    Task.Factory.StartNew(
       () => TrackResponseMessage.Add(FormatMessageResponseToString(message)),
       CancellationToken.None, TaskCreationOptions.None,
       uiScheduler);
}

This has the nice advantage of not pulling WPF or Silverlight specific resources and types into your ViewModel class (ie: Dispatcher), while still providing all of the benefits.  It also works, unchanged, in other routines with thread affinity (ie: WCF service work).

A: If the RaisePropertychanged is executed on a thread other than the UI thread AND the event handler for the event touches the UI you need to switch to the UI thread.


Q: Is there a simple way to remove one dependency from the local gradle cache? The local gradle cache stores copies of maven/gradle dependencies. How to clear gradle cache? covers how to clear the whole cache, but not individual packages.
Is there a simple way to remove one package from the local gradle cache? This would be useful, for example, when actively developing a library. To test a minor library change, I currently have to clear the entire cache from the filesystem so an old cached version of the library is not used.
I understand it is also possible to use the gradle ResolutionStrategy described in How can I force gradle to redownload dependencies?. I would prefer not to change the gradle configuration because most of the time and for most developers, the default caching behavior is fine.

A: So here's a quick script I whipped up:
seekanddestroy.gradle
defaultTasks 'seekAndDestroy'

repositories{ //this section *needs* to be identical to the repositories section of your build.gradle
    jcenter()
}

configurations{
    findanddelete
}

dependencies{
    //add any dependencies that  you need refreshed
    findanddelete 'org.apache.commons:commons-math3:3.2'
}

task seekAndDestroy{
    doLast {
        configurations.findanddelete.each{
            println 'Deleting: '+ it
            delete it.parent
        }
    }
}

You can invoke this script by running gradle -b seekanddestroy.gradle

Demo of how it works:
if your build.gradle looks like this:
apply plugin:'java'

repositories{
    jcenter()
}

dependencies{

    compile 'org.apache.commons:commons-math3:3.2'
}

First time build, includes a download of the dependency:
λ gradle clean build | grep Download
Download https://jcenter.bintray.com/org/apache/commons/commons-math3/3.2/commons-math3-3.2.jar

Second clean build, uses cached dependency, so no download:
λ gradle clean build | grep Download

Now run seekanddestroy:
λ gradle -b seekanddestroy.gradle  -q
Deleting: .gradle\caches\modules-2\files-2.1\org.apache.commons\commons-math3\3.2\ec2544ab27e110d2d431bdad7d538ed509b21e62\commons-math3-3.2.jar

Next build, downloads dependency again:
λ gradle clean build | grep Download
Download https://jcenter.bintray.com/org/apache/commons/commons-math3/3.2/commons-math3-3.2.jar

A: Works great, but for newer versions of gradle, use this instead:
task seekAndDestroy{
    doLast {
        configurations.findanddelete.each{
            println 'Deleting: '+ it
            delete it.parent
        }
    }
}


Q: Cannot run python file I am trying to run a stand-alone python file partitions.py that is in my home folder. When I type the command "python3 partition.py" the script runs.
However, when I type "python3 -m partition.py" it gives me an error
"/usr/local/bin/python3: No module named partition.py"
I do not know why this is the case. Any help would be greatly appreciated.
Thanks

A: To run the module as script directly use:
python3 -m partition

(without the .py ending).
That will cause python to search sys.path for a module called partition and execute it. partition.py in this context would mean a module in a file partition/py.py.

A: See the doc, specifically that the module must be on the path, and the extension shouldn't be included.


Q: I saved an image in local database. whenever i try to open using glide. i get the following log enter image description here
fail to get the list and getting null pointer exception.
whenever i add the product into cart then it proceed into cart but image is not loaded and getting error of null pointer exception
class CartFragment : Fragment() {

    private lateinit var binding: FragmentCartBinding
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        binding = FragmentCartBinding.inflate(layoutInflater)

        val preference = requireContext().getSharedPreferences("info", AppCompatActivity.MODE_PRIVATE)
        val editor = preference.edit()
        editor.putBoolean("isCart",false)
        editor.apply()

        val dao = AppDatabase.getInstance(requireContext()).productDao()
        dao.getAllProducts().observe(requireActivity()){
            binding.cartRecycler.adapter = CartAdapter(requireContext(),it)

            totalCost(it)
        }

        return binding.root
    }

    private fun totalCost(data: List<ProductModel>) {
        var total = "0"
        for (item in data){
            total += item.productSp!!.toString()

        }
        binding.textView12.text = "Total item in cart is ${data.size}"
        binding.textView13.text = "Total Cost $total"

        binding.checkout.setOnClickListener {
            val intent = Intent(context, AddressActivity::class.java)
            intent.putExtra("totalCost",total)
            startActivity(intent)
        }

    }
}


Q: how to create geohash tree in neo4j Based on a problem here an expert have answered with this code:
CALL spatial.addPointLayerGeohash('my_geohash_layer_name')
CREATE (n:Node {latitude:60.1,longitude:15.2}) WITH n
CALL spatial.addNode('my_geohash_layer_name',n) YIELD node
RETURN node

to create a geohash tree that organise spatial nodes.
so i tried that with two spatial nodes but unlike R-tree the spatial nodes aren't linked to the layer with any connection !? is this code true ? or what is wrong ?

A: If you want an in-graph tree structure as an index, you need to use the RTree index (which is the default in Neo4j Spatial). If you want a geohash index, there will be no tree in the graph because geohashes are being stored as strings in a lucene index for string prefix searches. String prefix searches are a common way of searching geohash based indexes.


Q: Why my text box's border color doesn't grow? I have a textbox as follow.

                    Repeat Password
                    <input type="password" class="form-control" required="" name="passwordr" value="">
                    Type the password again. Passwords must match.

I am expecting to have a textbox with a glowing colour when the user click the textbox.
But it doesn't happen now.
Please see it here.
I have another setting, it works here.
I think pretty much the same.
The second one has rounded corner and the light grows.
Why the first one doesn't have rounded corner and the light doesn't glow?
EDIT:

A: !imporant for apply css forcefully and effects same as bootstrap.
.form-control:focus{
 box-shadow: 0 0 5px rgba(81, 203, 238, 1) !important;
   border: 1px solid rgba(81, 203, 238, 1) !important;

}

Working Fiddle

A: If you want an input to have a different/special appearance once selected, use the :focus CSS pseudo-class.
A simple example:
#myInput:focus {
    border: 1px solid red;
}

PS. I assume you mean "glow", not "grow", and certainly not "blow" :-)


Q: list of numbers to a stack back to a list Imagine four railroad cars positioned on the input side of the track in the figure above, numbered 1, 2, 3, and 4, respectively. Suppose we perform the following sequence of operations (which is compatible with the direction of the arrows in the diagram and does not require cars to "jump over" other cars):
As a result of these operations the original order of the cars, 1234, has been changed into 2431.
The operations above can be more concisely described by the code SSXSSXXX, where S stands for move a car from the input into the stack, and X stands for move a car from the stack into the output. Some sequences of S's and X's specify meaningless operations, since there may be no cars available on the specified track; for example, the sequence SXXSSXXS cannot be carried out. (Try it to see why.)
Write and test a function that emulates the train car switching:
    # [import statements]
    import q2_fun
# [constants]

# [rest of program code]
cars = [1, 2, 3, 4]
s_x = input("enter a code with s's and x's to move one stack to another")
list1 = q2_fun.train_swicth(cars, s_x)
print(list1)

from stack_array import Stack

def train_swicth(cars, s_x):

    s = Stack()
    list1 = []

    for i in range(len(s_x)):
        if s_x[i] == "s":
            a = s_x.append()
            s.push(a)
        elif s_x[i] == "x":
            b = s.pop()
            list1.append(b)

    return list1

I keep getting [] as the return and it should be 2431 with ssxssxxx. Can I get some help?

A: if I understood you right you could do:
def train_swicth(cars, s_x):
    i=0
    s=[]
    out=[]
    for c in s_x:
        if c=="s":
            s.append(cars[i])
            i+=1
        elif c=="x":
            out.append(s.pop())
    return out

as lists can be used as stacks with append as push-operation


Q: ImageProcessing in WPF (Fant BitmapScalingMode) My application presents an image that can be scaled to a certain size. I'm using the Image WPF control with the scaling method of FANT.
However, there is no documentation how this scaling algorithm works.
Can anyone reference me to the relevant link for this algorithm description?
Nir

A: Avery Lee of VirtualDub states that it's a box filter for downscaling and linear for upscaling. If I'm not mistaken, "box filter" here means basically that each output pixel is a "flat" average of several input pixels.
In practice, it's a lot more blurry for downscaling than GDI's cubic downscaling, so the theory about averaging sounds about right.

A: I know what it is, but I couldn't find much on Google either :(
http://ieeexplore.ieee.org/xpl/freeabs_all.jsp?arnumber=4056711 is the appropriate paper I think; behind a pay-wall.
You don't need to understand the algorithm to use it.  You should explicitly make the choice each time you create a bitmap control that is scaled whether you want it high-quality scaled or low quality scaled.


Q: My jQuery script makes always the first  look like focused when not Thing is, no matter which <select> I'm clicking, it always looks like the first one gets focused when actually the second one isn't.
The code works, but I want to implement the $(this) thing so the button I press is the one who must look focused, and I can't figure how to do it.
Here's my jsfiddle: http://jsfiddle.net/Arkl1te/TeNaf/

A: You have all <div>s with the same ID. You should not duplicate the IDs. They should be unique. And also, a <label> cannot have a <div> inside it.
Since you are using $("#select"), it selects only the first <div>. Make sure your IDs are unique and try it. This code works for you:
$(document).ready( function(){
    $('select').focus( function(){
        $(this).closest("div").addClass('selected');
    });
    $('select').focusout( function(){
        $(this).closest("div").removeClass('selected');
    });
});

Fiddle: http://jsfiddle.net/praveenscience/TeNaf/2/


Q: How to align two figures with different labels? These are two figures in my paper. Apparently, the two axes are not in alignment. How can I make sure that two figures generated independently align with each other? The problem is that the two figures have different labels and different ticklabels. That makes the positions of the axes different.

A: For each subplot, find the x/y/width/height. Then adjust the second (or both) to be the same height and the same "y"
get(gca,'position')
set(gca, 'position', [0.1300    0.15    0.3347  0.3412]) %x y width height, dummy numbers


Q: NSIS "Bad text encoding" compilation error from _EndSwitch macro We've been using NSIS 2.50 for some time now and I'm trying to update to the newest 3.0x version. I'm using Unicode true. I've ran into an issue, which I'm failing to understand. We use a switch for mapping native language names to language IDs, more or less like this:
${Switch} "${LANGNAME}"
    ${Case} "${LANGFILE_ALBANIAN_NAME}"
        StrCpy $0 "${LANG_ALBANIAN}"
        ${Break}
    ${Case} "${LANGFILE_ARABIC_NAME}"
        StrCpy $0 "${LANG_ARABIC}"
        ${Break}
    ; Other cases
${EndSwitch}

The error I'm getting from compilation:
Bad text encoding: C:\Users\me\AppData\Local\Temp\nst9352.tmp:9
!include: error in script: "C:\Users\me\AppData\Local\Temp\nst9352.tmp" on line 9
Error in macro _EndSwitch on macroline 9

The temporary file is apparently created by LogicLib, which then tries to include it. The file really doesn't have any valid Unicode encoding (I'm posting just a snippet from the file):
!insertmacro _== `$2` `Shqip` _LogicLib_Label_433 ""
!insertmacro _== `$2` `???????` _LogicLib_Label_434 ""
!insertmacro _== `$2` `Catal�` _LogicLib_Label_441 ""

The strings with invalid UTF-8 characters seem to be encoded in various ANSI encodings (some seem to be Western European, some Central European etc.), while the question marks are saved as real question marks (0x3F). ${LANGFILE_NLFID_NAME} is defined in language files as native name using the LANGFILE macro from LangFile.nsh. I looked at the language files and they are encoded in UTF-8 BOM and look all right. So it looks like the native name is re-encoded to ANSI or something for ${LANGFILE_NLFID_NAME}?
I'm pretty sure I'm making some stupid mistake, but I can't really figure out what it is.

A: Looks like a bug, it will be fixed in the next release.
Since you are not using the fall-through Switch feature you can just use Select or If/ElseIf instead:
${Select} "${LANGNAME}"
    ${Case} "${LANGFILE_ALBANIAN_NAME}"
        DetailPrint LANG_ALBANIAN
    ${Case} "${LANGFILE_ARABIC_NAME}"
        DetailPrint LANG_ARABIC
${EndSelect}


Q: Recursively get every nth element from array Javascript I have an array of colors that I need to recursively get every nth element to generate a legend. The colors array might look something like this:
[
'red',
'dark_red',
'dark_dark_red',
'green',
'dark_green',
'dark_dark_green',
'blue',
'dark_blue',
'dark_dark_blue'
]

I have a variable amount of legend items that I want to generate colors for. I want to be able to generate the colors based off of the index when looping through the legend items in a pattern like so:
1 - green
2 - blue
3 - dark_red
4 - dark_green
5 - dark_blue
6 - etc...

How might I go about this? I tried using modulus and a double-loop statement but was not able to generate the colors properly.

A: To get the nthItems:

function nthItems(array, n){
  const r = [];
  for(let i=n-1,l=array.length; i<l; i+=n){
    r.push(array[i]);
  }
  return r;
}
const a = [
  'red',
  'dark_red',
  'dark_dark_red',
  'green',
  'dark_green',
  'dark_dark_green',
  'blue',
  'dark_blue',
  'dark_dark_blue'
];
console.log(nthItems(a, 2));
console.log(nthItems(a, 3));

A: StackSlave's answer is the most efficient way but if you want a recursive way you could do

const a = [
  'red',
  'dark_red',
  'dark_dark_red',
  'green',
  'dark_green',
  'dark_dark_green',
  'blue',
  'dark_blue',
  'dark_dark_blue'
];

const nthItems = (array, n) => {
  const results = [];
  const addItem = index => {
    if (index < array.length) {
      results.push(array[index]);
      addItem(index + n);
    }
  };
  addItem(0);
  return results;
};

console.log(nthItems(a, 2));
console.log(nthItems(a, 3));

But this is recursive purely for the sake of recursion, it adds values to the stack unnecessarily when a for loop will do.


Q: rxjava StackOverflowError exception in long chain I build very long rxjava chain (with retrofit request) with a lot of operators: doOnNext, doOnError, switchIfEmpty, onErrorResumeNext, flatMap
On some devices (Android 4.1 for example) it throws StackOverflowError exception when chain go by the longest route.
Are there some ways or best practices to optimize chains or prevent StackOverflowError?
Now I see only one way  - break chain, and call second part from first onComplete(OnNext), but it is not reactive way, I think.
Yet another way - change threads with .subscribeOn(Schedulers.newThread()); operator. Seems not the best solution too.
My code:
1) code with subscribing
fastSearch(keyphrase)
    .onErrorResumeNext(throwable -> {
        return correctKeyphraseAndSearch(keyphrase);
    })
    .doOnNext(resultsDao -> {...})
    .subscribe(...)

2) helper methods
public static Observable<SearchResultsDao> fastSearch(final String keyphrase) {
    String SRD = "true";
    final HttpQueryParams params = new HttpQueryParams();
    //read from cache chain
    Observable<SearchResultsDao> cacheChain = getCache().fastSearch(keyphrase, SRD)
            .doOnNext(...)
            .doOnError(...)
            .onErrorResumeNext(new HandleNoCacheEntry<SearchResultsDao>(params)); //save some data to "params", and return Observable.empty
    //network request chain
    Observable<SearchResultsDao> networkChain = getApi().fastSearch(keyphrase, SRD)
            .retryWhen(new OnNewSessionRequired())
            .doOnNext(new WriteToCacheAction<SearchResultsDao>(params)); //save to cache
    //combine cache+network chains
    return cacheChain
            .switchIfEmpty(networkChain)
            .doOnNext(resultsDao -> resultsDao.setKeyphrase(keyphrase));
}

public static Observable<SearchResultsDao> correctKeyphraseAndSearch(final String keyphrase) {
    return mainDiv()
            .flatMap(str -> syntax(str, keyphrase, true))
            .flatMap(syntaxDao -> {
                //get corrected keyphrase from server
                StringBuilder newKeyphrase = ... ;
                //repeat search request with new keyphrase
                return fastSearch(newKeyphrase.toString());
            });
}

3) some comments:
mainDiv() and syntax() methods identical to fastSearch() method, but doing another requests to server
getCache().fastSearch() - create observable that reads data from own cache (retrofit-like: getCache() implements retrofit Api methods interface)
Stacktrace:
Uncaught Exception
java.lang.IllegalStateException: Fatal Exception thrown on Scheduler.Worker thread.
at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:62)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:442)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:150)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:264)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)
Caused by: java.lang.StackOverflowError
okhttp3.HttpUrl.newBuilder (HttpUrl.java:633)
retrofit2.RequestBuilder.addQueryParam (RequestBuilder.java:144)
retrofit2.ParameterHandler$Query.apply (ParameterHandler.java:109)
retrofit2.ServiceMethod.toRequest (ServiceMethod.java:108)
retrofit2.OkHttpCall.createRawCall (OkHttpCall.java:178)
retrofit2.OkHttpCall.execute (OkHttpCall.java:162)
retrofit2.adapter.rxjava.RxJavaCallAdapterFactory$RequestArbiter.request (RxJavaCallAdapterFactory.java:171)
rx.internal.producers.ProducerArbiter.setProducer (ProducerArbiter.java:126)
rx.internal.operators.OnSubscribeRedo$2$1.setProducer (OnSubscribeRedo.java:272)
rx.Subscriber.setProducer (Subscriber.java:205)
retrofit2.adapter.rxjava.RxJavaCallAdapterFactory$CallOnSubscribe.call (RxJavaCallAdapterFactory.java:152)
retrofit2.adapter.rxjava.RxJavaCallAdapterFactory$CallOnSubscribe.call (RxJavaCallAdapterFactory.java:138)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable.unsafeSubscribe (Observable.java:8314)
rx.internal.operators.OnSubscribeRedo$2.call (OnSubscribeRedo.java:278)
rx.schedulers.TrampolineScheduler$InnerCurrentThreadScheduler.enqueue (TrampolineScheduler.java:80)
rx.schedulers.TrampolineScheduler$InnerCurrentThreadScheduler.schedule (TrampolineScheduler.java:59)
rx.internal.operators.OnSubscribeRedo$5.request (OnSubscribeRedo.java:366)
rx.internal.producers.ProducerArbiter.setProducer (ProducerArbiter.java:126)
rx.internal.operators.OperatorSwitchIfEmpty$AlternateSubscriber.setProducer (OperatorSwitchIfEmpty.java:106)
rx.Subscriber.setProducer (Subscriber.java:205)
rx.internal.operators.OnSubscribeRedo.call (OnSubscribeRedo.java:358)
rx.internal.operators.OnSubscribeRedo.call (OnSubscribeRedo.java:55)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable.unsafeSubscribe (Observable.java:8314)
rx.internal.operators.OperatorSwitchIfEmpty$ParentSubscriber.subscribeToAlternate (OperatorSwitchIfEmpty.java:78)
rx.internal.operators.OperatorSwitchIfEmpty$ParentSubscriber.onCompleted (OperatorSwitchIfEmpty.java:71)
rx.internal.operators.OperatorOnErrorResumeNextViaFunction$4$1.onCompleted (OperatorOnErrorResumeNextViaFunction.java:125)
rx.Observable$EmptyHolder$1.call (Observable.java:1123)
rx.Observable$EmptyHolder$1.call (Observable.java:1120)
rx.Observable.unsafeSubscribe (Observable.java:8314)
rx.internal.operators.OperatorOnErrorResumeNextViaFunction$4.onError (OperatorOnErrorResumeNextViaFunction.java:141)
rx.internal.operators.OperatorDoOnEach$1.onError (OperatorDoOnEach.java:71)
rx.internal.operators.OperatorDoOnEach$1.onError (OperatorDoOnEach.java:71)
com.testrx.app.retrofit.api.CacheHelper$1.call (CacheHelper.java:56)
com.testrx.app.retrofit.api.CacheHelper$1.call (CacheHelper.java:46)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable.unsafeSubscribe (Observable.java:8314)
rx.internal.operators.OperatorMerge$MergeSubscriber.onNext (OperatorMerge.java:235)
rx.internal.operators.OperatorMerge$MergeSubscriber.onNext (OperatorMerge.java:145)
rx.internal.operators.OperatorMap$1.onNext (OperatorMap.java:54)
rx.internal.operators.OperatorMerge$MergeSubscriber.emitScalar (OperatorMerge.java:368)
rx.internal.operators.OperatorMerge$MergeSubscriber.tryEmit (OperatorMerge.java:330)
rx.internal.operators.OperatorMerge$InnerSubscriber.onNext (OperatorMerge.java:807)
rx.internal.operators.OperatorSwitchIfEmpty$ParentSubscriber.onNext (OperatorSwitchIfEmpty.java:89)
rx.internal.operators.OperatorOnErrorResumeNextViaFunction$4.onNext (OperatorOnErrorResumeNextViaFunction.java:153)
rx.internal.operators.OperatorDoOnEach$1.onNext (OperatorDoOnEach.java:85)
rx.internal.operators.OperatorDoOnEach$1.onNext (OperatorDoOnEach.java:85)
com.testrx.app.retrofit.api.CacheHelper$1.call (CacheHelper.java:53)
com.testrx.retrofit.api.CacheHelper$1.call (CacheHelper.java:46)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable.unsafeSubscribe (Observable.java:8314)
rx.internal.operators.OperatorMerge$MergeSubscriber.onNext (OperatorMerge.java:235)
rx.internal.operators.OperatorMerge$MergeSubscriber.onNext (OperatorMerge.java:145)
rx.internal.operators.OperatorMap$1.onNext (OperatorMap.java:54)
rx.internal.operators.OperatorSwitchIfEmpty$ParentSubscriber.onNext (OperatorSwitchIfEmpty.java:89)
rx.internal.operators.OperatorOnErrorResumeNextViaFunction$4.onNext (OperatorOnErrorResumeNextViaFunction.java:153)
rx.internal.operators.OperatorDoOnEach$1.onNext (OperatorDoOnEach.java:85)
rx.internal.operators.OperatorDoOnEach$1.onNext (OperatorDoOnEach.java:85)
com.testrx.app.retrofit.api.CacheHelper$1.call (CacheHelper.java:53)
com.testrx.app.retrofit.api.CacheHelper$1.call (CacheHelper.java:46)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable.unsafeSubscribe (Observable.java:8314)
rx.internal.operators.OperatorOnErrorResumeNextViaFunction$4.onError (OperatorOnErrorResumeNextViaFunction.java:141)
rx.internal.operators.OperatorDoOnEach$1.onError (OperatorDoOnEach.java:71)
rx.internal.operators.OperatorSwitchIfEmpty$AlternateSubscriber.onError (OperatorSwitchIfEmpty.java:116)
rx.internal.operators.OperatorDoOnEach$1.onError (OperatorDoOnEach.java:71)
rx.internal.operators.OnSubscribeRedo$4$1.onError (OnSubscribeRedo.java:331)
rx.internal.operators.OperatorMerge$MergeSubscriber.reportError (OperatorMerge.java:243)
rx.internal.operators.OperatorMerge$MergeSubscriber.checkTerminate (OperatorMerge.java:779)
rx.internal.operators.OperatorMerge$MergeSubscriber.emitLoop (OperatorMerge.java:540)
rx.internal.operators.OperatorMerge$MergeSubscriber.emit (OperatorMerge.java:529)
rx.internal.operators.OperatorMerge$InnerSubscriber.onError (OperatorMerge.java:813)
rx.Observable$ThrowObservable$1.call (Observable.java:10200)
rx.Observable$ThrowObservable$1.call (Observable.java:10190)
rx.Observable.unsafeSubscribe (Observable.java:8314)
rx.internal.operators.OperatorMerge$MergeSubscriber.onNext (OperatorMerge.java:235)
rx.internal.operators.OperatorMerge$MergeSubscriber.onNext (OperatorMerge.java:145)
rx.internal.operators.OperatorMap$1.onNext (OperatorMap.java:54)
rx.internal.operators.OperatorMap$1.onNext (OperatorMap.java:54)
rx.internal.operators.OnSubscribeRedo$3$1.onNext (OnSubscribeRedo.java:307)
rx.internal.operators.OnSubscribeRedo$3$1.onNext (OnSubscribeRedo.java:289)
rx.internal.operators.NotificationLite.accept (NotificationLite.java:150)
rx.subjects.SubjectSubscriptionManager$SubjectObserver.emitNext (SubjectSubscriptionManager.java:253)
rx.subjects.BehaviorSubject.onNext (BehaviorSubject.java:160)
rx.internal.operators.OnSubscribeRedo$2$1.onError (OnSubscribeRedo.java:242)
retrofit2.adapter.rxjava.OperatorMapResponseToBodyOrError$1.onNext (OperatorMapResponseToBodyOrError.java:43)
retrofit2.adapter.rxjava.OperatorMapResponseToBodyOrError$1.onNext (OperatorMapResponseToBodyOrError.java:38)
retrofit2.adapter.rxjava.RxJavaCallAdapterFactory$RequestArbiter.request (RxJavaCallAdapterFactory.java:173)
rx.internal.producers.ProducerArbiter.setProducer (ProducerArbiter.java:126)
rx.internal.operators.OnSubscribeRedo$2$1.setProducer (OnSubscribeRedo.java:272)
rx.Subscriber.setProducer (Subscriber.java:205)
retrofit2.adapter.rxjava.RxJavaCallAdapterFactory$CallOnSubscribe.call (RxJavaCallAdapterFactory.java:152)
retrofit2.adapter.rxjava.RxJavaCallAdapterFactory$CallOnSubscribe.call (RxJavaCallAdapterFactory.java:138)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable.unsafeSubscribe (Observable.java:8314)
rx.internal.operators.OnSubscribeRedo$2.call (OnSubscribeRedo.java:278)
rx.schedulers.TrampolineScheduler$InnerCurrentThreadScheduler.enqueue (TrampolineScheduler.java:80)
rx.schedulers.TrampolineScheduler$InnerCurrentThreadScheduler.schedule (TrampolineScheduler.java:59)
rx.internal.operators.OnSubscribeRedo$5.request (OnSubscribeRedo.java:366)
rx.internal.producers.ProducerArbiter.setProducer (ProducerArbiter.java:126)
rx.internal.operators.OperatorSwitchIfEmpty$AlternateSubscriber.setProducer (OperatorSwitchIfEmpty.java:106)
rx.Subscriber.setProducer (Subscriber.java:205)
rx.internal.operators.OnSubscribeRedo.call (OnSubscribeRedo.java:358)
rx.internal.operators.OnSubscribeRedo.call (OnSubscribeRedo.java:55)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable.unsafeSubscribe (Observable.java:8314)
rx.internal.operators.OperatorSwitchIfEmpty$ParentSubscriber.subscribeToAlternate (OperatorSwitchIfEmpty.java:78)
rx.internal.operators.OperatorSwitchIfEmpty$ParentSubscriber.onCompleted (OperatorSwitchIfEmpty.java:71)
rx.internal.operators.OperatorOnErrorResumeNextViaFunction$4$1.onCompleted (OperatorOnErrorResumeNextViaFunction.java:125)
rx.Observable$EmptyHolder$1.call (Observable.java:1123)
rx.Observable$EmptyHolder$1.call (Observable.java:1120)
rx.Observable.unsafeSubscribe (Observable.java:8314)
rx.internal.operators.OperatorOnErrorResumeNextViaFunction$4.onError (OperatorOnErrorResumeNextViaFunction.java:141)
rx.internal.operators.OperatorDoOnEach$1.onError (OperatorDoOnEach.java:71)
rx.internal.operators.OperatorDoOnEach$1.onError (OperatorDoOnEach.java:71)
com.testrx.app.retrofit.api.CacheHelper$1.call (CacheHelper.java:56)
com.testrx.app.retrofit.api.CacheHelper$1.call (CacheHelper.java:46)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable.unsafeSubscribe (Observable.java:8314)
rx.internal.operators.OperatorSubscribeOn$1.call (OperatorSubscribeOn.java:94)
rx.internal.schedulers.ScheduledAction.run (ScheduledAction.java:55)
java.util.concurrent.Executors$RunnableAdapter.call (Executors.java:442)

A: Stackoverflows rarely happen with typical streams; without code I can't be sure what's wrong.
In earlier versions of RxJava, there were reentrancy problems in some operators that could result in StackOverflows but we haven't received any bug reports like it in some time now. Please make sure you are using the latest RxJava from the 1.x line (the RxAndroid plugin's dependency may need overriding as it is infrequently updated in this regard).
There are a few things you can do:

*

*compact subsequent doOnNext and doOnError calls into doOnEach

*add observeOn(Schedulers.computation()) occasionally

*avoid chaining too many mergeWiths, collect up sources into a List and use merge(Iterable)

*upgrade to RxJava 2.x which should have less stack depth (have not verified)

Edit:
Based on the stacktrace, my undestanding is that you have too many empty sequences and switchIfEmpty keeps deepening the stack when switching from one empty sequence to the next. As you found out, subscribeOn helps "restart" the stack. I'll investigate possible resolutions within RxJava itself.

A: The cause of this problem was Jack compiler (https://source.android.com/source/jack.html) which I use in the project for lambdas support. I switched it off and now everything works fine


Q: How to prevent Visual C Compiler from optimizing out "unused" global variable
Possible Duplicate:
Why does const imply internal linkage in C++, when it doesn’t in C?
What is external linkage and internal linkage in C++

I have a two C files that I'm trying to compile to an executable.  One file contains only a single declaration as follows (simplifed).
const char *foo[2] = {"thing1", "thing2"};

The second c file does this
extern const char *foo[2];
main()
{
 //Code that does stuff with foo
}

When compiling I get a linker error that foo is an unresolved external symbol.  I'm assuming the compiler is optimizing out foo.   Any ideas here?

A: There's nothing wrong with your declarations. The code should compile and link as is, assuming you add explicit int as the return type of your main. The only explanation for the linker error I can come up with is that you are forgetting to supply all required object files to the linker.
The answers that attempt to explain this issue through the fact that in C++ const objects have internal linkage are misleading and irrelevant. The above object foo is not a const object.


Q: Oracle: Finding the stored procedure that modifies record on a table I've got a C# code that calls stored procedures and UPDATES a table. Can I monitor each operation made on this table by a SID.

A: Yes, you can do this at the database level using Oracle auditing.  See here for good writeup and examples of its use.


Q: creating new variables in sas I am trying to create 3 new variables and have used this code however keep getting an error in my log, I am not sure what this issue is:
    Data birthdata
    SET birthdata;

    native=.;
    if race=3 THEN native=1;
    if race=1 THEN native=0;

    aarace=.;
    if race=2 then aarace=1;
    if race=1 then aarace=0;

   nonwhite=.;
   if (1<race=.) then nonwhite=1;
   if race=1 then nonwhite=0;

  label native  = "Maternal race"
  aarace  = "Maternal race"
  nonwhite = "Maternal race";

 FORMAT native native. aarace aarace. nonwhite nonwhite.;

 run;

`

A: You missed ; in first line of data step.


Q: Export data to pdf in Laravel downloading only 2 pages irrespective of data I have huge amount of data in my DB. But when I try to export data to pdf in Laravel only 2 pages are downloading.
 $members = DB::table('members')->where('id_card_issued',0)->get();
 $pdf = PDF::loadView('admin.myPDF', compact('members'));
 return $pdf->download('id_card.pdf');

I want all the data to be downloaded. But now only getting last 2 data in my database table

A: Are you trying to do to download large files from the server, I have changed the below settings in php.ini file in mine to do so :
Upload_max_filesize  - 1500 M
Max_input_time  - 1000
Memory_limit    - 640M
Max_execution_time -  1800
Post_max_size - 2000 M


Q: Javascript unit testing framework that doesn't work in strict mode Is there a way to unit test code from not strict mode. Most of the testing frameworks, mocha, jest, etc are strict mode only. My code involves use of eval that needs non-strict mode scope that I cannot rewrite into strict mode compatible form. Any idea or do I need to write my own unit testing framework.

A: I ended up using Karma with jasmine. Setting it to browser mode means no modules and no strict mode, yay.


Q: Clear filter from Table I'm trying to run a macro that replaces data in a table in Excel, when the data might initially be filtered.
The code should remove the filter first, then run the rest of the code.
I tried the "Autofilter" command, but then the normal filter option on the table's range weren't visible, and I had to manually create the filter option again (not a big deal to me, but other people use this file).
Is there a way to clear the filter WITHOUT removing filters from the table?

A: For a Table, you can simply use the ShowAllData method of its Autofilter object:
activesheet.listobjects(1).autofilter.showalldata

Note this won't error even if there is no filter currently applied.

A: This expands on the answer from @Rory (the go-to-answer I look up every time I can't remember the syntax).  It avoids errors that occur when the table doesn't contain an auto-filter.
The section If Not .AutoFilter Is Nothing checks for the AutoFilter object property of the ListObject (table).  If it Is Nothing then that table had it's auto-filter removed.
With Activesheet.Listobjects(1)
    If not .AutoFilter Is Nothing Then .AutoFilter.ShowAllData
End With

A: Hi Guys use this "Worksheets("Sheet1").ListObjects(1).Range.AutoFilter = False" and please note if already filter applied it will remove filter on the other hand if filter not applied before it will apply the filter.

A: I am finding that the "...ClearAllData" method fails.
Sneaky - not hugely elegant solution - that works by field (so cumbersome if you need to do the whole table), but easy if you just have one field (e.g. field 2 in my example) is to use the wildcard:
ActiveSheet.ListObjects(1).Range.AutoFilter Field:=2, Criteria1:="=*"

A: ActiveSheet.ShowAllData

Or
Cells.AutoFilter


Q: decrypt web.config file for specific project on a local machine I have a project that is running on the server. I want to modify it on a local machine, but connection strings in the web.config file are encrypted using regiis. To decrypt it I tried this article:
http://ryaremchuk.blogspot.com/2012/11/encrypting-and-decrypting-webconfig.html
I copied the project to a folder on the hard desk on my local machine; so its path is C:\project1.
In the prompt interface I reached: C:\windows\Microsoft.NET\Framework\v4.0.30319. Then I used this command with no luck:
aspnet_regiis -pd "connectionStrings" -app "C:\project1"

Is my command wrong? Should the project be in a different path?


Q: Get the detached object from the session in the Hibernate events PostLoadEvent and PostUpdateEvent I have an entity which has transient fields, after the merge / load i loose all the values of these transient fields in the returned managed object.
What i want to do , is to copy the values of the transient fields from the detached object to the managed object.
The solution that i want to follow is based on the events in Hibernate, but i only have access to the detached object (the original entity) in the MergeEventListener and not in the PostUpdateEventListener and PostLoadEventListener .
Do you have any suggestion to find a solution to this issue ?
Thank you


Q: Window 200x200 with circle 200x200 doesn't fit I'm trying to do something very simple. I'm trying to create a window that has a circle in it that fits perfectly. I made the window 200x200 and the circle 200x200 and it looks like this
This is the code I made:
using System.Windows.Forms;
using System.Drawing;

class HalloForm : Form
{
    public HalloForm()
    {
        this.Text = "Hallo";
        this.BackColor = Color.LightGray;
        this.Size = new Size(200, 200);
        this.Paint += this.tekenScherm;
        this.AutoScaleMode = AutoScaleMode.Font;
    }

    void tekenScherm(object obj, PaintEventArgs pea)
    {

        tekenSmiley(pea, 0, 0, 200);
        /*pea.Graphics.DrawString("Hallo!"
                               , new Font("Tahoma", 30)
                               , Brushes.Blue
                               , 10, 10
                               );*/

        //pea.Graphics.DrawArc(Pens.Black, )

        //pea.Graphics.FillEllipse(Brushes.Black, new Rectangle(new Point(x + 40, y + 40), new Size(50, 50)));
        //pea.Graphics.FillEllipse(Brushes.Black, new Rectangle(new Point(x + 110, y + 40), new Size(50, 50)));
        //pea.Graphics.FillPolygon(Brushes.Black, new Point[] { new Point(x + 85, x + 120), new Point(x + 115, y + 120), new Point(x + 100, x + 90) });
    }

    private void tekenSmiley(PaintEventArgs pea, int x, int y, int grootte)
    {
        pea.Graphics.FillEllipse(Brushes.Yellow, new Rectangle(new Point(x, y), new Size(grootte, grootte)));
    }
}

class HalloWin3
{
    static void Main()
    {
        HalloForm scherm;
        scherm = new HalloForm();
        Application.Run(scherm);
    }
}

I tried different auto scale modes and none of them changed anything. Can you help me find out why the circle doesn't fit in the window. I understand that maybe it wouldn't fit vertically because the top bar might be included in the height, but then it should still fit horizontally.

A: As you already mentioned, the Size of the form includes borders, title bars etc. So, try to set the ClientSize which defines the client area of the form:
this.ClientSize = new Size(200, 200);


Q: Displaying an image in a jsp from a byte array using struts I can get an image as a byte[] and store it in my database using form.jsp and FormFile.
Now I need to be able to retrieve that byte[] and display it back in the JSP as an image. Is there a way to create a resource and retrieve that image?

A: public ActionForward pageLoad(ActionMapping a,ActionForm b,HttpServletRequest c,HttpServletResponse d){
    b.setImageData(loadImageData());
    return a.findForward("toPage");
}

public ActionForward imageLoad(ActionMapping a,ActionForm b,HttpServletRequest c,HttpServletResponse d){
    byte[] tempByte = b.getImageData();
    d.setContentType("image/jpeg");
    ServletOutputStream stream = d.getOutputStream();
    /*
        Code to write tempByte into stream here.
    */
    return null;
}

Write the tempByte into stream, flush and close it. return null from the action.
now call the action from inside an <img src="yourAction.do">

A:        <%@ page import="java.sql.*" %>
       <%@ page import="java.io.*" %>

        Connection connection =  null;

      String connectionURL = "jdbc:mysql://localhost:3306/Test";
      ResultSet rs = null;

       PreparedStatement psmnt = null;

 InputStream sImage;
 try {

Class.forName("com.mysql.jdbc.Driver").newInstance();

 connection = DriverManager.getConnection(connectionURL, "Admin", "Admin");
psmnt = connection.prepareStatement("SELECT image FROM save_image WHERE id = ?");
psmnt.setString(1, "11"); // here integer number '11' is image id from the table
rs = psmnt.executeQuery();
if(rs.next()) {
byte[] bytearray = new byte[1048576];
int size=0;
sImage = rs.getBinaryStream(1);
response.reset();
response.setContentType("image/jpeg");
while((size=sImage.read(bytearray))!= -1 ){
response.getOutputStream().write(bytearray,0,size);
 }
 }
 }
     catch(Exception ex){
           out.println("error :"+ex);
        }
            finally {
                  rs.close();
                 psmnt.close();
                 connection.close();
         }
                  %>

By this u can retrive Image from Database


Q: Using SIFT and OpenCV for object recognition I have an image that is an image of one of a set of objects, and I'd like to use SIFT in Open CV to figure out which object it. I have this code:
Mat pic = imread(...);
vector<KeyPoint> picKP;
Mac picDesc;

Mat obj1 = imread(...);
Mat obj2 = imread(...);
Mat obj3 = imread(...);
vector<KeyPoint> obj1KP;
vector<KeyPoint> obj2KP;
vector<KeyPoint> obj3KP;
Mat obj1Desc;
Mat obj2Desc;
Mat obj3Desc;

SIFT sifter = SIFT();

sifter.detect(pic, picKP);
sifter.detect(obj1, obj1KP);
sifter.detect(obj2, obj2KP);
sifter.detect(obj3, obj3KP);

sifter.compute(pic, picKP, picDesc);
sifter.compute(obj1, obj1KP, obj1Desc);
sifter.compute(obj2, obj2KP, obj1Desc);
sifter.compute(obj3, obj3KP, obj1Desc);

FlannBasedMatcher matcher;
vector<DMatch> matches1;
vector<DMatch> matches2;
vector<DMatch> matches3;

matcher.match(picDesc, obj1Desc, matches1);
matcher.match(picDesc, obj2Desc, matches2);
matcher.match(picDesc, obj3Desc, matches3);

It generates a vector<DMatch> to compare my picture with each potential picture. But I don't know what to do with the 3 vector<DMatch>es to figure out which one is the best match.
Note: I'm doing this mostly to try and learn about SIFT, so even though I know better ways are available for my particular dataset, I still want to try to do it with SIFT.

A: See the API for DMatch data type here:
http://docs.opencv.org/modules/features2d/doc/common_interfaces_of_descriptor_matchers.html#dmatch


Q: Aws lambda java - Implement simple cache to read a file I have a lambda process in java and it reads a json file with a table everytime is triggered. I'd like to implement a kind of cache to have that file in memory and I wonder how to do something simple. I don't want to use elasticchache or redis.
I read something similar to my approach in javascript declaring a global variable with let but not sure how to do it in java, where it should be declared and how to test it. Any idea or example you can provide me? Thanks

A: *

*There are global variables in lambda which can be of help but they have to be used wisely.

*They are usually the variables declared out side of lambda_handler.

*There are pros and cons of using it.

*You can't rely on this behavior but you must be aware it exists. When you call your Lambda function several times, you MIGHT get the same container to optimise run duration and setup delay Use of Global Variables

*At the same time you should be aware of the issues or avoid wrong use of it caching issues

*If you don't want to use ElastiCache/redis then i guess you have very less options left.......may be dynamoDB or S3 that's all i can think of
again connection to dynamoDB or S3 can be cached here. It won't be as fast as ElastiCache though.

A: In Java it's not too hard to do.  Just create your cache outside of the handler:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.amazonaws.services.lambda.runtime.RequestStreamHandler;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class SampleHandler implements RequestStreamHandler {
    private static final Logger logger = LogManager.getLogger(SampleHandler.class);

    private static Map<String, String> theCache = null;

    public SampleHandler() {
        logger.info( "filling cache...");

        theCache = new HashMap<>();

        theCache.put("key1", "value1");
        theCache.put("key2", "value2");
        theCache.put("key3", "value3");
        theCache.put("key4", "value4");
        theCache.put("key5", "value5");
    }

    public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context) throws IOException {
        logger.info("handlingRequest");
        LambdaLogger lambdaLogger = context.getLogger();

        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = objectMapper.readTree(inputStream);

        String requestedKey = jsonNode.get("requestedKey").asText();

        if( theCache.containsKey( requestedKey )) {
            // read from the cache
            String result = "{\"requestedValue\": \"" + theCache.get(requestedKey) + "\"}";

            outputStream.write(result.getBytes());
        }

       logger.info("done with run, remaining time in ms is " + context.getRemainingTimeInMillis() );
    }
}

(run with the AWS cli with aws lambda invoke --function-name lambda-cache-test --payload '{"requestedKey":"key4"}' out with the output going the the file out)
When this runs with a "cold start" you'll see the "filling cache..." message and then the "handlingRequest" in the CloudWatch log.  As long as the Lambda is kept "warm" you will not see the cache message again.
Note that if you had hundreds of the same Lamda's running they would all have their own independent cache.  Ultimately this does what you want though - it's a lazy load of the cache during a cold start and the cache is reused for warm calls.