text:
Q: How to prevent Windows from opening Start menu on shortcut CTRL+ESC in electron.js or Powershell i'm trying to prevent Windows 10 from opening the Start Menu when an electron.js application is focused.
Right now when the electron.js app is focused and the shortcut Ctrl+Esc is pressed, the Windows menu opens.
https://imgur.com/a/oqrcHv9
I'm trying to create a Powershell Script that prevent the user input when the Ctrl key is pressed but is not efficient at all, and I've been using the globalShortcut object from electron but when the shortcut is pressed, it does not get catched in this code
  app.whenReady().then(() => {
    // Register a 'Ctrl+Esc' shortcut listener.

    const ret = globalShortcut.unregister('ctrl+esc', () => {
      console.log('Control+Esc is pressed')
      return false;
    })

    if (!ret) {
      console.log('registration failed')
    }

    // Check whether a shortcut is registered.
    console.log('registered',  globalShortcut.isRegistered('ctrl+esc'))
  });

PD. I have use AutoHotkey for that and that worked fine, but I can not install it on every machine so I'm looking for a electron/powershell solution.

A: Look to leverage PSReadLine for your use case.

About PSReadLine - PowerShell | Microsoft Docs

For example, using:

Set-PSReadLineKeyHandler (PSReadLine)

<#
Example 1: Bind the arrow key to a function
This command binds the up arrow key to the HistorySearchBackward function. This function searches command history for command lines that start with the current contents of the command line.
#>
Set-PSReadLineKeyHandler -Chord UpArrow -Function HistorySearchBackward

To get a list of what is in there, use:

Get-PSReadLineKeyHandler (PSReadLine)

<#
Example 1: Get all key mappings
This command returns all key mappings, bound and unbound.
#>
Get-PSReadLineKeyHandler -Bound -Unbound


text:
Q: A tool to transfer files using SSH in the browser on GCP it's doesn't work for run PHP files I use a tool to transfer files using SSH in the browser on GCP
 (centos7, Apache 2.4.6, php7.3) that copies PHP files
from Windows PC to /var/www/html. When I do this I cannot run my website.
But when I use the command cp to copy those files
I can run the website. Who recognizes this problem, please and can help me?

redpajama_set_name: RedPajamaStackExchange


text:
Q: SQL Server rename table takes very long I am trying to rename a table on sql server using the following command:
alter table <schema>.<old_name> RENAME TO <new_name>;
The table is fairly small: approximately 500 rows with 15 columns. The command runs for more than 15 minutes before I kill it.
I have verified that I have permissions to rename the tables since I have renamed a couple of other tables in the same schema (which took less than a minute because they were empty).
Any suggestions?

A: Copy the data into another table (select * into), then just drop and recreate the table using the correct name, then insert the data back in.


text:
Q: Share between Ubuntu 18.10 machines without Samba I have bought a new laptop and want to transfer files from the old machine to the new one. Both machines are running Ubuntu 18.10.
I have installed openssh-server on the old machine but when I right click on file and select "Share in local network" a popup tells me to install Samba. I thought that Samba was for sharing files with a Windows machine. Is there not a way to share between two Ubuntu (18.10) machines without using Samba?
The "duplicate" linked to is very old and deals with Ubuntu 10.10. Things have changed a bit in eight years.

A: First, Samba works on Ubuntu as well as Windows, so it is not only for Windows machines.
It is also easy to get similar functionality with ssh. One way is to type sftp://serverhostname in the file browser's address bar (ctrl+l). That should prompt for username and password, and then open a file browser window into the server filesystem. Then you can copy/paste files.
PS: You may need to login once from a terminal windows so that the known host file is updated.


text:
Q: Unmarshaller throws IllegalAccessError on simple XML String parsing I would like to deserialize a simple xml string to an object using the javax.xml.bind.Unmarshaller in an java EE application running in open-liberty. I have following method to deserialize:
Deserialize
package com.my.deserializer;

public class XmlDeserializer {
    private static Name deserialize() {
        try {
            JAXBContext jaxbContext = JAXBContext.newInstance(Name.class);
            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();

            StringReader reader = new StringReader("<Name xml:lang=\"en\">Acme, Inc.</Name>");
            Name cXml = (Name) unmarshaller.unmarshal(reader);
            return cXml;
        } catch (JAXBException e) {
            e1.printStackTrace();
        }
        return null;
    }
}

Class
package com.my.model;

@XmlRootElement(name = "Name")
public class Name implements Serializable {
    private static final long serialVersionUID = -4018453444627994825L;

    @XmlAttribute(name = "lang", namespace = "xml")
    public String lang;

    @XmlValue
    public String text;
}

When I call XmlDeserializer.deserialize(), I get following exception:
java.lang.IllegalAccessError: tried to access class com.my.model.Name from class com.my.deserializer.XmlDeserializer
I only can get this code working if I change class name from Name to any other name e.x. Name_Entity. Is there anything wrong with my code?
System specs

*

*Windows 10 x64

*Eclipse 2020-06

*Java SE-1.8

*Maven Dependency:

<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.3.1</version>
</dependency>

OpenLiberty (v. 20.0.0.9)
Feautures:
<feature>webProfile-8.0</feature>
<feature>mpJwt-1.1</feature>
<feature>localConnector-1.0</feature>
<feature>mpHealth-2.2</feature>
<feature>jaxws-2.2</feature>


text:
Q: How to add product image in the payload array of bulk product api via rabbitmq I have been importing the products via rest API using RabbitMQ
POST /magentoroot/rest/default/async/bulk/V1/products HTTP/1.1
Host: 127.0.0.1
Content-Type: application/json
[
   {
      "product":{
         "sku":"product_1_copy_qfvhc",
         "name":"Product 21",
         "attribute_set_id":4,
         "status":1,
         "visibility":4,
         "type_id":"virtual",
         "weight":"1",
         "price":"1800",
         "extension_attributes":{
            "category_links":[
               {
                  "position":0,
                  "category_id":"3"
               },
               {
                  "position":1,
                  "category_id":"4"
               }
            ],
            "stock_item":{
               "qty":10,
               "is_in_stock":true
            }
         },
         "custom_attributes":[
            {
               "attribute_code":"description",
               "value":"The Champ Tee keeps you cool and dry while you do your thing. Let everyone know who you are by adding your name on the back for only $10."
            },
            {
               "attribute_code":"tax_class_id",
               "value":"2"
            },
            {
               "attribute_code":"publisher",
               "value":"Jayashree"
            },
            {
               "attribute_code":"university",
               "value":"ASU"
            }
         ]
      }
   },
   {
      "product":{
         "sku":"product_6_copy",
         "name":"Product 14",
         "attribute_set_id":4,
         "status":1,
         "visibility":4,
         "type_id":"virtual",
         "weight":"1",
         "price":"1800",
         "extension_attributes":{
            "category_links":[
               {
                  "position":0,
                  "category_id":"3"
               },
               {
                  "position":1,
                  "category_id":"4"
               }
            ],
            "stock_item":{
               "qty":10,
               "is_in_stock":true
            }
         },
         "custom_attributes":[
            {
               "attribute_code":"description",
               "value":"The Champ Tee keeps you cool and dry while you do your thing. Let everyone know who you are by adding your name on the back for only $10."
            },
            {
               "attribute_code":"tax_class_id",
               "value":"2"
            },
            {
               "attribute_code":"publisher",
               "value":"Jayashree"
            },
            {
               "attribute_code":"university",
               "value":"ASU"
            }
         ]
      }
   }
]

The above one is my payload data for importing bulk products. but now I want to save images via rabbitMQ...
Could anyone please help to add image in payload data ?


text:
Q: How can I use runblocking on button click What is the purpose of runblocking?. Can I use it in OnClickListener?.
Here I am using runblocking{} in OnClickListener
This is my code
 mBinding.ivAdd.setOnClickListener{
println("before" + Thread.currentThread().id)
        runBlocking {
            println("in async" + Thread.currentThread().id)

            val job = launch {
                // launch new coroutine and keep a reference to its Job
                delay(1000L)
                println("World!" + Thread.currentThread().id)
                mBinding.tvNoDataFound.text = "test"
            }
            println("Hello,")
            println("after hello" + Thread.currentThread().id)
            delay(5000)
            job.join() // wait until child coroutine completes
        }
        println("after runBlocking" + Thread.currentThread().id)
    }

It shows error like this
 12-20 14:46:31.387 26915-26915/ I/System.out: before1
 12-20 14:46:31.399 26915-26915/ I/System.out: in async1
 12-20 14:46:31.405 26915-26915/ I/System.out: Hello,
 12-20 14:46:31.405 26915-26915/ I/System.out: after hello1
 12-20 14:46:32.410 26915-26937/I/System.out: World!1561
 12-20 14:46:32.422 26915-26937/ E/AndroidRuntime: FATAL EXCEPTION:
 ForkJoinPool.commonPool-worker-2

   android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
       at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6556)
       at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:907)
       at android.view.View.requestLayout(View.java:18728)
       at android.view.View.requestLayout(View.java:18728)
       at android.view.View.requestLayout(View.java:18728)
       at android.view.View.requestLayout(View.java:18728)
       at android.view.View.requestLayout(View.java:18728)
       at android.view.View.requestLayout(View.java:18728)
       at android.view.View.requestLayout(View.java:18728)
       at android.view.View.requestLayout(View.java:18728)
       at android.widget.TextView.checkForRelayout(TextView.java:7169)
       at android.widget.TextView.setText(TextView.java:4347)
       at android.widget.TextView.setText(TextView.java:4204)
       at android.widget.TextView.setText(TextView.java:4179)
       at MainActivity$onCreate$1$1$job$1.doResume(MainActivity.kt:164)
       at kotlin.coroutines.experimental.jvm.internal.CoroutineImpl.resume(CoroutineImpl.kt:54)
       at kotlinx.coroutines.experimental.DispatchTask.run(CoroutineDispatcher.kt:123)
       at java.util.concurrent.ForkJoinTask$RunnableExecuteAction.exec(ForkJoinTask.java:1388)
       at java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:251)
       at java.util.concurrent.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:845)
       at java.util.concurrent.ForkJoinPool.scan(ForkJoinPool.java:1674)
       at java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1629)
       at java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:108)

12-20 14:46:36.410 26915-26915/I/System.out: after runBlocking1
12-20 14:46:36.410 26915-26915/ I/Choreographer: Skipped 313 frames!  The
application may be doing too much work on its main thread.

If I use launch(UI){ } instead of launch{ }, it gives output like below
12-20 14:57:11.700 27338-27338/ I/System.out: before1
12-20 14:57:11.710 27338-27338/ I/System.out: in async1
12-20 14:57:11.714 27338-27338/ I/System.out: Hello,
12-20 14:57:11.714 27338-27338/ I/System.out: after hello1
12-20 14:57:16.718 27338-27338/ I/art: Note: end time exceeds epoch:

It doesn't print "World" which is come from another coroutine.
Here is another example of runblocking, which use runblocking from onCreate()
 println("before runblocking " + Thread.currentThread().id)
        runBlocking {
            println("in runblocking " + Thread.currentThread().id)

            val job = launch(UI) {

                println("In launch " + Thread.currentThread().id)

            }
            println("after launch " + Thread.currentThread().id)

        }
        println("after runBlocking " + Thread.currentThread().id)

Output of above code is
12-20 15:58:13.253 8588-8588/? I/System.out: before runblocking 1
12-20 15:58:13.266 8588-8588/? I/System.out: in runblocking 1
12-20 15:58:13.271 8588-8588/? I/System.out: after launch 1
12-20 15:58:13.273 8588-8588/? I/System.out: after runBlocking 1
12-20 15:58:13.363 8588-8588/? I/System.out: In launch 1

As we expect, "after runblocking" prints at last but it doesn't.
If I use job.join to wait completion of sub coroutine, the code is
  println("before runblocking " + Thread.currentThread().id)
        runBlocking {
            println("in runblocking " + Thread.currentThread().id)

            val job = launch(UI) {
                println("In launch " + Thread.currentThread().id)
            }
            println("after launch " + Thread.currentThread().id)
            job.join() // wait until child coroutine completes
        }
        println("after runBlocking " + Thread.currentThread().id)

Output of above code is
12-20 16:10:43.234 9194-9194/ I/System.out: before runblocking 1
12-20 16:10:43.249 9194-9194/ I/System.out: in runblocking 1
12-20 16:10:43.253 9194-9194/ I/System.out: after launch 1

Then what is the expected behavior of runblocking?. How can I use runblocking?

A: Even though you're blocking the code, the operation mBinding.tvNoDataFound.text = "test" runs on a pool worker thread.

runBlocking is designed to bridge regular blocking code to libraries that are written in suspending style, to be used in main functions and in tests.

In your case it should not be used. If you need to do background work, you should never block the UI thread. This happens regardless of using launch or launch(UI). The latter just makes everything run on the same thread and blocks even before the join.
So try not to block the UI thread and schedule a view update later via launch(UI) or with the standard View.post {}.


text:
Q: Navigation menu on javascript. DOM i have issues, how can I know for example contain <li> children <ul> or not?
thx all!

A: Try the following:
document.querySelectorAll("li > ul").length

or check querySelector for null
if (!document.querySelector("li > ul"))

A: If you want to check if a <ul> element contains any <li> elements, you only need to use one selector -
var elements = $('ul#selector').find('li');
if (elements.length){
  // the <ul> has child <li> elements
}else{
  // no <li> elements found
}

This of course can be written in a single conditional statement -
var childElements =  $('ul#selector > li').length;


text:
Q: IE9 syntax on jquery crossbrowser with jsonp and FF, Chrome I have the following code and i have a problem in ensuring part of it is used when a IE browser is used, and remove it when any other browser is used:
            $.ajax({
            url: 'http://mapit.mysociety.org/areas/'+ulo,
            type: 'GET',
            cache: false,
            crossDomain: true,
            dataType: 'jsonp',
        success: function(response) {

This works fine in IE9 because I have put the dataType as jsonp.  But this will not work on Chrome or FF.  So I need to remove the dataType.
I tried this:
<!--[IF IE]> dataType: 'jsonp', <![endif]-->

But it did not work.  It's worth noting, it does not need the dataType set when in FF or Chrome as it's json.
Whats the correct syntax to have this work ?
Thanks
Andrew

A: Managed it this way:
var version = navigator.appName;
            if(version == 'Microsoft Internet Explorer') {
                var theType = 'jsonp';
            }
            $.support.cors = true;
            $.ajax({
                        url: 'http://mapit.mysociety.org/areas/'+ulo,
                        type: 'GET',
                        cache: false,
                        crossDomain: true,
                        dataType: theType,

            success: function(response) {
                    etc etc

Andrew


text:
Q: How to connect to PC running VPN on the same home network I have a home network of several PCs all running Windows 10. One has a PIA VPN installed. There are two network adapters on that PC: the default one and the PIA.
I want to make sure if this VPN is down the internet traffic will not switch to the second (default) network adapter.
I tried to disable the default adapter but have immediately lost my Remote connection to this PC. I tried to use in RD the PC's name and the IP - nothing worked.
Any advice on how I can set this PC up so that it can have only a PIA network adapter? I also need to remotely connect to this PC from another PC on the same home network.

A: You will not be able to disable the physical adapter, because the VPN virtual adapter relies on it.
VPN Tunnels are not magic; they are just packets containing packets. The outer packet is the vpn tunnel, and the inner packet is the payload passing through. So, in order for the VPN to work, you must have a physical nic online with an IP address for your LAN, a default gateway (the interior of your home router) and DNS servers configured. your box must be able to send and receive traffic to and from PIA in order to start the tunnel in the first place, and will always carry both the outer and inner packets.


text:
Q: HtmlHelper Extension - User Conrol I have a custom user control called ErrorNotificationBox.  To place that on my page I do the old...
<%@ Register Src="~/PathTo/ErrorNotificationBox.ascx" TagName="ErrorNotificationBox" TagPrefix="uc" %>

<uc:ErrorNotificationBox Runat="server" id="myEnb" Caption="My Test Caption" />

Is it possible to extend HtmlHelper to include my user control?  I.e...
<%= Html.ErrorNotificationBox("My Test Caption")%>

Many thanks for any help.
ETFairfax

A: Most of the methods in html helper are Extension methods.  You can easily add your own.
public static class MyExtensions
{
    public static string ErrorNotificationBox(this HtmlHelper helper, string caption)
    {
        //generate and return the html for your error box here.
        // loading and returning an instance of a user control (.ascx)
        // as a string is difficult.  You may find it easier to
        // create the html with a string builder.
    }
}


text:
Q: Strobe light is working fine but doesn't work very well on click I have created the following strobe light. I want it to start on the press of a button and to stop if pressed again. Right now when it is open and I click, it closes but, on clicking again nothing happens!
Without the click listener, it starts on the start of the app but works great, but there is no way to stop it.
    public class Small extends Activity {

    private MMAdView adViewFromXml;
    RefreshHandler handler;
    ImageButton knob;
    int n=100000;
    Camera mCamera;
    Parameters params;
    int delay = 400; // in ms
    public boolean on;
    public boolean works;
    Thread logotimer;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_small_button);

        knob = (ImageButton) findViewById(R.id.pic);
        strobe();

        knob.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View iv) {
                  if(works == true){
                      logotimer.interrupt();
                  }else if(works != true)
                  {
                      strobe();
                  }
              }
            });

                });

    }

    /** Turn the devices FlashLight on */
    public void turnOn() {
      if (mCamera != null) {
        // Turn on LED
        params = mCamera.getParameters();
        params.setFlashMode(Parameters.FLASH_MODE_TORCH);
        mCamera.setParameters(params);
        mCamera.startPreview();
        on = true;
      }

    }

    /** Turn the devices FlashLight off */
    public void turnOff() {
      // Turn off flashlight
      if (mCamera != null) {
        params = mCamera.getParameters();
        params.setFlashMode(Parameters.FLASH_MODE_OFF);
        mCamera.setParameters(params);
        mCamera.stopPreview();

      }
      on = false;
    }

    /** Toggle the flashlight on/off status */
    /*public void toggleFlashLight() {
        if (!on) { // Off, turn it on
        turnOn();
      } else { // On, turn it off
        turnOff();
      }
}*/
    private void strobe(){
      Thread logotimer = new Thread() {
        public void run() {
          try {
            // Switch on the cam for app's life
            if (mCamera == null) {
              // Turn on Cam
              try{
                mCamera = Camera.open();
              } catch (RuntimeException e) {
                Log.e("Camera Error. Failed to Open. Error: ", e.getMessage());
              }
              try {
                mCamera.setPreviewDisplay(null);
              } catch (IOException e) {
                e.printStackTrace();
              }
              mCamera.startPreview();
            }
            int logotimer = 0;
            while(!interrupted() && logotimer <5000) {
                logotimer = logotimer ++;
                works = true;

                if (!on) { // Off, turn it on
                    turnOn();
                  } else if(on == true) { // On, turn it off
                    turnOff();
                  }
                sleep(delay);
            }
            if (mCamera == null) {
              mCamera.stopPreview();
              mCamera.release();
              mCamera = null;
            }
          } catch (InterruptedException e){

            e.printStackTrace();
          }
        }
      };logotimer.start();
    }
}

logcat:
01-08 15:17:33.807: W/System.err(28814): java.lang.InterruptedException
01-08 15:17:33.808: W/System.err(28814):    at java.lang.VMThread.sleep(Native Method)
01-08 15:17:33.808: W/System.err(28814):    at java.lang.Thread.sleep(Thread.java:1013)
01-08 15:17:33.808: W/System.err(28814):    at java.lang.Thread.sleep(Thread.java:995)
01-08 15:17:33.809: W/System.err(28814):    at com.light.oid.Small$4.run(Small.java:163)

A: Add strobe() call inside onClick:
@Override
public void onClick(View iv) {
    if(works) {
        logotimer.interrupt();

    } else {
        //mCamera = Camera.open(); //remove this
        //and add strobe()
        strobe();
    }
}

Also, you have global Thread logotimer, but in your strobe() method, you are creating a local variable with the same name, so when clicking button, logotimer is null, because the local shadows the global.
In strobe(), change:
 private void strobe(){
     Thread logotimer = new Thread() {
         public void run() {

to:
 private void strobe(){
     logotimer = new Thread() {
         public void run() {


text:
Q: PDF/XFDF setting action on submit button via Perl script I'm having trouble rewriting a Forms Data Format (FDF) file as XML Forms Data Format (XFDF).
I'm using a PDF form, which is filled by an FDF document generated by a Perl/CGI script.
The PDF contains a field which works as a submit button, which calls a Perl script to read the form data and write it to a database.
The action for the submit button is contained in the FDF, not coded directly in the PDF.
Perl Code
return qq# <</T($field) /A <</Flags 6 /S/SubmitForm /F << /F($script_url)/FS/URL>>>>>>\n#

This is working without any problems using the FDF format.
I can't find a code example for how the structure must look if I'm using the XFDF format.
Not working
<field name="Save"><value>/S/SubmitForm /F /F(http://..)/FS/URL </value></field>

Structure of FDF
> %FDF-1.2
1 0 obj
<<
/FDF << /Fields [
<< /V (somename)/T (name) >>
<< /V (* test * 740029 test)/T (adress) >>
<< /V...
<</T(save) /A <</Flags 6 /S/SubmitForm /F << /F(http://localhost:1234/save.cgi)/FS/URL>>>>>>
]
/F (http://localhost:8888/pdf/test.pdf)
>>
>>
endobj
trailer
<<
/Root 1 0 R

>>
%%EOF


text: Q: Status of WUXGA (1920x1200) laptops I have and application that absolutely requires at least 1200 lines vertical. I cannot seem to find a laptop from my usual vendors with this resolution. Is the 16:10 aspect ratio dead? Why is 1080 considered better? Is it all about playing movies on your computer?


text:
Q: Why we use return in the end of function while not returning any value I am confused about return statement , why we need to use return in end of function , for example
 function test($a){blah;
                   blahh ;
                   blahhh;
                  blahhhhh;
                    return;}

What the use of return here? Function automatically terminates when all the statements executed , I think there is no use of return here , but this picture from http://www.w3resource.com/php/statement/return.php make me confused
So
Can someone please explain the  use of return (when we not returning any value).

A: It depends on what you're trying to achieve.

If you write echo in several places, your code will get confusing. In general, a function that returns a value is also more versatile, since the caller can decide whether to further manipulate that value or immediately print it.

I'd recommend to stick to the convention and use return for a function.
You should check GuardClause.
Example:
function test() {
   return 10;
}

$a = test(); // $a stores the value 10

echo $a; // Prints 10
echo $a + 5; // We may want to manipulate the value returned by the function. So, it prints 15.

For further reference, check What is the difference between PHP echo and PHP return in plain English?

A: In that context: You don't.
return breaks out of the function, but since it is the last statement in that function, you would break out of it anyway without the statement.
return passes its argument back to the caller, but since it doesn't have an argument, there is nothing to pass.
So it does nothing.

Don't assume that every piece of code you stumble across has a purpuse. It might be left over from an earlier version of the code where something else (which gave it meaning) has been removed. It might be written by someone cargo culting. It might be placeholder for future development.

A: It's useful if you want a function to return a value.
i.e.
Function FavouritePie($who) {

     switch($who) {
                 case 'John':
                    return 'apple';

                 case 'Peter':
                    return 'Rhubarb';
                  }
}

So, considering the following:
$WhatPie = FavouritePie('John');

echo $WhatPie;

would give
apple
In a really simple form, it's useful if you want a function to return something, i.e. process it and pass something back.  Without a return, you'd just be performing a function with a dead end.
Some further reading:
http://php.net/manual/en/function.return.php
http://php.net/manual/en/functions.returning-values.php
To add some further context specific to the answer,  if the question boils down to "Do I need to add a return for the sake of it, at the end of a function, then the answer is no.  But that doesn't mean the correct answer is always to leave out your return.
it depends what you want to do with $a.
If you echo $a within the function, that function will spit out $a as soon as it is called.  If you return $a, assuming you set the calling of test to a variable (i.e. $something = $test('foo')), then you can use it later on.

A: "return" is important when you plan to call this function from other codes, it helps you to:

*

*Know if the function works correctly, or not.

*Obtain values from a function.

*Make sure other codes are not executed after return.

It might be useless when the code is simple as your sample, let's make it more complex.
function test($a){
    if(file_exists($a)){
        if(is_file($a)){
            return $a." IS A FILE\n";
        } else if(is_dir($a)) {
            return $a." IS A DIR\n";
        } else {
            return $a." EXISTS, BUT I DONT KNOW WHAT IT IS\n"
        }
    } else {
        return $a." NOT EXISTS\n";
    }
    return 0;
}

$filecheck = test("/abc/def.txt");
if($filecheck){
    echo $filecheck;
} else {
    echo "unknown error";
}

Above shows how to return a value, and do some basic handling.
It is always good to implement return in your functions so you can even specify error code for your functions for reference.
Based on your example, I'll modify slightly like below:
function test($a){
    blah;
    blahh;
    blahhh;
    blahhhhh;
    return 1;
}

So I know the code is running to last line.
Otherwise the function just finishes silently.


text:
Q: Concatenating new values to a particular cell of cell I have cell of cell with name TEMP(1x4). Each cell of cell has TEMP{1} to Temp{4} different set of values. Eg.
TEMP{1} =1:10
TEMP{2} =1:20
TEMP{3} =1:30
...

Now I have created a new cell lets name NEWTEMP={ 11 , 12, 13}. I want to concatenate NEWTEMP values with TEMP{1} such that now TEMP{1}= 1:13. How can I do it easily.
I need TEMP{1} and NEWTEMP values to be concatenated in a single cell (i.e. in TEMP{1})

A: You could do it this way:
temp = cell(4,1);
for i = 1:4
    temp{i} = 1:i*10;
end

newtemp = {};
newtemp{1} = 11:13;

temp{1} = [temp{1} newtemp{1}];

A: I think you meant to do
NEWTEMP = {[11,12,13]}

not
NEWTEMP = {11,12,13}

Look carefully at the difference between the two, the first is a 1x1 cell array containing a 1x3 numeric array
The second is a 1x3 cell array containing a 3 1x1 numeric arrays
If you use the first example, then concatenation is completed like this:
TEMP{1} = [TEMP{1} cell2mat(NEWTEMP)]


text:
Q: Can't decide MySQL or MongoDB for the Project I have problem with selecting database MongoDB or MySQL for my project.This is the MongoDB database design.
Ride:{
    Id: 12wtywbty21,
    driverId: t1@gmail.com,
    slectedRouteJunctions:[
                            Loc:{
                                    lat:50.25,
                                    lng:67.56
                            },
                            Loc:{
                                    lat:50.25,
                                    lng:67.56
                            },
                            Loc:{
                                    lat:50.25,
                                    lng:67.56
                            }
    ],
    availableSeats: 5 ,
    startDateTime: 2015-04-05 7:00 ,
    passengers:[
                Passanger:{
                    passangerId:t3gmail.com,
                    joinTime:2015-04-05 7:15,
                    endTime:null
                },
                Passanger:{
                    passangerId:t4gmail.com,
                    joinTime:2015-04-05 7:15,
                    endTime:null
                }
    ]
}

-----------------------------------------------------

User:{
    userId:t4gmail.com,
    name:t4,
    currentLocation:{
        lat:50,
        lng:60
    },
    friendRequest:[
                    FriendRequest:{
                        f_request_id:2,
                        friend_type:1
                    },
                    FriendRequest{
                        f_request_id:3,
                        friend_type:2
                    }

    ]
}

--------------------------------------------------------

FriendRequest{
    id:1,
    RequestDate:2015-04-05 7:15 ,
    assecptData:2015-04-05 7:15 ,
    State : 0

}

I want to store these kind of data set.But the problem is MongoDB does't support for relational query.When retrieving data ,MongoDB works with only one Collection.So I have retrieve data step by step .I think it will increase traffic between an application and the database server .
Another problem is MongoDB does't support Transactions. Is it a problem for a good application. I don't have good knowledge about Transactions. Because of  these reasons I also think about MySQL instead of MongoDB. But I can't clearly decide what is the best solution.What is the your opinion for this.Thanks in advance for any help

A: Comparing the advantages and disadvantages, I recommend mySQL only if you really need a relational database. I work with mongoDB and it's great advantage is rapid access and data entry, easy adaptation to project requirements change and virtually all transactions made in sql are possible in NoSQL.
For you have an idea, the project in which work need not be relational and mySQL takes minutes to process while with mongoDB were seconds.
But only you know the project and the real needs analysis before architect it.


text:
Q: Syntax error/ for loops I am having a problem with the simplest code, im sure its something stupid. When i put a ';' after the main function, it says something along the lines of old style formatting listing. So when i remove it, it says there is a ';' missing before ')'. Any help would be appreciated, the code is as follows:
#include "stdafx.h"
#include <iostream>

using namespace std;

int _tmain(int argc, _TCHAR* argv[]) {

int i;

for (i = 0, i < 10, i++)
    cout << i << endl;

system("pause");
return 0;
}

this is all in visual studio express by the way, also putting {} for the for loop makes no difference to the outcome.

A: You need to use ';' when separating elements of the for statement.
for (i = 0 ; i< 10; i++)

A: The for loop should be:
for (i = 0; i < 10; i++)
    cout << i << endl;

A: you are missing the basic for-loop syntax

for (init; condition; increment)
  statement_or_statement_block;

You should use ';' instead of ','
 for (i = 0;i < 10; i++)

A: put ';' instead of ','
    for( i = 0 ; i < 10 ; i++)

A: Eric Fortin's reply is correct. Also, if more than one line of code comes after the for statement and is included in the for loop you will need to use curly braces
for (int i = 0; i < 10; i++)
{
    some code;
    some code;
}


text:
Q: STOMP/Websocket architecture in Spring with decoupling between client and broker I was searching for some STOMP/Websocket examples with Spring and I found a lot of chats or news applications like this:

I would like to know why the client is coupled with the broker (look at the arrow from Request channel to Simple broker) instead of interacting only with the Spring application. Also, beyond the coupling between client and the broker technology, I think that this architecture allows the client to publish in the broker bypassing the application (that, for instance, maybe it would like to implement some spam filter).
In some sense, this is like using the endpoints of some application and at the same time be able to query the application's database. It looks like an antipattern and I cannot find any advantage, only disadvantages like no decoupling and security issues.
I saw a lot of architectures using STOMP/Websocket designed in this way so probably I am not seeing something.
Thanks in advance.


text:
Q: Method calling using reference variable public class Base {

    int var =0;
    Base(){
        System.out.println("Inside Base constructor .....");
        setVar();
    }

    public void setVar(){
        System.out.println("Inside base setVar method.....");
        var+=10;
    }

    public int getVar(){
        return var;
    }
}

Derived Class:
public class Derived extends Base {

    Derived(){
        System.out.println("Inside Derived constructor .....");
        setVar();
    }

    public void setVar(){
        System.out.println("Inside Derived setVar method.....");

        var+=20;
    }

    public static void main(String[] args){

        Base b = new Derived();
        System.out.println(b.getVar());
    }
}

Output.....
Inside Base constructor .....
Inside Derived setVar method.....
Inside Derived constructor .....
Inside Derived setVar method.....
40

Question ----> why when control goes to base class constructor , setVar() method of Derived class is called instead of Base class setVar() method.
I expected output as 30 , but when ran this program in debug mode found the flow and got output as 40. Could anyone please explain the logic behind this.
Thanks

A: Java will decide which method to run based on the runtime type of the variable, i.e. use polymorphism, at all times, even if the method called is from a base class constructor.
When the base class constructor is called, polymorphism means that the derived class's version of setVar is called, and 20 is added.  Then the derived class constructor is called, and again the derived class's version of setVar is called, and 20 is added, again, yielding 40.

A: Polymorphism at work.
When you override a super class method in derived class, then always your overridden method in derived class is called when someone operates on any object of derived class, even if that someone is a super class.
so Derived setVar() is called twice because it is overridden in 'Derived' and you tried to create an object of 'Derived' class.


text:
Q: Paypal SDK and Android I'm trying to implement Paypal Payment in my app. I get the example from here :
https://github.com/paypal/PayPal-Android-SDK.
When I launch the app with eclipse everything is good.
But when I try to add the activity, the xml file, and the manifest in my own app in Android Studio (V 0.6.0), an error appears since yesterday.
I can't call my method onBuyPressed with the line android:onClick="onBuyPressed" in my button.
I have this error :
06-09 20:57:45.851  10161-10161/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.IllegalStateException: Could not find a method onBuyPressed(View) in the activity class android.view.ContextThemeWrapper for onClick handler on view class android.widget.Button with id 'buyItBtn'
            at android.view.View$1.onClick(View.java:3724)
            at android.view.View.performClick(View.java:4274)
            at android.view.View$PerformClick.run(View.java:17357)
            at android.os.Handler.handleCallback(Handler.java:615)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4949)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1043)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:810)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.NoSuchMethodException: onBuyPressed [class android.view.View]
            at java.lang.Class.getConstructorOrMethod(Class.java:460)
            at java.lang.Class.getMethod(Class.java:915)
            at android.view.View$1.onClick(View.java:3717)
            at android.view.View.performClick(View.java:4274)
            at android.view.View$PerformClick.run(View.java:17357)
            at android.os.Handler.handleCallback(Handler.java:615)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4949)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1043)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:810)
            at dalvik.system.NativeStart.main(Native Method)

You can see my activity here :
package net.sparkeek.test.cubydroid.app;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.paypal.android.sdk.payments.PayPalAuthorization;
import com.paypal.android.sdk.payments.PayPalConfiguration;
import com.paypal.android.sdk.payments.PayPalFuturePaymentActivity;
import com.paypal.android.sdk.payments.PayPalItem;
import com.paypal.android.sdk.payments.PayPalPayment;
import com.paypal.android.sdk.payments.PayPalPaymentDetails;
import com.paypal.android.sdk.payments.PayPalService;
import com.paypal.android.sdk.payments.PaymentActivity;
import com.paypal.android.sdk.payments.PaymentConfirmation;

import org.json.JSONException;

import java.math.BigDecimal;

public class PaypalActivity extends ActionBarActivity {

    private static final String TAG = "paymentExample";
    /**
     * - Set to PaymentActivity.ENVIRONMENT_PRODUCTION to move real money.
     *
     * - Set to PaymentActivity.ENVIRONMENT_SANDBOX to use your test credentials
     * from https://developer.paypal.com
     *
     * - Set to PayPalConfiguration.ENVIRONMENT_NO_NETWORK to kick the tires
     * without communicating to PayPal's servers.
     */
    private static final String CONFIG_ENVIRONMENT = PayPalConfiguration.ENVIRONMENT_NO_NETWORK;

    // note that these credentials will differ between live & sandbox environments.
    private static final String CONFIG_CLIENT_ID = "credential from developer.paypal.com";

    private static final int REQUEST_CODE_PAYMENT = 1;
    private static final int REQUEST_CODE_FUTURE_PAYMENT = 2;

    private static PayPalConfiguration config = new PayPalConfiguration()
            .environment(CONFIG_ENVIRONMENT)
            .clientId(CONFIG_CLIENT_ID)
                    // The following are only used in PayPalFuturePaymentActivity.
            .merchantName("Hipster Store")
            .merchantPrivacyPolicyUri(Uri.parse("https://www.example.com/privacy"))
            .merchantUserAgreementUri(Uri.parse("https://www.example.com/legal"));

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_paypal);
        /*Button btnSouscription = (Button)findViewById(R.id.btnSouscription);
        btnSouscription.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBuyPressed(v);
            }
        });*/

        Intent intent = new Intent(this, PayPalService.class);
        intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
        startService(intent);
    }

    public void onBuyPressed(View v) {
        /*
         * PAYMENT_INTENT_SALE will cause the payment to complete immediately.
         * Change PAYMENT_INTENT_SALE to PAYMENT_INTENT_AUTHORIZE to only authorize payment and
         * capture funds later.
         *
         * Also, to include additional payment details and an item list, see getStuffToBuy() below.
         */
        PayPalPayment thingToBuy = getThingToBuy(PayPalPayment.PAYMENT_INTENT_SALE);

        Intent intent = new Intent(PaypalActivity.this, PaymentActivity.class);

        intent.putExtra(PaymentActivity.EXTRA_PAYMENT, thingToBuy);
        startActivityForResult(intent, REQUEST_CODE_PAYMENT);
    }

    private PayPalPayment getThingToBuy(String paymentIntent) {
        return new PayPalPayment(new BigDecimal("1.75"), "USD", "hipster jeans",
                paymentIntent);
    }

    /*
     * This method shows use of optional payment details and item list.
     */
    private PayPalPayment getStuffToBuy(String paymentIntent) {
        PayPalItem[] items =
                {
                        new PayPalItem("old jeans with holes", 2, new BigDecimal("87.50"), "USD",
                                "sku-12345678"),
                        new PayPalItem("free rainbow patch", 1, new BigDecimal("0.00"),
                                "USD", "sku-zero-price"),
                        new PayPalItem("long sleeve plaid shirt (no mustache included)", 6, new BigDecimal("37.99"),
                                "USD", "sku-33333")
                };
        BigDecimal subtotal = PayPalItem.getItemTotal(items);
        BigDecimal shipping = new BigDecimal("7.21");
        BigDecimal tax = new BigDecimal("4.67");
        PayPalPaymentDetails paymentDetails = new PayPalPaymentDetails(shipping, subtotal, tax);
        BigDecimal amount = subtotal.add(shipping).add(tax);
        PayPalPayment payment = new PayPalPayment(amount, "USD", "hipster jeans", paymentIntent);
        return payment.items(items).paymentDetails(paymentDetails);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_PAYMENT) {
            if (resultCode == Activity.RESULT_OK) {
                PaymentConfirmation confirm =
                        data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
                if (confirm != null) {
                    try {
                        Log.i(TAG, confirm.toJSONObject().toString(4));
                        Log.i(TAG, confirm.getPayment().toJSONObject().toString(4));
                        /**
                         *  TODO: send 'confirm' (and possibly confirm.getPayment() to your server for verification
                         * or consent completion.
                         * See https://developer.paypal.com/webapps/developer/docs/integration/mobile/verify-mobile-payment/
                         * for more details.
                         *
                         * For sample mobile backend interactions, see
                         * https://github.com/paypal/rest-api-sdk-python/tree/master/samples/mobile_backend
                         */
                        Toast.makeText(
                                getApplicationContext(),
                                "PaymentConfirmation info received from PayPal", Toast.LENGTH_LONG)
                                .show();

                    } catch (JSONException e) {
                        Log.e(TAG, "an extremely unlikely failure occurred: ", e);
                    }
                }
            } else if (resultCode == Activity.RESULT_CANCELED) {
                Log.i(TAG, "The user canceled.");
            } else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID) {
                Log.i(
                        TAG,
                        "An invalid Payment or PayPalConfiguration was submitted. Please see the docs.");
            }
        } else if (requestCode == REQUEST_CODE_FUTURE_PAYMENT) {
            if (resultCode == Activity.RESULT_OK) {
                PayPalAuthorization auth =
                        data.getParcelableExtra(PayPalFuturePaymentActivity.EXTRA_RESULT_AUTHORIZATION);
                if (auth != null) {
                    try {
                        Log.i("FuturePaymentExample", auth.toJSONObject().toString(4));

                        String authorization_code = auth.getAuthorizationCode();
                        Log.i("FuturePaymentExample", authorization_code);

                        sendAuthorizationToServer(auth);
                        Toast.makeText(
                                getApplicationContext(),
                                "Future Payment code received from PayPal", Toast.LENGTH_LONG)
                                .show();

                    } catch (JSONException e) {
                        Log.e("FuturePaymentExample", "an extremely unlikely failure occurred: ", e);
                    }
                }
            } else if (resultCode == Activity.RESULT_CANCELED) {
                Log.i("FuturePaymentExample", "The user canceled.");
            } else if (resultCode == PayPalFuturePaymentActivity.RESULT_EXTRAS_INVALID) {
                Log.i(
                        "FuturePaymentExample",
                        "Probably the attempt to previously start the PayPalService had an invalid PayPalConfiguration. Please see the docs.");
            }
        }
    }

    private void sendAuthorizationToServer(PayPalAuthorization authorization) {

        /**
         * TODO: Send the authorization response to your server, where it can
         * exchange the authorization code for OAuth access and refresh tokens.
         *
         * Your server must then store these tokens, so that your server code
         * can execute payments for this user in the future.
         *
         * A more complete example that includes the required app-server to
         * PayPal-server integration is available from
         * https://github.com/paypal/rest-api-sdk-python/tree/master/samples/mobile_backend
         */

    }

    @Override
    public void onDestroy() {
        // Stop service when done
        stopService(new Intent(this, PayPalService.class));
        super.onDestroy();
    }
}

My XML file :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="net.sparkeek.test.cubydroid.app.PaypalActivity" >

        <Button
            android:id="@+id/buyItBtn"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:onClick="onBuyPressed"
            android:text="Buy a Thing" />

</RelativeLayout>

And my manifest :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="net.sparkeek.test.cubydroid.app" >

    <!-- for most things, including card.io & paypal -->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />

    <!-- for card.io card scanning -->
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.VIBRATE" />

    <uses-feature
        android:name="android.hardware.camera"
        android:required="false" />
    <uses-feature
        android:name="android.hardware.camera.autofocus"
        android:required="false" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/logo_cuby"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:screenOrientation="portrait" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity
            android:name=".PaypalActivity"
            android:label="@string/title_activity_paypal" >
        </activity>

        <service
            android:name="com.paypal.android.sdk.payments.PayPalService"
            android:exported="false" />

        <activity android:name="com.paypal.android.sdk.payments.PaymentActivity" />
        <activity android:name="com.paypal.android.sdk.payments.LoginActivity" />
        <activity android:name="com.paypal.android.sdk.payments.PaymentMethodActivity" />
        <activity android:name="com.paypal.android.sdk.payments.PaymentConfirmActivity" />
        <activity android:name="com.paypal.android.sdk.payments.PayPalFuturePaymentActivity" />
        <activity android:name="com.paypal.android.sdk.payments.FuturePaymentConsentActivity" />
        <activity android:name="com.paypal.android.sdk.payments.FuturePaymentInfoActivity" />
        <activity
            android:name="io.card.payment.CardIOActivity"
            android:configChanges="keyboardHidden|orientation" />
        <activity android:name="io.card.payment.DataEntryActivity" />
    </application>

</manifest>

A: Your method is private but getMethod() only returns public method.
You need to use getDeclaredMethod().


text:
Q: I have a list with checkboxes left side and I want to add only checked list items in new array this is a image of list

from this list I want to create new array and add only checked items in new array, I don t know exactly data that will be in this list and I want dynamic solution for this problem. Sorry I could not show you the code I have no idea how the code might look.


text:
Q: Отправка через GCM без уведомления в шторке Задача следующая.
Пишу служебный список задач под андроид.
Идея сделать список задач для каждого пользователя. Задачи могут уходить и приходить, пользователь может назначить задачу тебе.
Нужно, чтобы backend отправлял задачи android- приложению.
Хотел сделать это через Google Cloud Messaging, но я видел примеры только с уведомлениями в шторке.
Но мне не нужны уведомления в шторке. Мне по факту нужно просто отправить информацию с бекенда и обработать её на клиенте в Android.
Возможно ли это? И как это реализовать?
Прошу объяснить или скинуть ссылку на данную информацию.
Прошу не дизлайкать мой вопрос ибо ответа на этот вопрос нет в stackoverflow
Android (kotlin)
Backend - Spring (java)


text:
Q: How to check if an application is it's first run or not in xamarin crosspaltform I want to show some pages in the first time app is installed, and the next time when I open the app show some other pages.
I tried this code
 protected override void OnStart()
    {
        if (Application.Current.Properties.ContainsKey("id"))
        {
            MainPage = new NavigationPage(new Page2());
        }
        else
        {
            Application.Current.Properties["id"] = 2;

            MainPage = new NavigationPage(new Page1());
        }
    }

The values in the Properties dictionary are only stored when the app goes to sleep

A: For a cross-platform approach, you can use the Settings Plugin
Then you can create a boolean property, for example, DidOpenOnce, and if it is false, show your initial welcome page or whatever. Then afterwards, set it to true.

A: protected void checkApplicationInstallState()
    {
        //retreive
        var prefs = Application.Context.GetSharedPreferences("MyApp", FileCreationMode.Private);
        var somePref = prefs.GetBool("IsApplicationOpenedForOnce", null);
        if (!somePref) {
            // Your Application is opened for the very first time. Now change the value to true as you have now opened the app so next time opening this application should get a true value.
            var prefEditor = prefs.Edit();
            prefEditor.PutBool(true, "IsApplicationOpenedForOnce");
            prefEditor.Commit();
        }

}

A: public MainPage()
        {
            InitializeComponent();
            if (Application.Current.Properties.ContainsKey("FirstUse"))
            {
                //Do things when it's NOT the first use...
                loadinit();
            }
            else
            {
                Application.Current.Properties["FirstUse"] = false;
                //Do things when it IS the first use...

            }

        }
        public async void loadinit()
        {
            await Navigation.PushAsync(new LoadPage());
        }


text:
Q: Fix a file/directory that says "refers to a location that is unavailable" / "file not found" when trying to open it I've got a bunch of folders that upon trying to browse into them, say "<directory> refers to a location that is unavailable". In Process Monitor, I see that the actual error code is NAME_NOT_FOUND -- but they are present.

*

*chkdsk finds no errors in the filesystem.

*Neither are they junctions or symbolic links (checked by installing the Link Shell Extension)

I've noticed that the names have a common trait:

*

*they all have a dot at the end

*in the past, I experienced the same with file/directories with broken names like in the picture:

What's happening here and how do I fix this?
How to delete a file ending in a dot in Windows 7? offers ways to delete it, but that's not acceptable 'cuz I need the contents.

*

*Unlike del suggested in that question, rename "<directory>" "<smth else>" produces the same "File not found".

*Neither \\?\<path> works (same error).

A: Windows API "preprocesses" paths before passing them to the kernel. The documentation on this is sketchy: instead, MSDN lists just the net limitations. In particular:

Do not end a file or directory name with a space or a period. Although the underlying file system may support such names, the Windows shell and user interface does not.

The Unicode I/O APIs that lift the MAX_PATH limitation seem to skip that preprocessing as well.

So, there are two ways of fixing:

*

*Use a program that uses the Unicode I/O API under the hood. Options include:

*

*Cygwin utilities:

*

*mv <bogus_name> <new_name>

*Scripting.FileSystemObject

*Some archivers like WinRAR/7-Zip (their GUI may allow to do renames on regular files/dirs)

*Use the 8.3 name to access the file/dir:
>dir /x
<...>
<DIR>          58B0~1       Для П.П.

>rename 58B0~1 new_name

Using the "native path" -- \\?\<full path> -- doesn't help here because for some cmd builtins  -- at least, dir and rename -- these paths are still subject for the preprocessing:
>dir "\\?\C:\Users\Me\Для П.П."
<...>
 Directory of \\?\C:\Users\Me\Для П.П

File Not Found

(note the missing end dot in the output).


text:
Q: keep Ratio in full screen - Extract Ratio from a movie (mp4) flash player This is what i'm trying to do , get the Ratio 4:3 9:16 etc from an mp4 movie (h264) so when ill open it in fullscreen using a flash player / action script 3 it will still keep the ratio.
regards

A: there is height and width varibles in the metadata recieved from loaded movies, divide one by the other to get the ratio of the video.
livedocs example

A: Or, if you are using flex: http://livedocs.adobe.com/flex/3/langref/flash/net/NetConnection.html
(see example at bottom of page)


text:
Q: Position in an list? I will check if a word exists in a list.
How can I show the position of this word?

A: To check if an object is in a list, use the in operator:
>>> words = ['a', 'list', 'of', 'words']
>>> 'of' in words
True
>>> 'eggs' in words
False

Use the index method of a list to find out where in the list, but be prepared to handle the exception:
>>> words.index('of')
2
>>> words.index('eggs')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 'eggs' is not in list

A: list = ["word1", "word2", "word3"]
try:
   print list.index("word1")
except ValueError:
   print "word1 not in list."

This piece of code will print 0, because that's the index of the first occurrence of "word1"

A: you can use ['hello', 'world'].index('world')

A: The following code:
sentence=["I","am","a","boy","i","am","a","girl"]
word="am"
if word in sentence:
    print( word, " is in the sentence")
    for i, j in enumerate(sentence):
        if j == word:
            print("'"+word+"'","is in position",i+1)

would produce this output:
"am" is in position 1
"am" is in position 5

This is because in python the indexing starts at 0
Hope this helped!

A: using enumeration - to find all occurences of given string in list
listEx=['the','tiger','the','rabit','the','the']
print([index for index,ele in enumerate(listEx) if ele=='the'])

output
[0, 2, 4, 5]

A: Sounds like you want indexof. From here:

operator.indexOf(a, b)¶
      Return the index of the first of occurrence of b in a.

A: Assuming the word is named for example "Monday":
You will need a list as your initial database:
myList = ["Monday", "Tuesday", "Monday", "Wednesday", "Thursday", "Friday"]

Then you need to loop through your list one by one to the end using for, next(), iter() and len() function:
myIter = iter(myList)
for i in range(0, len(myList)):
next_item = next(myIter)

Now while looping, you need to check if the wanted word exists and wherever it exists, print it:
if next_item == "Monday":
    print(i)

Altogether:
myList = ["Monday", "Tuesday", "Monday", "Wednesday", "Thursday", "Friday"]
myIter = iter(myList)
for i in range(0, len(myList)):
    next_item = next(myIter)
    if next_item == "Monday":
        print(i)

Since there are two Mondays in this list, the result for this example will be:
0
2


text:
Q: Scroll down listbox automatically I'm using Matlab R2018a where there is no scroll function. I just need to scroll down the listbox as items are added (dynamically).
I found this solution on Google but is not working for me.
handles.slider.Max = length(handles.listbox.String);
handles.slider.Value = handles.slider.Max;

Is there any other solution?

A: In order for the ListboxTop property to have an effect, the UI has to be redrawn (using drawnow) after adding the items to the listbox.
Example, using GUIDE with one listbox tagged as listbox1:
In the GUI's OpeningFcn, write
handles.t = timer('BusyMode', 'drop', 'ExecutionMode',...
'fixedRate', 'StartDelay', 4, 'Period', 4.0, 'TimerFcn', {@addItem, hObject});
handles.ctr = 0;
handles.t.start();
guidata(hObject, handles);

At the end, add
function addItem(hObject, EventData, parentO)

handles = guidata(parentO);
handles.ctr = handles.ctr + 1;
handles.listbox1.String{end+1} = sprintf('Item %i', handles.ctr);
drawnow
handles.listbox1.ListboxTop = numel(handles.listbox1.String) ;
guidata(parentO, handles);

Note that when uncommenting the drawnow line, the listbox will always jump to the selected item (the first one by default).


text:
Q: Jquery - Passing selected row values to a hidden text box I'm working on a postcode (airports & train station) search but can't seem to figure out why the selected row values are not writing the correct values to the hidden text boxes.
Basically if I search 'Gatwick' as shown below:

I get the following XML response:
<?xml version="1.0"?>
<addresslist resultcount="4">
    <address id="0" catagoryid="1" lat="184179968" lng="-639296">
        <companyname></companyname>
        <premiseno></premiseno>
        <streetname>GATWICK AIRPORT (NORTH)</streetname>
        <townname></townname>
        <postcode>RH6 0PJ</postcode>
    </address>
    <address id="1" catagoryid="1" lat="184161536" lng="-586944">
        <companyname></companyname>
        <premiseno></premiseno>
        <streetname>GATWICK AIRPORT (SOUTH)</streetname>
        <townname></townname>
        <postcode>RH6 0NP</postcode>
    </address>
    <address id="2" catagoryid="1" lat="184161664" lng="-580224">
        <companyname></companyname>
        <premiseno></premiseno>
        <streetname>GATWICK GATWICK AIRPORT RAILWAY STATION</streetname>
        <townname></townname>
        <postcode>RH6 0RD</postcode>
    </address>
    <address id="3" catagoryid="1" lat="184161536" lng="-586944">
        <companyname></companyname>
        <premiseno></premiseno>
        <streetname>GATWICK RAILWAY CONCOURSE</streetname>
        <townname></townname>
        <postcode>RH6 0NN</postcode>
    </address>
</addresslist>

At the moment, no matter which row I select, it always writes the last Lat & Long values to the hidden textbox. For example, If i select the first row, it will write 184161536, -586944 which is the Lat Long values for 'GATWICK RAILWAY CONCOURSE'
Here is the Jquery Code:
function buildResultView(xml_object,pageNum,rowdiv) {

// Remove existing page up page down click events
rowdiv.find('.lbl-addr-pgup').unbind('click');
rowdiv.find('.lbl-addr-pgdn').unbind('click');

// Remove result list if there is one
if (rowdiv.find('.ul-result-view')) {
    rowdiv.find('.ul-result-view').remove();
}

ul = $('

');
ul.addClass('ul-addr-res');
ul.addClass('ul-result-view');

// Prepend ul before resultinfo
rowdiv.find('.div-result-info').before(ul);

// Reset result count
var resCount = 0;

// Count Results
$(xml_object).find('address').each(function(){
    resCount += 1;
});

// Pull out start row and max rows
var pageRes = clientPaginate(resCount,pageNum).split(',');
var loopMax = parseInt(pageRes[0]);
var currentRow = parseInt(pageRes[1]);
var lastPge = parseInt(pageRes[2]);
var addType;

// Show maxRows starting at startIndex
for (var i = currentRow; i < loopMax; i++) {

    var li = $('

');
    li.addClass('li-addr-res');
    addType = parseInt($(xml_object).find("address[id='"+i+"']").attr("catagoryid"));
    var lat = ($(xml_object).find("address[id='"+i+"']").attr("lat"));
    var lng = ($(xml_object).find("address[id='"+i+"']").attr("lng"));

    li.css('cursor','pointer');

// Reset result count
var resCount = 0;

// Count Results
$(xml_object).find('address').each(function(){
    resCount += 1;
});

// Pull out start row and max rows
var pageRes = clientPaginate(resCount,pageNum).split(',');
var loopMax = parseInt(pageRes[0]);
var currentRow = parseInt(pageRes[1]);
var lastPge = parseInt(pageRes[2]);
var addType;

// Show maxRows starting at startIndex
for (var i = currentRow; i < loopMax; i++) {

    var li = $('

');
    li.addClass('li-addr-res');
    addType = parseInt($(xml_object).find("address[id='"+i+"']").attr("catagoryid"));
    var lat = ($(xml_object).find("address[id='"+i+"']").attr("lat"));
    var lng = ($(xml_object).find("address[id='"+i+"']").attr("lng"));

Then I write the lat, lng values to the hidden textbox:
    // Add this lat lng to hidden text box
    rowdiv.find('.hidden-lat-lng').val(lat+","+lng);

Any idea why this isn't selected the correct latitude longtitude values?
I just need to be able to get the latitude longtitude values of the row that is selected.
If anybody could help with this, I would be very greatful! :-)

A: When you have code like this:
for (var i = 0; i < 10; i++) {
   var foo = i;
}

foo is going to be 9. That's what's happening, your lat and lng values are simply the last ones in the loop, because that's where you're setting them.
Note that it doesn't matter whether you declare foo inside the for() loop or outside it; variable scope in javascript is not block-level like it is in many other languages and using var will give these ones the scope of the function.
You're trying to redeclare variables as well; I'm not sure whether that's just a result of copy-pasting the code or a misunderstanding of variable scope but in any case it will have no subsequent effect. It would be clearer and probably lead to fewer gotchas if you just declare your local variables at the top of the function.
There is presumably more code dealing with which row is selected. If it sets lat and lng then post it to your question. Otherwise, here's my take:
for (var i = currentRow; i < loopMax; i++) {
    var li = $('

');
    li.addClass('li-addr-res');
    addType = parseInt($(xml_object).find("address[id='"+i+"']").attr("catagoryid"));

    lat = ($(xml_object).find("address[id='"+i+"']").attr("lat"));
    lng = ($(xml_object).find("address[id='"+i+"']").attr("lng"));

    // Store the latitude and longitude alongside the li element itself
    li.data('lat', lat).data('lng', lng);

    // add a handler to copy that data to the hidden textarea when clicked
    // I'm assuming you mean the row is selected when it's clicked, otherwise
    // just bind to something else
    li.click(function() {
        // recover the data from this element (the
)
        var lat = $(this).data('lat'),
            lng = $(this).data('lng');

        // rowdiv is probably still in scope from the parent function,
        // though there is missing code in your question. I'm going to
        // assume there's only one hidden textarea for this purpose
        $('.hidden-lat-lng').val(lat + "," + lng);
    }


text:
Q: Way of saving arraylist of objects in android I am having difficulty saving an ArrayList of objects to a file in android. I want to be able be able to read these objects and call a method on each object to get one of their attributes. Here is the object class
public class Transaction {

private double amount;
private String store;
private Date date;

public Transaction(){
    amount = 0.0;
    store = null;
    date = null;
}

public Transaction(double amt, String str, Date dat ) {
    amount = amt;
    store = str;
    date = dat;
}

}
In my activity I take input and create a new Transaction object. I then add the Transaction object to an ArrayList. I want to save the ArrayList to a file and be able to access the ArrayList from a different activity. In this different activity I want to access and call getAmount() on each object in the ArrayList to create a total amount and display it on screen. Thanks.

A: You can implement Parcelable in your objects. There is online tool that can helps. Ones you implement Parcelable you can pass the ArrayList<Parcelable> trough activities by putting the array in Intent's extras or save the array in SharedPreferences for later usage.


text:
Q: Bash: replace specific text with its translation There is a huge file, in it I want to replace all the text between '=' and '\n' with its translation, here is an example:
input:

screen.LIGHT_COLOR=Lighting Color
screen.LIGHT_M=Light (Morning)
screen.AMBIENT_M=Ambient (Morning)

output:

screen.LIGHT_COLOR=Цвет Освещения
screen.LIGHT_M=Свет (Утро)
screen.AMBIENT_M=Эмбиент (Утро)

All I have managed to do until now is to extract and translate the targeted text.
while IFS= read -r line
do
        echo $line | cut -d= -f2- | trans -b en:ru

done < file.txt

output:
    Цвет Освещения
    Свет (Утро)
    Эмбиент (Утро)

*trans is short for translate-shell. It is slow, but does the job. -b for brief translation; en:ru means English to Russian.
If you have any suggestions or solutions i'll be glad to know, thanks!
edit, in case someone needs it:
After discovering trans-shell limitations I ended up going with the @TaylorG. suggestion. It is seams that translation-shell allows around 110 request per some time. Processing each line seperatly results in 1300 requests, which breaks the script.
long story short, it is faster to pack all the data into a single request. Its possible to reduce processing time from couple of minutes to mere seconds. sorry for the messy code, it's my third day with:
cut -s -d = -f 1 en_US.lang > option_en.txt
cut -s -d = -f 2 en_US.lang > value_en.txt

# merge lines
sed ':a; N; $!ba; s/\n/ :: /g' value_en.txt > value_en_block.txt

trans -b en:ru -i value_en_block.txt -o value_ru_block.txt

sed 's/ :: /\n/g' value_ru_block.txt > value_ru.txt

paste -d = option_en.txt value_ru.txt > ru_RU.lang

# remove trmporary files
rm option_en.txt value_en.txt value_en_block.txt value_ru.txt value_ru_block.txt

Thanks Taylor G., Armali and every commentator

A: Using pipe in a large loop is expensive. You can try the following instead.
cut -s -d = -f 1 file.txt > name.txt
cut -s -d = -f 2- file.txt | trans -b en:ru > translate.txt
paste -d = name.txt translate.txt

It shall be much faster than your current script. I'm not sure how your trans method is written. It needs to be updated to process batch input if it's not, e.g. using a while loop.
trans() {
    while read -r line; do
        # do translate and print result
    done
}

A: You already did most of the work, though it can be optimized a bit. What's missing is just to output the first part of the line up to the equal sign together with the translation:
while IFS== read left right
do  echo $left=`trans -b en:ru <<<$right`
done <file.txt


text:
Q: MySQL user creation date, modified date I have a question to all you MySQL experts out there: Is it possible to see when a user was created in MySQL? Let's say I create a user called 'monty':
CREATE USER 'monty'@'localhost' [...]
how can I see when I created this user? Is there also a way to check how the details of this user got modified?
Thanks a lot.

A: No, there is no way to do that. The only thing you can do is analyzing binary logs of MySQL Server; but internally it does not store neither user creation date nor modification dates/details.
If you're creating a new software or adding a feature to the existing one you might consider creating/modifying users through your stored procedures only, while in the same stored procedures you can log theis parameters, current date and everything else you want to.


text:
Q: Approximate simple moving average knowing only previous SMA? I know it's possible to calculate a regular average incrementally knowing the previous average, the next number and the number of items. But is this possible for a moving average of N items, at least approximately?
To calculate the exact SMA in this case you must know the first number in a set which you're about to leave out, as shown here. That's why I ask about the approximation.
I tried an approach similar to the one for a regular average: multiply the previous average by N - 1, add a new number and then divide by N. But the result looked like garbage to me.

A: You can try $a_{k+1}=ua_k+v x_{k+1}$. This will not produce a true moving average, but instead $x_i$ contributes to $a_n$ with a factor of $v\cdot u^{n-i}$. So if we let $0<u<1$, we will at least have that $x_i$ contributes less and less the "older" it is. We should ensure that $v+vu+vu^2+\ldots=1$, that is $v=1-u$. In contrast to the moving average where the influence of old values breaks off suddnely, this approximation gives as smooth "fade-out". Zis may even be an advantage: A big exceptional spike one year ago will cause a (small) spike today in the one-year moving average, even if nothing happened recently. The approximation will not cause this. Then again, seasonal oscillations do not vanish with this ...


text:
Q: MatDialog - should cover specific part of the page I am using MatDialog and opening it from the effect. I want to cover specific part of the page. In this example, it should not cover area which is covered by border. Is it possible?
https://stackblitz.com/edit/ngrx-dialog-effects-vj9qek

A: We can override the modal backdrop to leave a specific space at the top... we do this by introducing a styles to our component definition.
In your existing stackBlitz, change app.component.ts to be:
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { Store, select } from '@ngrx/store';

import * as fromRoot from './reducers/';
import { OpenDialog } from './actions';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styles: [`
    ::ng-deep .cdk-overlay-backdrop { top: 64px; }
`]
})
export class AppComponent {
  animal: Observable<string>;

  constructor(private store: Store<fromRoot.State>) {
    this.animal = this.store.pipe(select(fromRoot.getAnimalName))
  }

  openDialog() {
    this.store.dispatch(new OpenDialog());
  }
}


text:
Q: Using confidence interval from full sample to test statistics from a small sub-sample? I have already spoken to a statistician and he did not seem certain about the answer, so perhaps it may be of use to others. The study is not typical, so please bear with me while I try to explain it.
I have about 75,000 sentences of English conversations for a sample. I'm interested in whether sentences with a certain grammatical structure (specifically, missing verb phrases) tend to clump together. First, I calculated the relative frequency (empirical probability) of these sentences and got 910 hits/75,000 total sentences ≈ 0.012. To get confidence intervals for this statistic, I used bootstrapping with 10,000 resamples of the entire data set with replacement, and found that the 99% confidence interval is about 0.0109 - 0.0134.
To see whether and to what extent these sentences tend to be near each other in the data, I made a new sub-sample. For each sentence with a missing verb phrase, I counted how many sentences also had missing verb phrases in the five previous sentences. So, I have five "slots", each with a relative frequency of how often sentences in that slot lack verb phrases (i.e., the immediately preceding sentence is a slot, then the next preceding sentence, and so on). This gives me results like this:
Slot 1: 56 hits/910 total sentences = 0.061
Slot 2: 32 hits/902 total sentences = 0.035
etc...
My question is this. Can I compare these relative frequencies for each slot to the confidence interval I calculated from the whole data set? In other words, if slot 1 has a relative frequency of .061, that is beyond the 99% confidence interval from my bootstrap of the whole data set, so is it therefore valid to claim that this is higher than could be expected in that slot?
And if it isn't, is there a relatively straightforward way to make it work?


text:
Q: Changing units of buffer Desktop 10.3.1
GCS: WGS 1984
Created a Buffer of points based on a pre-specified radius from the points attribute table.
It appears all of the buffers were created with a decimal degree unit of measure.... How do I change the units of the buffer layer to miles?

A: Riffing off what @scw wrote, the buffer process will take the appended unit ("# Miles") as an input as per the ArcPy script:
arcpy.Buffer_analysis("input_points", "C:/workspace/points_buffered_10mi.shp", "10 Miles")

You could create a new string field with field calculator where you take the distance number and add " Miles" to it. The field calculation would look like (in python):
str(!field!) + " Miles"

You should then have a string field of "## Miles". Point to that new field as the distance field when you run the buffer and it should work.
EDIT: I just confirmed that this works. I made a group of points and assigned them random numbers, did the concatenation. Ran through the buffer just fine. My table looks like this:

EDIT 2, for posterity: The details on this can be found on the ArcGIS resource site here: Buffer (Analysis)

A: It isn't clear exactly how you created your buffers from your question, but my guess is that you're trying to use attributes of the PointGeometry representation and using the buffer function included with that representation. By default, that buffer function is limited to buffering in the same units as the input data, which in your case with unprojected geographic data, doesn't make sense -- a unit of degree varies with both latitude and longitude.
The easiest thing to do is to use the Buffer tool, which takes a linear unit for the parameter buffer_distance_or_field, and will automatically create geodesic buffers if passed in miles:
import arcpy
arcpy.Buffer_analysis("input_points", "C:/workspace/points_buffered_10mi.shp", "10 Miles")

Here's the set of linear units buffer will understand:
    'Centimeters', 'Decimal degrees', 'Decimeters', 'Feet', 'Inches', 'Kilometers', 'Meters', 'Miles', 'Millimeters', 'Nautical Miles', 'Yards'


text:
Q: Show a conjecture about $\arcsin\left(\frac{9}{10}\right)\cdot\left(\frac{6}{10}\right)!>1$ Recently I found the inequality :
$$\arcsin\left(\frac{9}{10}\right)\cdot\left(\frac{6}{10}\right)!>1$$
I don't ask for a proof .
I ask if someone can give some details on the link with the Gamma function and arcsin .
I ask also because we have a formula on wiki page for the Gamma's function  wich gives an equality with the function $\sin$ .
But now why arcsin ?
Can we find a infinite series ?

I can gives some other terms of the "series" we want :
$$\left(\frac{9}{10}\right)\cdot\frac{\left(\frac{6}{10}\right)!\arcsin\left(\left(\frac{99}{100}\right)^{\frac{1}{600}}\right)}{\arcsin\left(\left(\frac{999}{1000}\right)^{\frac{1}{80}}\right)}\frac{\arcsin\left(\left(\frac{9999}{10000}\right)^{\frac{1}{600}}\right)}{\arcsin\left(\left(\frac{99999}{100000}\right)^{\frac{1}{70}}\right)}>1$$
Edit :
I gives more terms :
$$\arcsin\left(\frac{9}{10}\right)\cdot\frac{\left(\frac{6}{10}\right)!\arcsin\left(\left(\frac{99}{100}\right)^{\frac{1}{600}}\right)}{\arcsin\left(\left(\frac{999}{1000}\right)^{\frac{1}{80}}\right)}\frac{\arcsin\left(\left(\frac{9999}{10000}\right)^{\frac{1}{600}}\right)}{\arcsin\left(\left(\frac{99999}{100000}\right)^{\frac{1}{70}}\right)}\frac{\arcsin\left(\left(\frac{999999}{1000000}\right)^{\frac{1}{600}}\right)}{\arcsin\left(\left(\frac{9999999}{10000000}\right)^{\frac{1}{62}}\right)}\frac{\arcsin\left(\left(\frac{99999999}{100000000}\right)^{\frac{1}{600}}\right)}{\arcsin\left(\left(\frac{999999999}{1000000000}\right)^{\frac{1}{85}}\right)}\frac{\arcsin\left(\left(\frac{9999999999}{10000000000}\right)^{\frac{1}{600}}\right)}{\arcsin\left(\left(\frac{99999999999}{100000000000}\right)^{\frac{1}{79}}\right)}>1$$
And made a conjecture :
Let $a_k>0$ such that :
$$\arcsin\left(\frac{9}{10}\right)\cdot\frac{\left(\frac{6}{10}\right)!\arcsin\left(\left(\frac{99}{100}\right)^{\frac{1}{600}}\right)}{\arcsin\left(\left(\frac{999}{1000}\right)^{\frac{1}{a_{k}}}\right)}\frac{\arcsin\left(\left(\frac{9999}{10000}\right)^{\frac{1}{600}}\right)}{\arcsin\left(\left(\frac{99999}{100000}\right)^{\frac{1}{a_{k+1}}}\right)}\cdot\cdot\cdot\frac{\arcsin\left(\left(\frac{9999\cdot\cdot\cdot9}{1000\cdot\cdot\cdot00}\right)^{\frac{1}{600}}\right)}{\arcsin\left(\left(\frac{99999\cdot\cdot\cdot9}{10000\cdot\cdot\cdot00}\right)^{\frac{1}{a_{m}}}\right)}\cdot\cdot\cdot=1$$
Then I conjecture that for $a_1=80,a_2=70,a_3=62,a_4=85,a_5=79,a_6=61.75$:
$$a_k<100$$
How to (dis)prove it ?

A: The solution to
$$\sin^{-1}\left(\frac32x\right)x!=1\implies x=0.59983…$$
is approximated by the series expansion of $x!$ about $x=\frac12$ and of $\sin^{-1}(x)$ about $x=\frac1{\sqrt3}$:
$$\frac{\sqrt\pi}2\left(\frac\pi3+3\left(x-\frac1{\sqrt3}\right)\right)=1\implies x=\frac1{\sqrt3}+\frac2{3\sqrt\pi}-\frac\pi9=0.60441…\approx\frac23$$
More terms give better approximations.

A: Define
$$f(\epsilon)=\sin ^{-1}(1-\epsilon^2 )\,\, \Gamma \left(\frac{3}{2}+\epsilon^2 \right)=\sqrt{\frac{\pi }{2}}\sum_{n=0}^\infty a_n\,\epsilon^n $$ where the first coefficients are
$$\left(
\begin{array}{cc}
n & a_n \\
 0 & \frac{\pi }{2 \sqrt{2}} \\
 1 & -1 \\
 2 & \frac{\pi  \psi ^{(0)}\left(\frac{3}{2}\right)}{2 \sqrt{2}} \\
 3 & -\frac{25}{12}+\gamma +\log (4) \\
 4 & \frac{\pi  \left(-8+\pi ^2+2 \psi ^{(0)}\left(\frac{3}{2}\right)^2\right)}{8
   \sqrt{2}} \\
 5 & \frac{1}{480} \left(951-120 \pi ^2-40 \psi ^{(0)}\left(\frac{3}{2}\right)
   \left(1+6 \psi ^{(0)}\left(\frac{3}{2}\right)\right)\right) \\
 6 & \frac{\pi  \psi ^{(0)}\left(\frac{3}{2}\right) \left(-24+3 \pi ^2+2 \psi
   ^{(0)}\left(\frac{3}{2}\right)^2\right)+2 \pi  \psi
   ^{(2)}\left(\frac{3}{2}\right)}{24 \sqrt{2}}
\end{array}
\right)$$
Now compute the partial sums
$$S_p=\sqrt{\frac{\pi }{2}}\sum_{n=0}^p a_n\,10^{-n/2}  $$
$$\left(
\begin{array}{cc}
p & S_p \\
 0 & 1.392081999 \\
 1 & 0.995749269 \\
 2 & 1.000828973 \\
 3 & 0.996079983 \\
 4 & 1.002595858 \\
 5 & 1.000654391 \\
 6 & 1.000485853 \\
 7 & 1.000515895 \\
 8 & 1.000538616 \\
 9 & 1.000532116 \\
 10 & 1.000530898 \\
 11 & 1.000531186 \\
 12 & 1.000531278 \\
 13 & 1.000531254 \\
 14 & 1.000531248 \\
 15 & 1.000531249
\end{array}
\right)$$
Otherwise, as @Tyma Gaidash did, starting with $\epsilon_0=0$, the first iterate of Newton method for $f(\epsilon)=1$ is
$$\epsilon_{(2)}=\frac{\pi ^{3/2}-4}{2 \sqrt{2 \pi }}$$ and, by Darboux theorem, we know that it is an underestimate of the solution since
$$\big[f(0)-1\big]f''(0)=\frac{1}{8} \pi ^{3/2} \left(\pi ^{3/2}-4\right) \psi
   ^{(0)}\left(\frac{3}{2}\right)~~>~0$$
Similarly, the first iterate of Halley method
$$\epsilon_{(3)}=\Bigg[\frac{2 \sqrt{2 \pi }}{\pi ^{3/2}-4}-\frac{\pi  \psi
   ^{(0)}\left(\frac{3}{2}\right)}{2 \sqrt{2}}\Bigg]^{-1}$$ is an overestimate of the solution.
We can expand
$$f(\epsilon)=\sum_{n=0}^\infty b_n\,(\epsilon-\epsilon_{(2)})^n $$
Computing again the partial sums
$$\left(
\begin{array}{cc}
p & S_p \\
 0 & 1.004658787 \\
 1 & 1.000530217 \\
 2 & 1.000531249
\end{array}
\right)$$
$$f(\epsilon)=\sum_{n=0}^\infty c_n\,(\epsilon-\epsilon_{(3)})^n $$ using only the first term gives $1.000531214$.
Edit
Pushing more and more
$$f\left(\frac{1159+686 \pi -116 \pi ^2}{324+227 \pi +589 \pi ^2}\right)=1.0000000000000000000250068\cdots$$
Update
It is interesting to look at the zero level plot of
$$f(x,y)=\sin ^{-1}(x)\,\, \Gamma (1+y)-1$$ (have a look here).
Using the same approach as above, you could prove that
$$f\left(\frac{900}{1000},\frac{332}{1000}\right)>0 \qquad \text{and} \qquad f\left(\frac{900}{1000},\frac{596}{1000}\right)>0$$
$$f\left(\frac{901}{1000},\frac{349}{1000}\right)>0 \qquad \text{and} \qquad f\left(\frac{901}{1000},\frac{578}{1000}\right)>0$$
$$f\left(\frac{902}{1000},\frac{369}{1000}\right)>0 \qquad \text{and} \qquad f\left(\frac{902}{1000},\frac{557}{1000}\right)>0$$
$$f\left(\frac{903}{1000},\frac{395}{1000}\right)>0 \qquad \text{and} \qquad f\left(\frac{903}{1000},\frac{530}{1000}\right)>0$$
$$f\left(\frac{904}{1000},\frac{445}{1000}\right)>0 \qquad \text{and} \qquad f\left(\frac{904}{1000},\frac{478}{1000}\right)>0$$


text:
Q: pass shared_ptr as a argument to a function which accepts object of a class type I am wondering , is it possible to pass shared_ptr as a argument to a function which accepts pointer of class type
Example
class class_A_type
{
 bla bl a

 private:
    IStuff *mStuff;
}

class IStuff
{
  public:
    IReporter(){};
    virtual ~IReporter(){};
    virtual void ReportResults( class_A_RESULT_TYPE *pResult) = 0;
};

void class_A_type::SendResultBack( bool status, std::string statusString )
{
        boost::shared_ptr< class_A_RESULT_TYPE >aResultBptr( new class_A_RESULT_TYPE ( mStuff, GetPropertyName() ) );
        bool lbool = false;
        std::string lstr = "running";
        aResultBptr->setStatus( lbool, lstr );
        myStuff->ReportResults( aResultBptr );// ERROR  HOw to pass shared _ptr ??
}

A: You should call get function on shared_ptr.
myStuff->ReportResults( aResultBptr.get() );


text:
Q: Не получается открыть базу данных в PyQT5 Есть код, создал базу данных сам (скрин ниже), запускаю программу, нажимаю на кнопку список фильмов, открывается пустое окно (скрин тоже приложу).
При чём с другой базой данных, не моей, уже готовой, он её открывает. Как исправить?
import sys
from PyQt5.QtWidgets import QWidget, QTableView, QDialog, QPushButton, QApplication, QVBoxLayout
from PyQt5.QtSql import QSqlDatabase, QSqlTableModel

class Films(QDialog):
    def __init__(self, parent):
        super().__init__(parent)

        self.setWindowTitle('Films')

        main_layout = QVBoxLayout()

        self.model = QSqlTableModel(self)
        self.model.setTable('films')

        self.view_films = QTableView()
        self.view_films.setModel(self.model)

        main_layout.addWidget(self.view_films)

        self.setLayout(main_layout)

    def refresh(self):
        self.model.select()

class MainWindow(QWidget):
    def __init__(self):
        super().__init__()

        self.db = QSqlDatabase.addDatabase('qsqlite')
        self.db.setDatabaseName('Database_05.sqlite')
        self.db.open()

        self.initUI()

    def initUI(self):
        main_layout = QVBoxLayout()

        self.button_films = QPushButton('список фильмов')
        self.button_films.clicked.connect(self._show_films)

        self.button_serials = QPushButton('список сериалов')

        main_layout.addWidget(self.button_films)
        main_layout.addWidget(self.button_serials)

        self.setLayout(main_layout)

    def _show_films(self):
        films = Films(self)
        films.refresh()
        films.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = MainWindow()
    ex.show()
    sys.exit(app.exec_())

A: Приведенный пример написан правильно. Я только подставил свою БД, название которой book.db, а название таблицы - card. Я отметил для вас строки, в которые внес изменения.
import sys
from PyQt5.QtWidgets import QWidget, QTableView, QDialog, QPushButton, QApplication, QVBoxLayout
from PyQt5.QtSql import QSqlDatabase, QSqlTableModel

class Films(QDialog):
    def __init__(self, parent):
        super().__init__(parent)

        self.setWindowTitle('Films')
        self.setWindowTitle('Гитара')

        main_layout = QVBoxLayout()

        self.model = QSqlTableModel(self)
        self.model.setTable('card')                          # ('films')   !!!

        self.view_films = QTableView()
        self.view_films.setModel(self.model)

        main_layout.addWidget(self.view_films)

        self.setLayout(main_layout)

    def refresh(self):
        self.model.select()

class MainWindow(QWidget):
    def __init__(self):
        super().__init__()

        self.setWindowTitle('Гитара')                       # +
        self.setGeometry(250, 55, 1200, 800)                # +

        self.db = QSqlDatabase.addDatabase('QSQLITE')       # 'qsqlite'
        self.db.setDatabaseName('book.db')                  #('Database_05.sqlite')  !!!
        self.db.open()

        self.initUI()

    def initUI(self):
        main_layout = QVBoxLayout()

        self.button_films = QPushButton('список фильмов')
        self.button_films.setFixedSize(200, 100)                              # +
        self.button_films.clicked.connect(self._show_films)

        self.button_serials = QPushButton('список сериалов')
        self.button_serials.setFixedSize(200, 100)                            # +

        main_layout.addWidget(self.button_films)
        main_layout.addWidget(self.button_serials)

        self.setLayout(main_layout)

    def _show_films(self):
        films = Films(self)
        films.refresh()
        films.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = MainWindow()
    ex.show()
    sys.exit(app.exec_())


text:
Q: getHeight() and getWidth() both return 0 I am trying to create a grid in a JPanel with lines, and to do this, I draw evenly spaced horizontal and vertical lines until I reach the end of the JPanel.  I use a class called Drawing which extends JPanel and is the object I add to the window.  Below is my code.
public final class Drawing extends JPanel {

    public Drawing() {
        super();
        setBackground(new Color(255, 255, 255));
        setBorder(BorderFactory.createLineBorder(new Color(0, 0, 0)));

        GroupLayout workspacePanelLayout = new GroupLayout(this);
        setLayout(workspacePanelLayout);
        workspacePanelLayout.setHorizontalGroup(workspacePanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING).addGap(0, 343, Short.MAX_VALUE));
        workspacePanelLayout.setVerticalGroup(workspacePanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING).addGap(0, 400, Short.MAX_VALUE));

        initWorkSpace();
    }

    private static class Line {

        final int x1;
        final int y1;
        final int x2;
        final int y2;
        final Color color;

        public Line(int x1, int y1, int x2, int y2, Color color) {
            this.x1 = x1;
            this.y1 = y1;
            this.x2 = x2;
            this.y2 = y2;
            this.color = color;
        }
    }

    private final LinkedList<Line> lines = new LinkedList<>();

    public void addLine(int x1, int x2, int x3, int x4) {
        addLine(x1, x2, x3, x4, Color.black);
    }

    public void addLine(int x1, int x2, int x3, int x4, Color color) {
        lines.add(new Line(x1, x2, x3, x4, color));
        repaint();
    }

    public void clearLines() {
        lines.clear();
        repaint();
    }

    @Override
    private void paintComponent(Graphics g) {
        super.paintComponent(g);
        for (Line line : lines) {
            g.setColor(line.color);
            g.drawLine(line.x1, line.y1, line.x2, line.y2);
        }
    }

    public void initWorkSpace() {
        int x = 0;
        int y = 0;
        while (x < this.getWidth()) {
            addLine(x, 0, x, this.getHeight(), new Color(153, 153, 153));
            x += getSpacing();
        }
        while (y < this.getHeight()) {
            addLine(0, y, this.getWidth(), y, new Color(153, 153, 153));
            y += getSpacing();
        }
    }
}

The problem is that 'this.getHeight()' and 'this.getWidth()' both return 0 so the grid doesn't get drawn.  drawing the lines works fine, its just that the panel apparently has no dimension.  How do I solve this.

A: Not the main problem but you need to override the getPreferredSize() method of your class to return the size.
Each component is responsible for determining its own preferred size.
Then the layout manager can use this information when the panel is added to a parent panel.
Of course this assumes the parent panel is using a layout manager which you should be doing.
For more information and working examples read the section from the Swing tutorial on Custom Painting
The real problem is when you invoke the following method:
    initWorkSpace();

All components have a zero size when the component is created. So when the above method is invoked from the constructor the size will always be zero.
If your painting code is dynamic which means it changes as the frame is resized, then you need to invoke that logic inside the paintComponent() method.
Or if your logic is too complex to execute every time the component is repainted, you can add a ComponentListener to the panel and handle the componentResized method and invoke that method.
Also, I'm not sure why you are using a GroupLayout when you are doing custom painting.