text:
Q: Android: Recyclerview in Bottom Navigation Bar Fragment populated with SQLite will not update I have a BottomNavigationBar with 3 fragments. In the first fragment, I try to put SQLite data into a recyclerview. It works fine except for the fact that I need to switch between the Navigation Bar items in order to see the refreshed recyclerview. When I use a handler with postDelayed however, it does show the refreshed recyclerview if I set around 1 sec of delay. 0.2 secs wont work already.
Even though this is still very generic: is there any best practice for this? It seems to me that I need to use AsyncTask which has been -however- deprecated.
Thanks!
Simon
HomeFragment
public class HomeFragment extends Fragment {

    private HomeViewModel homeViewModel;
    private Context context;
    private CardView cardview;
    private LinearLayout.LayoutParams layoutparams;
    private TextView textview;
    private RelativeLayout relativeLayout;
    private myDbAdapter helper;
    RecyclerView myView;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        homeViewModel =
                new ViewModelProvider(this).get(HomeViewModel.class);
        View root = inflater.inflate(R.layout.fragment_home, container, false);

        helper  = new myDbAdapter(getContext());
        myView = (RecyclerView) root.findViewById(R.id.recyclerview_home);
        RecyclerViewAdapter3 adapter = new RecyclerViewAdapter3(new ArrayList<String>(Arrays.asList(helper.classes())));
        myView.setHasFixedSize(true);
        myView.setAdapter(adapter);
        LinearLayoutManager llm = new LinearLayoutManager(getContext());
        llm.setOrientation(LinearLayoutManager.VERTICAL);
        myView.setLayoutManager(llm);

        homeViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {
                textView.setText(s);
            }
        });
        return root;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

    }

    public void refresh(View v){
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            public void run() {
                myView = (RecyclerView) v.findViewById(R.id.recyclerview_home);
                helper  = new myDbAdapter(v.getContext());
                ArrayList<String> classes = new ArrayList(Arrays.asList(helper.classes()));
                ArrayList<String> subClasses = new ArrayList(Arrays.asList(helper.subClasses()));
                RecyclerViewAdapter3 adapter = new RecyclerViewAdapter3(classes);
                myView.setHasFixedSize(true);
                myView.setAdapter(adapter);
                LinearLayoutManager llm = new LinearLayoutManager(v.getContext());
                llm.setOrientation(LinearLayoutManager.VERTICAL);
                myView.setLayoutManager(llm);
            }
        }, 1000); //time in millis
    }
}

RecyclerViewAdapter3
public class RecyclerViewAdapter3 extends RecyclerView.Adapter<RecyclerViewAdapter3.MyViewHolder> {
    public ArrayList<String> classArrayList;
    public ArrayList<String> subClassArrayList;
    myDbAdapter helper;

    public RecyclerViewAdapter3(ArrayList<String> classArrayList){
        this.classArrayList = classArrayList;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View listItem = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview, parent, false);
        return new MyViewHolder(listItem);

    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        holder.class.setText(classArrayList.get(position));

        holder.delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                helper = new myDbAdapter(v.getContext());
                helper.delete(classArrayList.get(position));
                HomeFragment homeFragment = new HomeFragment();
                homeFragment.refresh(v.getRootView());
            }
        });
        holder.selectButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

        }});}

    @Override
    public int getItemCount() {

        return classArrayList.size();
    }

    public static class MyViewHolder extends RecyclerView.ViewHolder {
        private TextView class;
        private Button selectButton;
        private ImageView delete;
        public MyViewHolder(View itemView) {
            super(itemView);
            class = (TextView)itemView.findViewById(R.id.name);
            selectButton = (Button) itemView.findViewById(R.id.selectButton);
            delete = (ImageView) itemView.findViewById(R.id.delete);
        }
    }
}

A: Thanks for posting your code :)
There are a fair few things that can go wrong in your code as it is right now, and I can't really pinpoint what causes it to work when you use postDelay. I'm going to list a few, which you can look into:
From your onClick() inside your ViewHolder

   HomeFragment homeFragment = new HomeFragment();
   homeFragment.refresh(v.getRootView());

You should really not instantiate your fragments like this. You can instead pass a callback from your fragment to your adapter (eg.: View.OnClickListener)
You keep re-instantiating your adapter and your helper needlessly. You should create your adapter only once, set it as your recycler view adapter, and save it in a member variable.
Proposed solution
I see that you're already using ViewModel, so you're on a great path for a less error-prone screen, so I suggest that you move your db query-ing logic to your view model. If you're using raw SQLite (instead of Room), you can extend AndroidViewModel, so you'll have access to a context right away. And as you do with your homeViewModel.getText(), you should expose the classes array as live data, observe it, and submit the new list to your adapter.
For submitting your list to your adapter I suggest using ListAdapter, this will provide you a submitList method for submitting the list in the fragment, and inside the adapter, you will have a getItem(int position) method, which you can query inside the onBindViewHolder method.
Inside your fragment, it'll look something like this:
ClassAdapter adapter = null;

View onCreateView(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState)
    View root = inflater.inflate(R.layout.fragment_home, container, false);

    adapter = new ClassAdapter(
        new ClassDeleteCallback() {
            @Override
            void onClassDeleted(Class class) {
                // inside view model we can modify db state, than refresh live data
                viewModel.deleteClass(class);
            }
        },
        new ClassSelectedCallback() {
            // follows same pattern of above
        }
    );
    RecyclerView rv = root.findViewById(R.id.my_rv);
    rv.setAdapter(adapter);
    rv.setLayoutManager(new LinearLayoutManager(getContext());

    homeViewModel.getClasses().observe(getViewLifecycleOwner(), new Observer<List<Class>>() {
        @Override
        public void onChanged(@Nullable List<Class> classes) {
            adapter.submitList(classes);
         }
     });

    homeViewModel.refreshClasses();
    return root;
}

I can highly recommend for you to study this project a bit, because it covers lot of the basics which can lead to a much stabler app: Sunflower sample app
I think you should read a bit more about the architecture components, and then go through some code-labs and stuff, and have another go with this screen starting from square one, because it will be easier than fixing the current state :)
I hope this was helpful, and not too discouraging!


text:
Q: A convoluted power series for $\log$ I've found in a paper the "standard result", without proof, stating that:
$$ \log(1-2yz+z^2)= -2 \sum\limits_{k=1}^\infty \frac{T_k(y)}{k}z^k \quad \text{for all} \quad \vert y\vert\leq 1 \quad \text{and} \quad \vert z\vert<1 $$
Where $T_k$ is the k-th Chebyshev polynomial. My question is can anyone refer to where one can find a proof of this "standard result", or how to go about finding a way to develop an equation of this form for orthogonal polynomials $\{ Q_k \}$.

A: The generating function of the Chebyshev polynomials of the first kind is
$$ \frac{1-yz}{1-2yz+z^2} = \sum_{k=0}^{\infty} z^k T_k(y) $$
(this really is a standard result: it's the first thing mentioned after the recurrence relation on Wikipedia).
The numerator is almost the derivative of the denominator: subtracting $1=T_0(y)$ and dividing by $-z/2$ gives
$$ \frac{-2y+2z}{1-2yz+z^2} = -2\sum_{k=1}^{\infty} z^{k-1} T_k(y) , $$
and integrating with respect to $z$ from $0$ gives the result (usual results about absolutely convergent power series, etc.)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Etags fails to understand access modifiers for PHP I was trying to generate etags for PHP class files and realised that it doesn't comprehend access modifiers (private/protected/public) and 'static' keyword in front of function declarations! For example, if the file contents are:
<?php
class Foo {
  public static function doBar() {}
  protected function isBaz() {}
}

Running etags -l php on the file will only result in class Foo being recognised. If I drop the keywords in front of function, it recognises the function names correctly.
Does anyone know of a solution for getting etags to identify PHP tags correctly?

A: use exuberant ctags with '-e' option.
find . -name \*php | xargs ctags -e -f TAGS --language-force=php


text:
Q: How can I listen assigned location permisson for the HMS Core? I try to migrate and GMS app to HMS app included maps and location service,But as I understand to get user location via Huawei Location kit, User need to assign location permission to HMS Core app but I can not follow this permission is assigned or not on my app , When the maps ready I check the locations but prompt and an allert about assign the location permission to HMS Core  and I can not listen in this permission assigned or not and it is crash so I want to ask how can I listen User assign the location permission to HMS Core app ? or can i solve this issue with onether way ? can i get the user GPS location without location permission for HMS Core app ? or there is any callback about listen user assign the location permission for the HMS core app

A: Permission request and management is exactly the same as a GMS app, as this is handled by the Android OS. If your original GMS app had the code to check the location permission, it should be fine. Here are two examples of how to setup GMS and HMS location permission checks. You can see that they are quite similar to each other.
Stack Overflow - GMS Location permission example https://stackoverflow.com/a/33070595/14880637
Huawei Developer - HMS Location Kit setup guide https://developer.huawei.com/

A: checkLocationSettings method may help you.

*

*Call the getSettingsClient() method to obtain a SettingsClient instance.

SettingsClient settingsClient = LocationServices.getSettingsClient(this);

*Call checkLocationSettings() to check the device location settings.

LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
mLocationRequest = new LocationRequest();
builder.addLocationRequest(mLocationRequest);
LocationSettingsRequest locationSettingsRequest = builder.build();
// Check the device location settings.
settingsClient.checkLocationSettings(locationSettingsRequest)
    // Define the listener for success in calling the API for checking device location settings.
    .addOnSuccessListener(new OnSuccessListener<LocationSettingsResponse>() {
        @Override
        public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
                LocationSettingsStates locationSettingsStates =
                        locationSettingsResponse.getLocationSettingsStates();
                StringBuilder stringBuilder = new StringBuilder();
                // Checks whether the location function is enabled.
                stringBuilder.append(",\nisLocationUsable=")
                        .append(locationSettingsStates.isLocationUsable());
                // Checks whether HMS Core (APK) is available.
                stringBuilder.append(",\nisHMSLocationUsable=")
                        .append(locationSettingsStates.isHMSLocationUsable());
                Log.i(TAG, "checkLocationSetting onComplete:" + stringBuilder.toString());
        }
    })
    // Define callback for failure in checking the device location settings.
    .addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(Exception e) {
            // Processing when the device is a Huawei device and has HMS Core (APK) installed, but its settings do not meet the location requirements.
            int statusCode = ((ApiException) e).getStatusCode();
            switch (statusCode) {
                case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                    try {
                        ResolvableApiException rae = (ResolvableApiException) e;
                        // Call startResolutionForResult to display a popup asking the user to enable related permission.
                        rae.startResolutionForResult(MainActivity.this, 0);
                    } catch (IntentSender.SendIntentException sie) {
                        // TODO
                    }
                break;
            }
        }
    });

Could check this Docs for more info.


text:
Q: how can i execute a function once the end of an array is reached? I have the following code...
 var min_val = [{"id":"driverDOA","value":date_of_accident},etc etc...];//put validation elements in an array

       for (var i=0;i<min_val.length;i++)//loop through each element if array
        {
            var object = min_val[i];
            if(object.value == "" || object.value == null)//if element is null or empty then execute code
                {
                    document.getElementById(object.id).parentNode.innerHTML += '
*
';
                    document.getElementById('accident-tab').innerHTML += '
*
';
                    return false;
                }
            else
                {
                    $('.prompt accident').remove();
                                            sendAjaxRequest();
                }
        }

basically,I'm validating a form by storing the elements required in an array. I then loop through the array and check for any empty values. If the user has left a value then an asterisk is shown next to that element and on the tab for that section.
Once the user has filled in all of the marked form elements then the code removes the asterisks and send an Ajax request.
However at the moment once an empty element has been found it displays the asterisk for that and stops.
What i need is for it to loop through the entire array each time and display all asterisks. I have a feeling that this will be remarkably simple but have been unable to find anything or figure it out.
Any help would be appreciated

A: var hasError=false;
for (var i=0;i<min_val.length;i++)//loop through each element if array
        {
            var object = min_val[i];
            if(object.value == "" || object.value == null)//if element is null or empty then execute code
                {
                    document.getElementById(object.id).parentNode.innerHTML += '
*
';
                    document.getElementById('accident-tab').innerHTML += '
*
';
                    hasError= true;
                    //return false; // remove this...
                } else $('.prompt accident').remove();
        }
  if(!hasError) {
       sendAjaxRequest();
  }

A: Here
Change return false to noerror=false, add var noerror=true to before the loop and end the function with return noerror
Like this
var noerror=false, min_val = [{"id":"driverDOA","value":date_of_accident},etc etc...];//put validation elements in an array
$('.prompt accident').remove(); // reset
for (var i=0;i<min_val.length;i++) { //loop through each element if array
  var object = min_val[i];
  if(object.value == "" || object.value == null) { //if element is null or empty then execute code
    document.getElementById(object.id).parentNode.innerHTML += '
*
';
    document.getElementById('accident-tab').innerHTML += '
*
';
    noerror=false;
  }
 }
 if (noerror) {
  sendAjaxRequest();
 }
 return noerror;
}

A: Don't return false. Just continue.
Edit: A better solution would be:
 var min_val = [{"id":"driverDOA","value":date_of_accident},etc etc...];//put validation elements in an array
       var valid = true; // I MADE A CHANGE HERE
       for (var i=0;i<min_val.length;i++)//loop through each element if array
        {
            var object = min_val[i];
            if(object.value == "" || object.value == null)//if element is null or empty then execute code
                {
                    document.getElementById(object.id).parentNode.innerHTML += '
*
';
                    document.getElementById('accident-tab').innerHTML += '
*
';
                    valid = false; // AND HERE
                }
            else
                {
                    $('.prompt accident').remove();
                                            sendAjaxRequest();
                }
        }
        return valid; // AND HERE


text:
Q: NSArray arrayWithObjects and undefined variables So let's say I'm trying to piece together someone's name, I have my variables:
@synthesize firstName = _firstName;
@synthesize middleName = _middleName;
@synthesize lastName = _lastName;

And I had a method where I wish to join these variables with a space in the middle, so I use:
NSArray *fullName = [NSArray arrayWithObjects:_firstName, _middleName, _lastName, nil];
self.fullName = [fullName componentsJoinedByString:@" "];

However, if _firstName is undefined, or nil, then the rest of the variables don't get added to my fullName array. What's another way around this?
The problem I want to solve is finding an efficient way of adding joining multiple strings together in a manner that'll avoid having extra whitespace.

A: Here is what I would do. When you initialize your names before they get loaded in set them to a blank string @"". This way they are never nil just empty.
Edit: You then could use the function below to build them together
- (NSString *)fullName:(NSArray *)names
{
    NSInteger c = 0;
    NSString *fullName = @"";
    for (NSString *name in names)
    {
        if ([name length] > 0)
        {
            if (c != 0)
            {
                fullName = [fullName stringByAppendingString:@" "];
            }
            fullName = [fullName stringByAppendingString:name];
            c++;
        }
    }
    return fullName;
}

A: Another option would be to use variable argument list. The downside is you either need to use a null terminal list (which is basically what arrayWithObjects: is) or specify or how many arguments you have.
See - http://www.cocoawithlove.com/2009/05/variable-argument-lists-in-cocoa.html.
It would look something like this
-(NSMutableArray *) arrayWithNumber:(int) num withValues:(NSString *)firstArg,...
{
    NSMutableArray *array = [[NSMutableArray alloc] init];

    va_list args;
    va_start(args, firstArg);
    NSString *arg = firstArg;

    for (int i = 0; i < num; i++)
    {
        // We have the first argument from va_start, so only grab the additional ones
        if (i > 0)
            arg = va_arg(args, NSString*);

        if (arg!= nil)
        {
            [array addObject:arg];
        }
    }

    return array;
}

-(void) testMethod
{
    NSString *first = @"First";
    NSString *second = nil;
    NSString *third = @"Third";

    NSMutableArray *a = [self arrayWithNumber:3 withValues:first,second,third];
    NSLog(@"%@",a);
}

Of course for you situation this is probably overkill but thought I would throw it out there as a possibility if you are dealing with something different then what you shown.

A: I would do something like this (using literals):
NSArray *fullName= @[(_firstName ? _firstName : [NSNull null]),
    (_middleName ? _middleName : [NSNull null]),
    (_lastName ? _lastName : [NSNull null])
];

A: So I took some inspiration from @GregP and @ansible and wrote this:
First I assigned empty strings to each variable
-(id)init {
    self = [super init];

    _firstName = @"";
    _middleName = @"";
    _lastName = @"";

    return self;
}

Then in my method I ran them through a loop:
-(void)updateFullName {
    NSMutableArray *fullName = [[NSMutableArray alloc] init];
    NSArray *names = @[_firstName, _middleName, _lastName];

    for (NSString *name in names) {
        if ([name length]) {
            [fullName addObject:name];
        }
    }

    self.fullName = [fullName componentsJoinedByString:@" "];
}

This meant that I can deal with a larger number of variables and also get around the problem of extra whitespace in the self.fullName final value.

A: I would make a loop or check all the strings before appending to the result and avoid using componentsJoinedByString, but if you really want to use it then this code works:
NSString *firstName = @"First";
NSString *middleName = nil;
NSString *lastName = @"Last";

NSMutableArray *fullNameArray = [NSMutableArray arrayWithArray:@[firstName ?: [NSNull null], middleName ?: [NSNull null], lastName ?: [NSNull null]]];
[fullNameArray removeObjectIdenticalTo:[NSNull null]];

NSString *fullName = [fullNameArray componentsJoinedByString:@" "];

NSLog(@"Full Name: '%@'", fullName);

And the result is:
Full Name: 'First Last'

A: You could ensure that _firstName, _middleName, and _lastName are not nil by initializing them with an empty value. Potentially in viewDidLoad you could do the following:
_firstName = [NSString string];
_middleName = [NSString string];
_lastName = [NSString string];

A: Try use an if statement?
if (_firstName && _middleName && _lastName){
    NSArray *fullName = [NSArray arrayWithObjects:_firstName, _middleName, _lastName, nil];
    self.fullName = [fullName componentsJoinedByString:@" "];
} else {
    //Behaviour you want if there is some missing.
}


text:
Q: regex - split only if a letter followed by comma + comma + ignore comma in bracket I am trying to figure out a way to split values based on a comma in regex but the problem is that I want to ignore commas that are inside the parenthesis ()
example :
'hist1234,geog293,lap_933,(a-20,110,60),(z-8,9,10),POLY5,9,3,8,ro water'

expected output :
['hist1234', 'geog293', 'lap_933', '(a-20,110,60)', '(z-8,9,10)', 'POLY5,9,3,8', 'ro water']

I tried: ,\s*(?![^()]*)) for the comma and ignoring the comma in brackets but im unsure about the ignoring if its a number followed by a comma

A: Since you guaranteed "no parenthesis inside a parenthesis" then this would work:
regex
,(?![^()]+\))(?=[a-zA-Z(])

replace
,

^ comma + space
If splitting then just ignore the replace.
https://regex101.com/r/Mk8mAI/1

*

*, - capture a comma

*(?![^()]+\)) - guarantee that ahead of me is not content followed by a closing parenthesis

*(?=[a-zA-Z(]) - guarantee that ahead of me is a letter or opening parenthesis


text:
Q: Background-image in jQuery Mobile I m beginner at jQuery , I have a problem to fix background , the image appears the display in 1 sec
<body id="content" style="display: none;background-image:url('images/wood.jpg'); ">

A: You're setting the display to none therefore after 1 second you'll need to remove this.
You should use the window.setTimeout function. 1000 ms = 1 second.
setTimeout
You can set the visiblity using jQuery like so:
$("#content").show();

So a complete code example would be:
setTimeout(function(){
 $("#content").show();
},1000)


text:
Q: No Voronoi polygons created I want to create the Voronoi diagram from a set of point (see below). When I use the "Voronoi Polygons" tool from QGIS, there is an error :

File
  "C:/PROGRA~1/QGIS3~1.0/apps/qgis/./python/plugins\processing\algs\qgis\VoronoiPolygons.py",
  line 128, in processAlgorithm self.tr('There were no polygons
  created.'))
  _core.QgsProcessingException: There were no polygons created.

What do you think is the reason for that?
I use QGIS 3.0, and the tool works for other sets of points (random, for example).

A: Just a guess, but perhaps you have multiple instances of points on top of one another? As a multi-point layer. That would create an error where no voronoi polygons are created.
Also, check out your coordinate systems - perhaps there is a discrepancy there.

A: Several problems with the QGIS Voronoi tool were fixed in QGIS 3.2.2.
Please try again with the lasted QGIS version.


text:
Q: Automatic SSH tunneling from Windows I'm trying to set up a Windows computer to always have two SSH tunnels to my Linux server.
Currently, I'm using PuTTY to open the two SSH tunnels: I log in to the server in PuTTY, leave it minimized, and never touch it. This works well, except when the SSH connection drops: PuTTY displays an error message, and I need to manually close the error and reconnect to the server.
What I'd like to do is have an application that can set up the two SSH tunnels, and can automatically reconnect, without needing to manually do anything, including enter a password. The data I'm sending across the two tunnels is VNC connections, so I often won't be at the machine to clear errors and enter passwords. The two tunnels are one local tunnel, and one remote tunnel.
(Yes, I am aware of the hazards of automatically logging in to SSH. I'm planning on making a dedicated user with no privileges and not allowed to interactively log in, and use that.)
I did find this question: How to reliably keep an SSH tunnel open?, but that's using Linux as the SSH client, and I'm using Windows.

A: I tried many solutions like SSH tunnel managers, but all were inconvinient for me: too many configuration screens, sometimes buggy (one time SSH tunnel manager purged all! settings I had! So I had to restore settings for all 30 tunnels). So they all lost my trust. That's why I come up with custom Powershell script, easy configurable, changeable, small, but works. Posted here and below:
To start using it you need a config like this:
# LocalPort TargetHost  TargetPort  SshHost SshUsername SshKeyPath
18080   google.com  80  bastion.example.com User    D:\secure\path\to\private_key.ppk

Save it as a config.csv. And use a powershell script to keep it up is:
<#
.SYNOPSIS
  Powershell script for keeping ssh tunnel up and running

.DESCRIPTION
  This script uses configuration of tunnels located in config.csv. For more information visit http://tsherlock.tech/2019/03/13/simple-ssh-tunnel-auto-reconnect-using-putty-and-powershell/

.NOTES
  Version:        1.0
  Author:         Anton Shkuratov
  Creation Date:  2019-03-13
  Purpose/Change: Initial script development

#>

$currentDir = $PSScriptRoot
if (-not $env:PATH.Contains($currentDir)) {
  $env:PATH="$env:PATH;$currentDir"
}

# Check plink is accessible
try {
  Start-Process plink.exe -WindowStyle Hidden
} catch {
  Write-Host Error running plink.exe Please make sure its path is in PATH environment variable
  EXIT 1
}

# Parse config
$config = [System.IO.File]::ReadAllLines("$currentDir\config.csv");
$bindings = New-Object System.Collections.ArrayList
$regex = New-Object System.Text.RegularExpressions.Regex("(\d)+\s([^ ]+)\s(\d+)\s([^ ]+)\s([^ ]+)\s([^ ]+)", [System.Text.RegularExpressions.RegexOptions]::IgnoreCase);
$keyPasswords = @{}
$procs = @{}

foreach($line in $config) {
  $match = $regex.Match($line)

  if ($match.Success) {
    $sshKey = $match.Groups[6];

    $bindings.Add(@{
      LocalPort = $match.Groups[1];
      TargetHost = $match.Groups[2];
      TargetPort = $match.Groups.Groups[3];
      SshHost = $match.Groups[4];
      SshUser = $match.Groups[5];
      SshKey = $match.Groups[6];
    });

    if (-not $keyPasswords.ContainsKey($sshKey)) {
      $pass = Read-Host "Please enter password for key (if set): $sshKey" -AsSecureString
      $keyPasswords.Add($sshKey, $pass);
    }
  }
}

# Starting Processes
function EnsureRunning($procs, $keyPasswords, $binding) {

  if ($procs.ContainsKey($binding) -and $procs[$binding].HasExited) {

    $proc = $procs[$binding]
    $sshKey = $binding.sshKey
    $out = $proc.StandardError.ReadToEnd()

    if ($out.Contains("Wrong passphrase")) {
      Write-Host "Wrong pass phrase for $sshKey, please re-enter"
      $pass = Read-Host "Please enter password for key: $sshKey" -AsSecureString
      $keyPasswords[$sshKey] = $pass;
    } else {
      $exitCode = $proc.ExitCode
      $tHost = $binding.sshHost

      Write-Host "Connection to $tHost is lost, exit code: $exitCode"
    }
  }

  if (-not $procs.ContainsKey($binding) -or $procs[$binding].HasExited) {
    $sshUser = $binding.SshUser
    $sshHost = $binding.SshHost
    $sshKey = $binding.SshKey
    $lPort = $binding.LocalPort
    $tPort = $binding.TargetPort
    $tHost = $binding.TargetHost
    $sshKeyPass = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($keyPasswords[$sshKey]))

    $psi = New-Object System.Diagnostics.ProcessStartInfo;
    $psi.FileName = "plink.exe";
    $psi.UseShellExecute = $false;

    $psi.CreateNoWindow = $true;
    $psi.RedirectStandardInput = $true;
    $psi.RedirectStandardError = $true;

    $psi.Arguments = "-ssh $sshUser@$sshHost -i `"$sshKey`" -batch -pw $sshKeyPass -L $lPort`:$tHost`:$tPort"

    $proc = [System.Diagnostics.Process]::Start($psi);

    Start-Sleep 1

    if (-not $proc.HasExited) {
      Write-Host Connected to $sshUser@$sshHost
    }

    $procs[$binding] = $proc;
  }
}

function EnsureAllRunning($procs, $keyPasswords, $bindings) {
  while($true) {
    foreach($binding in $bindings) {
      EnsureRunning $procs $keyPasswords $binding
    }
    Start-Sleep 1
  }
}

try {
  # Waiting for exit command
  Write-Host Working... Press Ctrl+C to stop execution...
  EnsureAllRunning $procs $keyPasswords $bindings
} finally {
  # Clean up
  Write-Host Clean up

  foreach($proc in $procs.Values) {
    if ($proc -ne $null -and -not $proc.HasExited) {
      $proc.Kill();
    }
  }
}

After it is configured just run it like:
powershell -File autossh.ps1

A: Two great tools :
Both have those features :

*

*Could be automated at boot

*Opensource

*Manage many tunnels at the same time

*Could reside in the system tray

*Free of charge (Mobaxterm have a free version)

*Encrypt stored password

1. Mobaxterm
Site : http://mobaxterm.mobatek.net/
Capture :

2. SSH Tunnel Manager
Site : https://code.google.com/archive/p/ssh-tunnel-manager/
Capture :

A: Have a look at Xshell - it's more scriptable than PuTTY and is free for home use (if that's where you need to use it). It claims to have an auto-reconnect feature but I haven't tried it and have been on a Linux-based laptop for a good few months now so don't have any means to test it at the mo.

A: Try Bitvise Tunnelier - it works for me. I set it to establish SSH tunnels while only being visible as a tray icon. It establishes the SSH connection on startup and re-establishes it as soon as connectivity is restored after a cut or after the system went to sleep. I still prefer the looks of the Putty console, so I keep using it - but for keeping tunnels up I now use Tunnelier. The only major downside I have found is the lack of IPv6 support, which Putty provides with no user action needed.

A: If your a fan of Putty, try out Putty Tray.
It has a few additional functions, including attempting to auto-reconnect after a connection failure and reconnecting when your computer wakes from standby.
As already mentioned by someone else, I'd combine this with public-key authentication with no pass-phrase.
In theory this should be pretty reliable, but i'm no security expert so can't advise you on that front.

A: Try MyEnTunnel. It can reconnect at connections failures.

A: I googled it and gota a few results for your question, basically you could always try a search combo of automate putty login which I did. Here is a particularly useful result that should suit you:
http://www.neox.net/w/2008/04/22/putty-auto-login-macro-putty-connection-manager/
It walks you through how to setup a macro for putty. Also download Putty connection manager here (as the link is broken from initial link):
http://sourceforge.net/projects/puttycm/

A: I used Putty as well and had the same problem until I found a better solution -
Try ADVSoft Persistent SSH
https://persistentssh.com
works as a Windows service and keeps SSH tunnels in run state. Free for personal use, no need to install anything else.

A: This simple PS script works well for me.
while($true) {
    echo "Starting Proxy"
    ssh <host> -R 23000:localhost:2276 -N
    echo "Connection Error"
    echo "Sleeping 10s"
    Start-Sleep -Seconds 10
}


text:
Q: Displaytag is exporting CSV into a .xls file I export an Excel document with DisplayTag.  It saves as a .xls file to my Desktop.  When I open it with Excel, this error displays:
"The file you are trying to open, 'filename.xls', is in a different format than specified by the file extension.  Verify that the file is not corrupted and is from a trusted source before opening the file."
If I click "Yes", it displays just fine in Excel.  If I open this with Textpad, I see that it's a binary file, but it appears to just be "." delimited strings.
Any ideas what I might have done wrong, or how next to debug this?
edit::
If I change the extension to .txt, it's not a binary file; it's simply a list of delimited strings.

A: Are you on Excel 2007?  Seems to be a known issue:

In some cases after upgrading to Excel
  2007, you may get the following error:
  The file you are trying to open .xlsx
  is in a different format than
  specified by the file extension.
  verify the file is not corrupted and
  is from trusted source before opening
  the file. Do you want to open the file
  now?

This errors particularly occurs when you're trying to open an XLS file (Excel 2000-2003) with Excel 2007. In most cases, the problem can be solved by defining MIME types and associating them with extensions.
...
However, if you don't want to look for a solution, but just want to solve the problem, insert this key in your registry to suppress the notification:
[HKEY_CURRENT_USER\Software\Microsoft\Office\12.0\Excel\Security] "ExtensionHardening"=dword:00000000
You can accomplish the above by doing the following:

*

*Open your Registry (Start -> Run ->
regedit.exe)

*Navigate to
HKEY_CURRENT_USER\SOFTWARE\MICROSOFT\OFFICE\12.0\EXCEL\SECURITY

*Right click in the right window and
    choose New -> DWORD

*Type "ExtensionHardening" as the
name (without the quotes)

*Verify that the data has the value
"0″

A: The default export class for Excel was set to the CSV class, but giving it the .xls extension.  Changing displaytag.properties was the key here, something like:
export.types=csv excel xml rtf pdf
export.excel=true
export.xml=true
export.csv=true
export.rtf=false
export.pdf=false
export.excel.class=org.displaytag.export.excel.DefaultHssfExportView
export.pdf.class=org.displaytag.export.DefaultPdfExportView
export.rtf.class=org.displaytag.export.DefaultRtfExportView
export.excel.filename=data.xls
export.pdf.filename=data.pdf
export.xml.filename=data.xml
export.csv.filename=data.csv
export.rtf.filename=data.rtf

A: You need to add the below lines in your properties file:
export.excel.class=org.displaytag.export.excel.DefaultHssfExportView
export.pdf.class=org.displaytag.export.DefaultPdfExportView

But this outputs the current page record only and not the complete list.


text:
Q: RestAssured Not able to extract response I am trying to get the id_token.basic value but its not working because of .basic
{
    "user_id": "12345",
    "id_tokens": [

        {
            "id_token.basic": "myid123"
        }
    ]

}

Tried the below, but because of .basic its not working.
response.jsonPath().get("id_tokens[0].id_token.basic")

I am able to retrieve user_id using:
response.jsonPath().get("user_id")


text:
Q: What should I learn to really understand NSData, NSMutableData, NSString in iOS? I am an intermediate student in iOS development, I am trying to make a method that uploads an image to a server. I understand the server side scripting in PHP.
But when I am following a tutorial to upload an image in Xcode, I don't really grasp about NSData, NSObject, NSMutableData, NSString, it seems the tutorial doesn't really the fundamental aspect of NSData, NSMutableData, NSString...
If want to take beautiful display, I should learn about auto layout, collection view etc.
So, what kind of topic in iOS development that I should learn to really understand about these things step by step? It seems that I never learn specifically about these things. I don't know where to start.
The code to upload an image is like this:
func createBodyWithParameters(parameters: [String: String]?, filePathKey: String?, imageDataKey: NSData, boundary: String) -> NSData {
        let body = NSMutableData();

        if parameters != nil {
            for (key, value) in parameters! {
                body.appendString("--\(boundary)\r\n")
                body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
                body.appendString("\(value)\r\n")
            }
        }

                let filename = "user-profile.jpg"
                let mimetype = "image/jpg"

                body.appendString("--\(boundary)\r\n")
                body.appendString("Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n")
                body.appendString("Content-Type: \(mimetype)\r\n\r\n")
                body.appendData(imageDataKey)
                body.appendString("\r\n")

        body.appendString("--\(boundary)--\r\n")

        return body
    }

    func generateBoundaryString() -> String {
        return "Boundary-\(NSUUID().UUIDString)"
    }

}

extension NSMutableData {

    func appendString(string: String) {
        let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
        appendData(data!)
    }
}

A: Learning about objects you have described may mean many things. If you are after their capabilities then the documentation should be enough. But if you are more after what is under the hood and why we need these objects then I could only suggest you to look into some older language like C.
These objects NSData, NSMutableData, NSString are all data containers, buffers. But NSObject is just a base class from which all other objects inherit.
So a bit about NSData and NSMutableData:
In C when creating a raw buffer you use malloc which reserves a chunk in memory which you may use as you please. Once done you need to call free to release that memory or you will have a memory leak.
void *voidPointer = malloc(100); // Reserved 100 bytes of whatever data
int *intPointer = (int *)malloc(sizeof(int)*100); // Reserved enough bytes to fit 100 integers whatever their size may be
intPointer[13] = 1; // You may use these as normal array
free(voidPointer); // Free this memory
free(intPointer); // Free this memory

So NSData is basically a wrapper for that and does all of it for you. You may even access the raw pointer by calling bytes on NSData object.
Then the mutable version NSMutableData is just a subclass which has some additional functionality. You may actually append data. From what is under the hood appending data is not so simple. You need to allocate a new memory chunk, copy old data to it, copy new data and release the previous memory chunk.
void *currentData = malloc(100); // Assume we have some data
void *dataToAppend = malloc(100); // Another chunk of data we want to append
void *combinedData = malloc(200); // We need a larger buffer now
memcpy(combinedData, currentData, 100); // Copy first 100 bytes to new data
memcpy(combinedData+100, dataToAppend, 100); // Copy next 100 bytes to new data
free(currentData); // Free old data
free(dataToAppend); // Free old data
... use combinedData here ...
free(combinedData); // Remember to free combined data once done

These are all really simple methods but they may already be pain to write and it is easy to produce bugs doing so. So NSData or NSMutableData and even Data in Swift are all just data containers that make your developer life easier. And in Objective-C conversion from data to C buffers is as easy as it gets:
NSData *myData = [NSData dataWithBytes:myDataPointer length:myDataLength];
void *myRawPointer = [myData bytes];

The NSString is not really that different. In C we again have character pointer which is used as string so we write something like:
char *myText = "Some text";

These are a bit special, a convenience really. We could as well do:
char *myText = (char *)malloc(sizeof(char)*100);

And then fill the data character by character:
myText[0] = 'S';
myText[1] = 'o';
myText[2] = 'm';
...
myText[9] = 't';
myText[10] = '\0'; // We even need to set a null terminator at the end

and then we needed to free the memory again... But never mind the C strings, NSString is again a wrapper that is responsible to allocate the memory, assign data and do whatever you want with it. It has may methods you can use simply to make your life easier.
As to the code you posted it is a combination of the two. In your case your API accepts images as multipart form data requests which you may understand as a raw image file with a few texts added around it just to explain what the data contains. It is one of a generally used way but not the only one. You might as well just post the raw image data or you might even post a JSON containing a base64 string encoded data. Also as usually these texts are represented as an utf8 encoded data.
In the end it is a set of standards that are generally used so our computers may communicate between each other. Your image is most likely defined by a standard from png or jpg on how to present it with a string of bytes, your strings are defined by utf8 standard and your whole request body is defined by some HTTP standards (not even sure what part of it is that). And the objects you use and want to learn about are just some helpers for achieving your result. Understanding them in most cases is like understanding a screwdriver; you won't need to in most cases, but you do need to know they exist and you need to know when to use them.
The code itself you posted is relatively bad but should do its job. For a beginner it might be a bit confusing even. Probably a more logical pseudocode for this solution would be something like:
let imageData: Data // My image data
let headerString: String // Text I need to put before the image data
let footerString: String // Text I need to put after the image data

var dataToSend: Data = Data() // Generate data object
dataToSend.append(headerString.utf8Data) // Append header
dataToSend.append(imageData) // Append raw data
dataToSend.append(footerString.utf8Data) // Append footer

I hope this clears up a few things.


text:
Q: Html.CheckboxFor vs Html.EditorFor vs straight HTML? I'm using a template with custom CSS (.less) for checkboxes (making them appear as "Yes|No", "On|Off", etc.)
Using @Html.CheckboxFor(model => model.BooleanProperty, new { @class="custom-switch" }) results in a checkbox not appearing, at all.
So I got to digging around, found many questions on here with similar issues, but none of the solutions worked for me so far.  The solution I'm currently working on is to use a custom EditorFor template.  This is rendering the checkbox correctly, however, what I'm experiencing is that if the slider is switched to "NO", it's passing across to the controller as null instead of false, and if it's switched to "YES" it's passing across to the controller as "on".
I know that Html.CheckboxFor renders a checkbox element followed by a hidden input element.  What purpose does this serve? Following are rendered HTML from the two methods as well any questions pertaining to that specific :
Straight HTML for Checkbox

    ::before ::after
When this is passed to the controller, why is the value of BoolProperty "true,false"?
@Html.CheckboxFor(model => model.BoolProperty, new { @class="custom-switch" })
<input checked="checked" data-val="true" data-val-required="The BoolProperty is required." id="BoolProperty" name="BoolProperty" type="checkbox" value="true" class="custom-switch">
<input name="BoolProperty" type="hidden" value="false">

What purpose does the hidden input field play?  If I remember right, only the first "BoolProperty" named value would actually be passed to the controller anyways.  I can't find anything that would suggest that one updates the other when the value changes, and through testing, I've noticed that the value does not change.
@Html.EditorFor(model => model.BoolProperty, new { @class = "custom-switch" })
<input type="checkbox" checked name="BoolProperty" class="custom-switch">
::before ::after

Why would this pass across the values of "on" or null to the controller? Why not true and false?
The Boolean Editor Template
@model Boolean?
var isChecked = ViewData["checked"] != null && ViewData["checked"].ToString() == "true";

<input type="checkbox" checked="@(isChecked ? "checked" : string.Empty)" name="@name"  class="@ViewData["class"].ToString()" />

A: About the hidden field

I can't find anything that would suggest that one updates the other
  when the value changes, and through testing, I've noticed that the
  value does not change.

No, it doesn't change. The browsers, then a checkbox is not checked, don't submit anything using that name. So, the hidden propose is to submit the value "false" (with the same name) when the checkbox isn't checked.
When the checkbox is checked (as you said) the posted value is "true,false" (first the value of the checkbox and then the value of the hidden). The MVC binder deals with this string to convert it to true value setting it to the BooleanProperty.
About the on value
It is the default value for the checkbox. See here.

A: The hidden field is there to force the field to be included in the form POST even when nothing is checked. Without it, the field is omitted altogether, per the standard. You wouldn't know the difference between a "false" value or a non-existent field.
http://www.w3.org/TR/html401/interact/forms.html
As far as why it uses "on" vs "true", that is something you can control yourself. If you want true/false instead of on/off, use that. "on" is just a default, but not required.
<input type="checkbox" class="checkbox" name="BoolProperty" value="true" />
<input type="hidden"   class="checkbox" name="BoolProperty" value="false" />


text:
Q: Pass Multiple Values and Get Selected Results In A Cell I am new with Excel VBA and trying to use it for a scenario in an Excel work book. I am trying to do a multiple value search in a cell and that should be highlighted. Say I've these ids - 1001, 1002, so in the specific cell these values should be highlighted or searched. I am not sure how can I use List<> in VBA but in C#, I can do the following:
List<string> aLst = new List<string>();
aLst.Add("1001");
aLst.Add("1002");

So with the list, I can iterate the ids and get the results matched. I was looking into the following VBA code and it gets one value as parameter. Then checks the matched one:
Function SingleCellExtract(Lookupvalue As String, LookupRange As Range, ColumnNumber As Integer)
Dim i As Long
Dim Result As String
For i = 1 To LookupRange.Columns(1).Cells.Count

If LookupRange.Cells(i, 1) = Lookupvalue Then
  Result = Result & " " & LookupRange.Cells(i, ColumnNumber) & ","
  End If
  Next i
  SingleCellExtract = Left(Result, Len(Result) – 1)
End Function

Here is the link that I am following: Excel VBA
So any way that I can use List<> and search the required values highlighted in the excel sheet?
Sample:
Id   -   Name
1001     John
1002     Jack

A: So copy this function into a new module.
Then you can access either via another function or procedure or through an excel formula in a cell like =MultiCellExtract(A2:A3;A2:B3;2)
' LookupValuesRange is an Excel Range of cells
Public Function MultiCellExtract(LookupValuesRange As Range, LookupRange As Range, ColumnNumber As Integer) As String

    Dim cellValue As Range

    Dim i As Long
    Dim Result As String

    For Each cellValue In LookupValuesRange

        For i = 1 To LookupRange.Columns(1).Cells.Count

            If LookupRange.Cells(i, 1) = cellValue.Value Then
                Result = Result & " " & LookupRange.Cells(i, ColumnNumber) & ","
            End If

        Next i

    Next cellValue

    MultiCellExtract = Left(Result, Len(Result) - 1)

End Function

Let me know if it helps or we can adjust it.


text:
Q: run a particular method using sudo How to run a single command in rhel for a particular user
e.g: only ls command should execute, if we try for other commands we should get a error like permission denied
I am uisng visduo file and created a user and assigned a permission like
abhitest        ALL=(ALL)       /bin/ls

and I tried too abhitest        ALL=/bin/ls
but its not working

A: I supposed you refer to sudo mecanism (visudo is part of sudo)
with
abhitest        ALL=(ALL)       /bin/ls

you should be able to run, as abhitest
sudo /bin/ls

*

*you will be asked root abhitest's password. (this may or may not what you intend, assuming a real command)

try ti use in sudoers
abhitest        ALL=(ALL) NOPASSWD:      /bin/ls /some/secret/dir

you should be able, as abhitest to run
sudo /bin/ls /some/secret/dir

note that both
sudo ls /some/secret/dir
sudo /bin/ls /some/other/secret/dir

won't "work". In first case ls is not /bin/ls, in second case directories are different.


text:
Q: How to write an SQL query that examines the previous row? I have table (already sorted) in SQL server with the following:
stringname
==========
stringA
stringA
stringB
stringB
stringA
stringC
stringC
stringC
stringA

I would like to output the following:
stringname previous_stringname count
========== =================== =====
stringA    NULL                1
stringA    stringA             1
stringA    stringB             1
stringA    stringC             1
stringB    stringA             1
stringB    stringB             1
stringC    stringA             1
stringC    stringC             2

That is, for each stringname in the original table and for each of that stringname's previous entry, I would like to output it with the number of times it had each previous string (with NULL for the first entry).
How would I write an SQL query for this?
I am using SQL Server 2008.

A: Recursion is not necessary; just use:
select b.stringname as stringname, a.stringname as previous_stringname
    into #tmp
    from (select stringname, row_number() over (order by id /* $/0 */) as row from testing) a
    right outer join (select stringname, row_number() over (order by id /* $/0 */) as row from testing) b
    on a.row = b.row - 1;
select *, count(*) as [count] from #tmp group by stringname, previous_stringname;

A: The folllowing will do the trick, but in return for the answer I want you to Google "recursion" and see what Google suggests to search for :)
Clarification: The recursion happens by joining on the row - 1 to row between the temp table and the CTE. This method is dependent on having an independent IDENTITY column (ID in this case) and uses ROWNUMBER() to account for any possible gaps in IDs. Since ROW_NUMBER() can't be used in a JOIN I had to resort to using a subquery in the recursive part of the CTE. Even if you know you have continuous IDs, I'd recommend using the ROW_NUMBER for this kind of query anyway just to be safe because gaps will mess it up.
CREATE TABLE #tmp (id INT IDENTITY(1,1),stringname NVARCHAR(MAX))

INSERT #tmp (stringname)

VALUES
('stringA')
,('stringA')
,('stringB')
,('stringB')
,('stringA')
,('stringC')
,('stringC')
,('stringC')
,('stringA')

;WITH StringNames
AS(
SELECT
    ROW_NUMBER() OVER (ORDER BY ID) AS Row  --Accounts for gaps in ID
    ,stringname
    ,CAST(NULL AS NVARCHAR(MAX)) AS previous_stringname
FROM #tmp
WHERE id = 1
UNION ALL
SELECT t.Row
    ,t.stringname
    ,s.stringname AS previous_stringname
    FROM (
            SELECT
            ROW_NUMBER() OVER (ORDER BY ID) AS Row --Accounts for gaps in ID
            ,stringname
            FROM #tmp) AS t
JOIN StringNames AS s ON t.row - 1 = s.row
)

SELECT
    DISTINCT
    stringname
    ,previous_stringname
    ,COUNT(*) AS count
 FROM StringNames
 GROUP BY
    stringname
    ,previous_stringname
ORDER BY stringname

A: @Wil, why do you need the identity column?
Data
CREATE TABLE #table (stringname NVARCHAR(MAX))

INSERT  #table (stringname)
VALUES  ('stringA')
        ,('stringA')
        ,('stringB')
        ,('stringB')
        ,('stringA')
        ,('stringC')
        ,('stringC')
        ,('stringC')
        ,('stringA')

Query
;WITH [cteRowNumbers] AS (
    SELECT  ROW_NUMBER() OVER (ORDER BY $/0) AS [RowNumber],
            [stringname],
            CAST(NULL AS NVARCHAR(MAX)) AS [previous_stringname]
    FROM #table
)
,[cteStringNames] AS (
    SELECT  [RowNumber],
            [stringname],
            [previous_stringname]
    FROM (
        SELECT TOP 1
                [RowNumber],
                [stringname],
                [previous_stringname]
        FROM [cteRowNumbers]
    ) t
    UNION ALL
    SELECT  t.[RowNumber],
            t.[stringname],
            s.[stringname] AS [previous_stringname]
    FROM [cteRowNumbers] AS t
    INNER JOIN [cteStringNames] AS s
        ON t.[RowNumber] - 1 = s.[RowNumber]
)

SELECT  [stringname],
        [previous_stringname],
        COUNT(*) AS [count]
FROM [cteStringNames]
GROUP BY stringname, previous_stringname
ORDER BY stringname


text:
Q: how to include a responsive header with php and css3 I am building a personal portfolio webpage as a school assignment for my study Information science at the university of Amsterdam. Right now I copy and paste my header to each new page I make, so I can make little changes which show people at which page they are. Copying and pasting everytime you make a new page is far from efficient. I want to include the header code with a php file. But how can I still make little changes per page then?
My page: http://annatol.nl/
I hope anybody can help me.
Thanks in advance,
Anna

A: In your main php script :
<?php
include_once('inc/header.php');
?>

In your inc/header.php script :
<?php
$page = $_SERVER['REQUEST_URI'];
switch($page) {
    case "/projects.html":
    //Do specific stuff for Projects page
    break;
    case "/otherpage.html":
    //Do specific stuff for another page
    break;
    default:
    //In other cases...
    break;
}
?>

Or if you need inline changes, you can do something like this in your header.php script :
<?php
$page = $_SERVER['REQUEST_URI'];
?>
<a href="/projects.html" <?php if($page == "/projects.html") { echo "class=\"active\""; } ?>>My projects

A: Something like this?
include 'header.php';

A: You can include all the files by using the include function
Example:
include "Path_To_File";
you can also use the require or require_once functions aswell


text:
Q: Handling multiple OpenId login from different OpenId providers for the same user Suppose I've an account at example which I used to login through OpenId, and hence it has only one profile of mine. If I login from another OpenId Provider different from the previous OpenId provider, now will there be a duplicate profile of mine? How does OpenId handles such kind of ambiguity, or is it upto that website of handling such kind of ambiguity?

A: OpenID Specification doesn't define any mechanism for this scenario. It is totally up to the website developer to handle this.


text:
Q: Declare A Column Name As A Variable I am running into an issue with the query below.
DECLARE @CC VARCHAR(100)
SET @CC = 'MKT_COV_CAR_LFR'
DECLARE @SQL VARCHAR(16384)
SET @SQL =
'INSERT INTO PP_Industry
SELECT
    R.Year,
    ''01'' AS Carline,
    Sales_Locality,
    '+@CC+' AS Reg,
    National_Reg,
    CAST('+@CC+' AS FLOAT) / CAST(National_Reg AS FLOAT) AS Reg_Share
FROM
    PP_Registrations AS R
    JOIN
        (
            SELECT
                Year,
                SUM('+@CC+') AS National_Reg
            FROM
                PP_Registrations
            GROUP BY
                Year
        ) AS SQ ON R.Year = SQ.Year'

EXEC @SQL

I receive the following error when I run it. Please help!

Error (2812) Stored procedure 'INSERT INTO PP_Industry
      SELECT
          R.Year,
          '01' AS Carline,
          Sales_Locality,
          MKT_COV_CAR_LFR AS Reg,
          Nationa' not found. Specify owner.objectname or use sp_help to check whether the object exists (sp_help may produce lots of output).

A: If you run an custom SQL statement you should execute it like that:
exec (@SQL)


text:
Q: MatLab to Python conversion - indexing? I am trying to convert the following MatLab code to Python:
    for i = 1:n
     I = (sum((N==M(1,i))+(N==M(2,i)))==2);
     P(:,i) = pit(:,I);

Here is my current attempt:
 for i in range(0,n):
     I = [sum(int(N == M)(1,i)) + int((int(N == M)(2,i))) == 2]

which raises the error:
ValueError: shape mismatch: objects cannot be broadcast to a single shape

The following Python code that I have already translated (correctly, I think) precedes the code I am struggling with:
 M = np.array(mypitches).transpose()

 n = M.size

 P = np.zeros((3,n))

 pit = pitches(h,-8,12)

 N = np.array(['Fb','Cb','Gb','Db','Ab','Eb','Bb','F-','C-','G-','D-','A-','E-','B-','F#','C#','G#','D#','A#','E#','B#']).transpose()

Full MatLab code:
function [P] = position(h,mypitches);

% position.m : gives pitch positions given
%        h = aspect ratio
%        mypitches = a list of pitch names from Fb-B#
% returns
%        P = a list of corresponding pc spiral positions
%
% created by EC, 20 Nov 1998; updated 28 Aug 2013
%
% usage:     [P] = position(mypitches)
% example: position(['Bb';'C-']);

M = mypitches';
[m,n] = size(M);

P = zeros(3,n);
pit = pitches2(h,-8,12);

N = ['Fb';'Cb';'Gb';'Db';'Ab';'Eb';'Bb';'F-';'C-';'G-';'D-';'A-';'E-';'B-';'F#';'C#';'G#';'D#';'A#';'E#';'B#']';

for i = 1:n
 I = (sum((N==M(1,i))+(N==M(2,i)))==2);
 P(:,i) = pit(:,I);
end;

A: Looks like you are trying to do this. The ndarray indexing is wrong.
for i in range(n):
    I = (sum(int(N == M[0, i]) + int(N == M[1, i])) == 2)
    P[:, i] = pit[:, I]

It could be written a little more clearer as
for i in range(n):
    I = (N == M[0, i] == M[1, i])   # True is equivalent to 1 and False 0
    P[:, i] = pit[:, I]


text:
Q: CoreData unique constraints: how to get field name on which constraint checking fails I have a simple table "Person" with two fields:
identity => String
name => String
This table have unique separated constraints: identity and name (not identity + name)
I try to insert into this table same data several times:
let names = ["Name1", "Name2", "Name3"]
for i in 0..<3 {
    let p = Person() //NSManagedObject sublass
    p.identity = "1111"
    p.name = names[i]
    do { try p.managedObjectContext!.save() }
    catch let e as NSError {
        if e.code == NSCocoaError.ManagedObjectConstraintMergeError.rawValue {
            print(e.userInfo["conflictList"]![0]!)
        }
    }
}

I have in log:

NSConstraintConflict (0x7ff12b84f600) for constraint (
      identity
  ): database:  (entity: Person; id: 0xd000000000040000  ; data: ), conflictedObjects: (
      " (entity: Person; id: 0xd000000000140000  ; data: {\n    identity = 1111;\n    name = Name1;\n})"
  )

How can I get field name on which constraint failes from userInfo  NSConstraintConflict (0x7ff12b84f600) for constraint ( identity ) ? Because in future I want to show messages with text like "Unique constraint check failed for field "identity" and "Unique constraint check failed for field "name" but while I cann't get field name from error it is not clear on which field check failed
Thank you!

A: AFAIK Nor NSConstraintConflict neither something like NSConstraint is documented. However, the constraint conflict knows the constraint:

NSConstraintConflict (0x7ff12b84f600) for constraint ( identity ): database: (entity: Person; id: 0xd000000000040000 ; data: ), conflictedObjects: ( " (entity: Person; id: 0xd000000000140000 ; data: {\n identity = 1111;\n name = Name1;\n})" )

I would bet that you can get the constraint with
[conflict valueForKey:@"constraint"]

Look for the class of the result.

A: Swift 5, Xcode 13
Here's how I got the violation info:
} catch let e as CocoaError {
    let errorDictionary = e.errorUserInfo

    if let conflictList = errorDictionary[NSPersistentStoreSaveConflictsErrorKey] {
        let constraintConflicts = conflictList as! [NSConstraintConflict]

        for conflict in constraintConflicts {
            validationError = "Constraint violation(s) from: " + conflict.constraint.joined(separator: ", ")

            var duplicates: [String] = []
            for (propertyName, value) in conflict.constraintValues {
                duplicates.append("The \(propertyName) field should have a unique value. '\(value)' already exists.")
            }
            duplicatesError = duplicates.joined(separator: "\n")
        }
    }
} catch {

It prints out this, for example:


text:
Q: TextAlign pointlabel Chart.js I have been experimenting with a multiline pointlabel (very long label) for a radar chart. When creating a multiline pointlabel the text in the label aligns left/right/center depending on the side of the radar chart. I searched and found out that the datalabel plugin https://chartjs-plugin-datalabels.netlify.app/guide/formatting.html#multiline-labels supports textAlign but there are no examples how to apply this. Is there a way to align the text in all the labels to center?

var data = {
  labels: [
    ["very", "long label"],
    ["very", "long label"],
    ["very", "long label"]
  ],
  datasets: [{
    label: [`dataset`],
    backgroundColor: "rgba(38,120,255,0.2)",
    borderColor: "rgba(38,120,255, 1)",
    data: [90, 90, 90]
  }]
};

var options = {
  responsive: true,
  tooltips: false,
  title: {
    text: 'Basic example',
    display: true,
    position: `bottom`,
  },
  scale: {
    angleLines: {
      display: true
    },
    ticks: {
      suggestedMin: 0,
      suggestedMax: 100,
      stepSize: 25,
      maxTicksLimit: 11,
      display: false,
    }
  }
};

var myChart = new Chart(document.getElementById("chart"), {
  type: 'radar',
  data: data,
  options: options
});

  <canvas id="chart" width="500" height="450"></canvas>

A: There's no option to define the text-alignment for the point labels, textAlign it computed depending on the angle by the function getTextAlignForAngle inside radialLinear.js.
You can however overwrite textAlign after the chart generation using the Plugin Core API. The API offers different hooks that may be used to execute custom code. The afterLayout hook for example may be used as follows.
afterLayout: chart => {
  chart.getDatasetMeta(0).rScale._pointLabelItems.forEach(o => o.textAlign = 'center');
}

Please take a look at your amended code below and see how it works.

var data = {
  labels: [
    ["very", "long label"],
    ["very", "long label"],
    ["very", "long label"]
  ],
  datasets: [{
    label: ['dataset'],
    backgroundColor: "rgba(38,120,255,0.2)",
    borderColor: "rgba(38,120,255, 1)",
    data: [90, 90, 90]
  }]
};

var options = {
  responsive: true,
  tooltips: false,
  plugins: {
    title: {
      text: 'Basic example',
      position: 'bottom'
    }
  },
  scales: {
    r: {
      min: 0,
      max: 100,
      ticks: {
        stepSize: 25
      }
    }
  }
};

new Chart('chart', {
  type: 'radar',
  plugins: [{
    afterLayout: chart => {
      chart.getDatasetMeta(0).rScale._pointLabelItems.forEach(o => o.textAlign = 'center');
    }
  }],
  data: data,
  options: options
});

  <canvas id="chart" width="500" height="450"></canvas>


text:
Q: request.getRemoteUser==null; how to log all traffic from apache to tomcat I have a connector defined as:
<Connector protocol="AJP/1.3" enableLookups="false" tomcatAuthentication="false"        scheme="https"
    secure="true"
    address="127.0.0.1"
    port="8009" />

however, request.getRemoteUser is returning null.
my question is how can i make Apache log 'everything' it sends to Tomcat?  i have apache and mod_jk log levels set to 'debug'.
Any pointers will be highly appreciated.

A: Enabling the mod_jk logs should do the trick:
# Where to put jk logs
JkLogFile     /var/log/httpd/mod_jk.log
# Set the jk log level [debug/error/info]
JkLogLevel    debug

Hope that helps.


text:
Q: How to update multiple records using peewee I'm using Peewee with Postgres database. I want to know how to update multiple records in a tabel at once?
We can perform this update in SQL using these commands, and I'm looking for a Peewee equivalent approach.

A: Yes, you can use the insert_many() function:

Insert multiple rows at once. The rows parameter must be an iterable
  that yields dictionaries. As with insert(), fields that are not
  specified in the dictionary will use their default value, if one
  exists.

Example:
usernames = ['charlie', 'huey', 'peewee', 'mickey']
row_dicts = ({'username': username} for username in usernames)

# Insert 4 new rows.
User.insert_many(row_dicts).execute()

More details at: http://docs.peewee-orm.com/en/latest/peewee/api.html#Model.insert_many

A: ORMs usually dose not support bulk update and you have to use custom SQL, you can see samples in this link (db.excute_sql)


text:
Q: How to insert given key-value pair at a given index? How would I insert a key value pair into an array at a specific index? Thats the code I have so far but it's not passing my test. it is failing at:
Fails on the below key value pairs:
size = 1, key-value pairs = (ZS, 160)
Failure in putting (ZS, 160) into the following symbol table:
size = 0, key-value pairs =

public class SortedArrayST<Key extends Comparable<Key>, Value> {
    private static final int MIN_SIZE = 2;
    private Key[] keys;      // the keys array
    private Value[] vals;    // the values array
    private int N = 0;       // size of the symbol table

    private void insert(Key key, Value val, int r) {
        // TODO
        //shift to the left
        if (keys == null) return;
        int i = rank(keys[r]);
        if (i == N || keys[i].compareTo(keys[r]) != 0){
            return;
        }
        for (int j = i; j < N-1; j++)  {
            keys[j] = keys[j+1];
            vals[j] = vals[j+1];
        }
            N--;
             keys[N] = null;
             vals[N] = null;
}}


text:
Q: Using Field Calculator to assign values to only Odd (or Even) page fields for Data Driven Pages? I am creating a map book but do not want the page numbers for each map page to be on the same side (since its printed double sided), I need the page numbers to be placed on opposite sides.
I am using data driven pages. On a previous post it was mentioned to use ODD and EVEN pages per How to make Map Book with facing pages numbered near outside edge?.
However I have over 200 pages.
Is there a "creative" field calculator expression to use?

A: The Field Calculator configuration below can be used to set values on any odd numbers in your Odd pages field (and blanks in the other rows).
In order to simulate a Data Driven Pages index for test data, I used Create Fishnet to create a polygon feature class in a file geodatabase, and then added text fields 4 characters in size called Odd and Even.
This index feature class has a numeric OID field and writes to an Odd field that is text.  I will leave you to work out how to do the Even field.  If you have a different numeric field specifying the page numbers (and order) just use that in place of OID.
The modulo (%) operator in Python, which is the crux of how to separate Odd from Even pages, is described here.

Parser: Python
Pre-logic Script Code:
def Reclass(oid):
  if oid % 2 == 1:
    return str(oid)
  else:
    return ""

Odd =
Reclass(!OID!)


text:
Q: How to determine if a package name is a service or launchable GUI app With ADB I get all preinstalled apps package names. I want to know which package name is a real app (not a service) so I can launch it.

A: adb gives you list of preinstalled applications. These applications may contain activities, services, content providers, and/or broadcast receivers. When you say "real app", you are asking for applications with activities. Even if you knew which application contains activities, you still need to find the name of that activity before you can launch it.
So to get what  you want, it is going to be few more steps. The answer below describes what you need:
https://stackoverflow.com/a/12700063/4406743
Basically, you need to go through each application that you are interested in, pull it to the PC and get it details using aapt. aapt will provide you all the details needed for launching any activities in that application.


text:
Q: How to customize TaxReport_IT - report SSRS? I would like to custom the Report SSRS TaxReport_IT, I need to add a new field in order to use in to SyntethicReport Design.
(for example)

The classes involved seems these:
TaxReport_IT
TaxReportDP_IT
TaxReportController_IT
TaxReportContract_IT
Tables involved:
TmpTaxReport_ITSummary
TmpTaxReport_IT
TaxReportTmp_IT
Are there others? Are there some Queries involved?'
I added the new fields in to table _TmpTaxReport_IT_, and I pupulated the related tables

I'm sure, in to the method I pupulated correctly the new Field (I have the values that I expect), but when I print the Report I get a lower value. Seems like I don't take the total data set.
How can I add the new field and take the correctly total value?
I saved the data (about my custom field in a RegularTable) and the sum is correct, but I have mismatch when I print the report.
I think I skip some step to Report DataSet.
I use Dynamics AX 2012.
Thanks in advice!

A: I have an idea what could be wrong, but I'm making some assumptions. If they are not correct, please edit your question to clarify.
From your screenshot, it looks like you want to add your new custom field in the header section of the report design. I'm assuming the expression of that field looks similar to
=First(Fields!MyCustomFIELD.Value, "TaxReportDS_IT")
Note the First key word in that expression. This indicates that the value for that field should be taken from the first of the records of the report's dataset.
I'm assuming that you calculate the value of the field while the records in table TaxReportTmp_IT are being created so that each record has a different value. Maybe it is a sum of some other field, so the first record would have the smallest value and the last record the highest.
If all those assumptions are correct, you can fix this by changing the First keyword to Last. This indicates that you want to take the value of the last record of the report data set.
See also the documentation of the Last Function.


text:
Q: Weblogic - Log outbound calls from webapplication I am working on a web application, which is deployed to weblogic cluster. Upon user invoking an action in jsp, at the server side we make an outbouond call (with 2-way ssl) to an external service. This service returns me some data, which we send to the client side for rendering on UI. This flow is working as fine.
Outbound request for 2-way SSL are made from a utility class within the application, using java.net.URLConnection. However, upon checking the access.log for weblogic, I don't see these outbounds call logs in the access logs.
Now, business has Access log monitoring software in place, to monitor specific urls/reponse code  and alert IT team if the number of non-200 responses crosses some threshold.
So, the challenge I am having currently is, how to log the outbound request's url & response status to the access log of weblogic server. I have been googling over the net, but couldn't find anything so far which can suggest how to go about it. I am new to weblogic, so not sure if this is possible OOTB or I need to write some custom code for this.
Need advice from weblogic experts out there. Thanks in advance!

A: Weblogic only traces incoming http/s requests in its access logs. Your application is responsible for logging its own outbound requests in its own logs. Do not log your entries in weblogic's logs.


text:
Q: How to turn off rename detection in git add and git rm How can I stop git from detecting rename of files when I do git add and git rm?
I removed many files at different paths under the working tree, like
tests/case066/chkpy000/active_set010.py
..
tests/case068/chkpy000/active_set010.py
tests/case069/chkpy000/active_set011.py
..
tests/case086/chkpy000/active_set011.py
tests/case087/chkpy000/active_set012.py
..
tests/case140/chkpy000/active_set012.py

I removed these files not by git rm but by rm of bash.
Some of the files (i.e., those with the same name) had the same contents, while others had similar contents to each other.
I created new files in the directories where those removed files existed, like
tests/case066/chkpy000/active_set013.py
..
tests/case068/chkpy000/active_set013.py
tests/case069/chkpy000/active_set013.py
..
tests/case086/chkpy000/active_set013.py
tests/case087/chkpy000/active_set013.py
..
tests/case140/chkpy000/active_set013.py

The all new files have the same contents, and they are similar to the deleted ones.
Now, if I try to stage the changes by git rm <deleted_files> and git add <created_files>, or by git add --all tests, git seems to detect a few of the changes as renames and the others delete and add. In fact, the rename is detected across directories, which does not make sense. How can I let git simply stage the deletion and addition without detecting any rename?
(It would be better if there is a way to specify the rename pairs manually, but I would be glad with simply disabling the rename detection.)

Edit
I found a similar question,
How can I prevent git from thinking I did a rename
I also see in the comments and answer to this question as well as in other places that rename information is not stored in git database but is generated from it. So, maybe I could ignore the result of the rename analysis if it's wrong, but I feel a bit uneasy.
I ended up making two commits, first for the created files and second for the deleted files. This won't break build at each of these commits in my case, but may not be good for other cases.

A: You can try again your rm/add after typing:
git config diff.renames false

But that might only affect only git diff Porcelain (git diff, git log).
Otherwise, this is just the result of using a similarity index, and does not influence how Git will store those (deleted/added) objects (an identical renamed file will still be stored only once).
If you really do not want those rename detections at git status, a workaround is to make, as the OP eventually did, two commits:

*

*one for deletion

*one for addition

But a git log -C might detect the renamed files.


text:
Q: Can't ping CentOS7 from Win 2k12 Host I have a service running on CentOS 7 in Oracle VM Virtual Box, but I can't ping the IP I configured in CentOS from windows.
I tried:

*

*Disabling windows firewall

*Changing network adapter to bridged mode

*Setting the static IP in centOS to the IP of the Virtual Box. Host-Only network adapter in Windows.

I can ping my windows box from the CentOS virtual machine though.  Any ideas?

A: I set adapter to bridged. Changed the IP to one a subnet of the adapter on the host server.  Changed gateway to server gateway.  Bounced services and was able to ping.
The issue was that Cent OS was trying to connect through an unused NIC.  Can't believe I didn't see it before.

A: It is possible that the firewall on CentOS is blocking the ICMP Ping requests.
To check if there is a rule in place, you can run (as sudo) iptables -L
You want to look at the chain labeled INPUT and see what policy is set. If it is set to DENY, then unless there is a rule specifically allowing ping requests, it will get dropped.
To quickly disable the firewall to check if this is the issue, you can run (as sudo) iptables -P INPUT ACCEPT. But be warned, this will allow everything in without an explicit rule denying it. You can set the policy back to drop after troubleshooting iptables -P INPUT DROP.
To allow ping to be responded to, you will need to add a new rule such as described here: https://www.cyberciti.biz/tips/linux-iptables-9-allow-icmp-ping.html
But these changes will exist only until next reboot unless you have a method for maintaining persistent iptables rules across reboots.

A: Make sure sshd service is running on Centos 7.
service sshd start


text:
Q: Existence of parametrizations of rational orthogonal matrices I suppose that there are formulas which parametrize all the orthogonal matrices with rational coefficients. Does anyone know anything about it? And what are some publications that discuss this?
Thanks.

A: The formula in @Carlo Beenakker answer does not give all rational orthogonal matrices, but only those for which $-1$ is not an eigenvalue. Here is a rational parametrization which gives all orthogonal matrices for $n=3$:
$$\frac{1}{a^2+b^2+c^2+d^2}\left(
\begin{array}{ccc}a^2+b^2-c^2-d^2 & 2bc-2ad & 2ac+2bd\\
2ad+2bc & a^2-b^2+c^2-d^2 & 2cd-2ab\\
2bd-2ac & 2ab+2cd & a^2-b^2-c^2+d^2\end{array}\right),$$
where $a,b,c,d$ are integers with no common factor, and not all equal to $0$. This is due to Euler,
and can be proved using quaternions. There is a similar formula for $n=4$.
The answer for $n=4$ is somewhat inconvenient to write here. It was obtained by Euler,  Problema algebraicum ob affectiones prorsus singulares memorabile, Novi Commentarii academiae Scientiarum Petropolitanae, XV, (1771) 75-106.
The formula was proved using quaternions in 1937 by D. Grave, and published in an obscure Ukrainian journal (Zhurnal Instituta Matematiki AN UkrSSR, 3, 73-74.) and in his book Treatease on Algebraic Analysis, vol. I Kiev, 1938.
In English, the formula for $n=4$ is reproduced in the book
S. Khrushchev, Orthogonal polynomials and continued fractions from Euler's point of view, Cambridge UP, 2008. (Encyclopedia of Math and Appl., vol. 122), on page 297.

A: you can use the Cayley transform: $O=(I+H)(I-H)^{-1}$, with $I$ the $n\times n$ identity matrix and $H$ an $n\times n$ skew-symmetric matrix; choose rational values for the matrix elements of $H$ and $O$ will be rational orthogonal; see
The Generation of All Rational Orthogonal Matrices (1991)


text:
Q: jQuery validation with Textbox naming on ASP.NET MVC page? I have two Textbox controls on my view.
Here jQuery validation function is working when the name is one word.
It is not working when the name is having any dots in it.
In the below jQuery function, if I use "lastname" textbox id for validation, it is not allowing any other keys except digits. But somehow if I use "AddressDetail.ZipCode" textbox id to allow only digits, it is not calling. I have to use only "AddressDetail.ZipCode" as it is referencing the child table.
Here is my code.

Last Name*
        <%= Html.TextBox("lastname", Model.LastName, new { @class = "required", size = "30" })%>

Zip*
        <%= Html.TextBox("AddressDetail.ZipCode", Model.AddressDetail.FirstOrDefault().ZipCode, new { @class = "required zip", minlength = "5"})%>

<input type="submit" id="btnUpdProfile" value="Update" />

JQuery function validation:

A: The . is interpreted as a class selector. You want:
$('#AddressDetail\\.ZipCode')
The double backslash is evaluated by the parser as '#AddressDetail\.ZipCode'. jQuery sees the backslash in front of the period and interprets it literally, instead of as a class selector.


text:
Q: Select unbolded text & change its colour (of a selected paragraph)- MS Word VBA Macro
*

*I would like to select a piece of text in MS Word 2010 document.

*Then using a macro: select the unbolded text & change the colour of that text to blue

NB: I don't want to do this to the whole of the document text, just to the paragraph/block of text I have selected)
Picture demonstrating what I would like to do:

I have tried creating the following macro - but it for some reason makes all of the text (bolded and unbolded) blue
    Sub MakeUnboldedTextBlue()
'
' MakeUnboldedTextBlue Macro
'
'
    Selection.Find.ClearFormatting
    Selection.Find.Font.Bold = False
    With Selection.Find
        .Text = ""
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindAsk
        .Format = True
        .MatchCase = False
        .MatchWholeWord = False
        .MatchKashida = False
        .MatchDiacritics = False
        .MatchAlefHamza = False
        .MatchControl = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    Selection.Font.Color = 15773696
End Sub

Update:
I would also like to exclude the bullet symbols from 'cyanizisation' (if possible)
For example:
Example of the bullet symbols not being cyanized

A: You look through every character in the selected text, then colour it if it isn't bold:
Option Explicit

Sub CyanizeNonBoldInSelection()
    Dim oRange As range
    Dim oChar As range
    Dim oListFormat As ListFormat

    Application.UndoRecord.StartCustomRecord "CyanizeNonBoldInSelection"

    Set oRange = Selection.range

    For Each oChar In oRange.Characters

        If oChar.Bold = False Then

            oChar.Font.ColorIndex = wdTurquoise

            If oChar.ListParagraphs.Count > 0 Then
                Set oListFormat = oChar.ListParagraphs(1).range.ListFormat
                oListFormat.ListTemplate.ListLevels(oListFormat.ListLevelNumber).Font.ColorIndex = wdTurquoise
            End If

        End If
    Next oChar

    Application.UndoRecord.EndCustomRecord

End Sub


text:
Q: Haskell - help understanding a function I have this mystery function that I'm having trouble understanding:
mystery :: [a] -> [[a]]
mystery [] = [[]]
mystery (x:xs) = sets ++ (map (x:) sets)
                 where sets = mystery xs

Here are some inputs with results:
mystery [1,2] returns [[],[2],[1],[1,2]]
mystery [1,2,3] returns [[],[3],[2],[2,3],[1],[1,3],[1,2],[1,2,3]]

By looking at the results I can see that its computing all the possible combinations of the numbers in the list, but not all the possible permuations...I think.
The trouble i'm having is actually going through the recursion and understanding how the function is getting those results.
I think I get the start of it --> mapping (1:) onto [2], yielding [1,2], but its at this point that I'm confused how the recursion works, and whether I'm still mapping (1:) or now (2:), and onto what exactly.
If anyone could please help me out by explaining step by step (using one of the examples provided) how this function works (with the map and sets recursion), that would be greatly appreciated!
Thank you!

A: Haskell will perform what is known as lazy evaluation, meaning it will only work things out as it needs them from left to right (generally). So taking your example of mystery [1, 2], Haskell will do the following:
sets ++ (map (x:) sets)

Which evaluates to:
mystery (2:[]) ++ (map (1:) sets)

At this point, we're calling mystery (2:[])
mystery ([]) ++ (map (2:) sets) ++ (map (1:) sets)

mystery ([]) will return an empty list of lists
[[]] ++ (map (2:) sets) ++ (map (1:) sets)
[[]] ++ (map (2:) mystery []) ++ (map (1:) sets)

So now Haskell will try to apply the function (2:) on a list containing an empty list
[[]] ++ (2:[[]]) ++ (map (1:) sets)
[[]] ++ [[2]] ++ (map (1:) sets)
[[], [2]] ++ (map (1:) sets)

This is where things get a little more confusing.
[[], [2]] ++ (map (1:) mystery (2:[]))

That last sets will evaluate mystery (2:[])
[[], [2]] ++ (map (1:) (sets ++ (map (2:) sets)))
[[], [2]] ++ (map (1:) (mystery [] ++ (map (2:) sets))
[[], [2]] ++ (map (1:) ([[]] ++ (map (2:) mystery []))
[[], [2]] ++ (map (1:) ([[]] ++ (2:[[]]))
[[], [2]] ++ (map (1:) ([[]] ++ [[2]])

Now (1:) will be applied to a list which contains an empty list, and a list containing the 2:
[[], [2]] ++ (map (1:) ++ [[], [2]])
[[], [2]] ++ [[1], [1, 2]]
[[], [2], [1], [1, 2]]

The real meat of the operation is in those last two sections. Haskell creates a list like [[], [2]] and then appends one to the head of each list to form [[1], [1, 2]].

A: your mystery function is computes the power set of its input.


text:
Q: How can I delay execution until after os.system finishes? I am using os.system to copy a file from a system to another. The logic of a very simple program is to execute another set of commands after this file gets copied.
The problem is that os.system does not actually wait for the file to be copied, and gets to executing the next line. This causes issues to the system. I could actually give some wait functions, through time.sleep(), but we have to copy files with sizes ranging from 500 MB to sometimes 20 GB, and the times taken are very different.
What's the solution? I need to somehow tell my program that the files are copied, and then to execute the next line.

A: The first thing I'd try is to use shutil.copyfile() instead of an external program to copy the file.  If you have to use an external program, you should call it via subprocess.Popen(), not via os.system().  You can use the Popen.wait() to wait for the subprocess to finish.

A: I think you should rather use shutil.copyfile than os.system to copy a file.
(Edit: woops, copy, not move)

A: use the shutil module for copying files.

The shutil module offers a number of
  high-level operations on files and
  collections of files. In particular,
  functions are provided which support
  file copying and removal.

also, use the subprocess module instead of os.system()

The subprocess module allows you to
  spawn new processes, connect to their
  input/output/error pipes, and obtain
  their return codes. This module
  intends to replace several other,
  older modules and functions, such as:
os.system

for a better answer, you need to provide more detail about what exactly you are trying to do and how (programmatically) you are stuck.


text:
Q: How to group photos using face api I am using face API to group similar images. I was using face group where I am sending faceids and then getting groups as result. but as mentioned in https://westus.dev.cognitive.microsoft.com/docs/services/563879b61984550e40cbbe8d/operations/563879b61984550f30395238 faceid is only for 24 hours and expire after that.But persistedFaceIds never get expire.Can you suggest how can i use persisted face ids to group images. Following is my requirement: I storing images on server. If I got new image I need to get face id and group accordingly. Whether I have to call api every time when I add an image to the server. please suggest how can I achieve this?
Thanks

A: Face Group is a very expensive/unefficient operation, you may try FindSimilar [1] or Identify to help in your scenario.

*

*[1] https://westus.dev.cognitive.microsoft.com/docs/services/563879b61984550e40cbbe8d/operations/563879b61984550f30395237

*[2] https://westus.dev.cognitive.microsoft.com/docs/services/563879b61984550e40cbbe8d/operations/563879b61984550f30395239


text:
Q: How to use use tokens in Sitecore SXA metadata partial design? I use a HTML snippet in the Sitecore SXA metadata partial design to add some links in the head of the resulting HTML:

This HTML is:
<link rel="stylesheet" href="https://unpkg.com/sxa-umbrella-webcomponents@0.0.1/dist/sxa-umbrella-webcomponents/sxa-umbrella-webcomponents.css" />
<script type="module" src="https://unpkg.com/sxa-umbrella-webcomponents@0.0.1/dist/sxa-umbrella-webcomponents/sxa-umbrella-webcomponents.esm.js"></script>
<script nomodule src="https://unpkg.com/sxa-umbrella-webcomponents@0.0.1/dist/sxa-umbrella-webcomponents/sxa-umbrella-webcomponents.js"></script>

But I would like to have the base path configurable using for example a token, like:
<link rel="stylesheet" href="$WebComponentsBasePath/sxa-umbrella-webcomponents.css" />
<script type="module" src="$WebComponentsBasePath/sxa-umbrella-webcomponents.esm.js"></script>
<script nomodule src="$WebComponentsBasePath/sxa-umbrella-webcomponents.js"></script>

where the token is set to: "https://unpkg.com/sxa-umbrella-webcomponents@0.0.1/dist/sxa-umbrella-webcomponents.
But token replacement does not work in the HTML snippet.
Any idea on how to make this base path configurable for the metadata partial design so I can have different configuration for my development environment and the production environment, and have the possibility to easily switch the base path on production to roll forward a version or roll back a version of the files used based on a configured base path?


text:
Q: Can't find and update record from MongoDB(nest js) userId in database:
 userId:"610405b8f3e5fb0484f5fac2"

I want to update tha data by that Id,but getting 500Internal Server Error.I am trying in this way:
service.ts
  public async updateUser(
    UserId: any,
    data: any
): Promise<any | Error> {
    try {
        return new Promise((resolve, reject) => {
            UserCollection.findByIdAndUpdate(
                UserId,
                { ...data },
                (err: any, success: any) => {
                    if (err) {
                        reject(err);
                    }
                    if (!success) {
                        resolve(false);
                    } else {
                        resolve(success);
                    }
                }
            );
        });
    } catch (e) {
        console.log('service error\n', e);
        throw e;
    }
}

controller.ts
  public updateUserController = async (req: Request, res: Response, next: NextFunction): Promise<Response | void> => {
    try {
        if (req.body.UserId!='') {
            let results = await this.ServicesService.updateUser(req.params.UserId, req.body);
            if (results != false) {
                this.success(res, 'Updated Successfully', 200, results._id);
            }
        }
        return await this.error(res, 'Something Went Wrong!.', 500);
    } catch (e) {
        next(e)
    }
}

How to achive this,thanks....

A: I realized my mistake,Instead of using findByIdAndUpdate,I used findOneAndUpdate,error solved.
UserCollection.findOneAndUpdate(
            UserId,
            { ...data },
            (err: any, success: any) => {
                if (err) {
                    reject(err);
                }
                if (!success) {
                    resolve(false);
                } else {
                    resolve(success);
                }
            }
        );

A: You can simple have the updateMany() method to update multiple documents with same userId at once.


text: Q: Oracle client mismatch I have taken a code from another environment onto my local system. The code is written in VB.NET and the backend technology is oracle 11g. While debugging the code in the local environment , I am unable to connect to the oracle database. The inner exception states 'The provider is not compatible with the version of Oracle client'. What should be the suggested action items to debug the issue and correct it?


text:
Q: Redimensionar Imagenes CSS react Estoy aprendiendo css y estaba intentado que estás 3 imágenes fueran del mismo tamaño en el ancho, ya que en el alto si que son de la misma medida.

.imagen-testimonio{
    height: 100%;
    width: auto;
}

He visto que para estos casos se suele usar max-heigth: 100%; y max-width100%; pero aún así me salen de diferente tamaño.
Gracias.


text:
Q: Reimplementing Array.prototype.sort and understanding the return 0; I'm trying to reimplement the sort algorithm. But to do that first I have to reimplement the compareFunction default. But I don't understand the return 0 behavior described on the documentation:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements.

I am trying to reimplement the same behavior using the bubble algorithm:
http://khan4019.github.io/front-end-Interview-Questions/sort.html#bubbleSort


text:
Q: Error Message: Can't determine a valid Java Home I think my path is not set correctly for some reason.
"Path" under System Variables looks following:

C:\Program Files\Common Files\Oracle\Java\javapath;C:\ProgramData\Oracle\Java\javapath;C:\Program Files\Common Files\Microsoft Shared\Windows Live;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\Windows Live\Shared;C:\Program Files\QuickTime\QTSystem\

Under User Variable Path or Java_home is not there?
Is there a way to start the path over again?

A: You have to do a few things:

*

*define a new variable JAVA_HOME and assign to it exactly JDK installation location, like C:\java\jdk_1.8.0

*update your Path variable with:

%JAVA_HOME%\bin

*

*important point set it first to Path.
Finally, your Path will look:

%JAVA_HOME%\bin;C:\Program Files\Common Files\Oracle\Java\javapath;C:\Program Files\Common Files\Microsoft Shared\Windows

*

*open console and type:

java -version

The output should be something like:
java version "1.8.0_192"
Java(TM) SE Runtime Environment (build 1.8.0_192-b12)
Java HotSpot(TM) 64-Bit Server VM (build 25.192-b12, mixed mode)

BTW your Path has some duplication. Just remove an unneeded part.


text:
Q: How to extract only file name from the path? I am running the code,
set /p "filepath=Drag and drop your file >"
cls
echo Your file name is : %filepath%
pause>nul

output i am getting
Your file name is : c:/users/philip/desktop/file.txt

When user drag and drop there file in command prompt and press enter it shows full file path as output..
expected output
Your file name is : file.txt

But, what i am expecting is, only the file name with extention..like shown above as output.
Note : File path and File name may varies..

A: You can use this:
set /p "filepath=Drag and drop your file >"
cls
for %%a in ("%filepath%") do echo Your file name is: %%~nxa
pause >nul

Here n and x are the modifiers of the for meta variables. To learn more about them, open cmd and type for /? and look at the end.


text:
Q: fold inverts the order of a sequence The order of my Sequence, array etc matters.  I have tried converting between List, Seq and Array to see if there are differences and in each case it inverses the order.
I have a seq of [noun] [verb] [ajective] for example, which is transformed into strings and then folded together.  A sample response given this template might be "bad run bandits" instead of "bandits run bad".
Any thoughts on why fold does this or how to get it to execute in the appropriate order?
let res = template |> Seq.map(fun pos ->
                    let e = s |> PredictionEngine.GetRandom
                    pos |> PredictionEngine.GetBestPartOfSpeechWord e)
                    |> Seq.fold(fun acc w -> w.Text + " " + acc) ""

A: I believe this is just a matter of changing the order of your last function to:
Seq.fold(fun acc w -> acc + " " + w.Text) ""

Like this the new itens get concatenated to the end of the old ones. A minimum example of this working can be seen in the following snippet:
["Bandits";"Run";"Bad"]
|> Seq.fold(fun acc w -> acc + " " + w) ""
|> printfn "%s"

A: If you have such common job as concatenating strings I recommend using functions from library.
["noun"; "verb"; "adj"]
|> String.concat " "

On daily basis work, I think, there are not so many problems that require writing custom folding.


text:
Q: How to capture a Direct3D/WPF/DWM window into a bitmap? The normal way to capture an image of a window is to call:
HDC SharedWndDC = GetWindowDC(SharedWnd);
BitBlt(BitmapDC, 0, 0, width, height, SharedWndDC, 0, 0, SRCCOPY /* |CAPTUREBLT */);
ReleaseDC(SharedWnd, SharedWndDC);

Which on a system running DWM, nicely grabs just the window in question, even if it's being overlapped by other windows or partly off the screen, or whatnot.
But, it doesn't work right on some windows (presumably those that use WPF), and does funny things with the glass areas.  Basically, the GDI capture doesn't work on non-GDI things.
I understand what I really want is to grab the Direct3D "back buffer" or "front buffer", but the numerous examples I've seen for that are for capturing the entire screen or desktop.  Not knowing Direct3D, I can't find an example or simple statement of how to obtain the proper object for an existing window, which I could then grab the buffers from.
Can some kind soul at least show that missing piece?
—John

A: I don't believe there is a way to capture the front buffer contents without capturing the whole screen, and the back buffer is private to the application running Direct3D. The front buffer's content can only be seen when the graphics card actually presents the data to the monitor. With GDI, Windows has access to the front and back buffers, because it is managing them itself. But with Direct3D (and I'm presuming WPF), this is no longer the case. Windows does not have access to the buffers, and as such, can't obtain the data unless the application gives it to Windows, which is impossible (there's no message defined to do so).
EDIT:
This looks like a dead question, but I'll add this anyway in case someone else comes along looking for answers. The aforementioned issues still apply to getting the window contents programmatically. However, it is possible in Windows to get the contents of a single window by utilizing the shortcut ALT+Print Screen when the window you want to capture has the keyboard focus (a.k.a. it's the active window). This may or may not help you, but it does capture the contents of just the window in question, even with DirectX stuff.