text:
Q: Panolens + p5js: using image BLEND SCREEN function with SLIDERS for PANORAMA pictures I have the following question: How to show panorama images (that can be moved with mouse, or in cardboard googles) that can have a sliders controlling an image blend between two panoramas?
Description: I am trying to make an app, where user can see a panorama image and move around in it (I used PANOLENS for it), and then using sliders be able to make the images blend with each other. The blend is made using SCREEN BLEND function (basically, as the sliders move to one side, some brighter elements from one panorama start to appear on the other panorama - so in a way, two panorama images are displayed at the same time).
I think I kinda figured the way to do it for normal rectangular images - I use p5js library with IMAGE BLEND SCREEN function with 3 sliders - it is in the script called sketch.js:

let DAYLIGHT;
let LAMPS1;
let LAMPS2;

function preload() {
  DAYLIGHT = loadImage('../img/OFFICEDL.JPG');
  LAMPS1 = loadImage('../img/OFFICEL2.JPG');
  LAMPS2 = loadImage('../img/OFFICEL1.JPG');
}
function setup() {
  canvas = createCanvas(1200,600).parent("recimage");
  DAYLIGHT.resize(1200,600);
  LAMPS1.resize(1200,600);
  LAMPS2.resize(1200,600);
  DLslider = createSlider(0, 255, 0).parent('slidersimage');
  DLslider.position(10, 0).parent('slidersimage');
  DLslider.style('width', '200px');
  L1slider = createSlider(0, 255, 0).parent('slidersimage');
  L1slider.position(10, 30).parent('slidersimage');
  L1slider.style('width', '200px');
  L2slider = createSlider(0, 255, 0).parent('slidersimage');
  L2slider.position(10, 60).parent('slidersimage');
  L2slider.style('width', '200px');

}

function draw() {
  background(0);
      blendMode(SCREEN);
const DLvalue = DLslider.value();
const L1value = L1slider.value();
const L2value = L2slider.value();
  tint(255, 255-DLvalue);
  image(DAYLIGHT,0,0);
  tint(255, L1value);
  image(LAMPS1,0,0);
  tint(255, L2value);
  image(LAMPS2,0,0);
  blendMode(BLEND);

}

Now for displaying the panoramas for now I have only used a workflow from tutorial to display the panorama, and for that I load three.min.js and panolens.js, and finally in the script main.js I use tell the app to display the panorama picture:

const panoImage = document.querySelector('.pano-image');
const testPano1 = '../img/OFFICEDL.jpg';
const panorama = new PANOLENS.ImagePanorama(testPano1);
const viewer = new PANOLENS.Viewer({
    container: panoImage,
});

viewer.add( panorama );

Finally, in my html it looks like this:

<!DOCTYPE html>

    <link rel="stylesheet" type="text/css" href="style.css">
    <meta charset="utf-8">

 PANORAMA TEST

        This is the panorama view of the room

        This is the stretched out panorama (equirectangular image view) with adjustable level of lighting

     End text

For now, altogether there is a panorama image on the top, and equirectangular version of it on the bottom, which has the sliders controlling it. Is there a way to implement similar control to the panoramic version?
Also, a side question: my sliders do not seem to position themselves relatively to the canvas, but rather to the whole website...anyone has any tips for that?
Any help would be greatly appreciated!


text:
Q: service in android I want to include a new service related to mediaserver in my android device.
I tried making changes to the mediaserver and pushing it into the device.
   When i compiled and pushed into the device, the device did not boot. My logcat showed "MediaPlayer is not published.. waiting...".
   When i checked running the service from the shell it showed, "link_image[1995]: failed to link mediaserver CANNOT LINK EXECUTABLE"
I removed the changes from mediaserver and tried to push the exe into the device. It showed the same problem but when i pushed the mediaserver exe(took backup fearing stuffs like this would happen. .:( )the device boots properly.
I created a new service and modified init.rc to run the new service but it does not the start the service. Instead it shows CANNOT LINK EXECUTABLE.
I tried to figure out the prob but the only difference I could find was the chmod to 777 and chown to shell. Even after that it is not booting.. :( If this is solved I think I will be able to make changes to mediaserver. Someone help me find out a solution..!

A: Actually the problem was there were lot of dependencies in the library .so files. After removing all the dependencies, the application worked.. :):)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Centering oversized content but make sure scrolling still works I have the following HTML and CSS which works okay for most cases in that the content is centered, but when the width of the browser becomes smaller than the oversized block the content remains centered and scrolling to the left does not show the content on the left.  Is there something I can do to the CSS for .oversized to handle this scenario?

main {
    width: 1080px;
    margin-left: auto;
    margin-right: auto;
    margin-top: 20px;
}

.oversized {

    display: flex;
    justify-content: center;
    margin: 0 auto;

}

table {
  border-collapse: collapse;
}

td {
  border: 1px solid black;
  padding: 5px;
  white-space: nowrap;
}

Normal content Normal content Normal content Normal content Normal content Normal content Normal content Normal content Normal content Normal content Normal content Normal content Normal content

        This table is a bit oversized slkfjs lkfjlksaf lksdjflk sajflksj lksjflk sfjlkj slkfj slkafjkls afjlksafj;lksadjf lksajf
        sajflksj lksjflk sfjlkj slkfj slkafjkls afjlksafj;lksadjf lksajf
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10

        aaskdfjalksdfjklasdjfklsaj lksdjflk slkfjs lkfjlksaf lksdjflk sajflksj lksjflk sfjlkj slkfj slkafjkls afjlksafj;lksadjf lksajf
        sajflksj lksjflk sfjlkj slkfj slkafjkls afjlksafj;lksadjf lksajf
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10

Normal content Normal content Normal content Normal content Normal content Normal content Normal content Normal content Normal content Normal content Normal content Normal content Normal content

Added in CodePen as well https://codepen.io/trajano/pen/YzXVrpE so you can see the full width.
The answers in Can't scroll to top of flex item that is overflowing container do not resolve the issue as it shifts the content to the right to align with the  element.


text:
Q: Passing a functor as C++ template parameter As an exercise for my personal enlightenment, I implement vector math with expression templates. I want to implement some operations that apply the same unary function to all elements to a vector expression. So far, I do this.
My base vector expression template is implemented like this
template <typename E>
class VectorExpr {
public:
  int size() const { return static_cast<E const&>(*this).size(); }

  float operator[](int i) const { return static_cast<E const&>(*this)[i]; }

  operator E& () { return static_cast<E&>(*this); }

  operator E const& () const { return static_cast<const E&>(*this); }
}; // class VectorExpr

Then, an object supposed to be a vector will look like this
class Vector2 : public VectorExpr<Vector2> {
public:
    inline size_t size() const { return 2; }

    template <typename E>
    inline Vector2(VectorExpr<E> const& inExpr) {
    E const& u = inExpr;
    for(int i = 0; i < size(); ++i)
        mTuple[i] = u[i];
   }

private:
   float mTuple[2];
};

Let's say I want to apply std::sin to all elements of an expression
template <typename E>
class VectorSin : public VectorExpr<VectorSin<E> > {
    E const& mV;

public:
    VectorSin(VectorExpr<E> const& inV) : mV(inV) {}

    int size() const { return mV.size(); }

    float operator [] (int i) const { return std::sin(mV[i]); }
};

Question => If I want to add more functions, I copy-paste what I do for the sin function, for every single function (like cos, sqrt, fabs, and so on). How I can avoid this kind of copy-pasting ? I tried things and figured out I'm still low in template-fu. No boost allowed ^^

A: template <typename F, typename E>
class VectorFunc : public VectorExpr<VectorFunc<F, E> > {
    E const& mV;

public:
    VectorSin(VectorExpr<E> const& inV) : mV(inV) {}

    int size() const { return mV.size(); }

    float operator [] (int i) const { return f(mV[i]); }

    // this assumes the Functor f is default constructible, this is
    // already not true for &std::sin. Adding the constructor that
    // takes f, is left as an exercise ;)
    F f;
};

A: In addition to the answer by pmr, The standard <cmath> functions aren't functors, so you couldn't use them directly to specify unique specialisations of your class - i.e. you wouldn't have a separate template instantiation for std::sin versus std::cos (which is what I gather you're aiming for?  correct me if I've misunderstood you on that).
You could create a wrapper in order to map a function pointer to a distinct type, e.g.
#include <iostream>

template< void (*FuncPtr)() > struct Func2Type
{
    void operator() () { FuncPtr(); }
};

void Hello() { std::cout << "Hello" << std::endl; }
void World() { std::cout << "world" << std::endl; }

int main()
{
    Func2Type<Hello> test1;
    Func2Type<World> test2;
    test1();
    test2();
}

That way you could use them as template arguments in the same way as a normal functor class


text:
Q: Markdown, How do I output raw backtick escapes? I want to output the raw backtick escapes.
I want like this :
`  <---  A backtick escapes

A: Use \` if you are outside inlined code (in a normal paragraph): \` = `
If you want to use it in inlined code, use double backticks for inlining the section (instead of a single backtick): Getting a backtick ` inside inlined code.
If inside a code block (with four spaces at the beggining of the line), you don't have to escape it at all:
This is a code block and I can write `single backticks`


text:
Q: How to hide/unhide rows based on cell value, multiple times in 1 sheet When the value in B16 is "0", I need to hide some other rows, and also un-hide them when the value is "1".
But, here's my issue:
Also, in the same sheet:
If the value in H4 is "0", I need to hide some rows. When the value is "1", I need to un-hide these rows.
The first part is working:
Private Sub Worksheet_Change(ByVal Target As Range)
With Sheets("Checklist")

If Range("b16").Value = 0 Then rows("17:21").EntireRow.Hidden = True
If Range("b16").Value >= 1 Then rows("17:21").EntireRow.Hidden = False

End With
End Sub

And here's where I understand I suck at VB
In other words, the code below is clearly not working. Can you please provide a working alternative?
Private Sub Worksheet_Change(ByVal Target As Range)
With Sheets("Checklist")

Select Case Taget.Address

Case "$b$16"
If IsNumeric(Target.Value) And Target.Value = 0 Then
rows("17:21").EntireRow.Hidden = True
End If

Case "$b$16"
If IsNumeric(Target.Value) And Target.Value = 0 Then
rows("17:21").EntireRow.Hidden = False
End If

Case "$h$4"
If IsNumeric(Target.Value) And Target.Value = 1 Then
rows("23:26").EntireRow.Hidden = True
End If

Case "$h$4"
If IsNumeric(Target.Value) And Target.Value = 1 Then
rows("23:26").EntireRow.Hidden = False
End If

End Select
End Sub

Thanks.


text:
Q: Android throwing up Error using jtwitter I am trying to write a twitter application on Android target 2.2 (using some sample code that I found on the net and using Marko Gargenta's O'Reilly text). I am stuck with the problem as in the log below. The source code is given first followed by the log. Any idea what's going wrong here ? Also does anyone have or can point to a sample jtwitter code working on Android.
Thanks,
Ravi

protected String doInBackground(String... statuses) {
  try {

         //Autho information
         /*OAuthSignpostClient oauthclient = new OAuthSignpostClient(cons_key,
           cons_secret, access_token, access_secret);*/

         OAuthSignpostClient oauthclient = new OAuthSignpostClient(access_token, access_secret,"oob");

         //***POSTING TO TWITTER CURRENTLY DOES NOT WORK WITH THIS INTERFACE
         twitter = new Twitter(mytwitterusername, oauthclient);
         //twitter.setAPIRootUrl("http://learningandroid.status.net/api");

   //***POSTING TO TWITTER CURRENTLY DOES NOT WORK WITH THIS INTERFACE
   Log.i(Logtag, "Status currently is " + statuses[0]);

   Twitter.Status status = twitter.updateStatus(statuses[0]);
   //return status.text;
   return statuses[0];
  } catch (TwitterException e) {
   Log.e(Logtag, e.toString());
   e.printStackTrace();
   return "Failed to post to Twitter";
  }

}

Log file:
E/dalvikvm(  719): Could not find method javax.swing.JOptionPane.showInputDialog, referenced from method winterwell.jtwi
tter.OAuthSignpostClient.askUser
W/dalvikvm(  719): VFY: unable to resolve static method 443: Ljavax/swing/JOptionPane;.showInputDialog (Ljava/lang/Objec
t;)Ljava/lang/String;
W/dalvikvm(  719): VFY:  rejecting opcode 0x71 at 0x0000
W/dalvikvm(  719): VFY:  rejected Lwinterwell/jtwitter/OAuthSignpostClient;.askUser (Ljava/lang/String;)Ljava/lang/Strin
g;
W/dalvikvm(  719): Verifier rejected class Lwinterwell/jtwitter/OAuthSignpostClient;
W/dalvikvm(  719): threadid=17: thread exiting with uncaught exception (group=0x4000fe70)
E/AndroidRuntime(  719): Uncaught handler: thread AsyncTask #1 exiting due to uncaught exception
E/AndroidRuntime(  719): java.lang.RuntimeException: An error occured while executing doInBackground()
E/AndroidRuntime(  719):        at android.os.AsyncTask$3.done(AsyncTask.java:200)
E/AndroidRuntime(  719):        at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:234)
E/AndroidRuntime(  719):        at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:258)
E/AndroidRuntime(  719):        at java.util.concurrent.FutureTask.run(FutureTask.java:122)
E/AndroidRuntime(  719):        at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:648)
E/AndroidRuntime(  719):        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:673)
E/AndroidRuntime(  719):        at java.lang.Thread.run(Thread.java:1058)
E/AndroidRuntime(  719): Caused by: java.lang.VerifyError: winterwell.jtwitter.OAuthSignpostClient
E/AndroidRuntime(  719):        at com.ravi.tweeto.StatusActivity$PostToTwitter.doInBackground(StatusActivity.java:81)
E/AndroidRuntime(  719):        at com.ravi.tweeto.StatusActivity$PostToTwitter.doInBackground(StatusActivity.java:1)
E/AndroidRuntime(  719):        at android.os.AsyncTask$2.call(AsyncTask.java:185)
E/AndroidRuntime(  719):        at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:256)
E/AndroidRuntime(  719):        ... 4 more
I/Process (  585): Sending signal. PID: 719 SIG: 3
I/dalvikvm(  719): threadid=7: reacting to signal 3
I/dalvikvm(  719): Wrote stack trace to '/data/anr/traces.txt'
----

A: Basically the JTwitter library has calls to Java swing classes that are not in the Android SDK as it does not use swing.  I had to get the source for JTwitter and remove the swing code for my application to work.  Hope this helps.

A: I found most of the code I use somewhere on GitHub (can't find the exact link right now)
A few searches on snippets of the code send me here, but I don't think that was the exact site I got it from.
But this is what I have in my semi-working code.
OAUTH.java

import junit.framework.Assert;
import oauth.signpost.OAuth;
import oauth.signpost.OAuthConsumer;
import oauth.signpost.OAuthProvider;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthProvider;
import oauth.signpost.exception.OAuthCommunicationException;
import oauth.signpost.exception.OAuthExpectationFailedException;
import oauth.signpost.exception.OAuthMessageSignerException;
import oauth.signpost.exception.OAuthNotAuthorizedException;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;

public class OAUTH extends Activity {
private static final String TAG = "OAUTH";

public static final String USER_TOKEN = "user_token";
public static final String USER_SECRET = "user_secret";
public static final String REQUEST_TOKEN = "request_token";
public static final String REQUEST_SECRET = "request_secret";

public static final String TWITTER_REQUEST_TOKEN_URL = "http://twitter.com/oauth/request_token";
public static final String TWITTER_ACCESS_TOKEN_URL = "http://twitter.com/oauth/access_token";
public static final String TWITTER_AUTHORIZE_URL = "http://twitter.com/oauth/authorize";

private static final Uri CALLBACK_URI = Uri.parse("gpsagenda://twitt");

public static final String PREFS = "MyPrefsFile";

private OAuthConsumer mConsumer = null;
private OAuthProvider mProvider = null;

SharedPreferences mSettings;

public void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    // We don't need to worry about any saved states: we can reconstruct the state
    mConsumer = new CommonsHttpOAuthConsumer(
            "myKey",
            "mySecret");

    mProvider = new CommonsHttpOAuthProvider (
            TWITTER_REQUEST_TOKEN_URL,
            TWITTER_ACCESS_TOKEN_URL,
            TWITTER_AUTHORIZE_URL);

    // It turns out this was the missing thing to making standard Activity launch mode work
    mProvider.setOAuth10a(true);

    mSettings = this.getSharedPreferences(PREFS, Context.MODE_PRIVATE);

    Intent i = this.getIntent();
    if (i.getData() == null) {
        try {
                            // This is really important. If you were able to register your real callback Uri with Twitter, and not some fake Uri
                            // like I registered when I wrote this example, you need to send null as the callback Uri in this function call. Then
                            // Twitter will correctly process your callback redirection
            String authUrl = mProvider.retrieveRequestToken(mConsumer, CALLBACK_URI.toString());
            saveRequestInformation(mSettings, mConsumer.getToken(), mConsumer.getTokenSecret());
            this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));
        } catch (OAuthMessageSignerException e) {
            e.printStackTrace();
        } catch (OAuthNotAuthorizedException e) {
            e.printStackTrace();
        } catch (OAuthExpectationFailedException e) {
            e.printStackTrace();
        } catch (OAuthCommunicationException e) {
            e.printStackTrace();
        }
    }
}

@Override
protected void onResume() {
    super.onResume();

    Uri uri = getIntent().getData();
    if (uri != null && CALLBACK_URI.getScheme().equals(uri.getScheme())) {
        String token = mSettings.getString(OAUTH.REQUEST_TOKEN, null);
        String secret = mSettings.getString(OAUTH.REQUEST_SECRET, null);
        Intent i = new Intent(this, DetailsContainer.class); // Currently, how we get back to main activity.

        try {
            if(!(token == null || secret == null)) {
                mConsumer.setTokenWithSecret(token, secret);
            }
            String otoken = uri.getQueryParameter(OAuth.OAUTH_TOKEN);
            String verifier = uri.getQueryParameter(OAuth.OAUTH_VERIFIER);

            // We send out and save the request token, but the secret is not the same as the verifier
            // Apparently, the verifier is decoded to get the secret, which is then compared - crafty
            // This is a sanity check which should never fail - hence the assertion
            Assert.assertEquals(otoken, mConsumer.getToken());

            // This is the moment of truth - we could throw here
            mProvider.retrieveAccessToken(mConsumer, verifier);
            // Now we can retrieve the goodies
            token = mConsumer.getToken();
            secret = mConsumer.getTokenSecret();
            OAUTH.saveAuthInformation(mSettings, token, secret);
            // Clear the request stuff, now that we have the real thing
            OAUTH.saveRequestInformation(mSettings, null, null);
            i.putExtra(USER_TOKEN, token);
            i.putExtra(USER_SECRET, secret);
        } catch (OAuthMessageSignerException e) {
            e.printStackTrace();
        } catch (OAuthNotAuthorizedException e) {
            e.printStackTrace();
        } catch (OAuthExpectationFailedException e) {
            e.printStackTrace();
        } catch (OAuthCommunicationException e) {
            e.printStackTrace();
        } finally {
            startActivity(i); // we either authenticated and have the extras or not, but we're going back
            finish();
        }
    }
}

public static void saveRequestInformation(SharedPreferences settings, String token, String secret) {
    // null means to clear the old values
    SharedPreferences.Editor editor = settings.edit();
    if(token == null) {
        editor.remove(OAUTH.REQUEST_TOKEN);
        Log.d(TAG, "Clearing Request Token");
    }
    else {
        editor.putString(OAUTH.REQUEST_TOKEN, token);
        Log.d(TAG, "Saving Request Token: " + token);
    }
    if (secret == null) {
        editor.remove(OAUTH.REQUEST_SECRET);
        Log.d(TAG, "Clearing Request Secret");
    }
    else {
        editor.putString(OAUTH.REQUEST_SECRET, secret);
        Log.d(TAG, "Saving Request Secret: " + secret);
    }
    editor.commit();

}

public static void saveAuthInformation(SharedPreferences settings, String token, String secret) {
    // null means to clear the old values
    SharedPreferences.Editor editor = settings.edit();
    if(token == null) {
        editor.remove(OAUTH.USER_TOKEN);
        Log.d(TAG, "Clearing OAuth Token");
    }
    else {
        editor.putString(OAUTH.USER_TOKEN, token);
        Log.d(TAG, "Saving OAuth Token: " + token);
    }
    if (secret == null) {
        editor.remove(OAUTH.USER_SECRET);
        Log.d(TAG, "Clearing OAuth Secret");
    }
    else {
        editor.putString(OAUTH.USER_SECRET, secret);
        Log.d(TAG, "Saving OAuth Secret: " + secret);
    }
    editor.commit();

}

}

DetailsTwitter.java (my "implementation")

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.LinkedList;

import oauth.signpost.OAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.exception.OAuthCommunicationException;
import oauth.signpost.exception.OAuthExpectationFailedException;
import oauth.signpost.exception.OAuthMessageSignerException;

import org.apache.http.HttpVersion;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.gpsagenda.OAUTH;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class DetailsTwitter extends Activity {

    public SharedPreferences mSettings;

    private LinkedList<UserStatus> mHomeStatus = new LinkedList<UserStatus>();
    public String mToken;
    public String mSecret;
    private OAuthConsumer mConsumer = null;
    private HttpClient mClient;
    private EditText mEditor;
    private TextView mLast;
    private CheckBox mCB;
    private Button mButton;
    private TextView mUser;
    private int ID;

    public static final String VERIFY_URL_STRING = "http://twitter.com/account/verify_credentials.json";
    public static final String PUBLIC_TIMELINE_URL_STRING = "http://twitter.com/statuses/public_timeline.json";
    public static final String USER_TIMELINE_URL_STRING = "http://twitter.com/statuses/user_timeline.json";
    public static final String HOME_TIMELINE_URL_STRING = "http://api.twitter.com/1/statuses/home_timeline.json";
    public static final String FRIENDS_TIMELINE_URL_STRING = "http://api.twitter.com/1/statuses/friends_timeline.json";
    public static final String STATUSES_URL_STRING = "http://twitter.com/statuses/update.json";

    ProgressDialog postDialog = null;

    public static final String TWITTER_REQUEST_TOKEN_URL = "http://twitter.com/oauth/request_token";
    public static final String TWITTER_ACCESS_TOKEN_URL = "http://twitter.com/oauth/access_token";
    public static final String TWITTER_AUTHORIZE_URL = "http://twitter.com/oauth/authorize";

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.detailstwittertab);

        HttpParams parameters = new BasicHttpParams();
        HttpProtocolParams.setVersion(parameters, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(parameters, HTTP.DEFAULT_CONTENT_CHARSET);
        HttpProtocolParams.setUseExpectContinue(parameters, false);
        HttpConnectionParams.setTcpNoDelay(parameters, true);
        HttpConnectionParams.setSocketBufferSize(parameters, 8192);

        SchemeRegistry schReg = new SchemeRegistry();
        schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        ClientConnectionManager tsccm = new ThreadSafeClientConnManager(parameters, schReg);
        mClient = new DefaultHttpClient(tsccm, parameters);

        mCB = (CheckBox) this.findViewById(R.id.enable);
        mCB.setChecked(false);
        mEditor = (EditText) this.findViewById(R.id.editor);
        mButton = (Button) this.findViewById(R.id.post);
        mUser = (TextView) this.findViewById(R.id.user);
        mLast = (TextView) this.findViewById(R.id.last);

        mSettings = getSharedPreferences(OAUTH.PREFS, Context.MODE_PRIVATE);
        mConsumer = new CommonsHttpOAuthConsumer(
            "myKey",
            "mySecret");
    }

    public void PostTweet(View v) {
        String postString = mEditor.getText().toString();
        if (postString.length() == 0) {
            Toast.makeText(this, getText(R.string.tweet_empty), Toast.LENGTH_SHORT).show();
        } else {
            BitlyAndroid bitly = new BitlyAndroid("iarwain01", "R_1bffd0176aa731a27e5b2d23cf043199");
            String shortUrl = "";
            // Try to get the corresponding ID of the POI
           try
           {
               ID = getIntent().getExtras().getInt("id");
           } catch (NullPointerException e)
           {
               e.printStackTrace();
           }
            try {
                shortUrl = bitly.getShortUrl("http://gpsagenda.ikdoeict.be/projecten2/index.php?module=places&id=" + ID);
            } catch (Exception e) {
                Log.e("Debug", "Link shortening failed!");
                e.printStackTrace();
            }

            new PostTask().execute(postString + " " + shortUrl);
        }
    }

    protected void onFinish() {
        mClient.getConnectionManager().shutdown();
    }

    public void ConnectWithTwitter(View v)
    {
        if(mCB.isChecked()) {
            Intent i = new Intent(this, OAUTH.class);
            startActivity(i);
        } else {
            OAUTH.saveAuthInformation(mSettings, null, null);
            mButton.setEnabled(false);
            mEditor.setEnabled(false);
            mCB.setChecked(false);
            mUser.setText("");
        }
        mCB.setChecked(false); // the oauth callback will set it to the proper state
    }

    @Override
    public void onResume()
    {
        super.onResume();

        // We look for saved user keys
        if(mSettings.contains(OAUTH.USER_TOKEN) && mSettings.contains(OAUTH.USER_SECRET)) {
            mToken = mSettings.getString(OAUTH.USER_TOKEN, null);
            mSecret = mSettings.getString(OAUTH.USER_SECRET, null);
            if(!(mToken == null || mSecret == null)) {
                mConsumer.setTokenWithSecret(mToken, mSecret);
            }
        }
        new GetCredentialsTask().execute();
    }

    // These parameters are needed to talk to the messaging service
    public HttpParams getParams() {
        // Tweak further as needed for your app
        HttpParams params = new BasicHttpParams();
        // set this to false, or else you'll get an Expectation Failed: error
        HttpProtocolParams.setUseExpectContinue(params, false);

        return params;
    }

    //----------------------------
    // This task posts a message to your message queue on the service.
    private class PostTask extends AsyncTask<String, Void, JSONObject> {

        ProgressDialog postDialog;

        @Override
        protected void onPreExecute() {
            postDialog = ProgressDialog.show(DetailsTwitter.this,
                    getText(R.string.tweet_progress_title),
                    getText(R.string.tweet_progress_text),
                    true,   // indeterminate duration
                    false); // not cancel-able
        }

        @Override
        protected JSONObject doInBackground(String... params) {

            JSONObject jso = null;
            try {
                HttpPost post = new HttpPost("http://twitter.com/statuses/update.json");
                LinkedList<BasicNameValuePair> out = new LinkedList<BasicNameValuePair>();
                out.add(new BasicNameValuePair("status", params[0]));
                post.setEntity(new UrlEncodedFormEntity(out, HTTP.UTF_8));
                post.setParams(getParams());
                // sign the request to authenticate
                mConsumer.sign(post);
                String response = mClient.execute(post, new BasicResponseHandler());
                jso = new JSONObject(response);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (OAuthMessageSignerException e) {
                e.printStackTrace();
            } catch (OAuthExpectationFailedException e) {
                e.printStackTrace();
            } catch (OAuthCommunicationException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            } finally {

            }
            return jso;
        }

        // This is in the UI thread, so we can mess with the UI
        protected void onPostExecute(JSONObject jso) {
            postDialog.dismiss();
            if(jso != null) { // authorization succeeded, the json object contains the user information
                mEditor.setText("");
                mLast.setText(getCurrentTweet(jso));
            } else {
                mLast.setText(getText(R.string.tweet_error));
            }
        }
    }

    // Get stuff from the two types of Twitter JSONObject we deal with: credentials and status
    private String getCurrentTweet(JSONObject status) {
        return status.optString("text", getString(R.string.bad_value));
    }

    //----------------------------
    // This task is run on every onResume(), to make sure the current credentials are valid.
    // This is probably overkill for a non-educational program
    private class GetCredentialsTask extends AsyncTask<Void, Void, JSONObject> {

        ProgressDialog authDialog;

        @Override
        protected void onPreExecute() {
            authDialog = ProgressDialog.show(DetailsTwitter.this,
                getText(R.string.auth_progress_title),
                getText(R.string.auth_progress_text),
                true,   // indeterminate duration
                false); // not cancel-able
        }

        @Override
        protected JSONObject doInBackground(Void... arg0) {
            JSONObject jso = null;
            HttpGet get = new HttpGet(VERIFY_URL_STRING);
            try {
                mConsumer.sign(get);
                String response = mClient.execute(get, new BasicResponseHandler());
                jso = new JSONObject(response);
            } catch (OAuthMessageSignerException e) {
                e.printStackTrace();
            } catch (OAuthExpectationFailedException e) {
                e.printStackTrace();
            } catch (OAuthCommunicationException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return jso;
        }

        // This is in the UI thread, so we can mess with the UI
        protected void onPostExecute(JSONObject jso) {
            authDialog.dismiss();
            mCB.setChecked(jso != null);
            mButton.setEnabled(jso != null);
            mEditor.setEnabled(jso != null);
            mUser.setText(jso != null ? getUserName(jso) : getString(R.string.userhint));
            mLast.setText(jso != null ? getLastTweet(jso) : getString(R.string.userhint));
            if(jso != null) {
                TimelineSelector ss = new TimelineSelector(HOME_TIMELINE_URL_STRING);
                new GetTimelineTask().execute(ss);
            }
        }
    }

    private String getLastTweet(JSONObject credentials) {
        try {
            JSONObject status = credentials.getJSONObject("status");
            return getCurrentTweet(status);
        } catch (JSONException e) {
            e.printStackTrace();
            return getString(R.string.tweet_error);
        }
    }

    private String getUserName(JSONObject credentials) {
        return credentials.optString("name", getString(R.string.bad_value));
    }

    private class TimelineSelector extends Object {
        public String url; // the url to perform the query from
        // not all these apply to every url - you are responsible
        public Long since_id; // ids newer than this will be fetched
        public Long max_id; // ids older than this will be fetched
        public Integer count; // # of tweets to fetch Max is 200
        public Integer page; // # of page to fetch (with limits)

        public TimelineSelector(String u) {
            url = u;
            max_id = null;
            since_id = null;
            count = null;
            page = null;
        }

        @SuppressWarnings("unused")
        public TimelineSelector(String u, Long since, Long max, Integer cnt, Integer pg) {
            url = u;
            max_id = max;
            since_id = since;
            count = cnt;
            page = pg;
        }
    }

    private class UserStatus {

        JSONObject mStatus;
        @SuppressWarnings("unused")
        JSONObject mUser;

        public UserStatus(JSONObject status) throws JSONException {

            mStatus = status;
            mUser = status.getJSONObject("user");
        }
        @SuppressWarnings("unused")
        public long getId() {
            return mStatus.optLong("id", -1);
        }
        /*public String getUserName() {
            return mUser.optString("name", getString(R.string.bad_value));
        }
        public String getText() {
            return getCurrentTweet(mStatus);
        }
        public String getCreatedAt() {
            @SuppressWarnings("unused")
            Time ret1 = new Time();
            return mStatus.optString("created_at", getString(R.string.bad_value));
        }*/
    }

    private class GetTimelineTask extends AsyncTask<TimelineSelector, Void, JSONArray> {

        @Override
        protected JSONArray doInBackground(TimelineSelector... params) {
            JSONArray array = null;
            try {
                for(int i = 0; i < params.length; ++i) {
                    Uri sUri = Uri.parse(params[i].url);
                    Uri.Builder builder = sUri.buildUpon();
                    if(params[i].since_id != null) {
                        builder.appendQueryParameter("since_id", String.valueOf(params[i].since_id));
                    } else if (params[i].max_id != null) { // these are mutually exclusive
                        builder.appendQueryParameter("max_id", String.valueOf(params[i].max_id));
                    }
                    if(params[i].count != null) {
                        builder.appendQueryParameter("count", String.valueOf((params[i].count > 200) ? 200 : params[i].count));
                    }
                    if(params[i].page != null) {
                        builder.appendQueryParameter("page", String.valueOf(params[i].page));
                    }
                    HttpGet get = new HttpGet(builder.build().toString());
                    mConsumer.sign(get);
                    String response = mClient.execute(get, new BasicResponseHandler());
                    array = new JSONArray(response);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            } catch (OAuthMessageSignerException e) {
                e.printStackTrace();
            } catch (OAuthExpectationFailedException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (OAuthCommunicationException e) {
                e.printStackTrace();
            }
            return array;
        }

        // This is in the UI thread, so we can mess with the UI
        protected void onPostExecute(JSONArray array) {
            if(array != null) {
                try {
                    for(int i = 0; i < array.length(); ++i) {
                        JSONObject status = array.getJSONObject(i);
                        UserStatus s = new UserStatus(status);
                        mHomeStatus.add(s);
                    }
                    //mAA.notifyDataSetChanged();

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
            }
        }
    }
}

My AndroidManifest.xml

    <activity android:name="DetailsTwitter" />
    <activity android:name="OAUTH" >
        <intent-filter>
            <action android:name="android.intent.action.VIEW"></action>
            <category android:name="android.intent.category.DEFAULT"></category>
            <category android:name="android.intent.category.BROWSABLE"></category>
            <data android:scheme="gpsagenda" android:host="twitt" />
        </intent-filter>
    </activity>

This should be enough to get you going, I hope.
If something is wrong in here, pleas do comment.
Regards,
iarwain

A: Might be worth looking at using the Twitter4J library as an alternative. I've had no issues using it within an Android application.


text:
Q: How to make "Edit Links" visible again As part of our Sharepoint rebranding project, the 3rd party which was doing our template changes, made the edit link option invisible . Now as the site collection admin I am wondering how am I going to simply edit the top navigation links. I tried created a subsite which is not inheriting permission from the parent site but it the same.
I know this script might been used to hide the edit link , but is there any way to change it ( at least for a subsite to be able to see the option? )
< style>
  .ms-displayInlineBlock{
     display: none;
  }
< /style>

Thank you!
Aysan

A: It seems likely that the problem you are encountering is caused by your site being a publishing site.  Once you enable the publishing feature, the method for editing the Quick Launch changes.  You probably don't want to disable this feature because it will change other behaviors as well. Here's how to edit the links on either:

*

*On non-publishing sites, you can modify the Quick Launch via Edit Links or Site Settings -> Look and Feel -> Quick Launch

*On publishing sites, it is Settings -> Look and Feel -> Navigation (there is no shortcut to it like Edit Links on non-publishing sites)

The interface is a bit different for publishing sites too, because you modify both the Top Link Bar and the Quick Launch on the same page.

A: The workaround I found was to create a subsite with unique permission and different site template from the parent site, then I was able to see the "edit link" option again


text:
Q: Closing Wizard on button click in OpenERP 7 I open the wizard from button in OpenERP 7. But when click on button Compute of wizard my wizard got close but I do not want to close the wizard on button click of Compute instead of my wizard close when click on button Close of wizard.
I am using OpenERP 7.
class test_pass_student(osv.osv_memory):
    _name = 'test.pass.student'
    _column ={
        'pass_id': fields.many2one('pass.student', 'Passed'),
        'student_id':fields.many2one('student.student', 'Student'),
    }

test_pass_student()

def _reopen(self, res_id, model):
    return {'type': 'ir.actions.act_window',
            'view_mode': 'form',
            'view_type': 'form',
            'res_id': res_id,
            'res_model': self._name,
            'target': 'new',
            'context': {
                'default_model': model,
            },
    }

class pass_student(osv.osv_memory):
    _name = 'pass.student'

    _columns = {
        'student_id':fields.many2one('student.student', 'Student'),
        'lines': fields.one2many('test.pass.student','pass_id', 'Passed students'),
    }

    def add_student(self, cr, uid, ids,context=None):
        lines_obj = self.pool.get('test.pass.student')
        for record in self.browse(cr,uid,ids,context):
            for line in record.student_id.scores:
                    if line.pass_score > 50:
                        lines_obj.create(cr,uid,{'pass_id': record.id,'student_id':line.student_id.id})

            return _reopen(self, record.id, record._model)

pass_student()

Shen S select first student check, if his/her marks greater than 50 then added in one2many, and then again check another student, same things repeat again.

A: The default behavior for wizard buttons (with type="object) as of OpenERP 6.1 (hence in 7.0 as well) is to immediately close the wizard pop-up. The method called by the button can return an action definition dictionary that will be executed.
When you do not want the wizard to close it is usually because you have several steps. As multi-steps wizards usually have different form views, their button methods simply return actions to open the same wizard record using the next step's view (it could also be the same view if it needs to be displayed again).
You can find examples in the official addons source code, for example in the mail.compose.message wizard modified by the email_template module, that uses a similar trick to re-open itself.
This question and this other one may also contain useful examples.

A: For closing the wizard on button click add this code on view form xml:
<button string="Cancel" class="oe_link" special="cancel"/>

A: no need to write separate method to open wizard again. You can just take object reference and return it with view id. for example.
def add_student(self, cr, uid, ids,context=None):
    model_data_obj = self.pool.get('ir.model.data')
    lines_obj = self.pool.get('test.pass.student')
    for record in self.browse(cr,uid,ids,context):
        for line in record.student_id.scores:
                if line.pass_score > 50:
                    lines_obj.create(cr,uid,{'pass_id': record.id,'student_id':line.student_id.id})
    view_rec = model_data_obj.get_object_reference(cr, uid, 'pass_student', 'add_student_form_view_id')
    view_id = view_rec and view_rec[1] or False
    return {
       'view_type': 'form',
       'view_id' : [view_id],
       'view_mode': 'form',
       'res_model': 'pass.student',
       'type': 'ir.actions.act_window',
       'target': 'new',
       'context': context
    }

Hope it will help you!

A: I reply myself, in the wizard if, instead of button type workflow, I put button type object and there trigger wf works (no close), but is that the right path?
If someone need this is my object button event code (for my picking.import.wizard wizard):
def signal_import_load_2(self, cr, uid, ids, context=None):
    import netsvc

    wf_service = netsvc.LocalService("workflow")
    wf_service.trg_validate(uid, 'picking.import.wizard', ids[0], 'signal_import_load', cr)

    view_id = self.pool.get('ir.ui.view').search(cr,uid,[('model','=','picking.import.wizard'), ('name','=','Wizard import picking from CSV')])

    return {
         'type': 'ir.actions.act_window',
         'name': "Import",
         'res_model': 'picking.import.wizard',
         'res_id': ids[0],
         'view_type': 'form',
         'view_mode': 'form',
         'view_id': view_id,
         'target': 'new',
         'nodestroy': True,
           }


text:
Q: Como ocultar duas DIVs uma dentro da outra com JavaScript? estou enfrentando um problema ao tentar ocultar duas DIV´s, ou seja, uma dentro da outra. Apenas consigo ocultar uma DIV a outra fica visível.
Segue o que estou utilizando:
Java Script:

CSS:
#guaraparivirtualsuperpopup {
    position:relative;
    width:1215px;
    height:500px;
    background-color:#000000;
    /* background-image:url(http://www.guaraparivirtual.com.br/Lay_Out/dr-bruno.jpg);
    background-repeat:no-repeat;
    background-position:50% 50%;
    */
    margin: 0 auto;
    z-index: 9;
    border: 1px solid #EA8419;
}
#guaraparivirtualsuperpopupbtn {
    width:100px;
    height:36px;
    background-image:url(http://www.guaraparivirtual.com.br/img-novo/fechar.png);
    background-repeat:no-repeat;
    float:right;
    position: relative;
    z-index: 9999;
}

DIV´s

<a href="<?php echo $linkbannerrt; ?>" target="_blank" title="Super Pop-Up" / >
<div id="guaraparivirtualsuperpopup" style="background-image:url(superpopup/<?php echo $rt; ?>);">

A: Obs: getComputedStyle(el) vai retornar os estilos atuais do elemento, o que torna melhor de obter o display do elemento.

O problema é porque você está declarando "#guaraparivirtualsuperpopupbtn" e + elementos fora da div "#guaraparivirtualsuperpopup". Seu código precisa de uma nova estrutura para encaixar todos aqueles itens fora da div principal. Na verdade isso não é um problema, mas nada está acontecendo com os elementos fora da div principal. Sua div principal está sendo tratada como filha.


text:
Q: Python class cannot open file when object is created from directory below I have a app.py file which is using a custom class which I created one level below, ie.
from myfolder import util_file

def get_data():

    dataContainer = util_file.MyDataContainer()
    # do more stuff

One folder down my util_file I create MyDataContainer as a class that uses data from two local files to instantiate itself. ie.
class MyDataContainer:

    def __init__(self):
        with open('file1.txt', 'r'):
            #get needed init data part 1
        #repeat operation with data in file2.txt

The object is created fine when I run from the file itself, ie.
if __name__ == '__main__':
    testcont = MyDataContainer()

The issue is that when I run the code in app.py I get:
FileNotFoundError: [Errno 2] No such file or directory: 'file1.txt'
thrown at the line
with open('file1.txt', 'r'):

I am guessing that python is unable to see the file1.txt and file2.txt since it is in another directory at runtime but I checked the my path and the subfolder is in sys.path at runtime, so I believe these should be visible. I really do not understand what is going on here. Is there a different reason python is unable to see these files?


text:
Q: Solve the integral $\int_{0}^{\pi}e^{\cos^{2}x}\cos\left\{ \left(2n+1\right)x\right\} dx$ Question For any integer $n$, solve the integral $\int_{0}^{\pi}e^{\cos^{2}x}\cos\left\{ \left(2n+1\right)x\right\}\, dx$
My Approach I don't know how to approach .Please give me Hints


text:
Q: Android-linear layout arrangement varies in emulator and device I am developing project with 26 cards design alphabets in linear layout fashion in android. I had included android:adjustViewBounds="true" and android:scaleType="centercrop".
Forunately it works well in emulator and does not show up in the real device. What would be the issue to make it work as well in device? Could you assist me regarding this? Below is the piece of code working in emulator not in device.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".Linear_layout_equal" >

<ScrollView
            android:id="@+id/scrollView1"
            android:layout_width="match_parent"
            android:layout_height="fill_parent" >
 <LinearLayout
     android:id="@+id/NumberPad"
     android:layout_width="match_parent"
     android:layout_height="0dp"
     android:layout_weight="1"
     android:gravity="center"
     android:orientation="vertical">

     <LinearLayout
         android:id="@+id/NumberRow123"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:orientation="horizontal"
         android:gravity="center" >

         <ImageView
             android:id="@+id/button1"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_weight="1"
             android:adjustViewBounds="true"
             android:src="@drawable/lettera"
             android:layout_margin="5dp"
             android:scaleType="centerCrop"/>

         <ImageView
             android:id="@+id/button2"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_margin="5dp"
             android:layout_weight="1"
             android:adjustViewBounds="true"
             android:src="@drawable/letterb"
             android:scaleType="centerCrop"/>

         <ImageView
             android:id="@+id/button3"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_weight="1"
             android:adjustViewBounds="true"
             android:src="@drawable/letterc"
             android:layout_margin="5dp"
             android:scaleType="centerCrop"/>

         <ImageView
             android:id="@+id/button4"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_weight="1"
             android:adjustViewBounds="true"
             android:src="@drawable/lettere"
             android:layout_margin="5dp"
             android:scaleType="centerCrop"/>
     </LinearLayout>

     <LinearLayout
         android:id="@+id/NumerRow456"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:orientation="horizontal"
         android:gravity="center" >

         <ImageView
             android:id="@+id/button4"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_weight="1"
             android:adjustViewBounds="true"
             android:src="@drawable/lettere"
             android:layout_margin="5dp"
             android:scaleType="centerCrop"/>

         <ImageView
             android:id="@+id/button5"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_weight="1"
             android:adjustViewBounds="true"
             android:src="@drawable/letterf"
             android:layout_margin="5dp"
             android:scaleType="centerCrop"/>

         <ImageView
             android:id="@+id/button6"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_weight="1"
             android:adjustViewBounds="true"
             android:src="@drawable/letterg"
             android:layout_margin="5dp"
             android:scaleType="centerCrop"/>

         <ImageView
             android:id="@+id/button9"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_weight="1"
             android:src="@drawable/letterh"
             android:adjustViewBounds="true"
             android:layout_margin="5dp"
             android:scaleType="centerCrop"/>
     </LinearLayout>

     <LinearLayout
         android:id="@+id/NumerRow456"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:orientation="horizontal"
         android:gravity="center">

         <ImageView
             android:id="@+id/button9"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_weight="1"
             android:adjustViewBounds="true"
             android:layout_margin="5dp"
             android:scaleType="centerCrop"
             android:src="@drawable/letteri"/>

         <ImageView
             android:id="@+id/button5"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_weight="1"
             android:src="@drawable/letterj"
             android:adjustViewBounds="true"
             android:layout_margin="5dp"
             android:scaleType="centerCrop"/>

         <ImageView
             android:id="@+id/button6"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_weight="1"
             android:src="@drawable/letterk"
             android:adjustViewBounds="true"
             android:layout_margin="5dp"
             android:scaleType="centerCrop"/>

         <ImageView
             android:id="@+id/button9"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_weight="1"
             android:src="@drawable/letterl"
             android:adjustViewBounds="true"
             android:layout_margin="5dp"
             android:scaleType="centerCrop"/>
     </LinearLayout>
     <LinearLayout
         android:id="@+id/NumerRow456"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:orientation="horizontal"
         android:gravity="center">

         <ImageView
             android:id="@+id/button9"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_weight="1"
             android:src="@drawable/letterm"
             android:scaleType="centerCrop"
             android:adjustViewBounds="true"
             android:layout_margin="5dp" />

         <ImageView
             android:id="@+id/button5"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_weight="1"
             android:src="@drawable/lettern"
             android:adjustViewBounds="true"
             android:layout_margin="5dp"
             android:scaleType="centerCrop"/>

         <ImageView
             android:id="@+id/button6"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_weight="1"
             android:src="@drawable/lettero"
             android:adjustViewBounds="true"
             android:layout_margin="5dp"
             android:scaleType="centerCrop"/>

         <ImageView
             android:id="@+id/button9"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_weight="1"
             android:src="@drawable/letterp"
             android:adjustViewBounds="true"
             android:layout_margin="5dp"
             android:scaleType="centerCrop"/>
     </LinearLayout>

     <LinearLayout
         android:id="@+id/NumerRow456"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:orientation="horizontal"
         android:gravity="center" >

         <ImageView
             android:id="@+id/button9"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_weight="1"
             android:src="@drawable/letterq"
             android:adjustViewBounds="true"
             android:layout_margin="5dp"
             android:scaleType="centerCrop"/>

         <ImageView
             android:id="@+id/button5"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_weight="1"
             android:src="@drawable/letterr"
             android:adjustViewBounds="true"
             android:layout_margin="5dp"
             android:scaleType="centerCrop"/>

         <ImageView
             android:id="@+id/button6"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_weight="1"
             android:src="@drawable/letters"
             android:adjustViewBounds="true"
             android:layout_margin="5dp"
             android:scaleType="centerCrop"/>

         <ImageView
             android:id="@+id/button9"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_weight="1"
             android:src="@drawable/lettert"
             android:adjustViewBounds="true"
             android:layout_margin="5dp"
             android:scaleType="centerCrop"/>
     </LinearLayout>

     <LinearLayout
         android:id="@+id/NumerRow456"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:orientation="horizontal"
         android:gravity="center" >

         <ImageView
             android:id="@+id/button9"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_weight="1"
             android:src="@drawable/letteru"
             android:adjustViewBounds="true"
             android:layout_margin="5dp"
             android:scaleType="centerCrop"/>

         <ImageView
             android:id="@+id/button5"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_weight="1"
             android:src="@drawable/letterv"
             android:adjustViewBounds="true"
             android:layout_margin="5dp"
             android:scaleType="centerCrop"/>

         <ImageView
             android:id="@+id/button6"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_weight="1"
             android:src="@drawable/letterw"
             android:adjustViewBounds="true"
             android:layout_margin="5dp"
             android:scaleType="centerCrop"/>

         <ImageView
             android:id="@+id/button9"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_weight="1"
             android:src="@drawable/letterx"
             android:adjustViewBounds="true"
             android:layout_margin="5dp"
             android:scaleType="centerCrop"/>
     </LinearLayout>
     <LinearLayout
         android:id="@+id/NumerRow456"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:orientation="horizontal"
         android:gravity="center">

         <ImageView
             android:id="@+id/button9"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_weight="1"
             android:src="@drawable/lettery"
             android:adjustViewBounds="true"
             android:layout_margin="5dp"
             android:scaleType="centerCrop"/>

         <ImageView
             android:id="@+id/button5"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_weight="1"
             android:src="@drawable/letterz"
             android:adjustViewBounds="true"
             android:layout_margin="5dp"
             android:scaleType="centerCrop"/>
         <ImageView
             android:id="@+id/button9"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_weight="1"
             android:src="@drawable/blankspace"
             android:adjustViewBounds="true"
             android:layout_margin="5dp"
             android:scaleType="centerCrop" />

         <ImageView
             android:id="@+id/button5"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_weight="1"
             android:src="@drawable/blankspace"
             android:adjustViewBounds="true"
             android:layout_margin="5dp"
             android:scaleType="centerCrop" />
      </LinearLayout>
 </LinearLayout>

        As to believe the real screenshots of image, am attaching the image


text:
Q: How to find the min/max of values in an array of json objects (javascript) I have a JSON array that looks something like this:
arr = [{"range":4, "time":56, id:"a4bd"},
{"range":5, "time":65, id:"a4bg"},
{"range":3, "time":58, id:"a4cd"},
{"range":3, "time":57, id:"a4gh"},
{"range":8, "time":60, id:"a5ab"}]

I'd like to know the best way in javascript to find the minimum or maximum value for one of these properties, eg.
min(arr["time"])

or something similar, which would return 56

A: Use Math.max and Math.min with array
Reference

*

*Math.min

*Math.max
These functions will return the minimum/maximum values from a list of input numbers.
what you have to do is generate the list od numbers against which you need to find min or max. I used Array.map to return the vaues from each node of array. Spread the array to a list of numbers and apply Math.min and Math.max

const arr = [{ "range": 4, "time": 56, id: "a4bd" },
{ "range": 5, "time": 65, id: "a4bg" },
{ "range": 3, "time": 58, id: "a4cd" },
{ "range": 3, "time": 57, id: "a4gh" },
{ "range": 8, "time": 60, id: "a5ab" }];

function findMinMax(key) {
  const datas = arr.map((node) => node[key]);
  return {
    min: Math.min(...datas),
    max: Math.max(...datas),
  }
}
console.log(findMinMax('range'));
console.log(findMinMax('time'));

A: For example lodash solution for minimum option:
import _ from 'lodash';

const myMin = (arr, prop) => _.minBy(arr, (o) => o[prop])[prop];

myMin(arr, 'time');  // 56
myMin(arr, 'range'); // 3


text:
Q: focus() doesn't work in input (all browsers) I know there is tons of questions like that on stackoverflow but none of them solved my problem. I'm  trying to build a small "pyramid" word game. You have to find the right translation for a korean word, then a new input with a new word will pop up. Solve this word, the next input field will pop up, ...
HTML:
<input id="ha_1" class="halter" placeholder="안녕하세요"  type="text" onblur="checkSol(id);"></input>

<input id="ha_2" class="halter" placeholder="얼굴" type="text" onblur="checkSol(id);"></input>

<input id="ha_3" class="halter" placeholder="문" type="text" onblur="checkSol(id);"></input>

Here is the relevant piece of code:
// compare if user input is correct solution
if (user_input == solution){
// if correct, display the next input field:
             $('#' + e_dies).nextAll('.halter:first').css('display', 'block');
    // ==> supposed to focus the fadedIn input
             $('#next_input').focus();
// count up to the next word
             l_count++;
// give correct/incorrect feedback
                    if(l_count == last_sol){
                            tell_me.innerHTML = 'Correct';
                        return false;
                    };
            } else if(document.getElementById(e_dies).value == "") {
            tell_me.innerHTML = '';
        }

This line here $('#' + e_dies).nextAll('.halter:first').css('display', 'block'); displays a input field. Right after, $('#next_input').focus(); is supposed to focus this input field , which just faded in. I tried some solutions like using setTimeout or moving it to the end of the function. Nothing worked for me.
Strangely, other commands like  $('#next_input').css('color', 'red'); work just fine, just the .focus() makes trouble.
Help would be much appreciated!

A: Though the question seems to be not that clear i have implemented a small fiddle showing input box focus working on conditional value.I hope this can give some help

<input id="ha_1" class="halter" placeholder="안녕하세요"  type="text" onblur="checkSol(id);" />

<input id="ha_2" class="halter" placeholder="얼굴" type="text" onblur="checkSol(id);" />

<input id="ha_3" class="halter" placeholder="문" type="text" onblur="checkSol(id);" />

<input id ='focusinputbox' placeholder='inputtobefocussed'/>


text:
Q: Policy based authorization on razor pages I trying to set up policy-based authorization on razor pages on Core2.1.
I have set up the policy and decorated the razor page with the authorize attribute. I cannot figure what am I doing wrong or if something else needs to be done, but I cannot get the page to authorize. It always gives me

No web page was found for the web address:
localhost/ADENETCore/Account/AccessDenied?ReturnUrl=%2FADENETCore%2FContact

Can you please point me in the right direction?
ConfigureServices:
services.AddAuthorization(options =>
                {
                    options.AddPolicy("AtLeast21", policy =>
                        policy.Requirements.Add(new MinimumAgeRequirement(21)));
                });
            services.AddMvc().AddRazorPagesOptions(options =>
                    {
                        options.Conventions.AuthorizePage("/Contact", "AtLeast21"); // with policy
                    })
                .SetCompatibilityVersion(CompatibilityVersion.Version_2_1).AddSessionStateTempDataProvider();

Configure:
    app.UseAuthentication();
    app.UseMvc();

Policy Requirement:
    public class MinimumAgeRequirement : IAuthorizationRequirement
    {
     public int MinimumAge { get; private set; }

     public MinimumAgeRequirement(int minimumAge)
     {
      MinimumAge = minimumAge;
     }
    }

Policy Handler:
public class MinimumAgeHandler : AuthorizationHandler<MinimumAgeRequirement>
        {
            protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
                                                           MinimumAgeRequirement requirement)
            {
    context.Succeed(requirement);
     return Task.CompletedTask;

    }
}

Razor Page:
[Authorize(Policy = "AtLeast21")]
public class ContactModel : PageModel

It is redirecting to the Account/AccessDenied page

A: You need to add your authorization handlers as singletons.
services.AddSingleton<IAuthorizationHandler, MinimumAgeHandler>();

For more info check: https://learn.microsoft.com/en-us/aspnet/core/security/authorization/resourcebased?view=aspnetcore-2.2


text:
Q: ruby nokogiri not reading my xml file I have an metadata.xml file that has :
<MediaItem ActualEndTime="8/2/2017 5:05:01 PM" ActualStartTime="8/2/2017 4:00:01 PM" Clip="False" ClipEndTime="1/1/0001 12:00:00 AM" ClipParentId="00000000-0000-0000-0000-000000000000" ClipStartTime="1/1/0001 12:00:00 AM" CreatedDate="1/1/0001 12:00:00 AM" DateAdded="1/1/0001 12:00:00 AM" Duration="01:04:59.8290000" FileFormat="0" FileSize="0" Genre="Interview" GuideEndTime="8/2/2017 5:00:00 PM" GuideStartTime="8/2/2017 4:00:00 PM" MovieId="00000000-0000-0000-0000-000000000000" MovieYear="0" NumParts="0" OriginalAirDate="8/2/2017 12:00:00 AM" OriginalFileSize="3636725627" PartNum="0" RecordingType="Episodic" ShowSqueeze="True" TargetEndTime="8/2/2017 5:05:00 PM" TargetStartTime="8/2/2017 4:00:00 PM" UserId="" VideoHeight="0" VideoWidth="0" />

How do I parse it with ruby and nokogiri?
I've tried :
f = File.open path
puts "f  : #{f}"
metadata  = {}
doc = Nokogiri::XML(f)
puts "doc : #{doc}"
p = doc.xpath("//ActualStartTime")
puts "p : #{p}"
puts "++++++++++++++++++++++++++++++++++++++"

but I get this output :
f  : #<File:0x00000002755c40>
doc : <?xml version="1.0"?>
p :
+++++++++++++++++++++++++++++++++++++++++++

What I am missing? I want to get ActualStartTime value, Duration value and Genre value.
update
metadata  = {}
f = File.read(path)
puts "f  : #{f}"
doc = Nokogiri::XML(f)
p = doc.xpath("//@ActualStartTime")
puts "p : #{p}"
metadata['Duration'] = doc.xpath("//MediaItem/@Duration")
puts "metadata['Duration']  : #{metadata['Duration']}"

output:
f : <MediaItem ActualEndTime="8/2/2017 5:05:01 PM" ActualStartTime="8/2/2017 4:00:01 PM" Clip="False" ClipEndTime="1/1/0001 12:00:00 AM" ClipParentId="00000000-0000-0000-0000-000000000000" ClipStartTime="1/1/0001 12:00:00 AM" CreatedDate="1/1/0001 12:00:00 AM" DateAdded="1/1/0001 12:00:00 AM" Duration="01:04:59.8290000" FileFormat="0" FileSize="0" Genre="Interview" GuideEndTime="8/2/2017 5:00:00 PM" GuideStartTime="8/2/2017 4:00:00 PM" MovieId="00000000-0000-0000-0000-000000000000" MovieYear="0" NumParts="0" OriginalAirDate="8/2/2017 12:00:00 AM" OriginalFileSize="3636725627" PartNum="0" RecordingType="Episodic" ShowSqueeze="True" TargetEndTime="8/2/2017 5:05:00 PM" TargetStartTime="8/2/2017 4:00:00 PM" UserId="" VideoHeight="0" VideoWidth="0" />
p :
metadata['Duration']  :

A: You're opening the file, but you're never actually reading the file contents (and also not closing the file after). You can read the file through
begin
  file = File.open './metadata.xml'
  f = file.read
ensure
  file.close
end

or through one of the shortcuts:
# closes file after block finishes
f = File.open('./metadata.xml') { |f| f.read }

or, since reading is such a common thing, you can use File.read
f = File.read('./metadata.xml')

and now Nokogiri will read f just fine, though you'll need to use
p = doc.xpath("//@ActualStartTime")

since it's an attribute.


text:
Q: JSON for command-line arguments Supposed I want to write a tool, that needs to accept slightly-structured data, is it reasonable to use json for command-line arguments, and while at it, environment?
For example
fudge_files "['file1', 'file2']"  # here list of files could be used
fudge_files --dirs "['dir1', 'dir2']" pattern.* another*.foo

Or in a more convoluted example
fudge_files --dst "{'txt': ['/foo', '/bar'], 'pdf': ['/foo']}" pattern.*

Is this a good or bad idea?
What are the pitfalls?

A: Most (all) shells will see the single and dbl quotes and process them per their standard procedures.
To keep the quotes so they get passed in as data, you'll need to escape them, i.e.
\"[\'file1\', \'file2\']\"

Once your data starts containing legitimate "\" chars, it gets really ugly. You can come up with hacks, but it will be painful and you can spend a lot of time trying debug issues related to this sort of quoting.
AND, if you persist, and make it work, then, 2-3 months later, you may think "I can put some of this in variables and use eval" or other craziness to expand the variable into a string. Now you're really in for a debug nightmare.
Also, I did quick test using shell ANSI strings to see if that would help, but
$ var=$'"['file1', 'file2']"'
$ echo $var
"[file1, file2]"
$ echo "$var"
"[file1, file2]"
$ var=$""['file1', 'file2']""
-ksh: file2]: not found [No such file or directory]

ANSI Strings are strings defined like $'My Static ANSI String' or $"myANSIString with $var input"
Note how in even the first example, the shell matched the single quotes at the first opportunity, and stripped them out of your input string. Hoping that it was the echo that was stripping them, I used best practice on the 2nd echo line an surrounded "$var" in quotes. Nope, single-quotes are gone. :-(
I don't have that much experience working with ANSI strings, so others may offer a solution that will keep the single and dbl quotes intact.
Otherwise, I don't see this working.

Your work flow isn't quite clear, but guessing that something is emitting these values (I hope you're not having to type them), I think you're much better off getting them into a file. If a separate program is printing them to the terminal, then just redirect into a file
  json_emitting_program --args .... > $tmpFile

Or use the Unix tool designed to elimiate tmp files, the pipe |, and write your tool to read its data from std-in, rather that as command-line arguments.
Then you would say either
  json_emitting_program --args .... | fudge_files

OR, using a tmp file
fudge_files < "$tmpFile"

If the source of your data is in a a MS Windows output (for instance), you can create temp files on-the-file using Unix here-documents, something like
 cat - > $tmpFile << EOS
 paste your input here
 and here
 etc
 EOS

Note that EOS has to be on a line of it's own, with no trailing white-space.
The shell should return the prompt to you if done it correctly.
Confirm that file is there and up-to-date
 ls -l $tmpFile

and the as above, run  your program
fudge_files < "$tmpFile"

In case you don't know, you create tmpFile with a simple assignment to any path/file you care to name:
tmpFile=/path/to/myTempFile

IHTH


text:
Q: VLAN & Communication I'm working on a project regarding Network Security and I've come to the topic regarding VLANs.
I was wondering if it is possible to set up multiple VLANs (VLAN0, 10, 20, 30) in a way that all VLANs can communicate with VLAN0 but not with eachother?
Thanks in Advance!

A: Yes, It is possible to do that. Example in cisco product, you use something call Access List (ACL), ie
access-list 101 permit ip <vlan10 net> <mask> <vlan0 net> mask
access-list 101 permit ip <vlan20 net> <mask> <vlan0 net> mask
..............................................................
access-list 101 deny ip any any

Or if you only one VLAN 10 communicate with VLAN 20, add this line
access-list 101 permit ip <vlan10 net> <mask> <vlan20 net> mask

But remember to put it above the last line.
Best Regards.

A: Yes, this is entirely possible, in many ways. In Cisco terminology, you should search for settings related to isolated VLANs (vs private VLANs which isolate a single port from talking to any ports other than the one configured).
In addition to the other answer which suggests using ACLs, it should be noted that you can easily do this by controlling your routing, provided the router that interconnects the VLANs is not the same device(switch) that has the VLANs on it (and that we are actually talking about distinct subnetworks here, which are often confused with VLANs, but are totally different).


text:
Q: cron reboot after script I want a daily backup, update and reboot on my raspberry pi (Raspbian GNU/Linux 9 (stretch) using a cron job.
So with root I use crontab -e and set the following jobs:
30 3 * * * /mnt/usb/backup/scripts/backup_daily.sh
00 3 * * * apt-get update
To update and backup a couple folders every day between 3am and 3:30.
Now after this I want to reboot the system. I know I can do something like
0 4 * * * reboot now
But I'm afraid that maybe my backup is still doing it's thing. Is there a way I can add a reboot job after my script has successfully finished?

A: At the last line of the backup_daily.sh put the reboot command.
and don't do it from cron.


text:
Q: Sort array of objects by the length of a field using lodash I have an array like below, and I need to sort the array by the string length of name field.
for an example,
[
  {
    "_id": 10,
    "name": "AAAAAA"
  },
  {
    "_id": 11,
    "name": "AA"
  },
  {
    "_id": 12,
    "name": "AAAA"
  },
  {
    "_id": 13,
    "name": "A"
  },
  {
    "_id": 14,
    "name": "AAAAAAAA"
  }
]

I need the array like this,
[
  {
    "_id": 13,
    "name": "A"
  },
  {
    "_id": 11,
    "name": "AA"
  },
  {
    "_id": 12,
    "name": "AAAA"
  },
  {
    "_id": 10,
    "name": "AAAAAA"
  },
  {
    "_id": 14,
    "name": "AAAAAAAA"
  }
]

can any one help me out with this. Thanks.

A: This can be accomplished with the _.orderBy method:
_.orderBy(data, [({ name }) => name.length, 'name'], ['desc']);

Here is a break-down:
I threw some "B"s into the mix to show the secondary sorting (after length is compared). Sorting the length alone is not unique enough.

const data = [
  { "_id":  1, "name": "AAAAAA"   },
  { "_id":  2, "name": "AA"       },
  { "_id":  3, "name": "AAAA"     },
  { "_id":  4, "name": "A"        },
  { "_id":  5, "name": "AAAAAAAA" },
  { "_id":  6, "name": "BBBBBB"   },
  { "_id":  7, "name": "BB"       },
  { "_id":  8, "name": "BBBB"     },
  { "_id":  9, "name": "B"        },
  { "_id": 10, "name": "BBBBBBBB" }
];

const sorted = _.orderBy(
  data,                               // Data to be sorted
  [
    ({ name: { length } }) => length, // First, sort by length
    'name'                            // Them sort lexicographically
  ], [
    'desc',                           // Length (descending)
    'asc'                             // This is implied, and could be removed
  ]
);

console.log(sorted);
.as-console-wrapper { top: 0; max-height: 100% !important; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>


text:
Q: Rails generate subsclass doesn't create new table Here are the commands I use to generate rails models:
rails g scaffold fruit name variety colour
rails g scaffold vegetable harvested_at:time --parent Fruit

The 2nd command was executed without error but it does not work, it only creates a model without the extra attribute, and there is no db migration generated either. Why is it so?

A: ActiveRecord supports mapping inheritance hierarchies to a single table. You can not create extra fields in your database when you create a child class from parent AR class in this case.
You can see more about scaffolding, if you write
rails g scaffold --help

in your terminal. For AR models you can see this:
ActiveRecord options:
      [--migration], [--no-migration]    # Indicates when to generate migration
                                         # Default: true
      [--timestamps], [--no-timestamps]  # Indicates when to generate timestamps
                                         # Default: true
      [--parent=PARENT]                  # The parent class for the generated model
      [--indexes], [--no-indexes]        # Add indexes for references and belongs_to columns
                                         # Default: true   -t, [--test-framework=NAME]            # Test framework to be invoked
                                         # Default: test_unit

This is full list of options that you can use.


text:
Q: heroku rake aborted! could not connect to server: Connection timed out Recently I have resetted my database on heroku by the below command.
heroku pg:reset SHARED_DATABASE

And I have ran the below command.
heroku run rake db:migrate

The response I have received is shown below.
rake aborted!
could not connect to server: Connection timed out
Is the server running on host "ec2-23-23-203-225.compute-1.amazonaws.com" and accepting
TCP/IP connections on port 5432?

Tasks: TOP => db:migrate
(See full trace by running task with --trace)

Any idea?
Thank you.

A: There has been shared db issues today I can see on status.heroku.com - does it still do it now? Chances are you were affected by an outage of a shared DB server.


text:
Q: Adding text to Gif file (ios) I'm looking for some help/advice on how to add text to an animated gif file /combining  gifs. This app seems to do what I'm trying to do- https://itunes.apple.com/us/app/pimp-my-text-send-color-text/id489972714?mt=8. So there needs to be the ability to have animated gifs with text on top as well as the ability to add a gif onto another gif.
Here's what my approach will be to accomplish this, I want to make sure it's the best and most effective way to go about it.
1) Have the initial background as a png sequence of UIImages
2) Draw the text onto each Image
3) Add other Images to each background Image to appear animated as well
4) combine all the background images into one gif
Let me know if I'm on the right path or if there is an easier way to go about this. Thanks for your help!

A: I'm not sure if what you want is possible. I don't think that there is any service to add a gif to another gif  because of timing differences. there are many sites online to combine multiple images into a gif and GifBomb from the Appstore on iOS can add headers and text onto gifs. I don't think that this is the site to ask a question like this, try google or a different stack exchange site first.


text:
Q: Connecting to redis on render.com I received this error when I wanted to connect to redis instance created on render.com. It should be mentioned that I enabled the instance to connect servers outside render.com.
Error: connect ECONNREFUSED 127.0.0.1:6379
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1247:16) {
errno: -4078,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 6379
}
this is my redis config
import redis from "redis";
const client = redis.createClient({
  url: process.env.REDIS_URL_EXTERNAL,
});

export default client;

and this is how I connected the client in the server.js file
(async () => {
  await client.connect();
})();

I tried to connect to a Redis instance created on Render.com using the redis library in Node.js. I expected the connection to be successful, and for the Connected to Redis message to be logged to the console. However, I received the mentioned error.


text:
Q: Find a function's differential I need to prove that the following function is differentiable and find $df$.
$$
f(x,y,z)=\frac{\sqrt{x^2-y^2}}{z^2+x+y}
$$
I found all partial derivatives:
$$
\frac{\partial f}{\partial x}=\frac{x(y+z^2)+y^2}{(z^2+x+y)^2\sqrt{x^2-y^2}} \\
\frac{\partial f}{\partial y}=-\frac{y(x+z^2)+x^2}{(z^2+x+y)^2\sqrt{x^2-y^2}} \\
\frac{\partial f}{\partial z}=-\frac{2z\sqrt{x^2-y^2}}{(z^2+x+y)^2}
$$
And then wrote something like this:
$$
\text{If}\
\begin{cases}
z^2+x+y\ne 0 \\
x^2-y^2 \ne 0
\end{cases}
\ \ \text{then}\ \
\exists df=\frac{\partial f}{\partial x}dx+
\frac{\partial f}{\partial y}dy+
\frac{\partial f}{\partial z}dz
$$
The problem is I am not sure if my last line of solution is correct. Maybe the initial function has differentials even if the conditions above are not met. Can anyone explain if I am right?

A: I think you've completely answered the question.
Firstly, logically speaking, if you want to know whether your last line is correct, you shouldn't care about the points that don't meet those two conditions, as you make no claim about them. And since, for every point that meets those conditions, you have continuous partial derivatives in a neighborhood, your sentence is indeed correct.
And secondly, I don't think you're supposed to check anything on the remaining points: I think "differentiable" here means differentiable at points that respect both your conditions (these are the points in the interior of your function domain). I claim this because of two reasons:
1) It doesn't make sense to talk about differentiability of a function outside the function's domain, so checking differentiability at points that don't respect your first condition (and therefore are outside the function's domain) doesn't make sense.
2) The points for which the second condition doesn't hold are in the boundary of your domain and you usually don't define derivative at these points either, at least for multivariable functions. It's still an interesting case though, so I suggest you read
Are derivatives defined at boundaries?
I hope this helps.


text:
Q: constexpr variable 'params' must be initialized by a constant expression I'm trying to vreate a minimum reproducible example. I created it but mine works. Howeveron Android it doesn't. Here's the working example:
#include <iostream>
#include <array>
#include <variant>

template<typename T>
class ParamInterval {
public:
    constexpr ParamInterval(){}
    constexpr ParamInterval(const ParamInterval &other) = delete;
    ParamInterval &operator=(const ParamInterval &other) = delete;
    constexpr ParamInterval(ParamInterval &&other) = default;
    constexpr ParamInterval &operator=(ParamInterval &&other) = delete;

};

using ParamVariant = std::variant<ParamInterval<float>, ParamInterval<int>>;

template<class EffectType, size_t N>
class EffectDescription {
public:
    static constexpr size_t getNumParams() {
        return N;
    }

    template<typename R>
    static constexpr R getDefaultParam(int i) {
        const constexpr std::array<ParamVariant, N> params = EffectDescription::getParams();
        auto param = std::get<ParamInterval<R>>(params[i]);
        return 0;
    }
    static constexpr std::array<ParamVariant , N> getParams();
};

class VibratoDescription : public EffectDescription<VibratoDescription, 2> {
public:
    static constexpr std::array<ParamVariant , getNumParams()> getParams() {
        return std::array<ParamVariant, getNumParams()> {
                ParamInterval<float>(),
                ParamInterval<float>()
        };
    }
};

I get these errors:
/home/lz/my_app_pro_2/my_app_pro/android/app/src/main/cpp/juce/fx/EffectDescription.h:69:54: error: constexpr variable 'params' must be initialized by a constant expression
In file included from /home/lz/my_app_pro_2/my_app_pro/android/app/src/main/cpp/juce/FxAudioProcessor.cpp:1:
In file included from /home/lz/my_app_pro_2/my_app_pro/android/app/src/main/cpp/juce/FxAudioProcessor.h:3:
In file included from /home/lz/my_app_pro_2/my_app_pro/android/app/src/main/cpp/juce/ProcessorBase.h:5:
/home/lz/my_app_pro_2/my_app_pro/android/app/src/main/cpp/juce/fx/EffectDescription.h:69:63: note: undefined function 'getParams' cannot be used in a constant expression
In file included from /home/lz/my_app_pro_2/my_app_pro/android/app/src/main/cpp/juce/FxAudioProcessor.cpp:1:
In file included from /home/lz/my_app_pro_2/my_app_pro/android/app/src/main/cpp/juce/FxAudioProcessor.h:3:
In file included from /home/lz/my_app_pro_2/my_app_pro/android/app/src/main/cpp/juce/ProcessorBase.h:5:
/home/lz/my_app_pro_2/my_app_pro/android/app/src/main/cpp/juce/fx/EffectDescription.h:80:51: note: declared here
In file included from /home/lz/my_app_pro_2/my_app_pro/android/app/src/main/cpp/juce/FxAudioProcessor.cpp:1:
In file included from /home/lz/my_app_pro_2/my_app_pro/android/app/src/main/cpp/juce/FxAudioProcessor.h:3:
In file included from /home/lz/my_app_pro_2/my_app_pro/android/app/src/main/cpp/juce/ProcessorBase.h:5:
/home/lz/my_app_pro_2/my_app_pro/android/app/src/main/cpp/juce/fx/EffectDescription.h:70:14: error: call to deleted constructor of 'ParamInterval<float>'
In file included from /home/lz/my_app_pro_2/my_app_pro/android/app/src/main/cpp/juce/FxAudioProcessor.cpp:1:
In file included from /home/lz/my_app_pro_2/my_app_pro/android/app/src/main/cpp/juce/FxAudioProcessor.h:3:
In file included from /home/lz/my_app_pro_2/my_app_pro/android/app/src/main/cpp/juce/ProcessorBase.h:5:
/home/lz/my_app_pro_2/my_app_pro/android/app/src/main/cpp/juce/fx/EffectDescription.h:41:15: note: 'ParamInterval' has been explicitly marked deleted here
In file included from /home/lz/my_app_pro_2/my_app_pro/android/app/src/main/cpp/juce/FxAudioProcessor.cpp:1:
In file included from /home/lz/my_app_pro_2/my_app_pro/android/app/src/main/cpp/juce/FxAudioProcessor.h:3:
In file included from /home/lz/my_app_pro_2/my_app_pro/android/app/src/main/cpp/juce/ProcessorBase.h:5:
/home/lz/my_app_pro_2/my_app_pro/android/app/src/main/cpp/juce/fx/EffectDescription.h:68:24: note: must qualify identifier to find this declaration in dependent base class

As you see, I get errors about ParamInterval having the copy constructor deleted, but I'm trying to bind it to a reference std::array<ParamVariant , getNumParams()>& so it should work.
What is wrong?


text:
Q: Three.js - Questions about (the use of) THREE.BufferGeometry As I understood using buffer geometries will increase performance and decrease memory usage because it reduces the cost of passing all this data to the GPU.
And as I understood from @WestLangley his post here:

THREE.BufferGeometry is slowly replacing THREE.Geometry as it is computationally more efficient.

I am currently using three.js - r72. When I draw my geometries make meshes and add them to the scene I see that there are two properties inside my geomtries __directGeometry and _bufferGeometry.
Here in a THREE.BoxGeometry:

Here in a THREE.Geometry:

Here in a THREE.ShapeGeometry:

My questions:

*

*What is a THREE.DirectGeometry and what does it do? (I cannot seem to find any documentation on this)

*Is this THREE.BufferGeometry stored in _bufferGeometry already automatically used? If not, can I simply use it instead of my geometry to boost performance?

*There are conversion methods: THREE.BufferGeometry has toGeometry and THREE.Geometry has toBufferGeometry. If I convert all my normal geometries to buffer geometries using this method, will it give me the same performance increase compared to drawing them as a THREE.BufferGeometry from the start?

*How and when should I use THREE.BufferGeometry?

*When will three.js stop supporting THREE.Geometry in favor of THREE.BufferGeometry?

NOTE: I couldn't find detailed information on when and how to use buffer geometries or when it is going to be replacing THREE.Geometry. But if someone has a good source or reference please leave a comment.

A: *

*__directGeometry is an internal data structure used to transition between THREE.Geometry and THREE.BufferGeometry. Do not mess with it.

*THREE.BufferGeometry.toGeometry() and THREE.Geometry.toBufferGeometry() are convenience methods. The first one is helpful if your model loads as BufferGeometry and you feel more comfortable manipulating Geometry. If you want answers regarding performance, you need to do a test. Buffer geometries definitely load faster.

*There are many examples showing the use of BufferGeometry. It would be wise if you understood the difference between "indexed" and "non-indexed" BufferGeometry. BufferGeometry with the index attribute defined allows for the sharing of vertices. Non-Indexed BufferGeometry is what we call "triangle soup".

*THREE.Geometry will remain for the foreseeable future.

three.js r.73


text:
Q: What is difference between getOrderId and getLastRealOrder() function in magento 2? As I'm new to magento 2 I can't anble to trigger out the difference between getOrderId and getLastRealOrder function ?
How to get product id using getLastRealOrder() function?

A: getOrderId() will give Order Id and getLastRealOrder() wil give that last placed order data object

A: Actually getLastRealOrder() loads order by using last increment id for the session, which is unique id but not primary key of any sales_order_* tables. As you may see the implementation.
public function getLastRealOrder()
 {
    $orderId = $this->getLastRealOrderId();
    if ($this->_order !== null && $orderId == $this->_order->getIncrementId()) {
        return $this->_order;
    }
    $this->_order = $this->_orderFactory->create();
    if ($orderId) {
        $this->_order->loadByIncrementId($orderId);
    }
    return $this->_order;
}

Whereas getOrderId() function is used to get order id of the particular order in various contexts.

A:
getOrderId();  //Returns order Id
getLastRealOrder(); //Get order instance based on last order ID

A: In Magento 2, the getOrderId() function and the getLastRealOrder() function are used to retrieve order information, but they work slightly differently.
The getOrderId() function is a method of the \Magento\Checkout\Model\Session class
, and it is used to retrieve the order ID of the last order that was placed. The method retrieves the order ID from the session data and returns it as an integer.
For example, you could use the getOrderId() method to retrieve the order ID of the last order placed by a customer, and then use that ID to load the order object and display order details to the customer.
$orderId = $this->checkoutSession->getLastOrderId();
$order = $this->orderFactory->create()->load($orderId);

On the other hand, the getLastRealOrder() function is a method of the \Magento\Sales\Model\Order class and it is used to retrieve the last real order object that was placed by the customer. This method returns an instance of the \Magento\Sales\Model\Order class, which contains all of the information about the order, including the order items, billing and shipping addresses, and order totals.
$order = $this->_order->load($this->_checkoutSession->getLastOrderId());

So in short, the main difference between these two functions is that getOrderId() retrieves the order ID as integer and getLastRealOrder() retrieves the complete order object, which you can use to access various data about the order.


text:
Q: Row updating a Row in the same table with a condition Lets say I have some dupe rows in a table, and I want to save whatever information that was saved in the dupe rows to be saved on the proper row if that field is empty or null in the proper row, otherwise do nothing.
For example before:
ID   NAME   EMAIL         VALUE
1    NULL                 1000
2    Sam    asd@asd.com   0550

After:
ID   NAME   EMAIL         VALUE
1    Sam    asd@asd.com   1000
2    Sam    asd@asd.com   0550

UPDATE Real
SET Real.A = Dupe.A
FROM Table1 Real, Table1 Dupe
where ((Real.id = @Rea_ID and Dupe.ID = @Dup_ID) and ((Real.A is null or Real.A = '')))

UPDATE Real
SET Real.B = Dupe.B
FROM Table1 Real, Table1 Dupe
where ((Real.id = @Rea_ID and Dupe.ID = @Dup_ID) and ((Real.B is null or Real.B = '')))

.
.
.

And so on for each field in Table1.
This works, but is there a better way?

A: If you want to update all the fields at once, you can just list them all in the update statement like this:
UPDATE Real
SET Real.A = Dupe.A
,   Real.B = Dupe.B
,   Real.C = Dupe.C
-- , etc for as many fields as you wish
FROM ...

You also mentioned updating only "if that field is empty or null", in which case you can use the isnull function, which will keep the existing value if there is one, but replace it with the new value if it is NULL. You can pair this with the nullif function to turn blank values into NULLs like this:
UPDATE Real
SET Real.A = isnull(nullif(Real.A,''),Dupe.A)
,   Real.B = isnull(nullif(Real.B,''),Dupe.B)
,   Real.C = isnull(nullif(Real.C,''),Dupe.C)
-- , etc for as many fields as you wish
FROM Table1 Real, Table1 Dupe
where ((Real.id = @Rea_ID and Dupe.ID = @Dup_ID)

A: You can do this using case expressions:
UPDATE Real
    SET Real.A = (CASE WHEN Real.A IS NULL OR Real.A = '' THEN Dupe.A ELSE Real.A END),
        Real.B = (CASE WHEN Real.B IS NULL OR Real.B = '' THEN Dupe.B ELSE Real.B END),
        Real.C = (CASE WHEN Real.C IS NULL OR Real.C = '' THEN Dupe.C ELSE Real.C END)
FROM Table1 Real JOIN
     Table1 Dupe
     ON Real.id = @Rea_ID AND Dupe.ID = @Dup_ID


text:
Q: How do I delete the middle node from a LinkedList? I'm trying to delete the middle node from a linked list given access to that node. I'm wondering if there is a difference between the two methods below, or do they accomplish the same thing?
public boolean deleteMiddle(Node middle){
    Node next = middle.next; //line 2
    middle.data = next.data;
    middle.next = next.next;
    return true;

}

public boolean deleteMiddle(Node middle){
    middle.data = middle.next.data;
    middle.next = middle.next.next;
    return true;

}

The first method is what the textbook recommended but it seems like creating the Node "next" in the first method(line 2) is an unnecessary line of code.

A: I think you're probably right that they are equivalent (or certainly look that way)
In both cases it looks like there is a null pointer exception (on next.next) if the item you're deleting is the last in the list (e.g. if next is null then next.next is an error).
And if you get passed null of course that's also going to be a NPE.

A: Yes, they're equivalent. I prefer the first one because it avoids the repetition of the expression middle.next.
As @Rick pointed out, when middle is the last element, you'll get an NPE in both cases.

A:
creating the Node "next" in the first method(line 2) is an unnecessary line of code.

Both snippets achieve the same result.
But what the extra variable assignment (it does not "create a Node", it just assigns a new name to an existing one) does is avoiding to call middle.next twice, avoiding doing the same "calculation" twice.
In this example that won't make any real difference, but in general, it can be a usual performance optimization to avoid redundant work (especially if method calls are involved that do some "heavy lifting"). Before engaging in these adventures, though, one should think about if it is worth making the code potentially less legible, especially given that the JVM will try to do all kinds of optimization automatically. So apply this mindset only to simple patterns or real bottlenecks.
On top of that, giving names to intermediate results can also lead to more self-explanatory code (also not much difference here).
Final remarks: Sometimes (but not here) it is necessary to introduce extra variables to store things temporarily that would otherwise be overwritten in the course of the operation, such as the famous int h = x; x = y; y = h; example.