text:
Q: How to use a thread to take photo in a service I want to use a service to take photo secretly. Here is the code:
** Takes a single photo on service start. */
public class PhotoTakingService extends Service {
    static String TAG = "Khan";
    private boolean isRunning  = false;

    @Override
    public void onCreate() {
        Log.d("shahjahan", "i am in photo taking service.");
        super.onCreate();

        Log.d(TAG, "the name of the for ground process is: " + getForgroundProcessName());

        takePhoto(this);

    }

    @SuppressWarnings("deprecation")
    private static void takePhoto(final Context context) {
        final SurfaceView preview = new SurfaceView(context);
        SurfaceHolder holder = preview.getHolder();
        // deprecated setting, but required on Android versions prior to 3.0
        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

        holder.addCallback(new SurfaceHolder.Callback() {
            @Override
            //The preview must happen at or after this point or takePicture fails
            public void surfaceCreated(SurfaceHolder holder) {
                showMessage("Surface created");

                Camera camera = null;

                try {
                    camera = Camera.open();
                    showMessage("Opened camera");

                    try {
                        camera.setPreviewDisplay(holder);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }

                    camera.startPreview();
                    showMessage("Started preview");

                    camera.takePicture(null, null, new Camera.PictureCallback() {

                        @Override
                        public void onPictureTaken(byte[] data, Camera camera) {
                            showMessage("Took picture");
                            File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
                            if (pictureFile == null){
                                Log.d(TAG, "Error creating media file, check storage permissions: ");
                                return;
                            }

                            try {
                                FileOutputStream fos = new FileOutputStream(pictureFile);
                                fos.write(data);
                                fos.close();
                            } catch (FileNotFoundException e) {
                                Log.d(TAG, "File not found: " + e.getMessage());
                            } catch (IOException e) {
                                Log.d(TAG, "Error accessing file: " + e.getMessage());
                            }

                            camera.release();
                        }
                    });
                } catch (Exception e) {
                    if (camera != null)
                        camera.release();
                    throw new RuntimeException(e);
                }
            }

            @Override public void surfaceDestroyed(SurfaceHolder holder) {}
            @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {}
        });

        WindowManager wm = (WindowManager)context
                .getSystemService(Context.WINDOW_SERVICE);
        WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                1, 1, //Must be at least 1x1
                WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
                0,
                //Don't know if this is a safe default
                PixelFormat.UNKNOWN);

        //Don't set the preview visibility to GONE or INVISIBLE
        wm.addView(preview, params);
    }

    public static final int MEDIA_TYPE_IMAGE = 1;
    public static final int MEDIA_TYPE_VIDEO = 2;

    /** Create a file Uri for saving an image or video */
    private static Uri getOutputMediaFileUri(int type){
        return Uri.fromFile(getOutputMediaFile(type));
    }

    /** Create a File for saving an image or video */
    private static File getOutputMediaFile(int type){
        // To be safe, you should check that the SDCard is mounted
        // using Environment.getExternalStorageState() before doing this.

        File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES), "MyCameraApp");
        // This location works best if you want the created images to be shared
        // between applications and persist after your app has been uninstalled.

        // Create the storage directory if it does not exist
        if (! mediaStorageDir.exists()){
            if (! mediaStorageDir.mkdirs()){
                Log.d("MyCameraApp", "failed to create directory");
                return null;
            }
        }

        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        File mediaFile;
        if (type == MEDIA_TYPE_IMAGE){
            mediaFile = new File(mediaStorageDir.getPath() + File.separator +
                    "IMG_"+ timeStamp + ".jpg");
        } else if(type == MEDIA_TYPE_VIDEO) {
            mediaFile = new File(mediaStorageDir.getPath() + File.separator +
                    "VID_"+ timeStamp + ".mp4");
        } else {
            return null;
        }

        return mediaFile;
    }

    private static void showMessage(String message) {
        Log.i("Camera", message);
    }

    @Override public IBinder onBind(Intent intent) { return null; }

    public String getForgroundProcessName()
    {
        ActivityManager activityManager = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
//                Log.i("Foreground App", appProcess.processName);
//                Toast.makeText(this, "the forground application is: " + appProcess.processName, Toast.LENGTH_LONG).show();
                return appProcess.processName;

            }
        }
        return "None";
    }

}

But, I want to run takePhoto(this) after a regular interval in background. I tried handler, but it's not working fine:
Handler uiHandler = new Handler(Looper.getMainLooper());
Runnable runnable = new Runnable() {

    @Override
    public void run() {
        // TODO Auto-generated method stub
        int i = 0;
        while(true)
        {
            Log.d(TAG,"I am in while.");
            i++;
            takePhoto(getApplicationContext());
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            if ( i > 5 )
                break;
        }
    }
};

uiHandler.post(runnable);

Using above code freezes my app. Please guide me to implement above code correctly.


text:
Q: How to download content in background at specific time? What I need to do is fetching content on iOS from network at a specific time (let's say 21:00) on a daily basis.
If I use background fetch approach: there is no guarantee that fetching happens at a specific time. Also, there is no guarantee that it happens at any time at all since if user kills the app explicitly no fetch occurs.
If I use local notifications: I cannot execute anything as my app does not wake up from background state, therefore no fetch at all.
Is there any way to achieve that on iOS? Am I missing a point about local notifications or background fetch?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Terminology: Contraction *of* normed spaces? *Between* normed spaces? *On* normed spaces? I have a terminological question. Suppose $X$ and $Y$ are normed spaces, and let $f$ be a contraction $X \to Y$. Which of the following expressions is correct?

*

*$f$ is a contraction of normed spaces.

*$f$ is a contraction between normed spaces.

*$f$ is a contraction on normed spaces.

*$f$ is a normed space contraction.

*Something else suggested by you.

I need an expression in these lines as I would like to differentiate, even from the linguistic point of view, a contraction acting from a normed space to another normed space from a contraction acting from a normed ring to another normed ring.


text:
Q: Does PHP allow named parameters so that optional arguments can be omitted from function calls? Is it possible in PHP to specify a named optional parameter when calling a function/method, skipping the ones you don't want to specify (like in python)?
Something like:
function foo($a, $b = '', $c = '') {
    // whatever
}

foo("hello", $c="bar"); // we want $b as the default, but specify $c

A: No, PHP cannot pass arguments by name.
If you have a function that takes a lot of arguments and all of them have default values you can consider making the function accept an array of arguments instead:
function test (array $args) {
    $defaults = array('a' => '', 'b' => '', 'c' => '');
    $args = array_merge($defaults, array_intersect_key($args, $defaults));

    list($a, $b, $c) = array_values($args);
    // an alternative to list(): extract($args);

    // you can now use $a, $b, $c
}

See it in action.

A: No, it isn't.
The only way you can somewhat do that is by using arrays with named keys and what not.

A: As of PHP 5.4 you have shorthand array syntax (not nessecary to specify arrays with cumbersome "array" and instead use "[]").
You can mimic named parameters in many ways, one good and simple way might be:
bar('one', ['a1' => 'two', 'bar' => 'three', 'foo' => 'four']);
// output: twothreefour

function bar ($a1, $kwargs = ['bar' => null, 'foo' => null]) {
    extract($kwargs);
    echo $a1;
    echo $bar;
    echo $foo;
}

A: No, it is not possible (before PHP 8.0): if you want to pass the third parameter, you have to pass the second one. And named parameters are not possible either.

A "solution" would be to use only one parameter, an array, and always pass it... But don't always define everything in it.
For instance :
function foo($params) {
    var_dump($params);
}

And calling it this way : (Key / value array)
foo([
    'a' => 'hello',
]);

foo([
    'a' => 'hello',
    'c' => 'glop',
]);

foo([
    'a' => 'hello',
    'test' => 'another one',
]);

Will get you this output :
array
  'a' => string 'hello' (length=5)

array
  'a' => string 'hello' (length=5)
  'c' => string 'glop' (length=4)

array
  'a' => string 'hello' (length=5)
  'test' => string 'another one' (length=11)

But I don't really like this solution :

*

*You will lose the phpdoc

*Your IDE will not be able to provide any hint anymore... Which is bad

So I'd go with this only in very specific cases -- for functions with lots of optional parameters, for instance...

A: You can keep the phpdoc and the ability to set defaults by passing an object instead of an array, e.g.
class FooOptions {
  $opt1 = 'x';
  $opt2 = 'y';
  /* etc */
};

That also lets you do strict type checking in your function call, if you want to:
function foo (FooOptions $opts) {
  ...
}

Of course, you might pay for that with extra verbosity setting up the FooOptions object.  There's no totally-free ride, unfortunately.

A: PHP 8 was released on November 26, 2020 with a new feature called named arguments.
In this major version release, "named parameters" (aka "named arguments") afford developers some really cool new techniques when calling native and custom functions.
The custom function in this question can now be called with the first parameter (because there is no default for it) and then only the third parameter passed by using named parameters like this: (Demo)
function foo($a, $b = '', $c = '') {
    echo $a . '&' . $b . '&' . $c;
}

foo("hello", c: "bar");
// output: hello&&bar

Notice that the second parameter did not need to be declared in the function call because it has a default value defined -- the default value is automatically used within the function body.
Part of the beauty of this new feature is that you don't need to be careful about the order of your named parameters -- the order of their declaration is irrelevant. foo(c: "bar", a: "hello"); works just the same. Having the ability to "skip" declarations and write declarative parameters will improve the readability of your scripts.  The only downside of this new feature is that there will be a little bit more bloat in the function calls, but I (and many others) think the benefits outweigh this "cost".
Here is an example of a native function omitting the limit parameter, writing the parameters out of their normal order, and declaring a reference variable. (Demo)
echo preg_replace(
         subject: 'Hello 7',
         pattern: '/[a-z ]/',
         count: $counted,
         replacement: ''
     )
     . " & " . $counted;
// output: H7 & 5

There is more to tell about this new feature.  You can even use an associative array to pass the named parameters to the function where the spread/splat operator can be used to unpack the data!
(*notice the slight difference in declaring the reference variable.) (Demo)
$params = [
    'subject' => 'Hello 7',  // normally third parameter
    'pattern' => '/[a-z ]/', // normally first parameter
    // 'limit'               // normally fourth parameter, omitted for this demonstration; the default -1 will be used
    'count' => &$counted,    // normally fifth parameter
    //         ^-- don't forget to make it modifiable!
    'replacement' => '',     // normally second parameter
];
echo preg_replace(...$params) . " & " . $counted;
// same output as the previous snippet

For more information, here are a few leads that explain further about this feature and some common related errors: (I have no affiliation with the following sites)

*

*https://wiki.php.net/rfc/named_params

*https://stitcher.io/blog/php-8-named-arguments

*https://stitcher.io/blog/why-we-need-named-params-in-php

A: It's not exactly pretty, but it does the trick, some might say.
class NamedArguments {

    static function init($args) {
        $assoc = reset($args);
        if (is_array($assoc)) {
            $diff = array_diff(array_keys($assoc), array_keys($args));
            if (empty($diff)) return $assoc;
            trigger_error('Invalid parameters: '.join(',',$diff), E_USER_ERROR);
        }
        return array();
    }

}

class Test {

    public static function foobar($required, $optional1 = '', $optional2 = '') {
        extract(NamedArguments::init(get_defined_vars()));
        printf("required: %s, optional1: %s, optional2: %s\n", $required, $optional1, $optional2);
    }

}

Test::foobar("required", "optional1", "optional2");
Test::foobar(array(
    'required' => 'required',
    'optional1' => 'optional1',
    'optional2' => 'optional2'
    ));

A: Normally you can't but I think there a lot of ways to pass named arguments to a PHP function. Personally I relay on the definition using arrays and just call what I need to pass:
class Test{
    public $a  = false;
    private $b = false;
    public $c  = false;
    public $d  = false;
    public $e  = false;
    public function _factory(){
        $args    = func_get_args();
        $args    = $args[0];
        $this->a = array_key_exists("a",$args) ? $args["a"] : 0;
        $this->b = array_key_exists("b",$args) ? $args["b"] : 0;
        $this->c = array_key_exists("c",$args) ? $args["c"] : 0;
        $this->d = array_key_exists("d",$args) ? $args["d"] : 0;
        $this->e = array_key_exists("e",$args) ? $args["e"] : 0;
    }
    public function show(){
        var_dump($this);
    }
}

$test = new Test();
$args["c"]=999;
$test->_factory($args);
$test->show();

live example here:
http://sandbox.onlinephpfunctions.com/code/d7f27c6e504737482d396cbd6cdf1cc118e8c1ff
If I have to pass 10 arguments, and 3 of them are the data I really need, is NOT EVEN SMART to pass into the function something like
return myfunction(false,false,10,false,false,"date",false,false,false,"desc");

With the approach I'm giving, you can setup any of the 10 arguments into an array:
$arr['count']=10;
$arr['type']="date";
$arr['order']="desc";
return myfunction($arr);

I have a post in my blog explaining this process in more details.
http://www.tbogard.com/2013/03/07/passing-named-arguments-to-a-function-in-php

A: With PHP, the order of arguments is what matters. You can't specify a particular argument out of place, but instead, you can skip arguments by passing a NULL, as long as you don't mind the value in your function having a NULL value.
foo("hello", NULL, "bar");

A: If you really really want, try the reflection.
And skip with null.
function getDefaultValueByNull($fn, $inputs) {
    $ref = new ReflectionFunction($fn);

    $args = array_map(function($p) {
        return [
            $p->getName(),
            $p->isDefaultValueAvailable() ? $p->getDefaultValue() : NULL,
        ];
    }, $ref->getParameters());

    foreach($inputs as $i=>$val) { if ($val!==NULL) $args[$i][1] = $val; }

    return array_column($args, 1, 0);
}

function sum($a=9, $b) {
    extract(getDefaultValueByNull(__FUNCTION__, func_get_args()));
    return $a+$b;
}
echo sum(NULL, 1); // 10

A: Here's what I've been using.  A function definition takes one optional array argument which specifies the optional named arguments:
function func($arg, $options = Array()) {
  $defaults = Array('foo' => 1.0,
                    'bar' => FALSE);
  $options = array_merge($default, $options);

  // Normal function body here.  Use $options['foo'] and
  // $options['bar'] to fetch named parameter values.
  ...
}

You can normally call without any named arguments:
func("xyzzy")

To specify an optional named argument, pass it in the optional array:
func("xyzzy", Array('foo' => 5.7))

A: No not really. There are a few alternatives to it you could use.
test(null,null,"hello")

Or pass an array:
test(array('c' => "hello"));

Then, the function could be:
function test($array) {
    $c = isset($array[c]) ? $array[c] : '';
}

Or add a function in between, but i would not suggest this:
function ctest($c) { test('','',$c); }

A: I dont think so...
If you need to call, for example, the substr function, that has 3 params, and want to set the $length without set the $start, you'll be forced to do so.
substr($str,0,10);

a nice way to override this is to always use arrays for parameters

A: In very short, sometimes yes, by using reflection and typed variables. However I think this is probably  not what you are after.
A better solution to your problem is probably to pass in the 3 arguments as functions handle the missing one inside your function yourself
<?php
   function test(array $params)
   {
     //Check for nulls etc etc
     $a = $params['a'];
     $b = $params['b'];
     ...etc etc
   }

A: You can't do it the python way. Anway, you could pass an associative array and than use the array entries by their name:
function test ($args=array('a'=>'','b'=>'','c'=>''))
{
    // do something
}

test(array('c'=>'Hello'));

This doesn't reduce the typing, but at least it's more descriptive, having the arguments' names visible and readable in the call.

A: Here is a work around:
function set_param_defaults($params) {
  foreach($params['default_values'] as $arg_name => $arg_value) {
    if (!isset($params[$arg_name])) {
      $params[$arg_name] = $arg_value;
    }
  }

  return $params;
}

function foo($z, $x = null, $y = null) {
  $default_values = ['x' => 'default value for x', 'y' => 'default value for y'];
  $params = set_param_defaults(get_defined_vars());

  print "$z\n";
  print $params['x'] . "\n";
  print $params['y'] . "\n";
}

foo('set z value', null, 'set y value');
print "\n";
foo('set z value', 'set x value');

ALTERNATIVELY:
Personally I would go with this method.
function foo($z, $x_y) {
  $x_y += ['x' => 'default value for x', 'y' => 'default value for y'];

  print "$z\n";
  print $x_y['x'] . "\n";
  print $x_y['y'] . "\n";
}

foo('set z value', ['y' => 'set y value']);
print "\n";
foo('set z value', ['x' => 'set x value']);

Print outs for both examples.
1st call:

*

*set z value

*default value for x

*set y value

2nd call:

*

*set z value

*set x value

*default value for y

A: Just use the associative array pattern Drupal uses. For optional defaulted arguments, just accept an $options argument which is an associative array. Then use the array + operator to set any missing keys in the array.
function foo ($a_required_parameter, $options = array()) {
    $options += array(
        'b' => '',
        'c' => '',
    );
    // whatever
}

foo('a', array('c' => 'c's value')); // No need to pass b when specifying c.


text:
Q: How to create drawable layer-list for android in Eclipse? I create resource drawable layer-list but i can't find?

Please help me, thanks.

A: Eclipse doesn't show the layer-list option in that dialog for me either so i guess it's one of the ADT plugin + Eclipse bugs(or feature:) ).
A layer-list it's just a xml file in the drawable folder that has a layer-list element in it so you could make it manually:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
       // the items of the layer-list, you coul have many items in the layer-list
    </item>
</layer-list>

Check this link.


text:
Q: Getting the nth names of vars in scope I have a few variables set up like this:
var foo, bar, fizz, buzz, hello, world;

Now I want to find out how to get those names as a collection of some sort. I am trying to get them since I want to push them in an array as a string.
I hope it doesnt require eval or something hacky. Is what I am trying to do possible?
I just need to know how to get the names, I prefer to solve the rest myself.
Edit: About the answer from the linked duplicate, I dont really get what he is doing there as I get everything other than names. Ive read it before.

A: In my opinion it would be better if you have used javascript object here and put variables in it as properties:
var obj = {foo:'', bar:'', fizz:''};

This way you can access both name of the property and its value:
obj.foo
for(key in obj) {
  alert(key + ': ' + obj[key]);
}

A: You can get list of variables by Object.keys() method, but it returns all variables that object has:
var ar = Object.keys(this);
console.log(ar);


text:
Q: Unable to communicate between libwebsocket as client and socket.io as server This is client code by using libwebsocket version 1.5

#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <string.h>
#include <assert.h>
#include <signal.h>

#include <syslog.h>
#include <sys/time.h>
#include <unistd.h>

#include <libwebsockets.h>

static volatile int force_exit = 0;
static int state, command_received = 0, forked = 0;

#define MAX_ECHO_PAYLOAD 1400
#define LOCAL_RESOURCE_PATH "./"

struct per_session_data {
 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + MAX_ECHO_PAYLOAD + LWS_SEND_BUFFER_POST_PADDING];
 unsigned int len;
};

//for temporary storing data from tcpdump
struct per_session_data data1;

static int callback_echo(struct libwebsocket_context *context, struct libwebsocket *wsi, enum libwebsocket_callback_reasons reason, void *user, void *in, size_t len)
{
 struct per_session_data *pss = (struct per_session_data *)user;
 int n;

 switch (reason) {

 /* when the callback is used for client operations --> */

 case LWS_CALLBACK_CLOSED:
 case LWS_CALLBACK_CLIENT_CONNECTION_ERROR:
  printf("Closed\n");
  state = 0;
  break;
 case LWS_CALLBACK_ESTABLISHED:
 case LWS_CALLBACK_CLIENT_ESTABLISHED:
  printf("Client connected\n");
  state = 2;
  break;

 /* we will receive our packet here*/
 case LWS_CALLBACK_RECEIVE:
 case LWS_CALLBACK_CLIENT_RECEIVE:
  printf("Rx from server: %s\n", (char *)in);
  if (!strcmp((char *)in, "tcpdump"))
  {
   command_received = 1;
  }
  break;

 /* we will send our packet here */
 case LWS_CALLBACK_CLIENT_WRITEABLE:
  printf("client writing to server\n");
  pss->len = sprintf((char *)&pss->buf[LWS_SEND_BUFFER_PRE_PADDING], "%s", data1.buf + LWS_SEND_BUFFER_PRE_PADDING);

  n = libwebsocket_write(wsi, &pss->buf[LWS_SEND_BUFFER_PRE_PADDING], pss->len, LWS_WRITE_TEXT);
  printf("Data: %s\n\n\n\n\n\n\n", &pss->buf[LWS_SEND_BUFFER_PRE_PADDING]);

  //error handling for write fail and partial writes
  if (n < 0) {
   printf("ERROR %d writing to socket, hanging up\n", n);
   return -1;
  }

  if (n < (int)pss->len) {
   printf("Partial write\n");
   return -1;
  }
  break;

 default:
  printf("default...\n");
  break;
 }

 return 0;
}

/* List of available protocols  */
static struct libwebsocket_protocols protocols[] = {
 {
  "default",  /* name */
  callback_echo,  /* callback */
  sizeof(struct per_session_data) /* per_session_data_size */
 },
 {
  NULL, NULL, 0  /* End of list */
 }
};

void sighandler(int sig)
{
 force_exit = 1;
}

int main(int argc, char **argv)
{
 //pipe stuff
 int pipe_fd[2];

 if (pipe(pipe_fd) < 0)
 {
  perror("PIPE:");
  exit(-1);
 }

 //for libwebsocket_service
 int n = 0;

 //test port can be overidden
 int port = 9000;
 struct libwebsocket_context *context;
 int opts = 0;

 char interface_name[128] = "";
 const char *interface = NULL;

 int use_ssl = 0;
 char ssl_cert[256] = LOCAL_RESOURCE_PATH"/libwebsockets-test-server.pem";
 char ssl_key[256] = LOCAL_RESOURCE_PATH"/libwebsockets-test-server.key.pem";

 int listen_port = 80;

 struct lws_context_creation_info info;
 char passphrase[256];
 char uri[256] = "/";
 char address[256], ads_port[256 + 30];

 //lws servicing time intervals
 int rate_us = 250000;
 unsigned int oldus = 0;

 struct libwebsocket *wsi;

 //should check this
 int debug_level = 2;

 memset(&info, 0, sizeof info);

 lwsl_notice("Built to support client operations\n");

 //re-configuring server ip and port here
 if (argc == 3)
 {
  strncpy(address, argv[1], sizeof(address) - 1);
  address[sizeof(address) - 1] = '\0';
  port = atoi(argv[2]);
 }
 else if (argc == 1)
 {
  strncpy(address, "localhost", sizeof(address) - 1);
  address[sizeof(address) - 1] = '\0';
  port = 9000;
 }
 else
 {
  printf("Try: ./client.exec <ip> <port>\n");
  exit(-1);
 }

 /* we will only try to log things according to our debug_level */
 setlogmask(LOG_UPTO (LOG_DEBUG));
 openlog("lwsts", 0, LOG_DAEMON);

 /* tell the library what debug level to emit and to send it to syslog */
 lws_set_log_level(debug_level, lwsl_emit_syslog);
 lwsl_notice("libwebsockets echo test - "
   "(C) Copyright 2010-2015 Andy Green <andy@warmcat.com> - "
   "licensed under LGPL2.1\n");

 lwsl_notice("Running in client mode\n");

 listen_port = CONTEXT_PORT_NO_LISTEN;

 lwsl_info("requiring server cert validation againts %s\n", ssl_cert);
 info.ssl_ca_filepath = ssl_cert;

 info.port = listen_port;
 info.iface = interface;
 info.protocols = protocols;

#ifndef LWS_NO_EXTENSIONS
 info.extensions = libwebsocket_get_internal_extensions();
#endif

 info.gid = -1;
 info.uid = -1;
 info.options = opts;

 context = libwebsocket_create_context(&info);
 if (context == NULL) {
  lwsl_err("libwebsocket init failed\n");
  return -1;
 }

 signal(SIGINT, sighandler);

 n = 0;

 while (n >= 0 && !force_exit)
 {
  //do connect only once
  if (!state) {
   state = 1;
   printf("Client connecting to %s:%u....\n", address, port);

   address[sizeof(address) - 1] = '\0';
   sprintf(ads_port, "%s:%u", address, port & 65535);

   wsi = libwebsocket_client_connect(context, address, port, use_ssl, uri, ads_port, ads_port, NULL, -1);
   if (!wsi) {
    printf("Client failed to connect to %s:%u\n", address, port);
    goto bail;
   }
  }

  if (command_received == 1 && !forked)
  {
   printf("Going to fork\n");
   forked = 1;
   pid_t child_pid = fork();

   if (child_pid == -1)
   {
    perror("FORK:");
    exit(-1);
   }

   else if (child_pid == 0)
   {
    close(pipe_fd[0]);
    printf("Starting tcpdump\n");

    if (dup2(pipe_fd[1], 1) < 0)
    {
     perror("DUP2:");
     exit(-1);
    }

    //closing the connection to server for child
    libwebsocket_context_destroy(context);
    closelog();

    char *cmd[] = {"tcpdump", "-i", "any", NULL};

    if (execv("/usr/sbin/tcpdump", cmd) < 0)
    {
     perror("EXECV:");
     exit(-1);
    }
   }
  }

 /* if (forked == 1)
  {
   close(pipe_fd[1]);
  }
*/
  if (command_received == 1)
  {
   //stay here if the pipe is empty else try to read max 1400 bytes of data
   while ((data1.len  = read(pipe_fd[0], data1.buf + LWS_SEND_BUFFER_PRE_PADDING, 1400)) <= 0);
   //check if server wants any service

   //printf("%s\n\n\n\n\n\n\n", data1.buf + LWS_SEND_BUFFER_PRE_PADDING);
   libwebsocket_callback_on_writable(context, wsi);
  }

  //This fn times out every 10usec
  n = libwebsocket_service(context, 10);

 }

 //bail: jump from while loop also if connect fails
bail:
 libwebsocket_context_destroy(context);

 printf("libwebsockets-test-echo exited cleanly\n");
 closelog();

 return 0;
}

This is my server code by using socket.io

var io = require('socket.io')();
var middleware = require('socketio-wildcard')();

io.use(middleware);

io.on('connection', function(socket) {
  console.log('On socket connection')
  socket.on('*', function(event, data){
    console.log("---- Event ----- : " + JSON.stringify(event));
    console.log("---- Data ----- : " + JSON.stringify(data))
  });
});

io.listen(9000, 'localhost');

The client is unable to connect with server. when i tested client with strace it infinitely does receive as below

recv(8, "", 1, 0)                       = 0
recv(8, "", 1, 0)                       = 0
recv(8, "", 1, 0)                       = 0
.
.
.
.

Please point out my mistake. Any help is appreciated.
Thanks


text:
Q: Setting up my MVC project on IIS 6 I am very new at web development in general and I am trying to publish my first web app.  I am using ASP.Net MVC 1 and IIS 6.  I have read the post How to make ASP.NET MVC work in IIS 6? and Phil Haack's blog post at http://haacked.com/archive/2008/11/26/asp.net-mvc-on-iis-6-walkthrough.aspx.  However, the problem I am having is that I don't have IIS on my own work computer and it is only up on the server I am publishing to.
I don't know what steps need to be taken before I put my build up on the server and what steps are after.  Also, I am not really sure how I should setup my properties on my program before I build on the server.
I am using TFS as source control and using that to create the build and copying to the server.
Any help would be very appreciated.

A: It shouldn't matter that you don't have IIS (of any version) installed on your development machine, but there are two major issues you need to take care of when deploying an ASP.NET MVC site to IIS6, and they are

*

*Getting IIS to invoke MVC's UrlRoutingModule

*Making sure the web server has the appropriate DLLs

Working with IIS
IIS6 only invokes ASP.NET when it sees a filename extension mapped to aspnet_isapi.dll in the URL, and ASP.NET must be invoked in order for MVC's URLRoutingModule to (and hence, any of your controllers) to work. Steve Sanderson has a great write up of the 4 ways you can get around this.
I personally use option 2 in one of my intranet apps because you don't need to mess with aspnet_isapi.dll or URL rewriting. If you just pretend there's some .aspx file in each of your routes, it's good enough to trick IIS. (eg. {controller}.aspx/{action}/{id})
Make sure the web server has appropriate DLLs
Your server may already be set up, so this may not be necessary. The server must have the .NET framework 3.5 installed. If ASP.NET MVC isn't installed, you'll need to add the following to your application's Bin directory:

*

*System.Web.Mvc.dll

*System.Web.Abstractions.dll (only if .NET 3.5 SP1 is not installed)

*System.Web.Routing.dll (only if .NET 3.5 SP1 is not installed)

Hope that helps.

A: I always create a subdomain: dev.domain.com
I deploy my site to the sub-domain first, test like crazy, then deploy to the real location.
I am not really sure what you are asking, since it will probably be different for every site, so just test, fix, repeat.

A: I'd recommend following the steps here, and let us know what problems you're having if that doesn't work.

A: Is there some reason you can't do your testing on the local built-in Visual Studio web server?
For deploying, go to Build | Publish, then copy the contents of the output directory to your server.

A: Url rewriting can help you to solve the problem. I've implemented solution allowing to deploy MVC application at any IIS version even when virtual hosting is used.
http://www.codeproject.com/KB/aspnet/iis-aspnet-url-rewriting.aspx


text:
Q: How to make two specific lengths of regression lines in a single plot in R? I did linear regression in minitab
I want to produce a nice plot in R but I cannot figure out how to limit the length of the lines. I was be able to produce something like
this
but I want to limit the length of the lines and want to make one just like the minitab output.
Thanks for your time and help !
Here is the code:
plot(y=c(-3,-2,-1,0,1,2),  x=c(-102,-100,-98,-96,-94,-92), type="n", xlab = 'Longitude', ylab = 'Factor4Score')
g <- points(f1[1:38] ~ LON[1:38], col = "red", pch=21)
g.lm <-lm(f4[1:38] ~ LON[1:38])
abline(g.lm, col = "red")
plot(y=c(-3,-2,-1,0,1,2), x=c(-102,-100,-98,-96,-94,-92), type="n", xlab = 'Longitude', ylab = 'Factor3Score')
s <-points(f4[39:102] ~ LON[39:102], col="green",pch=23 )
s.lm <-lm(f4[39:102] ~ LON[39:102])
abline(s.lm, col = "green")

A: Instead of using
abline(g.lm, col = "red")
abline(s.lm, col = "green")

you can use the built in lines() function to create your regression lines.
In your example, I would use
lines(x = -102:-95, y = coefficients(g.lm)[1] + coefficients(g.lm)[2]* (-102:-95), col = 'red')
lines(x = -95:-92, y = coefficients(s.lm)[1] + coefficients(s.lm)[2]* (-95:-92), col = 'green')


text:
Q: Referencing CreateJS from Flash CC 2015 Does anyone know how to reference createjs from Flash CC 2015?
I've been trying out this tutorial page for preloadJS:
http://code.tutsplus.com/tutorials/using-createjs-preloadjs-soundjs-and-tweenjs--net-36292
but when running the next line, the JavaScript console complains that createjs is undefined:
var preload = new createjs.LoadQueue(true);

I'm new to CreateJS and I'm trying to get a good grasp of the HTML5 workflow of CC 2015.

A: Okay, we figured it out:
If you don't include a bitmap image in your Flash library, Flash will not put this into the HTML file, causing references to preloadJS to fail:
<script src="http://code.createjs.com/preloadjs-0.6.1.min.js"></script>
To force it to insert include, stick in any external image, and that will force it to put in preloadJS in the HTML file. A 1x1 transparent pixel will do. Cheers all!

A: With regards to this URL that you referenced above:
http://code.tutsplus.com/tutorials/using-createjs-preloadjs-soundjs-and-tweenjs--net-36292  This link looks like it is showing the output from Flash CS6 resultant from the publishing with CreateJS Tool kit.
On the other hand FlashCC has CreateJS "stuff" already baked into the IDE.  All you have to do is set up a NEW FLA for "canvas" output.  This output depends on the CreateJS tool kit when publishing.  In addition, there are some differences between the tool kit for CS6 and canvas output in CC.  In particular is the way the two handle imagery within the Flash environment.  CreateJS tool kit for CS6 will bring each image separately.  In contrast to FlashCC output, if you have two or more images, the code will automatically set up an image sprite sheet and an associated JSON file to tell the code where to "cut" programmatically to get the right imagery.
A sprite sheet for multiple images really helps in loading in assets; its quicker and it reducing the total number of server requests.
The preloadjs.min.js is simply code to aide in the loading in of the imagery assets. It will automatically be put into the HTML IF the code needs it.
I do this all the time with my creative work.  I'll start out with crude PSD cuts of images that i need in my final out put.  I will test publish to make sure it looks right.  I will then, if feasible, make SVG (scale-able vector graphics) to replace the original PNGs, GIFs or JPGs I put into the FLA.  After publishing to test, and if I was to remove all images for SVGs, my HTML output would no longer need that prelaodJS file any longer.  And generally speaking if I made the correct choices (SVG for images or visa versa), my file overall size would also go down.
Hope this helps,
B

A: You should have a line that says
<script src="http://code.createjs.com/createjs-2013.12.12.min.js"></script>`

See the preload.html file in your tutorial.


text:
Q: excel get row range or actual values based on matching value I have the following structure in my excel sheet.
          A         B
      ---------   -----
 1 |  category1   test1
 2 |  category1   test2
 3 |  category1   test3
 4 |  category2   test4
 5 |  category2   test5
 6 |  category3   test6
 7 |  category3   test7
 8 |  category3   test8
 9 |  category3   test9
10 |  category4   test10

Can you suggest a way using EXCEL functions (not VBA) of getting back either the range or the actual values given the category text as input?
For example given category2 I need to get back something like B4:B5 or "test4"/"test5"
I need a way of doing this dynamically i.e. I need a function that will still work if I do an insert and add a new value to a category e.g.
          A         B
      ---------   -----
 4 |  category2   test4
 5 |  category2   test5
 6 |  category2   test200
 7 |  category2   test203

Now given category2 I would get back B4:B7

A: Assuming categories are always contiguous, you can get reference:
=OFFSET($A$1,MATCH("category2",$A:$A,0)-1,1,COUNTIF($A:$A,"category2"))

A: If your category always starts with the same prefix, you could use something like:
=ADDRESS(MATCH("category"&$C$1,B:B,0),2,4,1)&":"&ADDRESS(MATCH("category"&($C$1+1),B:B,0)-1,2,4,1)

So if you put "2" in C1, it will return "B4:B5"
This also assumes that categories are named in increasing values, so if there was no category3 this would not work.


text:
Q: Flutter: account-exists-with-different-credential after changing Facebook app I was using a temporal Facebook app but today I moved to the final one with a different account so I had to change app ID and secret app ID from my flutter app.
I also modified these IDs from Firebase and downloaded again the GoogleService-Info.plist. The functionality and migration to the new app is working.
The problem is that many users created an account using the previous Facebook app and now, when they login they get this: account-exists-with-different-credential.
I had this fixed for Google/Facebook accounts doing something like this (for example a Facebook user already registered with Google):
if (signInMethods.first == 'google.com') {
   return await googleSignIn(context, email, credential);
}

So we would display the login with Google instead after trying with Facebook.
What's the problem now? That these old users are getting facebook.com and I cannot show again the Facebook login due to infinite loop.
For each user I have some info (name, email and picture) and some collections. How can I overwrite these info?


text:
Q: HTML, why aren't columns staying in a row? Bootstrap Fiddle

        <input class="form-control" id="daterange" type="text" placeholder="Run Range"
        maxlength="128" readonly="readonly" style="background-color:White;cursor:pointer;" />

            <button type="button" class="btn btn-primary btn-lg has-spinner" id="btn-search">Go!</button>

I have literally dozens of other instances of rows and columns in my site but this row refuses to behave. Why?

A: input-group class in Bootstrap is displayed as a block element, so it will push anything after it to a new line. If you want the button to be next to the input field, you need to add a class for example input-group-inline and override the default style from Boostrap.
.input-group-inline {
   display: inline-block;
}

A: Your fiddle is missing a reference to bootstrap.css, i added it and it all works fine https://jsfiddle.net/ujbh3z4p/ try checking the references in your html

A: Remove padding from a row. This can cause to rows to be different widths.


text:
Q: Possible to use USBTinyISP as an FTDI? So, I have an atmega328p and I need to communicate with a computer from it, so I need an FTDI. However, all I have is a USBTinyISP. Is there some way I could hack something together so that I can use the FTDI in the USBTinyISP as a general FTDI without having to mess with the firmware of the USBTinyISP?

A: If all you need is serial communication with the computer then yes this can be done. However, if you need true FTDI functionality (i.e. using an FTDI driver on the computer etc.) then you need an FTDI chip.
For an example of serial communication to the computer using the SPI lines from the USBTinyISP see here. That should do for a basic FTDI serial comm port type interface, but like I said it is not actually an FTDI comm port emulator IC.

A: The USBTinyISP I can find (http://dicks.home.xs4all.nl/avr/usbtiny/) has not FTDI chip in it, so the answer is obviously NO.


text:
Q: method in JavaScript object didnt work i write this sourse, but i dont understand why if i put this.isExist() function inside the chat() function (the main function), its didnt work.
but if i put this.isExsist() function outside the this.chat function, its works as well.
someone can explain to me why its like this?

here is the source that didnt work:
 new chat 1

 new chat 2

 new chat 3

 new chat 4

 new chat 5

here is the source that works fine:
 new chat 1

 new chat 2

 new chat 3

 new chat 4

 new chat 5

A: You are using the "method" before it's being defined!
Just grab it up (above the line that uses it) and should work fine.
Hope it helps
function chat(id, nic) {
    // ....

    if (this.isExist(id) == false) {     // At this stage, your method is not yet defined
        this.arrChat['i']++;             // It should be put above this line for example
        this.arrChat['n']++;
        this.arrChat[this.arrChat['i']] = [id,nic];

        design = "
 nnn

 info "
               + this.arrChat['i'] + " - "
               + this.arrChat[this.arrChat['i']].toString()
               + "
";
        document.getElementById('chatBar.' + this.arrChat['n']).innerHTML = design;
    }

    // ....
}

Hope it helps


text:
Q: sql database design default value is it nesessary to add a default value to int,bit,datetime... fields? what's the benefit of having a default value?

A: It's only necessary when a field is marked as not nullable.  The benefit is that for a new row, you don't have to explicitly enter values for every field.  This can be especially helpful when adding new fields to an existing schema - you would avoid having to go back and update all your code.
Edit - sorry, here's what I was thinking of.  It's necessary when adding a field that is not nullable to a non-empty table.  MySQL will assign a default value to all fields marked not nullable; not sure about SQL Server.

A: It's not necessary.

*

*If you add a column to a table with existing data, the new column will be initialized. Example: you did not collect some data item for a while, then you started doing so. For the preexisting records, you want 'N/A' or zero or something.

*If you want the same value for a column when a row is inserted and there's a default, you don't have to spell it out in the SQL. Example: all SO users start off with zero reputation.

A: A default constraint just means that if either no value or NULL are provided in an INSERT or UPDATE statement, the DEFAULT constraint value will be used.
Is it necessary to have them defined?  That depends entirely on what the business rules are for the column(s) involved.

A: if you are not allowing nulls in a field (especially a new one added to an existing table) it is a good idea to add a default value. if you do not, existing INSERT code that does not contain the new field will fail because the field's value will be considered null. its also useful on a field like a time-stamp so you don't have to code the value on every insert.
-don

A: The main use is enforcing your domain model, i.e. if a column should be zero rather than null, and if the column is marked as non-nullable then it will either need a default value (preferable) or be enforced at the application layer.
One benefit is that it simplifies your code (i.e. don't worry about handling nulls)
A bit field should almost always be non-nullable and have a default.

A: Useful for two reasons, if you expect 90% of the entries to have the same value e.g. You can default the LANGUAGE column to "EN" and save 90% of your users typing in the two characters. This is escpecially recommend where a foriegn key relationship exists if LANGUAGE was a blank then the insert would fail when referential integrity was enforced - or rows would dissapear if an inner join was made to the LANGUAGES table.
Secondly -- as mention above when adding a new column to a table you need to give it a default value if the column is not nullable.


text:
Q: vlookup with string as variable I've searched the forum and found part of answers, but still can't figure it out.
I have the following vlookup:
=VLOOKUP(B8, '[CONSO_SISO FY15_ME (without TUR-ISR)_BTQ.xlsx]**Abu Shakra**'!$A$13:$N$563, 3, FALSE)

'Abu Shakra' is the name of a sheet in another file.
I have a drop down list with all the sheet names and I would like to be able to change the formula when a different name is chosen from the list.
I tried using =indirect(), but it doesn't seem to work.

A: Use like this:
=VLOOKUP(B8, INDIRECT("'[CONSO_SISO FY15_ME (without TUR-ISR)_BTQ.xlsx]"&A1&"'!$A$13:$N$563"), 3, FALSE)

Where A1 is cell with your sheet name.


text:
Q: Titanium ListView with TextField do an error in Android I have to do a list of people.
This list have 2 fields, name and lastname.
I've created a listview, with a template like this :
                    <ListView id="partenairesList" defaultItemTemplate="template">
                        <Templates>
                            <ItemTemplate name="template">
                                <View class="textField-demi">
                                    Prénom
                                    <TextField bindId="field_name"></TextField>
                                    <View class="border-bottom textField-border"></View>
                                </View>
                                <View class="textField-demi textField-right">
                                    Nom
                                    <TextField bindId="field_lastname"></TextField>
                                    <View class="border-bottom textField-border"></View>
                                </View>
                            </ItemTemplate>
                        </Templates>
                        <ListSection id="partenairesListSection">
                        </ListSection>
                    </ListView>

This work on ios.
But when i add item in list on android, the app is killed with an error.
This is my function who add the item :
function addEmptyItemPartenaire(){
    $.partenairesListSection.appendItems([{
        template:'template',
        field_name:'',
        field_lastname:'',
    }]);
}

This is the console debug with errors :
[WARN] :   TiUIScrollView: (main) [137999,176598] Scroll direction could not be determined based on the provided view properties. Default VERTICAL scroll direction being used. Use the 'scrollType' property to explicitly set the scrolling direction.
[INFO] :   I/dalvikvm-heap: Grow heap (frag case) to 15.674MB for 635812-byte allocation
[WARN] :   dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x40aa9300)
[ERROR] :  TiApplication: (main) [28953,205551] Sending event: exception on thread: main msg:java.lang.ClassCastException: java.lang.String cannot be cast to java.util.HashMap; Titanium 3.2.0,2013/12/20 10:57,d9182d6
[ERROR] :  TiApplication: java.lang.ClassCastException: java.lang.String cannot be cast to java.util.HashMap
[ERROR] :  TiApplication:   at ti.modules.titanium.ui.widget.listview.TiListViewTemplate.updateOrMergeWithDefaultProperties(TiListViewTemplate.java:231)
[ERROR] :  TiApplication:   at ti.modules.titanium.ui.widget.listview.ListSectionProxy.processData(ListSectionProxy.java:432)
[ERROR] :  TiApplication:   at ti.modules.titanium.ui.widget.listview.ListSectionProxy.handleAppendItems(ListSectionProxy.java:492)
[ERROR] :  TiApplication:   at ti.modules.titanium.ui.widget.listview.ListSectionProxy.handleMessage(ListSectionProxy.java:236)
[ERROR] :  TiApplication:   at android.os.Handler.dispatchMessage(Handler.java:95)
[ERROR] :  TiApplication:   at android.os.Looper.loop(Looper.java:137)
[ERROR] :  TiApplication:   at android.app.ActivityThread.main(ActivityThread.java:4931)

Anyone can help me ?

A: My problem is caused by the item object data :
$.partenairesListSection.appendItems([{
    template:'template',
    field_name:'',
    field_lastname:'',
}]);

"field_name" and "field_lastname" are the bind id to my textfield.
So, for set a value, i need to give it an object with a "value" properties :
{
    template:'template',
    field_name:{value:''},
    field_lastname:{value:''},
}

A: Remove defaultItemTemplate="template" from ListView and add template="template" in ListSection. Sometimes Android add random element to ListView it can not be handled by defaultItemTemplate
Additionaly you can create default template:
      <ItemTemplate name="defaultTemplate" height="0dp">
        <View height="0dp">
        </View>
      </ItemTemplate>


text:
Q: UIPrintInteractionController - Limit print copies / Get number of printed copies I'm developing an iPad app that includes the ability to print a document.  Some documents require rights management wherein a limited number of copies may be printed and the number of copies printed must be recorded.
I've scoured the UIPrintInteractionController documentation and have found no such capabilities.  This question was asked here over a year ago: iOS Printing UI - limit number of copies and at the time this feature was not available - here's hoping it has since changed.
My questions are:

*

*A year later, does cocoa touch still not have the ability to limit number of copies that can be printed?

*Is there any way to GET the number of copies printed?

*Is one forced to use the UIPrintInteractionController?  If I'm unable to set or get copies, then I may be forced to write my own (if at all possible).

A: Trying to control the number of copies a user can print using UIPrintInteractionController.
I have the same problem and I was walking home and it hit me. Why dont I just create a category for the UIStepper and override its behavior.
I dont use the UIStepper in my app so this wont effect my app, but if you do theres probably a way you can selectively apply this code.
Anyway, you want something like this:
@implementation UIStepper (MJStepper)

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.minimumValue = 1;
        self.maximumValue = 1;
    }
    return self;
}

@end

So create a category and include it in the same view which uses the UIPrintInteractionController
Then set the min and max values on init, and BAM. The print modal says 1 copy and has no uistepper. :)
You could set this to any number programmatically or even give the user a fixed range.
I really wish Apple had a full programmatic API for printing.
I am building a Kiosk app and the last thing I want is for the user to be able to print 100 copies of something.
I think the paper type and printer selection is still annoying but I can probably live with that.
Does anyone know if theres a way to control what Paper types your printer supports?
I know theres a delegate callback which I might be able to use to force a specific type of paper so I might try that.
Anyway, hope this helps! :)


text:
Q: Windows Phone 8.1 MenuFlyout Bug? I have an Page AppBar that contains an CommandBar in this command bar I have AppBar Buttons that when on clicked open a MenuFlyout like below:
<AppBarButton Icon="World" Label="Maps" ToolTipService.ToolTip="Map Providers!" IsCompact="True">
                    <AppBarButton.Flyout>
                        <MenuFlyout>
                            <MenuFlyoutItem Click="mapProviderMenuFlyoutItem_Click">Unison Maps</MenuFlyoutItem>
                            <MenuFlyoutItem Click="mapProviderMenuFlyoutItem_Click">Google Maps</MenuFlyoutItem>
                            <MenuFlyoutItem Click="mapProviderMenuFlyoutItem_Click">Bing Maps</MenuFlyoutItem>
                            <MenuFlyoutItem Click="mapProviderMenuFlyoutItem_Click">OpenStreetMap</MenuFlyoutItem>
                            <MenuFlyoutItem Click="mapProviderMenuFlyoutItem_Click">OpenCycleMap</MenuFlyoutItem>
                            <MenuFlyoutItem Click="mapProviderMenuFlyoutItem_Click">OCM Transport</MenuFlyoutItem>
                            <MenuFlyoutItem Click="mapProviderMenuFlyoutItem_Click">OCM Landscape</MenuFlyoutItem>
                            <MenuFlyoutItem Click="mapProviderMenuFlyoutItem_Click">MapQuest OSM</MenuFlyoutItem>
                        </MenuFlyout>
                    </AppBarButton.Flyout>
                </AppBarButton>

The first button works great, it shows all menu items in the menu flyout, however the other buttons are stripping out menu items as the MenuFlyout is not large enough to display all results.
The above code can be added multiple times in the project and results in the same bug.
Does anyone have a solution for this?

A: EDIT: it appears to be a known bug. See this answer for a workaround.

I don't think MenuFlyout is designed for use with an AppBarButton. It's more suitable as a longpress menu on a ListViewItem. In any case, I've never seen MenuFlyout used on an AppBarButton in any official Microsoft apps. Usually they'd use ListPickerFlyout instead.
For example, you could use the following XAML:
<Page
    x:Class="App7.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
    DataContext="{Binding RelativeSource={RelativeSource Self}}">

    <Page.BottomAppBar>
        <CommandBar>
            <AppBarButton Icon="World" Label="Maps" ToolTipService.ToolTip="Map Providers!" IsCompact="True">
                <AppBarButton.Flyout>
                    <ListPickerFlyout ItemsSource="{Binding MapProviders}" />
                </AppBarButton.Flyout>
            </AppBarButton>
        </CommandBar>
    </Page.BottomAppBar>

    <Grid></Grid>
</Page>

with code behind:
public sealed partial class MainPage : Page
{
    public List<string> MapProviders { get; private set; }

    public MainPage()
    {
        this.InitializeComponent();
        this.NavigationCacheMode = NavigationCacheMode.Required;

        MapProviders = new List<string>
        {
            "Unison Maps",
            "Google Maps",
            "Bing Maps",
            "OpenStreetMap",
            "OpenCycleMap",
            "OCM Transport",
            "OCM Landscape",
            "MapQuest OSM"
        };
    }
}

to produce a flyout like this (which is scrollable):

Of course, this is a very simplified example and you could set the ItemsSource by other means.


text:
Q: Кастомная сортировка массива Приходит массив с данными -  [JavaScript, Python, C++, Java, PHP, HTML, CSS]. Нужно сделать сортировку массива, чтоб на выходе получить [Javascript, CSS, HTML, Java, Python, C++]. Никак не могу сделать алгоритм, чтоб дополнительно не присваивать каждому элементу цифровой индекс и сортировать их просто по числам.

A: Вот эффективный алгоритм в синтаксисе ES6.
Вывод смотреть в браузерной консоли, открыв её до запуска скрипта.

var order = ["JavaScript", "Python", "C++", "Java", "PHP", "HTML", "CSS"];

var data = [];

for (var q=0; q<10; ++q) {
  data.push({lang: order[Math.random()*order.length|0], val: q})
}

console.table(data)

function orderData(data, order) {
  var temp = Object.create(null), res = [];

  order = [].concat(order);

  for (var key of order) {
    temp[key] = [];
  }

  for (var x of data) {
    if (!temp[x.lang]) {
      order.push(x.lang);
      temp[x.lang] = [];
    }

    temp[x.lang].push(x);
  }

  for (var key of order) {
    //temp[key].sort(выполнить сортировку по дополнительным параметрам)
    res.push(...temp[key]);
  }

  return res;
}

console.table(orderData(data, order));
console.table(orderData([{lang: 'new', val: -1}].concat(data), order));

console.log(order);


text:
Q: Scale Image to fill ImageView width and keep aspect ratio I have a GridView. The data of GridView is request from a server.
Here is the item layout in GridView:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/analysis_micon_bg"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    android:paddingBottom="@dimen/half_activity_vertical_margin"
    android:paddingLeft="@dimen/half_activity_horizontal_margin"
    android:paddingRight="@dimen/half_activity_horizontal_margin"
    android:paddingTop="@dimen/half_activity_vertical_margin" >

    <ImageView
        android:id="@+id/ranking_prod_pic"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true"
        android:contentDescription="@string/app_name"
        android:scaleType="centerCrop" />

    <TextView
        android:id="@+id/ranking_rank_num"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/ranking_prod_num"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/ranking_prod_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

I request data from server, get image url and load image to Bitmap
public static Bitmap loadBitmapFromInputStream(InputStream is) {
    return BitmapFactory.decodeStream(is);
}

public static Bitmap loadBitmapFromHttpUrl(String url) {
    try {
        return loadBitmapFromInputStream((InputStream) (new URL(url).getContent()));
    } catch (Exception e) {
        Log.e(TAG, e.getMessage());
        return null;
    }
}

and there is the code of getView(int position, View convertView, ViewGroup parent) method in adapter
Bitmap bitmap = BitmapUtil.loadBitmapFromHttpUrl(product.getHttpUrl());
prodImg.setImageBitmap(bitmap);

The image size is 210*210. I run my application on my Nexus 4. The image does fill ImageView width, but the ImageView height does not scale. ImageView does not show the whole image.
How do I solve this problem?

A: I did something similar to the above and then banged my head against the wall for a few hours because it did not work inside a RelativeLayout.  I ended up with the following code:
package com.example;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

public class ScaledImageView extends ImageView {
    public ScaledImageView(final Context context, final AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) {
        final Drawable d = getDrawable();

        if (d != null) {
            int width;
            int height;
            if (MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY) {
                height = MeasureSpec.getSize(heightMeasureSpec);
                width = (int) Math.ceil(height * (float) d.getIntrinsicWidth() / d.getIntrinsicHeight());
            } else {
                width = MeasureSpec.getSize(widthMeasureSpec);
                height = (int) Math.ceil(width * (float) d.getIntrinsicHeight() / d.getIntrinsicWidth());
            }
            setMeasuredDimension(width, height);
        } else {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }
}

And then to prevent RelativeLayout from ignoring the measured dimension I did this:
    <FrameLayout
        android:id="@+id/image_frame"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/something">

        <com.example.ScaledImageView
            android:id="@+id/image"
            android:layout_width="wrap_content"
            android:layout_height="150dp"/>
    </FrameLayout>

A: This will not be applicable if you set image as background in ImageView, need to set at src(android:src).
Thanks.

A: Without using any custom classes or libraries:
<ImageView
    android:id="@id/img"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:adjustViewBounds="true"
    android:scaleType="fitCenter" />

scaleType="fitCenter" (default when omitted)

*

*will make it as wide as the parent allows and up/down-scale as needed keeping aspect ratio.

scaleType="centerInside"

*

*if the intrinsic width of src is smaller than parent widthwill center the image horizontally

*if the intrinsic width of src is larger than parent widthwill make it as wide as the parent allows and down-scale keeping aspect ratio.

It doesn't matter if you use android:src or ImageView.setImage* methods and the key is probably the adjustViewBounds.

A: Yo don't need any java code. You just have to :
<ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:adjustViewBounds="true"
    android:scaleType="centerCrop" />

The key is in the match parent for width and height

A: To create an image with width equals screen width, and height proportionally set according to aspect ratio, do the following.
Glide.with(context).load(url).asBitmap().into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {

                        // creating the image that maintain aspect ratio with width of image is set to screenwidth.
                        int width = imageView.getMeasuredWidth();
                        int diw = resource.getWidth();
                        if (diw > 0) {
                            int height = 0;
                            height = width * resource.getHeight() / diw;
                            resource = Bitmap.createScaledBitmap(resource, width, height, false);
                        }
                                              imageView.setImageBitmap(resource);
                    }
                });

Hope this helps.

A: I like answer of arnefm but he made a small mistake (see comments) which I will try to correct:
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

/**
 * ImageView that keeps aspect ratio when scaled
 */
public class ScaleImageView extends ImageView {

  public ScaleImageView(Context context) {
    super(context);
  }

  public ScaleImageView(Context context, AttributeSet attrs) {
    super(context, attrs);
  }

  public ScaleImageView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
  }

  @Override
  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    try {
      Drawable drawable = getDrawable();
      if (drawable == null) {
        setMeasuredDimension(0, 0);
      } else {
        int measuredWidth = MeasureSpec.getSize(widthMeasureSpec);
        int measuredHeight = MeasureSpec.getSize(heightMeasureSpec);
        if (measuredHeight == 0 && measuredWidth == 0) { //Height and width set to wrap_content
          setMeasuredDimension(measuredWidth, measuredHeight);
        } else if (measuredHeight == 0) { //Height set to wrap_content
          int width = measuredWidth;
          int height = width *  drawable.getIntrinsicHeight() / drawable.getIntrinsicWidth();
          setMeasuredDimension(width, height);
        } else if (measuredWidth == 0){ //Width set to wrap_content
          int height = measuredHeight;
          int width = height * drawable.getIntrinsicWidth() / drawable.getIntrinsicHeight();
          setMeasuredDimension(width, height);
        } else { //Width and height are explicitly set (either to match_parent or to exact value)
          setMeasuredDimension(measuredWidth, measuredHeight);
        }
      }
    } catch (Exception e) {
      super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
  }

}

Thus your ImageView will be scaled properly and will have no dimension problems if (for instance) put inside of ScrollView

A: I had a similar problem once. I solved it by making a custom ImageView.
public class CustomImageView extends ImageView

Then override the onMeasure method of the imageview. I did something like this I believe:
    @Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    try {
        Drawable drawable = getDrawable();

        if (drawable == null) {
            setMeasuredDimension(0, 0);
        } else {
            float imageSideRatio = (float)drawable.getIntrinsicWidth() / (float)drawable.getIntrinsicHeight();
            float viewSideRatio = (float)MeasureSpec.getSize(widthMeasureSpec) / (float)MeasureSpec.getSize(heightMeasureSpec);
            if (imageSideRatio >= viewSideRatio) {
                // Image is wider than the display (ratio)
                int width = MeasureSpec.getSize(widthMeasureSpec);
                int height = (int)(width / imageSideRatio);
                setMeasuredDimension(width, height);
            } else {
                // Image is taller than the display (ratio)
                int height = MeasureSpec.getSize(heightMeasureSpec);
                int width = (int)(height * imageSideRatio);
                setMeasuredDimension(width, height);
            }
        }
    } catch (Exception e) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

This will stretch the image to fit the screen while maintaining the aspect ratio.

A: Use android:scaleType="centerCrop".

A: Use these properties in ImageView to keep aspect ratio:
android:adjustViewBounds="true"
android:scaleType="fitXY"

A: FOR IMAGE VIEW (set these parameters)
android:layout_width     = "match_parent"
android:layout_height    = "wrap_content"
android:scaleType        = "fitCenter"
android:adjustViewBounds = "true"

Now whatever the size of the image is there, it's width will match the parent and height will be according to match the ratio. I have tested this and I am 100% sure.
we want this -->
not this -->
// Results will be:
Image width -> stretched as match parent
Image height -> according to image width (maximum to aspect ratio)

// like the first one

A: You can try to do what you're doing by manually loading the images, but I would very very strongly recommend taking a look at Universal Image Loader.
I recently integrated it into my project and I have to say its fantastic. Does all the worrying about making things asynchronous, resizing, caching images for you.  It's really easy to integrate and set up. Within 5 minutes you can probably get it doing what you want.
Example code:
//ImageLoader config
DisplayImageOptions displayimageOptions = new DisplayImageOptions.Builder().showStubImage(R.drawable.downloadplaceholder).cacheInMemory().cacheOnDisc().showImageOnFail(R.drawable.loading).build();

    ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext()).
            defaultDisplayImageOptions(displayimageOptions).memoryCache(new WeakMemoryCache()).discCache(new UnlimitedDiscCache(cacheDir)).build();

    if (ImageLoader.getInstance().isInited()) {
        ImageLoader.getInstance().destroy();
    }
    ImageLoader.getInstance().init(config);

    imageLoadingListener = new ImageLoadingListener() {
        @Override
        public void onLoadingStarted(String s, View view) {

        }

        @Override
        public void onLoadingFailed(String s, View view, FailReason failReason) {
            ImageView imageView = (ImageView) view;
            imageView.setImageResource(R.drawable.android);
            Log.i("Failed to Load " + s, failReason.toString());
        }

        @Override
        public void onLoadingComplete(String s, View view, Bitmap bitmap) {

        }

        @Override
        public void onLoadingCancelled(String s, View view) {

        }
    };

//Imageloader usage
ImageView imageView = new ImageView(getApplicationContext());
    if (orientation == 1) {
        imageView.setLayoutParams(new LinearLayout.LayoutParams(width / 6, width / 6));
    } else {
        imageView.setLayoutParams(new LinearLayout.LayoutParams(height / 6, height / 6));
    }
    imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
    imageLoader.displayImage(SERVER_HOSTNAME + "demos" + demo.getPathRoot() + demo.getRootName() + ".png", imageView, imageLoadingListener);

This can lazy load the images, fit them correctly to the size of the imageView showing a placeholder image while it loads, and showing a default icon if loading fails and caching the resources.
-- I should also add that this current config keeps the image aspect ratio, hence applicable to your original question

A: Try this: it solved the problem for me
   android:adjustViewBounds="true"
    android:scaleType="fitXY"

A: Just use UniversalImageLoader and set
DisplayImageOptions.Builder()
    .imageScaleType(ImageScaleType.EXACTLY_STRETCHED)
    .build();

and no scale settings on ImageView

A: try with this simple line... add this line in your xml code in image view tag with out adding any dependency
android:scaleType="fitXY"

A: use android:ScaleType="fitXY" im ImageView xml

A: I had a similar issue, I found the reason for this is because you need to calculate the dp. Android studio is calculating the ImageView when you load it from the drawable, but when you are using another method, like loading from bitmap the dp is not automatically accounted for,
Here is my xml
<ImageView
  android:id="@+id/imageViewer"
  android:layout_width="match_parent"
  android:layout_height="match_parent"//dp is not automaticly updated, when loading from a other source
  android:scaleType="fitCenter"
  tools:srcCompat="@drawable/a8" />

I'm using Kotlin, and loading drawable from an asset file, here's how I calculate this
val d = Drawable.createFromStream(assets.open("imageData/${imageName}.png"), null)
bitHeight = d.minimumHeight//get the image height
imageViewer.layoutParams.height = (bitHeight * resources.displayMetrics.density).toInt()//set the height
imageViewer.setImageDrawable(d)//set the image from the drawable
imageViewer.requestLayout()//here I apply it to the layout


text:
Q: FTP Server not accepting connections despite port being open I'm working on setting up an FTP server, due to my situation I am working through a VPN (Mullvad) and using their port-forwarding feature to open specific ports (this definitely works as I have it working with a Minecraft server and another application). I am using FileZilla Server after trying and failing with the default windows setup.
I seem to have set up port-forwarding properly, as the port registers as open with yougetsignal and like I said I've done this before and it worked. I have the server configured to connect on the open port and it works fine locally.
When I use ftptest to specifically test if the ftp works I get the following: Error: Could not read from socket: Connection reset by peer (I am also unable to connect with my local filezilla client as well as another online ftp client) This is different than the error I get if I try a random port: Error: Could not connect to server: Connection refused.
As far as I know I have set up my firewall, VPN and server properly as tests for each show that they work (VPN & Firewall; port is open & FileZilla server; local connection on the port works) but a combination of both somehow causes issues.
Any help would be much appreciated as I am at somewhat of a loss at this point.


text:
Q: Compare this two columns with different format in hive I have source table: b_ACCOUNT.b_curreny and target table account.currency.
The source table b_ACCOUNT.b_curreny currency format is 'c' and 'U' and the target table account.currency format is 'CAD' and 'USD'
I use case to change 'c' and 'U' format to 'CAD' and 'USD' and compare this two columns. I use the following query and this query is still compared target column acc.CURRENCY (CAD) with the source column b.b_curreny(c)'
SELECT count(*) count ,
case
WHEN b_curreny ='C' THEN 'CAD'
WHEN b_curreny ='U' THEN 'USD'
ELSE NULL END
FROM ACCOUNT acc
join b_ACCOUNT b on acc.account_NUMBER=b.account_NUMBER
and acc.CURRENCY <> b.b_curreny
If I use the following query, I get error message Invalid table alias or column reference 'souce_currency':
SELECT count(*) count ,
case
WHEN b_curreny ='C' THEN 'CAD'
WHEN b_curreny ='U' THEN 'USD'
ELSE NULL END assource_curreny
FROM ACCOUNT acc
join b_ACCOUNT b on acc.account_NUMBER=b.account_NUMBER
and acc.CURRENCY <> source_curreny
Could you help me to compare these two columns with a different format?

A: The column - source_curreny is created in the select clause of query and being used in the same query. Hence, this error. You may use a outer query to refer to this alias.
If you are interested in the mismatch count, you may try the below query. (I haven't tested it)
SELECT sum (case WHEN b.b_curreny ='C' and acc.CURRENCY!='CAD' THEN 1
             WHEN b_curreny ='U' and  acc.CURRENCY!='USD' THEN 1
             ELSE 0
            END) as mismatch_count
FROM ACCOUNT acc
join b_ACCOUNT b
on acc.account_NUMBER=b.account_NUMBER;


text:
Q: Custom role to link PDF file as static content I am trying to write a custom role for Sphinx to allow linking to PDF files that are then displayed in the browser (rather than being downloaded when using the :download: role).
I have got as far as a role that creates a link to the PDF file:
:pdf:`Document Title <pdf/document.pdf>`

generates something like:
Document Title

However, I don't know how to get Sphinx to copy the pdf directory to the output directory.
Is this possible?

A: Use html_static_path in your conf.py.
html_static_path = ['_static', 'pdf']


text:
Q: Updating a variable based on a list of other variables This is more of a logic question than implementation.
class Step {
  public string StepStatus {get ; set;}

  public List<Task> Tasks {get ; set;}

  public Step() {

    Tasks= new List<Task>() ;
  }

  //on some event I call this method that updates StepStatus based on status of
  //all task statuses

  private void UpdateStepStatusFromTasks() {
    foreach (Task t in Tasks) {
            // t.TaskStatus
            // set StepStatus here
            // LOGIC here

    }
  }
}

Each Task object t has its own TaskStatus string.

*

*if All Task Statuses are "DONE" , set Step Status to "DONE"

*if All Task Statuses are "TODO" , set Step Status to "TODO"

*if one of the Task Statuses are "DOING" , set Step Status to "DOING"

*if one of the Task Statuses are "DONE"  and one is "TODO" , set Step Status to "DOING"
What is the best way to implement this? In terms of code complexity and less kludgyness.
How I solved it :
 private void UpdateStepStatusFromTasks()
        {

            if ( Tasks.All(t => t.TaskStatus.Equals("Not Started")))
                StepStatus = "Not Started";
            else if (Tasks.All(t => t.TaskStatus.Equals("Completed")))
                StepStatus = "Completed";
            else
                StepStatus = "In Progress";

        }

A: foreach(var step in steps)
{
    step.StepStatus =
        step.Tasks.All(x => x.Status == "DONE") ? "DONE" :
        step.Tasks.All(x => x.Status == "TODO") ? "TODO" :
        step.Tasks.Any(x => x.Status == "DOING") ? "DOING" :
        step.Tasks.Any(x => x.Status == "DONE ") && step.Tasks.Any(x => x.Status == "TODO") ? "DOING"
        : "UNKNOWN_STATUS";
}

A: As Blorgbeard pointed out, this is the perfect use case for all and any. An example:
tasks.All( (t) => t.Status == Done);

t.Status == Done is just an example, it can be any boolean expression.

A: You could do something like this:
var taskStatuses = Tasks.Select(t => t.TaskStatus).Distinct().ToList();
if (taskStatuses.Count == 1) {
    // all tasks are the same status, so that's the step status
    return taskStatuses[0];
}
if (taskStatuses.Contains("DOING")) return "DOING";
if (taskStatuses.Contains("DONE") && taskStatuses.Contains("TODO")) {
    return "DOING";
}
// whatever other logic you want


text:
Q: How to find the specific BLE 4.0 peripheral from two devices with same service UUID For BLE 4.0, it provides API to discover peripherals with array of service UUID.
I just want to find the specific one. How to achieve this ?
If need assign the identifier to the specific device, how to do it ?
(I think my question need some context of core bluetooth of iOS. )

A: The process for reconnecting to known peripherals is described in the Core Bluetooth Programming Guide.
Essentially if you know the UUID of the device you want to reconnect to (which is the identifier property of the CBPeripheral object) then you can use the retrievePeripheralsWithIdentifiers: method of the CBCentralManager to obtain the CBPeripheral object and then attempt a connection -
NSUUID *pid=[[NSUUID alloc]initWithUUIDString:@"45D956BB-75E4-6CEB-C06C-D531B00174E4" ];
NSArray *peripherals=[self.centralManager retrievePeripheralsWithIdentifiers:@[pid]];
if ([peripherals count]>0)
{
      CBPeripheral *peripheral=[peripherals objectAtIndex:0];
      peripheral.delegate=self;
      [self.connectingPeripherals addObject:peripheral];

      NSLog(@"Found peripheral %@ with name %@",peripheral.identifier,peripheral.name);
      [self.centralManager connectPeripheral:peripheral options:nil];
 }

This may not work, and you may have to scan for your peripheral as the identifier of some peripherals (iOS devices in particular) periodically change their UUID.
The programming guide notes -

Note: A peripheral device may not be available to be connected to for
  a few reasons. For instance, the device may not be in the vicinity of
  the central. In addition, some Bluetooth low energy devices use a
  random device address that changes periodically. Therefore, even if
  the device is nearby, the address of the device may have changed since
  the last time it was discovered by the system, in which case the
  CBPeripheral object you are trying to connect to doesn't correspond to
  the actual peripheral device. If you cannot reconnect to the
  peripheral because its address has changed, you must rediscover it
  using the scanForPeripheralsWithServices:options: method.

You will also have to scan the first time you encounter a peripheral.

A: Tell me if I'm wrong. You have 2 devices working as central role who wants to connect to one BLE peripheral.
What it is important is the UUID of the services in the BLE peripheral. From your devices in central role you should search peripherals with a wanted UUID Service. Thats all.
To develop with iOS please follow Core Bluetooth Programming Guide. You have a good tutorial there.
As an example of the Apple documentation:
[myCentralManager scanForPeripheralsWithServices:nil options:nil];

In this line of code you can add an Array of UUID objects (CBUUID) instead of nil for scanForPeripheralsWithServices:


text:
Q: Can you summon a blind mob in minecraft 1.16 I would like to attempt to fight a zombie that has 84 health and can do 31 damage, just like the warden that will be added in Minecraft 1.17. I know how you can make custom health and damage values, but I do not know how to summon a blind mob. Is it possible to summon a blind mob? Also, give me the exact command to do it if it is possible.

A: You can just throw a splash potion of blindness at him, or execute the command
/effect give @e [name=the name of your creature so zombie] minecraft:blindness 1000000 1 true
1000000 is I believe, the longest amount of seconds you can /give an effect, 1 will make him be able to see only the two or three blocks in front of him, and true is simply so you do not see the particles. You could just decide to erase the true and then the particles would be visible, but you can still turn them down in your visibility settings. Is this for Java, bedrock? And survival or creative? It might be possible in survival, but it would either be extremely hard, or impossible...


text:
Q: Override publish folder (url) of publish profile during the build pipeline We have one ASP.Net solution with several projects.  each project have build.pubxml with unique folder path.
For example:
In project Test we have this line inside the build.pubxml:
<publishUrl>C:\publish\SolutionName\Test</publishUrl>

In project Exam we have this line inside the build.pubxml:
<publishUrl>C:\publish\SolutionName\Exam</publishUrl>

In the build pipeline (in TFS) with have MSBuild step with this argument:
/p:PublishProfile=build.pubxml

After the build we got 2 folders - Test and Exam in C:\publish\SolutionName.
So far so good.
The problem is we have few branches, and we want to separate the publish folder for each branch, so we added .pubxml for each branch and in the build pipeline we specified the correct one. but is make are a lot of work on each new branch created and can cause mistakes.
We tried to pass the /p:publishUrl=C:\publish\BranchName in the MSBuild but then we got a one folder with all the content of Test and Exam and not two folders.
The idea is to have only one .pubxml file for each project with a parameter and pass the value in the pipeline, for example:
<publishUrl>C:\publish\$(Parameter)\Test</publishUrl>

And in the build we will pass the parameter according to the branch.
It is possible to do something like this?

A:
It is possible to do something like this?

The answer is Yes. Since msbuild accepts Global Properties in command-line. If we define one Property in build.pubxml like <publishUrl>C:\PublishFolders\$(BranchID)\xxx(Test,Exam...)</publishUrl>, then we can simply pass the value in msbuild arguments like this:

Then we'll get Test and Exam folders under C:\PublishFolders\NewTest. Also we can choose to pass the pipeline predefined variables to the command like: /p:BranchID=$(Build.SourceBranch)...
This works for build in local machine, tfs and Azure Devops pipeline. Hope all above helps :)


text:
Q: Why is typeof === 'number' not the same as !isNaN(number) I have the following code to solve this problem: https://leetcode.com/problems/letter-case-permutation. The end result should be ["a1b2","a1B2","A1b2","A1B2"] for the string "a1b2"
function letterCasePermutation(str) {
    const res = [];
    helper(str, res, 0, "");
    return res;
}

function helper(str, res, i, slate) {
    const char = str[i];
    const parsed = parseInt(char, 10);
    //base case
    if(i >= str.length) {
        res.push(slate);
        return;
    }

    // if(!isNaN(parsed)){
    if(typeof parsed === 'number') {
        slate = slate += char;
        helper(str, res, i+1, slate)
    }
    // check for letter
    else if(char.toLowerCase() !== char.toUpperCase()) {
        slate = slate += char.toUpperCase();
        helper(str, res, i+1, slate);

        slate = slate += char.toLowerCase();
        helper(str, res, i+1, slate);
    }
}

letterCasePermutation("a1b2"); //[ 'a1b2' ]

The code above doesn't work because when I do:
console.log(typeof parsed === 'number') // false

The result is always false, even if it is a number (1 and 2). However, when I changed this line:
if(typeof parsed === 'number') {

to:
if(!isNaN(parsed)){

It works perfectly. Why is that?

A: The reason is because NaN is a number! This is one of those weird gotchas with javascript that bites all of us in the butt every now and then. The correct way to handle this is by using !isNaN(...) as you did above.
Read more: https://claritydev.net/blog/what-is-the-type-of-nan/


text:
Q: Remove  from column headers in tabulator xlsx export I am using Tabulator as frontend table framework in my browser. Some of my columns have long titles and are splitted by html line breaks (
).
When I download the table data in Excel file format, my column headers (= first row in this spreadsheet export) contain those
 as plain text, e.g.: Foo
bar.
How can I remove these characters in my excel export? Is this even possible? Any ideas?
EDIT
Here a screenshot from my Excel export for clarification:

A: You can specify the title you want to be substituted for in the download here  Download Title as:
columns: [
    { title: "Name", field: "name", titleDownload: "Full Name" } //change column title to "Full Name" in download
]

If you really want to customize things you build your own custom file formatter Custom Format.


text:
Q: Get an object to remove itself from a list in another class? I have a "connection pool handler" which in its class has a array list of "Connection Handlers" I was wondering whether it is possible to have the "Connection Handlers" remove themselves from said list when they close the connections themselves and if so how?
public class ConnectionHandlerPool
{
private static final ArrayList<ConnectionThread> POOL = new ArrayList<ConnectionThread>;

<code to get stuff out of pool>

Connection thread class
public class ConnectionHandlerThread
{
<stuff that creates the connection>
<stuff that if exceptions occur i.e. a stream or socket closes it needs to close all the connections and remove from pool>
<that way of removing it from arraylist in the class above it>

A: The simplest way to achieve this doesn't require complicated listener design or even interfaces. Note: Following code does not take into account all other required logic (checking out, ensuring a connection can't be checked out twice, etc.).
public class ConnectionHandlerPool {
    private static final List<ConnectionThread> pool = new ArrayList<ConnectionThread>();
    // When new threads are created, they get a reference to the pool they're in
    private void addConnection() {
        pool.add(new ConnectionThread(pool));
    }
    private void disconnect(ConnectionThread ct) {
        pool.remove(ct);
    }
}

public class ConnectionHandlerThread {
    private final ConnectionHandlerPool pool;
    public ConnectionHandlerThread(ConnectionHandlerPool pool) {
        this.pool = pool;
    }

    private void destroy() {
        pool.disconnect(this);
    }
}

A: After a bit of tinkering and talking to some technical mates I have resolved it.

*

*Create a interface which has a method in it that takes a ConnectionHandlerThread

*Have the pool implement said interface and have said method remove the ConnectionHandlerThread removed from the arraylist.

*Have the connection handler pool class add itself as a listener to the ConnectionHandlerThread by creating a method called addListener

*Call addListener in the thread and have it pull through the interface

*Call the interface.method from the class when you want to remove it.


text:
Q: Client side React componentDidMount not called (without JSX) I am learning React and following their step by step tutorial but without the use of JSX. I am not very far into the tutorial but I hit a snag. The componentDidMount method is not being called, and so my timer does not update.
Any help would be appreciated.

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>React Test</title>

A: I think the problem is there in one place

*

*ReactDOM.render(new App().render(), document.getElementById("root"));
Why this will not work ?

Because render will return chilren of App component not the App itself
  . Your children will be mounted first and your App is neverbe rendered
  , hence no componentDidMount for App component

the context is not proper.  Try using arrrow funciton here

class App extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                message: "Hello World!",
                date: new Date(),
            }
        }

        componentDidMount() {
          console.log("mounting")
            this.timerID = setInterval(
                () => {
                this.tick()
                },
                1000
            );
        }

        componentWillUnmount() {
            clearInterval(this.timerID);
        }

        render() {
            let fragment = React.createElement(React.Fragment, null, [
                React.createElement("h1", {key: "message"}, this.state.message),
                React.createElement("p", {key: "time"}, this.state.date.toLocaleTimeString())
            ]);

            return fragment;
        }

        tick = () => {
        debugger
            this.setState({
                date: new Date()
            });
        }
    }
    ReactDOM.render(React.createElement(App), document.getElementById("root"));


text:
Q: wordpress editor role remove all but 'menus' in appearance menu I'm trying to remove access to everything in the appearance menu in WP admin for the role editor. Or at the least, just remove access to themes and plugins. I have found how to remove the whole appearance menu but not parts of it like that. is this possible?
Preferably something in functions.php so I could toggle this on/off if ever I needed.

A: by default the editor role should not have access to plugins nor appearance menu. But maybe this roles is already customised in your installation? here is a list of editor default capabilities
via functions.php you can remove everything in the appearance menu like so:
$role_object = get_role( 'editor' );
$role_object->remove_cap( 'edit_theme_options' );

to remove access to plugins you would have to remove some more capabilities i assume. update_plugins, delete_plugins and so on...
otherwise you could use a plugin to handle different roles comfortable.
i do use adminimize quite a while.


text:
Q: Is there a better way for handling SpatialPolygons that cross the antimeridian (date line)? TL;DR
What is the best way in R to handle SpatialPolygons intersecting/overlapping the anti meridian at +/-180° of latitude and cut them into two sections along that meridian?
Preface
This is going to be a long one, but only because I'm going to include a lot of code and figures for illustration. I'll show you what my goal is and how I normally achieve that and then demonstrate how it all breaks together in a literal edge case. As the title suggests, I already found one possible solution to my problem, so I'll include that too. But it is not 100% clean and I'd like to see if somebody can come up with something more elegant. In any case I think this is an interesting problem, as only a couple of days ago I wouldn't have have suspected in my wildest dreams that this could even be an issue in 2019.
Regular work flow in R
First, create an example data set that works
library(sp)
library(rgdal)
library(rgeos)
library(dismo)
library(maptools) # this is just for plotting a simple world map in the background
data("wrld_simpl")

# create a set of locations
locations <- SpatialPoints(coords=cbind(c(50,0,0,0), c(10, 30, 50, 70)), proj4string = CRS("+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0"))
plot(wrld_simpl, border="grey50")
points(locations, pch=19, col="blue")

Looks like this:

Then, I use circles() from the dismo package to create circular buffers around those locations. I use this function, because it takes into account that the Earth is not flat:
buffr <- circles(p = locations, d = 1500000, lonlat=TRUE, dissolve=FALSE)
plot(wrld_simpl, border="grey50")
plot(buffr, add=TRUE, border="red", lwd=2)
points(locations, pch=19, col="blue")

That looks like this:

Then, merge the single buffers into one big (multi-) polygon:
buffr <- buffr@polygons # extract the SpatialPolygons object from the "CirclesRange" object
buffr <- gUnaryUnion(buffr) # merge

plot(wrld_simpl, border="grey50")
plot(buffr, add=TRUE, border="red", lwd=2)
points(locations, pch=19, col="blue")

This is exactly what I need:

The problem
Now observe what happens when we introduce locations that so are close to the anti-meridian (+/-180° of longitude) that the buffer has to cross that line:
locations <- SpatialPoints(coords=cbind(c(50,0,0,0, 175, -170), c(10, 30, 50, 70,0,-10)), proj4string = CRS("+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0"))
buffr <- circles(p = locations, d = 1500000, lonlat=TRUE, dissolve=FALSE)

plot(wrld_simpl, border="grey50")
plot(buffr, add=TRUE, border="red", lwd=2)
points(locations, pch=19, col="blue")

The circles() command does manage to create polygon segments on the other side of the antimeridian (if dissolve=FALSE):

but the polygon crosses the entire globe instead of wrapping around properly (intersecting with 0° instead of 180°). That leads to self-intersections and
buffr <- gUnaryUnion(buffr@polygons)

will fail with

Error in gUnaryUnion(buffr@polygons) :    TopologyException: Input
  geom 0 is invalid: Self-intersection at or near point
  170.08604674698876 12.562175561621103 at 170.08604674698876 12.562175561621103

The quick and slightly dirty solution
First, we need to detect whether a polygon crosses the anti meridian. However, none of them actually intersects +/-180°. Instead, I'm using two pseudo anti meridians that lie close to the real one, but far enough to the east and west to probably intersect the polygons in question. If a polygon intersects both of them, it must also cross the anti meridian.
antimeridian <- SpatialLines(list(Lines(slinelist=list(Line(coords=cbind(c(179,179), c(90,-90)))), ID="1"),
              Lines(slinelist=list(Line(coords=cbind(c(-179,-179), c(90,-90)))), ID="2")),
                                   proj4string = CRS("+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0"))
intrscts <- gIntersects(antimeridian, buffr, byid = TRUE)
any(intrscts[,1] & intrscts[,2])
intrscts <- which(intrscts[,1] & intrscts[,2])
buffr.bad <- buffr[intrscts,]
buffr.good <- buffr[-intrscts,]

plot(wrld_simpl)
plot(buffr.good, border="blue", add=TRUE)
plot(buffr.bad, border="red", add=TRUE)

After having detected and separated the "bad" polygons I simply split them into two separate sections by looking at the longitudinal coordinates. Every coordinate pair that has a negative value there goes into the new western polygon, positive ones into the eastern one. Then I just merge it all back together, do my gUnaryUnion and have pretty much what I need:
buffr.fixed <- buffr.good
for(i in 1:length(buffr.bad)){
  thispoly <- buffr.bad[i,]                              # select first problematic polygon
  crds <- thispoly@polygons[[1]]@Polygons[[1]]@coords   # extract coordinates
  crds.west <- subset(crds, crds[,1] < 0)               # western half of the polygon
  crds.east<- subset(crds, crds[,1] > 0)
  # turn into Spatial*, merge back together, re-add original crs
  sppol.east <- SpatialPolygons(list(Polygons(list(Polygon(crds.east)), paste0("east_", i))))
  sppol.west <- SpatialPolygons(list(Polygons(list(Polygon(crds.west)), paste0("west_", i))))
  sppol <- spRbind(sppol.east, sppol.west)
  proj4string(sppol) <- proj4string(thispoly)

  buffr.fixed <- spRbind(buffr.fixed, sppol)
}
buffr.final <- gUnaryUnion(buffr.fixed)
plot(wrld_simpl, border="grey50")
points(locations, pch=19, col="blue")
plot(buffr.final, add=TRUE, border="red", lwd=2)

The final outcome:

The actual question
So, this solution works for me for my current use case, but it has some issues:

*

*It will probably break completely as soon as one of the buffers crosses both the anti- and the prime-meridian (which is not so unlikely if the original point locations lie close to the poles).

*it is not quite exact, as the two polygon sections are not cut at +/-180° but at the highest negative/positive values of latitude that were present in the original polygon.

*I find it hard to believe that there is no "proper" way of doing this.

So the question all this boils down to is: Is there a better way of doing this?
While I was trying to figure this out, I came across the nowrapRecenter() and nowrapSpatialPolygons() functions from the maptools package, which at first sight looked like they do exactly what I want. Upon closer inspection, they are aimed at pretty much the opposite use case (centering a map on the anti meridian and thus cutting polygons along the prime meridian). I played around with them, but failed to make them work for me – in fact, they only managed to make things worse.
Thanks for you attention!

A: You're right, it's the current year and there is a solution for your problem. The sf-package has the function st_wrap_dateline(), which is exactly what you need.
library(dismo)
library(sf)

locations <- SpatialPoints(coords=cbind(c(50,0,0,0, 175, -170), c(10, 30, 50, 70,0,-10)), proj4string = CRS("+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0"))
buffr <- circles(p = locations, d = 1500000, lonlat=TRUE, dissolve=FALSE)

buffr2 <- as(buffr@polygons, Class = "sf") %>%
            st_wrap_dateline(options = c("WRAPDATELINE=YES")) %>%
             st_union()

plot(wrld_simpl, border="grey50")
plot(buffr2, add=TRUE, border="red", lwd=2)
points(locations, pch=19, col="blue")

st_wrap_dateline converts the polygons which cross the international date line, or "antimeridian", into MULTIPOLYGON. And that's about it.
Does that solve your problem? At least it shortens the way quite a bit, to get where you are now. ^^