问:
Is it possible to open screen on core module from activity or class in android module in Libgdx?
I am developing a game that uses google maps. I have made my game to check the availability of internet connection.
So, when there is no internet connection , there is offline mode for the game which works very fine but when there is internet connection,
game displays specific place with the help of google maps. I have kept markers on the place that needs to be shown on maps. And i want to
open game screen when i click on markers on the maps. Code for google map is in Android module and screen is in core module.
Can anyone help me out how can i open screen when i click on markers using the method provided by google maps which is as follow:

```<code>public boolean onMarkerClick(Marker marker) {
    mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
        @Override
        public boolean onMarkerClick(Marker marker) {};
        return false;
    }
}
</code>```

I have researched about it but i am not able to find the suitable refrence for it. So is it possible to do this or it is not?

答:
Yes it is possible to change Screen from android module.

core module is injected in all platform specific module so you can access all Class/Interface in any module.

Only you need reference of Game class object and an object of new Screen so keep reference of Game's child object in AndroidLauncher class.

```<code>MyGdxGame gdxGame;

@Override
protected void onCreate (Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
     gdxGame = new MyGdxGame();
     View gameView = initializeForView(gdxGame, config);

     setContentView(gameView);
}
</code>```

Now you've reference of MyGdxGame, You can change screen inside AndroidLauncher class by calling setScreen(Screen screen) method of Game class.

```<code> gdxGame.setScreen(new MenuScreen());
</code>```

MyGdxGame and MenuScreen are in core module

MyGdxGame class

```<code>public class MyGdxGame extends Game {

    @Override
    public void create() {
        setScreen(new MainScreen());
    }
}
</code>```

MenuScreen class

```<code>public class MenuScreen extends ScreenAdapter {

}
</code>```

EDIT

```<code>@Override
public boolean onMarkerClick(Marker marker) {
       Gdx.app.postRunnable(new Runnable() {
            @Override
            public void run() {
                 gdxGame.setScreen(new MenuScreen());
            }
        });
     return false;
}
</code>```

EDIT 2

Your question Is it possible to change screen from android module,
I am not focusing on another part of your game so make it simple as possible so I tested with only four classes.

GdxTest

```<code>public class GdxTest extends Game{

   @Override
   public void create() {
       setScreen(new FirstScreen());
   }
}
</code>```

FirstScreen

```<code>public class FirstScreen extends ScreenAdapter {

  @Override
  public void render(float delta) {

      Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
      Gdx.gl.glClearColor(0,0,1,1);
  }
}
</code>```

SecondScreen

```<code>public class SecondScreen extends ScreenAdapter {

   SpriteBatch batch;

  @Override
  public void show() {
      batch=new SpriteBatch();
  }

  @Override
  public void render(float delta) {

    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    Gdx.gl.glClearColor(1,0,0,1);
  }
}
</code>```

AndroidLauncher inside android module

```<code>public class AndroidLauncher extends AndroidApplication {

   GdxTest gdxTest;
   boolean swap;

  @Override
  protected void onCreate (Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);

       gdxTest =new GdxTest();
       initialize(gdxTest);
  }

  @Override
  public void onBackPressed() {
      Gdx.app.postRunnable(new Runnable() {
          @Override
          public void run() {
              swap=!swap;
              gdxTest.setScreen(swap?new SecondScreen():new FirstScreen());
        }
    });
  }
}
</code>```

Each time when I press back on android device, screen changes from one to another (this changes from android module), It sure that, this is possible to change screen from android module.

Body:
I am developing a game that uses google maps. I have made my game to check the availability of internet connection.
So, when there is no internet connection , there is offline mode for the game which works very fine but when there is internet connection,
game displays specific place with the help of google maps. I have kept markers on the place that needs to be shown on maps. And i want to
open game screen when i click on markers on the maps. Code for google map is in Android module and screen is in core module.
Can anyone help me out how can i open screen when i click on markers using the method provided by google maps which is as follow:

public boolean onMarkerClick(Marker marker) {
    mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
        @Override
        public boolean onMarkerClick(Marker marker) {};
        return false;
    }
}

I have researched about it but i am not able to find the suitable refrence for it. So is it possible to do this or it is not?

Body:
Yes it is possible to change Screen from android module.

core module is injected in all platform specific module so you can access all Class/Interface in any module.

Only you need reference of Game class object and an object of new Screen so keep reference of Game's child object in AndroidLauncher class.

MyGdxGame gdxGame;

@Override
protected void onCreate (Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
     gdxGame = new MyGdxGame();
     View gameView = initializeForView(gdxGame, config);

     setContentView(gameView);
}

Now you've reference of MyGdxGame, You can change screen inside AndroidLauncher class by calling setScreen(Screen screen) method of Game class.

 gdxGame.setScreen(new MenuScreen());

MyGdxGame and MenuScreen are in core module

MyGdxGame class

public class MyGdxGame extends Game {

    @Override
    public void create() {
        setScreen(new MainScreen());
    }
}

MenuScreen class

public class MenuScreen extends ScreenAdapter {

}

EDIT

@Override
public boolean onMarkerClick(Marker marker) {
       Gdx.app.postRunnable(new Runnable() {
            @Override
            public void run() {
                 gdxGame.setScreen(new MenuScreen());
            }
        });
     return false;
}

EDIT 2

Your question Is it possible to change screen from android module,
I am not focusing on another part of your game so make it simple as possible so I tested with only four classes.

GdxTest

public class GdxTest extends Game{

   @Override
   public void create() {
       setScreen(new FirstScreen());
   }
}

FirstScreen

public class FirstScreen extends ScreenAdapter {

  @Override
  public void render(float delta) {

      Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
      Gdx.gl.glClearColor(0,0,1,1);
  }
}

SecondScreen

public class SecondScreen extends ScreenAdapter {

   SpriteBatch batch;

  @Override
  public void show() {
      batch=new SpriteBatch();
  }

  @Override
  public void render(float delta) {

    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    Gdx.gl.glClearColor(1,0,0,1);
  }
}

AndroidLauncher inside android module

public class AndroidLauncher extends AndroidApplication {

   GdxTest gdxTest;
   boolean swap;

  @Override
  protected void onCreate (Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);

       gdxTest =new GdxTest();
       initialize(gdxTest);
  }

  @Override
  public void onBackPressed() {
      Gdx.app.postRunnable(new Runnable() {
          @Override
          public void run() {
              swap=!swap;
              gdxTest.setScreen(swap?new SecondScreen():new FirstScreen());
        }
    });
  }
}

Each time when I press back on android device, screen changes from one to another (this changes from android module), It sure that, this is possible to change screen from android module.


来源: stackexchange

问:
How to hook a callback on Angular UI Popover's trigger
I have used Angular UI Popover like below

```<code><div popover-is-open="prfList.isProfileClosed===false" popover-trigger="'outsideClick'" popover-append-to-body="true" popover-placement="right-top" popover-class="popover1 dmspopover"
    uib-popover-template="prfList.popupUrl">

</div>
</code>```

What I need is a way to hook a callback when the popover's trigger gets called . The popopover is getting closed successfully clicking outside..its just that I want to catch that event to execute my code.

答:
You have attribute popover-is-open="prfList.isProfileClosed===false"

You need to watch prfList.isProfileClosed for changes and call needed function

ContentLicense: CC BY-SA 3.0

Body:
I have used Angular UI Popover like below

What I need is a way to hook a callback when the popover's trigger gets called . The popopover is getting closed successfully clicking outside..its just that I want to catch that event to execute my code.


问:
Allow Indian and US phone numbers in Laravel 5.4
I want to allow only some specific types of phone number format.
Ex:

xxx-xxx-xxxx

+91-xxxxxxxxxx.

I don't know what will be the regular expression for this.
I refered some sites and got this

```<code>/^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$/
</code>```

which works for 1st one but not worked for +91 format.

Basically, I want to allow India and US numbers only.

2nd Question:

I want a regular expression which will allow +, -, (, ), and the numbers i.e. 0-9 .

答:
Here is a suggestion that accept your inputs, with separators , . and -:

```<code>\+91[\s-]\d{10}|\(?\d{3}\)?[\s-]\d{3}[\s-]\d{4}
</code>```

Try it on regex101

The following inputs are valid:

```<code>123-456-7890
123 456 7890
(123) 123-6547
(999)-999-9999
+91-1234567890
+91 1234567890
</code>```

If you only want to accept - as a separator, change all [\s-] by - in the regex.

Body:
I want to allow only some specific types of phone number format.
Ex:

xxx-xxx-xxxx

+91-xxxxxxxxxx.

I don't know what will be the regular expression for this.
I refered some sites and got this

/^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$/

which works for 1st one but not worked for +91 format.

Basically, I want to allow India and US numbers only.

2nd Question:

I want a regular expression which will allow +, -, (, ), and the numbers i.e. 0-9 .

Body:
Here is a suggestion that accept your inputs, with separators , . and -:

\+91[\s-]\d{10}|\(?\d{3}\)?[\s-]\d{3}[\s-]\d{4}

Try it on regex101

The following inputs are valid:

123-456-7890
123 456 7890
(123) 123-6547
(999)-999-9999
+91-1234567890
+91 1234567890

If you only want to accept - as a separator, change all [\s-] by - in the regex.


问:
Webscraping using VBA excel
Which code should I use to extract price from this HTML code? I would like to get element either by

Id

tagname

classname

Website url: https://www.tatacliq.com/vivo-v5-32gb-gold-4-gb-ram-dual-sim-4g/p-mp000000000734559

Let's say I want to fetch data for "price" in below HTML (i.e. get this "14999"):

```<code>    <h3 class="company author">
    </h3>
    <div itemprop="offers" itemscope="" itemtype="http://schema.org/Offer"
    class="price">
    <p class="old" id="mrpPriceId" style="display:none">
    </p>
    <p class="sale" id="mopPriceId" style="display:none">
    </p>
    <p class="sale" id="spPriceId" style="display:none">
    <!-- For TPR-4358 Start -->
    <span itemprop="price">14999.00</span>
    <span itemprop="priceCurrency">INR</span>
    <meta itemprop="itemCondition" content="http://schema.org/NewCondition"
    />
    <meta itemprop="availability"
    content="http://schema.org/InStock"/>Available online</meta>
    <!-- For TPR-4358 End -->
    </p>
    <p class="savings pdp-savings" id="savingsOnProductId"
    style="display:none">
      <span></span>
    </p>
    <br>
</code>```

Here is my code:

```<code>    Function Scraptatacliq(tatacliq_url As String, the_display_price As String, the_display_seller As String)

    ''MsgBox "Inside the function"

    'Dim objIE As New InternetExplorerMedium
    Scraptatacliq = ""
    If tatacliq_url = "" Then Exit Function

     the_display_price = ""
     the_display_seller = ""

    'MsgBox tatacliq_url
     the_start:

    Dim objIE As Object
    Set objIE = CreateObject("InternetExplorer.Application")
   'Set objIE = New InternetExplorerMedium
    objIE.Top = 0
    objIE.Left = 0
    objIE.Height = 800
   'objIE.Visible = True
    objIE.Navigate (tatacliq_url)

  'MsgBox tatacliq_url

  Do
  DoEvents
  If Err.Number <> 0 Then
  objIE.Quit
  Set objIE = Nothing
  GoTo the_start:
  End If
  Loop Until objIE.ReadyState = 4

 'Loop
  Count = 500000
  Do
  If Count <> 0 Then
  Count = Count - 1
  End If
  Loop Until Count = 0

 'EXTRACT DISPLAY PRICE
 'On Error Resume Next
 'MsgBox "I am about to extract display price"
  Set the_input_element =       objIE.Document.getElementById("spPriceId").getElementsbyTagName("price")
  product_display_price = the_input_element.innertext
 'MsgBox product_display_price
 'If product_display_price = "" Then
   '    Set the_input_element =
   objIE.Document.getElementById("product_list_price")
 '      product_display_price = the_input_element.innertext
  'End If
</code>```

[ Placeholder to explain what is currently going wrong with my code ]

答:
There is something happening with javascript that I cannot understand, and might change the way you can scrap your thing.

Here, it is possible to scrape the price with outertext once you have objIE.Document.getElementById("spPriceId"):

```<code>Function Scraptatacliq(tatacliq_url As String)
  Scraptatacliq = ""
  If tatacliq_url = "" Then Exit Function
  the_display_price = ""
  the_display_seller = ""

the_start:
    Dim objIE As Object
    Set objIE = CreateObject("InternetExplorer.Application")
    objIE.Top = 0
    objIE.Left = 0
    objIE.Height = 800
    objIE.Navigate (tatacliq_url)

  Do
    DoEvents
    If Err.Number <> 0 Then
      objIE.Quit
      Set objIE = Nothing
      GoTo the_start:
    End If
  Loop Until objIE.ReadyState = 4

  objIE.Visible = True
  Set the_input_element = objIE.Document.getElementById("spPriceId")
  product_display_price = the_input_element.outertext
  MsgBox product_display_price

End Function
</code>```

Another solution might be cleaner if you can see what happens if you deactivate javascript

Title: Webscraping using VBA excel

Body:
Which code should I use to extract price from this HTML code? I would like to get element either by

Id

tagname

classname

Website url: https://www.tatacliq.com/vivo-v5-32gb-gold-4-gb-ram-dual-sim-4g/p-mp000000000734559

Let's say I want to fetch data for "price" in below HTML (i.e. get this "14999"):

    14999.00
    INR
    <meta itemprop="itemCondition" content="http://schema.org/NewCondition"
    />
    <meta itemprop="availability"
    content="http://schema.org/InStock"/>Available online</meta>

Here is my code:

    Function Scraptatacliq(tatacliq_url As String, the_display_price As String, the_display_seller As String)

    ''MsgBox "Inside the function"

    'Dim objIE As New InternetExplorerMedium
    Scraptatacliq = ""
    If tatacliq_url = "" Then Exit Function

     the_display_price = ""
     the_display_seller = ""

    'MsgBox tatacliq_url
     the_start:

    Dim objIE As Object
    Set objIE = CreateObject("InternetExplorer.Application")
   'Set objIE = New InternetExplorerMedium
    objIE.Top = 0
    objIE.Left = 0
    objIE.Height = 800
   'objIE.Visible = True
    objIE.Navigate (tatacliq_url)

  'MsgBox tatacliq_url

  Do
  DoEvents
  If Err.Number <> 0 Then
  objIE.Quit
  Set objIE = Nothing
  GoTo the_start:
  End If
  Loop Until objIE.ReadyState = 4

 'Loop
  Count = 500000
  Do
  If Count <> 0 Then
  Count = Count - 1
  End If
  Loop Until Count = 0

 'EXTRACT DISPLAY PRICE
 'On Error Resume Next
 'MsgBox "I am about to extract display price"
  Set the_input_element =       objIE.Document.getElementById("spPriceId").getElementsbyTagName("price")
  product_display_price = the_input_element.innertext
 'MsgBox product_display_price
 'If product_display_price = "" Then
   '    Set the_input_element =
   objIE.Document.getElementById("product_list_price")
 '      product_display_price = the_input_element.innertext
  'End If

[ Placeholder to explain what is currently going wrong with my code ]

Body:
There is something happening with javascript that I cannot understand, and might change the way you can scrap your thing.

Here, it is possible to scrape the price with outertext once you have objIE.Document.getElementById("spPriceId"):

Function Scraptatacliq(tatacliq_url As String)
  Scraptatacliq = ""
  If tatacliq_url = "" Then Exit Function
  the_display_price = ""
  the_display_seller = ""

the_start:
    Dim objIE As Object
    Set objIE = CreateObject("InternetExplorer.Application")
    objIE.Top = 0
    objIE.Left = 0
    objIE.Height = 800
    objIE.Navigate (tatacliq_url)

  Do
    DoEvents
    If Err.Number <> 0 Then
      objIE.Quit
      Set objIE = Nothing
      GoTo the_start:
    End If
  Loop Until objIE.ReadyState = 4

  objIE.Visible = True
  Set the_input_element = objIE.Document.getElementById("spPriceId")
  product_display_price = the_input_element.outertext
  MsgBox product_display_price

End Function

Another solution might be cleaner if you can see what happens if you deactivate javascript


问:
how to run particular http request to multiple times in jmeter?
I've multiple http samples in Test Plan but i want to run only one request for multiple times based on csv data set config and remaining http requests will run once particular sample is complete all the iteration based on csv data set config.

In above image i've 5 http samples and i've csv data set for first request,once first request is run for entire csv data set test data then another samples should run,please provide solution how to perform this type of operation in jmeter.

答:
Configure your CSV Data Set Config like:

Reference name: foo

Recycle on EOF: false

Stop thread on EOF: false

Put the CSV Data Set Config under the While Controller and put ${__javaScript("${foo}" != "<EOF>",)} into "Condition" input

Add If Controller under the While Controller and put "${foo}" != "<EOF>" into the "Condition" input

Put your first request as a child of the If Controller

Replace foo with your actual JMeter Variable reference name everywhere in the script.

This way JMeter will loop until there are entries in the CSV file and will proceed with the remaining requests when the end of CSV file will be reached.

See Reading all Values from the CSV and Continue chapter of the Using the While Controller in JMeter article for more detailed information on configuring JMeter for your scenario.


问:
Trying to run Django tests, get error loading either pysqlite2 or sqlite3?
I am trying to run tests on a project that is not mine when i python manage.py test, I get

```<code>raise ImproperlyConfigured("Error loading either pysqlite2 or sqlite3 modules (tried in that order): %s" % exc)
django.core.exceptions.ImproperlyConfigured: Error loading either pysqlite2 or sqlite3 modules (tried in that order): No module named '_sqlite3'
</code>```

I have installed the sqlite3 and pysqlite2 and all the dev-lib packages, it tells me the requirements are already satisfied. I installed them outside of the virtual env, I believe this is my problem, but I am afraid to use sudo apt-get remove because last time I used this command I deleted almost my entire Ubuntu. Any suggestions?

答:
Since I am using Ubuntu I had installed python from the terminal, not from source. The installation I did must not have included sqlite3.

Steps I took to solve issue:

Download the source file of the Python version that you need, from source. Extract the folder somewhere, cd into the folder,

```<code>./configure
make
make install
</code>```

fixed my issue.

Body:
I am trying to run tests on a project that is not mine when i python manage.py test, I get

raise ImproperlyConfigured("Error loading either pysqlite2 or sqlite3 modules (tried in that order): %s" % exc)
django.core.exceptions.ImproperlyConfigured: Error loading either pysqlite2 or sqlite3 modules (tried in that order): No module named '_sqlite3'

I have installed the sqlite3 and pysqlite2 and all the dev-lib packages, it tells me the requirements are already satisfied. I installed them outside of the virtual env, I believe this is my problem, but I am afraid to use sudo apt-get remove because last time I used this command I deleted almost my entire Ubuntu. Any suggestions?

Body:
Since I am using Ubuntu I had installed python from the terminal, not from source. The installation I did must not have included sqlite3.

Steps I took to solve issue:

Download the source file of the Python version that you need, from source. Extract the folder somewhere, cd into the folder,

./configure
make
make install

fixed my issue.


问:
What's the best way to get data from PHP to an iOS-app?
What is the best way to get data from the internet, compressed and composed by PHP, to an iOS app?
Currently, the app reads a string formatted like this:

```<code>category1#object2#object3#object4~category2#object2#object3[…]
</code>```

And that is split up by the #'s and ~'s.

Is there a better way to do this, both in the way the data is retrieved (the site it gets it from is open for everyone), and the way the data is formatted?

答:
Instead of yet another JSON answer, I'm going to give some links on "Picking the best JSON library":

Comparison of JSON Parser for Objective-C (JSON Framework, YAJL, TouchJSON, etc)

Best JSON library to use when developing an iPhone application?

And now for the shameless plug for my own JSON parsing solution, JSONKit:

What's the most efficient way of converting a 10 MB JSON response into an NSDictionary?

Cocoa JSON parsing libraries, part 2

Body:
What is the best way to get data from the internet, compressed and composed by PHP, to an iOS app?
Currently, the app reads a string formatted like this:

category1#object2#object3#object4~category2#object2#object3[…]

And that is split up by the #'s and ~'s.

Is there a better way to do this, both in the way the data is retrieved (the site it gets it from is open for everyone), and the way the data is formatted?

ContentLicense: CC BY-SA 2.5


问:
Problems navigating to Angular UI router state
I have a route definition as follows:

```<code>        $stateProvider
          .state('vehicles', {
            url: '/vehicles',
            templateUrl: 'foo/bar1.html'
        }).state('vehicles.id', {
            url: '/{id}',
            templateUrl: 'foo/bar3.html'
        }).state('vehicles.create', {
            url: '/create',
            templateUrl: 'foo/bar2.html',
            controller: 'VehicleCreateController'
        });
</code>```

I have a button that does

```<code>$state.go("vehicles.create");
</code>```

The problem is, that while the URL changes correctly, the page remains the same. Only after the second click, the correct template appears.

答:
After a hint from my colleague I realized, that it was the state definitions that caused the problem. Reordering the states from "more specific" (URL-wise - i.e. /create) to less specific (/{id}) did the trick. So the thing that was wrong was having the more generic URL /vehicles/{id} before the very similar, but less generic /vehicles/create.

So here's the improved version:

```<code>        $stateProvider
          .state('vehicles', {
            url: '/vehicles',
            templateUrl: 'foo/bar1.html'
        }).state('vehicles.create', {
            url: '/create',
            templateUrl: 'foo/bar2.html',
            controller: 'VehicleCreateController'
        }).state('vehicles.id', {
            url: '/{id}',
            templateUrl: 'foo/bar3.html'
        });
</code>```

Body:
I have a route definition as follows:

        $stateProvider
          .state('vehicles', {
            url: '/vehicles',
            templateUrl: 'foo/bar1.html'
        }).state('vehicles.id', {
            url: '/{id}',
            templateUrl: 'foo/bar3.html'
        }).state('vehicles.create', {
            url: '/create',
            templateUrl: 'foo/bar2.html',
            controller: 'VehicleCreateController'
        });

I have a button that does

$state.go("vehicles.create");

The problem is, that while the URL changes correctly, the page remains the same. Only after the second click, the correct template appears.

Body:
After a hint from my colleague I realized, that it was the state definitions that caused the problem. Reordering the states from "more specific" (URL-wise - i.e. /create) to less specific (/{id}) did the trick. So the thing that was wrong was having the more generic URL /vehicles/{id} before the very similar, but less generic /vehicles/create.

So here's the improved version:

        $stateProvider
          .state('vehicles', {
            url: '/vehicles',
            templateUrl: 'foo/bar1.html'
        }).state('vehicles.create', {
            url: '/create',
            templateUrl: 'foo/bar2.html',
            controller: 'VehicleCreateController'
        }).state('vehicles.id', {
            url: '/{id}',
            templateUrl: 'foo/bar3.html'
        });


问:
netbeans php - cannot get breakpoints to work
I have read and tried what I've found yet I cannot get it to work, it just keeps on hanging at "Waiting for connection (netbeans-xdebug)" when starting debugging.

I do have xdebug installed (I am using wamp) and I've actually managed to get breakpoints working with sublime text 2 (yea that's right!) so the problem is not with php/xdebug on my pc per se but some setting I am missing.

my php.ini for xdebug:

```<code>; XDEBUG Extension
[xdebug]
;zend_extension ="c:/wamp64/bin/php/php5.6.25/zend_ext/php_xdebug-2.4.1-5.6-vc11-x86_64.dll"
zend_extension ="c:\wamp64\bin\php\php5.6.25\ext\php_xdebug-2.5.4-5.6-vc11-x86_64.dll"
xdebug.remote_enable = 1
xdebug.profiler_enable = 0
xdebug.profiler_enable_trigger = off
xdebug.profiler_output_name = cachegrind.out.%t.%p
xdebug.profiler_output_dir ="c:/wamp64/tmp"
xdebug.show_local_vars=0

xdebug.remote_hander =dbgp
xdebug.remote_mode = req
xdebug.remote_host =127.0.0.1
xdebug.remote_port = 9000
xdebug.idekey=netbeans-xdebug
xdebug.remote_connect_back=1
xdebug.remote_autostart=1
</code>```

Netbeans debugging options are set as defaults except I unchecked "stop at first line" coz I read somewhere to do so.

If you need more info on something let me know.

答:
I've found the issue for myself (since everything else seems to be in order on my side), netbeans will not debug non root urls for some reason, and of course I dont want to open the root every time so I've made a virtual host for that specific project with a regular url (www.someurl.com) and it seems to be working fine now.

Also I am not sure every single line is needed from my php.ini xdebug settings but I've kept it so, since I am not bothered to check for redundant lines, so if you are not sure about your xdebug settings just copy the whole thing from my Q.

Body:
I have read and tried what I've found yet I cannot get it to work, it just keeps on hanging at "Waiting for connection (netbeans-xdebug)" when starting debugging.

I do have xdebug installed (I am using wamp) and I've actually managed to get breakpoints working with sublime text 2 (yea that's right!) so the problem is not with php/xdebug on my pc per se but some setting I am missing.

my php.ini for xdebug:

; XDEBUG Extension
[xdebug]
;zend_extension ="c:/wamp64/bin/php/php5.6.25/zend_ext/php_xdebug-2.4.1-5.6-vc11-x86_64.dll"
zend_extension ="c:\wamp64\bin\php\php5.6.25\ext\php_xdebug-2.5.4-5.6-vc11-x86_64.dll"
xdebug.remote_enable = 1
xdebug.profiler_enable = 0
xdebug.profiler_enable_trigger = off
xdebug.profiler_output_name = cachegrind.out.%t.%p
xdebug.profiler_output_dir ="c:/wamp64/tmp"
xdebug.show_local_vars=0

xdebug.remote_hander =dbgp
xdebug.remote_mode = req
xdebug.remote_host =127.0.0.1
xdebug.remote_port = 9000
xdebug.idekey=netbeans-xdebug
xdebug.remote_connect_back=1
xdebug.remote_autostart=1

Netbeans debugging options are set as defaults except I unchecked "stop at first line" coz I read somewhere to do so.

If you need more info on something let me know.


问:
Foreach loop in CodeIgniter
I'm using the CI framework and I'm trying to make a foreach loop so that all products of my site are displayed.

This is my controller file:

```<code>class AlleCadeausController extends CI_Controller {

public function index()
{
    $this->load->model('allecadeaus_model');
    $data['cadeaus'] = $this->allecadeaus_model->get_cadeaus();
    $this->load->view('allecadeaus');
}
</code>```

This is my model file:

```<code><?php
class Allecadeaus_model extends CI_Model {
   public function __construct()
   {
       parent::__construct();
   }
    public function get_cadeaus()
    {
        $query = $this->db->query('SELECT * FROM products');
        $result = $query->result_array();
        return $result;
    }
}
</code>```

this is my view:

```<code><?php
foreach ($cadeaus as $cadeau)
{
    echo $cadeau->product_naam;
}
?>
</code>```

The error is:

A PHP Error was encountered

Severity: Notice

Message: Undefined variable: cadeaus

Filename: views/allecadeaus.php

Line Number: 3

Backtrace:

File: /home/ubuntu/workspace/application/views/allecadeaus.php Line: 3
  Function: _error_handler

File:
  /home/ubuntu/workspace/application/controllers/AlleCadeausController.php
  Line: 11 Function: view

File: /home/ubuntu/workspace/index.php Line: 315 Function:
  require_once

My table name is products

答:
```<code>public function index()
{
    $this->load->model('allecadeaus_model');
    $data['cadeaus'] = $this->allecadeaus_model->get_cadeaus();
    $this->load->view('allecadeaus',$data);

}
</code>```

try this in you controller

Title: Foreach loop in CodeIgniter

Body:
I'm using the CI framework and I'm trying to make a foreach loop so that all products of my site are displayed.

This is my controller file:

class AlleCadeausController extends CI_Controller {

public function index()
{
    $this->load->model('allecadeaus_model');
    $data['cadeaus'] = $this->allecadeaus_model->get_cadeaus();
    $this->load->view('allecadeaus');
}

This is my model file:

<?php
class Allecadeaus_model extends CI_Model {
   public function __construct()
   {
       parent::__construct();
   }
    public function get_cadeaus()
    {
        $query = $this->db->query('SELECT * FROM products');
        $result = $query->result_array();
        return $result;
    }
}

this is my view:

<?php
foreach ($cadeaus as $cadeau)
{
    echo $cadeau->product_naam;
}
?>

The error is:

A PHP Error was encountered

Severity: Notice

Message: Undefined variable: cadeaus

Filename: views/allecadeaus.php

Line Number: 3

Backtrace:

File: /home/ubuntu/workspace/application/views/allecadeaus.php Line: 3
  Function: _error_handler

File:
  /home/ubuntu/workspace/application/controllers/AlleCadeausController.php
  Line: 11 Function: view

File: /home/ubuntu/workspace/index.php Line: 315 Function:
  require_once

My table name is products

Body:
public function index()
{
    $this->load->model('allecadeaus_model');
    $data['cadeaus'] = $this->allecadeaus_model->get_cadeaus();
    $this->load->view('allecadeaus',$data);

}

try this in you controller


问:
google map android error
I saw many question is similar to me

Google Maps Android API: In the Google Developer Console (https://console.developers.google.com)
                                                                                Ensure that the "Google Maps Android API v2" is enabled.                                                                            Ensure that the following Android Key exists:
                                                                                API Key: ###############################
                                                                                Android Application (;): #######################################################;

but not working

答:
this problem is due to disable api. You need to enable Google Map API from Google API Manager and then follow these steps to enable api.

Steps

Open your project dashboard and it will look like below image

Click on ENABLE API button and you will get below screen with library of APIs that you can enable or disable

Now select Google Maps Android API and you will get below screen

If you get button DISABLE API means your APIs are enable or if you found ENABLE button that means your api is not enable yet

Hope this will help you.

Title: google map android error


问:
How to use Google Apps Script code in my pages
I'm building a web app using HTML, CSS and JavaScript and using Google Spreadsheet as a database. I'm planning to use PhoneGap to turn my web app into a real app.

I was able to read from my Google Sheet, using the Google Visualization API, now I'm working about the writing options: I used a function set with Google Apps Script, inside the Google Spreadsheet and it works correctly.

A great user of this site gave me the advice to use this command to go back to my pages:return HtmlService.createHtmlOutputFromFile('redirect').setSandboxMode(HtmlService.SandboxMode.IFRAME);

and told me to create the redirect page, in which a simple JS function uses window.location.href to go back to my pages. In this way, the address is the same of the script, but I need it to be mine, because I cannot run my app in an iframe.

Long story short, I want that the address in my browser to be mine and not use GAS sandbox to navigate my site.

I wasn't able to find a solution so I'm here again for the millionth time... is there a way to use Google Apps Script functions in my own pages, maybe calling some APIs in it? In this way I'm sure I could use some line of standard code to go back where I need.

This is the function code:

```<code>    function doPost(e){
    var sheet = SpreadsheetApp.openById("myID").getSheetByName('SheetName');
    var column = 1;
    var colArray = sheet.getRange(2, column, sheet.getLastRow()).getValues();
    var maxi = Math.max.apply(Math, colArray);

    var id = maxi+1;
    var name = e.parameter['name'];
    var surname = e.parameter['surname'];
    var serial = e.parameter['serial'];
    var eMail = e.parameter['mail'];
    var text = e.parameter['text'];
    var area = e.parameter['area'];
    var date = new Date();
    var ans = ""
    var flag = "Work In Progress";

    var vals = [id, date, name, surname, serial, eMail, area, text, ans, flag];

    var sheetObj = sheet.appendRow(vals);
    return HtmlService.createHtmlOutputFromFile('redirect').setSandboxMode(HtmlService.SandboxMode.IFRAME);
</code>```

and that's the page:

```<code>        <html>
          <head>
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
            <script>
            function test()
            {
               window.location.href = "myAdd";
            }
        </script>
          </head>
          <body onload="test()">
          </body>
        </html>
</code>```

Could someone help me?
Thanks a lot!

答: If your project can accomodate that (if, for example, you have a form and you want it to write on a spreadsheet) perhaps you could try to use the REST Execution API and pass the proper payload so that you can run your script RPC-style.</p>

Body:
I'm building a web app using HTML, CSS and JavaScript and using Google Spreadsheet as a database. I'm planning to use PhoneGap to turn my web app into a real app.

I was able to read from my Google Sheet, using the Google Visualization API, now I'm working about the writing options: I used a function set with Google Apps Script, inside the Google Spreadsheet and it works correctly.

A great user of this site gave me the advice to use this command to go back to my pages:return HtmlService.createHtmlOutputFromFile('redirect').setSandboxMode(HtmlService.SandboxMode.IFRAME);

and told me to create the redirect page, in which a simple JS function uses window.location.href to go back to my pages. In this way, the address is the same of the script, but I need it to be mine, because I cannot run my app in an iframe.

Long story short, I want that the address in my browser to be mine and not use GAS sandbox to navigate my site.

I wasn't able to find a solution so I'm here again for the millionth time... is there a way to use Google Apps Script functions in my own pages, maybe calling some APIs in it? In this way I'm sure I could use some line of standard code to go back where I need.

This is the function code:

    function doPost(e){
    var sheet = SpreadsheetApp.openById("myID").getSheetByName('SheetName');
    var column = 1;
    var colArray = sheet.getRange(2, column, sheet.getLastRow()).getValues();
    var maxi = Math.max.apply(Math, colArray);

    var id = maxi+1;
    var name = e.parameter['name'];
    var surname = e.parameter['surname'];
    var serial = e.parameter['serial'];
    var eMail = e.parameter['mail'];
    var text = e.parameter['text'];
    var area = e.parameter['area'];
    var date = new Date();
    var ans = ""
    var flag = "Work In Progress";

    var vals = [id, date, name, surname, serial, eMail, area, text, ans, flag];

    var sheetObj = sheet.appendRow(vals);
    return HtmlService.createHtmlOutputFromFile('redirect').setSandboxMode(HtmlService.SandboxMode.IFRAME);

and that's the page:

Could someone help me?
Thanks a lot!


问:
Laravel API expired session
In Laravel 5.4 I created some API on my routes/web.php. These API are called by .NET application.
The first called API is the login, after that, I put in session some datas.
Before to call other API, I check if the datas are in session, but after the first call (login), when I try to call the second one, the session seems to be flushed/expired.

Here my route code:

```<code>// API
Route::group(["prefix" => "api"], function() {
    // Login
    Route::post("login", "APIController@login");

    Route::group(["middleware" => "isNotAuthenticatedAPI"], function() {
        Route::group(["middleware" => "loginDBUser"], function() {
            // Importazioni
            Route::group(["prefix" => "importazioni"], function() {

                // Utenti
                Route::post("utenti", "APIController@importCustomers");
                // Attività (Abbonamenti)
                Route::post("attivita", "APIController@importSubscriptions");
                // Iscrizioni
                Route::post("iscrizioni", "APIController@importCustomersSubscriptions");
            });

            // Richieste
            Route::group(["prefix" => "richieste"], function() {
                // Ultima iscrizione
                Route::post("ultima_iscrizione/{subscription_external_id?}", "APIController@getLastCustomerSubscription");
            });
        });
    });
});
</code>```

Middleware isNotAuthenticatedAPI:

```<code>public function handle($request, Closure $next) {
        $res = [
            "result" => null,
            "errors" => [
            ]
        ];

        if (!$request->session()->get("user.api")) {
            $res["result"] = false;
            $res["errors"][] = [
                "code" => APIController::WARNING_SESSION_EXPIRED,
                "message" => trans("api.w_session_expired")
            ];
            return response()->json($res);
        }

        return $next($request);
    }
</code>```

My config/session.php:

```<code>'lifetime' => 120,

    'expire_on_close' => false,
</code>```

I tried to put the route's code into routes/api.php, but the result doesn't change.

答:
please set property in config/session.php
lifetime =value set to increase time out of session
or
other this option with set middle ware handler set " config('session.lifetime') * 60; // min to hours conversion to solved this issue</p>

Title: Laravel API expired session

Body:
In Laravel 5.4 I created some API on my routes/web.php. These API are called by .NET application.
The first called API is the login, after that, I put in session some datas.
Before to call other API, I check if the datas are in session, but after the first call (login), when I try to call the second one, the session seems to be flushed/expired.

Here my route code:

// API
Route::group(["prefix" => "api"], function() {
    // Login
    Route::post("login", "APIController@login");

    Route::group(["middleware" => "isNotAuthenticatedAPI"], function() {
        Route::group(["middleware" => "loginDBUser"], function() {
            // Importazioni
            Route::group(["prefix" => "importazioni"], function() {

                // Utenti
                Route::post("utenti", "APIController@importCustomers");
                // Attività (Abbonamenti)
                Route::post("attivita", "APIController@importSubscriptions");
                // Iscrizioni
                Route::post("iscrizioni", "APIController@importCustomersSubscriptions");
            });

            // Richieste
            Route::group(["prefix" => "richieste"], function() {
                // Ultima iscrizione
                Route::post("ultima_iscrizione/{subscription_external_id?}", "APIController@getLastCustomerSubscription");
            });
        });
    });
});

Middleware isNotAuthenticatedAPI:

public function handle($request, Closure $next) {
        $res = [
            "result" => null,
            "errors" => [
            ]
        ];

        if (!$request->session()->get("user.api")) {
            $res["result"] = false;
            $res["errors"][] = [
                "code" => APIController::WARNING_SESSION_EXPIRED,
                "message" => trans("api.w_session_expired")
            ];
            return response()->json($res);
        }

        return $next($request);
    }

My config/session.php:

'lifetime' => 120,

    'expire_on_close' => false,

I tried to put the route's code into routes/api.php, but the result doesn't change.


问:
span class locator is not visible/clickable - selenium
Following is the HTML for span: </p>

```<code><td class="header-logout-btn">
 <a href="logout.htm" class="btn switch-btn">
  <i class="fa fa-times"></i><span class="hidden-xs">Home</span>
 </a>
</td>
</code>```

<p>Tried with: </p>

```<code>driver.findElement(By.linkText("HOME"));
driver.findElement(By.xpath("//div[@class="header-logout-btn"]/span[@class="hidden-xs"]));
driver.findElement(By.xpath("//span"));
driver.findElement(By.className("hidden-xs"));
</code>```

答:
Try following solution :

Xpath=  //*[contains(text(),'Home')]

Hope it will help you.

Body:
Following is the HTML for span:

  Home

Tried with:

driver.findElement(By.linkText("HOME"));
driver.findElement(By.xpath("//div[@class="header-logout-btn"]/span[@class="hidden-xs"]));
driver.findElement(By.xpath("//span"));
driver.findElement(By.className("hidden-xs"));


问:
Randomize images on imageview with "if" function working strange
I'm trying to randomize images when a button is clicked and if the image is what I want it to be, randomize again, but if it's not, close the activity.

I cant randomize in my code, it closes always, but if I delete the call to the finish() function, it will randomize normally.

I just want that imageview to recognize the image without a sqlite DB

```<code>@Override
            public void onClick(View v) {
                int[] cards={R.drawable.bg,R.drawable.bg1};
                Random r = new Random();
                int n = r.nextInt(2);
                ImageView imgview1 = (ImageView) findViewById(R.id.imgv1);
                imgview1.setImageResource(cards[n]);

                if (imgview1.equals(R.drawable.bg){
                    imgview1.setImageResource(cards[n]);
                }
                else  {
                    finish();
                }
            }
</code>```

答:
here
1)if condition misses One bracket.
(imgview1.equals(R.drawable.bg))

2) Compare Image With int Because R.drawble.bg gives You Resource ID that not match..thats why its always goes to else

Solution:

```<code>ImageView imgview1 = (ImageView) findViewById(R.id.imgv1);
    imgview1.setImageResource(id);
    imgview1.setTag(id);

    if (imgview1.getTag() == R.drawable.bg) {
        imgview1.setImageResource(id);
    } else {
        finish();
    }
</code>```

Body:
I'm trying to randomize images when a button is clicked and if the image is what I want it to be, randomize again, but if it's not, close the activity.

I cant randomize in my code, it closes always, but if I delete the call to the finish() function, it will randomize normally.

I just want that imageview to recognize the image without a sqlite DB

@Override
            public void onClick(View v) {
                int[] cards={R.drawable.bg,R.drawable.bg1};
                Random r = new Random();
                int n = r.nextInt(2);
                ImageView imgview1 = (ImageView) findViewById(R.id.imgv1);
                imgview1.setImageResource(cards[n]);

                if (imgview1.equals(R.drawable.bg){
                    imgview1.setImageResource(cards[n]);
                }
                else  {
                    finish();
                }
            }

Body:
here
1)if condition misses One bracket.
(imgview1.equals(R.drawable.bg))

2) Compare Image With int Because R.drawble.bg gives You Resource ID that not match..thats why its always goes to else

Solution:

ImageView imgview1 = (ImageView) findViewById(R.id.imgv1);
    imgview1.setImageResource(id);
    imgview1.setTag(id);

    if (imgview1.getTag() == R.drawable.bg) {
        imgview1.setImageResource(id);
    } else {
        finish();
    }


问:
Keep css animation appearing after unhovering state
I have a div. When I hover into this div, 3 circles should pop in using css animation. But they disappear, when I move the mouse away from the div. How can I make them stay without using jquery? Here is my code:

.circle {
  width: 50px;
  height: 50px;
  border-radius: 50px;
  background-color: blue;
  list-style: none;
  opacity: 0;
  transform: scale(0);
}

.circles li {
  margin-top: 10px;
}

.hoverover:hover + .circles .circle {
  animation: popin .25s forwards;
}

@keyframes popin {
  80% {
    transform: scale(1.15);
  }
  100% {
    opacity: 1;
    transform: scale(1);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="hoverover">Hover Over Me</div>

<ul class="circles">
  <li class="circle"></li>
  <li class="circle"></li>
  <li class="circle"></li>
</ul></code>```

答:
To make the circles stay as long as the .hoverover element or they are hovered you need to insert the .circles container into .hoverover, and make some changes to the way .circles behave when hovered, and not hovered:

.circles {
  margin: 0;
  padding: 15px;
}

.hoverover {
  display: inline-block; /** limit it to the size and height of the text **/
  height: 20px;
}

.hoverover:not(:hover) > .circles { /** prevent opening circles by hovering it when invisible **/
  pointer-events: none;
}

.circle {
  width: 50px;
  height: 50px;
  border-radius: 50px;
  background-color: blue;
  margin-top: 10px;
  list-style: none;
  opacity: 0;
  transform: scale(0);
}

.hoverover:hover .circle {
  animation: popin .25s forwards;
}

@keyframes popin {
  80% {
    transform: scale(1.15);
  }
  100% {
    opacity: 1;
    transform: scale(1);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="hoverover">
  <span>Hover Over Me</span>

  <ul class="circles">
    <li class="circle"></li>
    <li class="circle"></li>
    <li class="circle"></li>
  </ul>

</div></code>```

Previous answer:

When the .hoverover element is hovered, it applies the animation animation: popin .25s forwards; to the .circle elements. When the hover ends the animation is removed, and the element disappears.

To solve that start the animation paused on the .circle, and "resume" it when .hoverover is hovered:

.circle {
  width: 50px;
  height: 50px;
  border-radius: 50px;
  background-color: blue;
  list-style: none;
  opacity: 0;
  transform: scale(0);
  animation: popin .25s forwards;
  animation-play-state: paused;
}

.circles li {
  margin-top: 10px;
}

.hoverover:hover + .circles .circle {
  animation-play-state: running;
}

@keyframes popin {
  80% {
    transform: scale(1.15);
  }
  100% {
    opacity: 1;
    transform: scale(1);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="hoverover">Hover Over Me</div>

<ul class="circles">
  <li class="circle"></li>
  <li class="circle"></li>
  <li class="circle"></li>
</ul></code>```

Body:
I have a div. When I hover into this div, 3 circles should pop in using css animation. But they disappear, when I move the mouse away from the div. How can I make them stay without using jquery? Here is my code:

.circle {
  width: 50px;
  height: 50px;
  border-radius: 50px;
  background-color: blue;
  list-style: none;
  opacity: 0;
  transform: scale(0);
}

.circles li {
  margin-top: 10px;
}

.hoverover:hover + .circles .circle {
  animation: popin .25s forwards;
}

@keyframes popin {
  80% {
    transform: scale(1.15);
  }
  100% {
    opacity: 1;
    transform: scale(1);
  }
}

Hover Over Me

Body:
To make the circles stay as long as the .hoverover element or they are hovered you need to insert the .circles container into .hoverover, and make some changes to the way .circles behave when hovered, and not hovered:

.circles {
  margin: 0;
  padding: 15px;
}

.hoverover {
  display: inline-block; /** limit it to the size and height of the text **/
  height: 20px;
}

.hoverover:not(:hover) > .circles { /** prevent opening circles by hovering it when invisible **/
  pointer-events: none;
}

.circle {
  width: 50px;
  height: 50px;
  border-radius: 50px;
  background-color: blue;
  margin-top: 10px;
  list-style: none;
  opacity: 0;
  transform: scale(0);
}

.hoverover:hover .circle {
  animation: popin .25s forwards;
}

@keyframes popin {
  80% {
    transform: scale(1.15);
  }
  100% {
    opacity: 1;
    transform: scale(1);
  }
}

<div class="hoverover">
  <span>Hover Over Me</span>

  <ul class="circles">
    <li class="circle"></li>
    <li class="circle"></li>
    <li class="circle"></li>
  </ul>

</div>

Previous answer:

When the .hoverover element is hovered, it applies the animation animation: popin .25s forwards; to the .circle elements. When the hover ends the animation is removed, and the element disappears.

To solve that start the animation paused on the .circle, and "resume" it when .hoverover is hovered:

.circle {
  width: 50px;
  height: 50px;
  border-radius: 50px;
  background-color: blue;
  list-style: none;
  opacity: 0;
  transform: scale(0);
  animation: popin .25s forwards;
  animation-play-state: paused;
}

.circles li {
  margin-top: 10px;
}

.hoverover:hover + .circles .circle {
  animation-play-state: running;
}

@keyframes popin {
  80% {
    transform: scale(1.15);
  }
  100% {
    opacity: 1;
    transform: scale(1);
  }
}

<div class="hoverover">Hover Over Me</div>

<ul class="circles">
  <li class="circle"></li>
  <li class="circle"></li>
  <li class="circle"></li>
</ul>


问:
Auto tab to next input field when fill 4 characters
What I am trying to do is, point to next tab when filling four characters. Each field should have 4 characters and once it is completed it should move to next input box.

```<code> $(".inputs").keyup(function () {
        if (this.value.length == this.maxLength) {
          $(this).next('.inputs').focus();
        }
  });
</code>```

Fiddle.

答:
Here is a improved Version for all who need this for some kind of splitted Informations like a serial key or something like that:

$(document).ready(function(){
    $(".amazonInput").keydown(function (e) {
        var code = e.which;
        $this=$(this);
        if ($this.val().length >=$this.data("maxlength") && code != 8) {
            if($this.val().length>$this.data("maxlength")){
                $this.val($this.val().substring(0,4));
            }
            $this.next(".amazonInput").focus();
        }
        if($this.val().length == 0 && code == 8) {
            $this.prev(".amazonInput").focus();
        }
    });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

Body:
What I am trying to do is, point to next tab when filling four characters. Each field should have 4 characters and once it is completed it should move to next input box.

 $(".inputs").keyup(function () {
        if (this.value.length == this.maxLength) {
          $(this).next('.inputs').focus();
        }
  });

Fiddle.

Body:
Here is a improved Version for all who need this for some kind of splitted Informations like a serial key or something like that:

$(document).ready(function(){
    $(".amazonInput").keydown(function (e) {
        var code = e.which;
        $this=$(this);
        if ($this.val().length >=$this.data("maxlength") && code != 8) {
            if($this.val().length>$this.data("maxlength")){
                $this.val($this.val().substring(0,4));
            }
            $this.next(".amazonInput").focus();
        }
        if($this.val().length == 0 && code == 8) {
            $this.prev(".amazonInput").focus();
        }
    });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


问:
Android plugin using Google Fitness API for Unity3D
The main goal of my project is to create a Unity plugin that will be able to use Google Fitness step counter API. It have to provide several features like: getting daily steps count, getting total steps, saving steps amount on the google account and finally the most important and the most difficult sending notifications when steps amount have reached a specified value.

I decided to make an android plugin with running background service that will be able to send those notifications as mentioned above, but I encountered a problem on the very beginning of this project. There is a problem with Google Services initialization, which working perfectly when I’m using it in native android app, but when I’m trying to use it as android library in Unity it always fails.

logcat error:

```<code>06-05 13:49:27.991 15144-15144/? E/GMPM: GoogleService failed to initialize, status: 10, Missing an expected resource: 'R.string.google_app_id' for initializing Google services.  Possible causes are missing google-services.json or com.google.gms.google-services gradle plugin.
06-05 13:49:27.991 15144-15144/? E/GMPM: Scheduler not set. Not logging error/warn.
06-05 13:49:28.005 15144-15158/? E/GMPM: Uploading is not possible. App measurement disabled
</code>```

I was thinking that key to this problem may be to somehow provide data (appIds, SHAs etc.) from generated in the Google Developers console “google-services.json” file into Unity, but .aar library which was generated from android studio contains those informations in res/values/strings file as I think it should.

I was testing many probable solutions including:

exporting android project from unity and adding my library module to it

providing my library as .jar file and “google-services.json” separately

providing necessary data directly in Unity in res/values/strings file

adding it to exported project

Ended up with the same error as I mentioned above.

Am I doing something wrong, or maybe there is an entirely different approach to this problem?

Edit:

Android Manifest from Unity (Plugins/Android):

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="<UNITY APP PACKAGE NAME>" android:versionName="1.0" android:versionCode="1" android:installLocation="preferExternal">
  <supports-screens android:smallScreens="true" android:normalScreens="true" android:largeScreens="true" android:xlargeScreens="true" android:anyDensity="true" />

  <uses-permission android:name="android.permission.INTERNET" />
  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

  <application android:theme="@style/UnityThemeSelector" android:icon="@drawable/app_icon" android:label="@string/app_name" android:debuggable="true" android:isGame="true" android:banner="@drawable/app_banner">

    <activity android:name="<PLUGIN PACKAGE NAME + CLASS NAME>" android:label="@string/app_name" android:screenOrientation="fullSensor" android:launchMode="singleTask" android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|uiMode|screenSize|smallestScreenSize|fontScale">

      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
        <category android:name="android.intent.category.LEANBACK_LAUNCHER" />
      </intent-filter>

      <meta-data android:name="unityplayer.UnityActivity" android:value="true" />
    </activity>

  </application>

  <uses-sdk android:minSdkVersion="19" android:targetSdkVersion="23" />
  <uses-feature android:glEsVersion="0x00020000" />

  <uses-feature android:name="android.hardware.touchscreen" android:required="false" />
  <uses-feature android:name="android.hardware.touchscreen.multitouch" android:required="false" />
  <uses-feature android:name="android.hardware.touchscreen.multitouch.distinct" android:required="false" />
</manifest>
</code>```

答:
After a little more testing on different devices I have discovered how to encounter this problem. On both of my primary testing devices logcat shows this error each time any application got installed. Including directly builded from Unity or Android Studio and those from Google Play Store. This error seems to have no relation to my problem at all.

The problem was that I had to extend UnityPlayerActivity in my plugin to allow the Google login window pop-up to show up.

Body:
The main goal of my project is to create a Unity plugin that will be able to use Google Fitness step counter API. It have to provide several features like: getting daily steps count, getting total steps, saving steps amount on the google account and finally the most important and the most difficult sending notifications when steps amount have reached a specified value.

I decided to make an android plugin with running background service that will be able to send those notifications as mentioned above, but I encountered a problem on the very beginning of this project. There is a problem with Google Services initialization, which working perfectly when I’m using it in native android app, but when I’m trying to use it as android library in Unity it always fails.

logcat error:

06-05 13:49:27.991 15144-15144/? E/GMPM: GoogleService failed to initialize, status: 10, Missing an expected resource: 'R.string.google_app_id' for initializing Google services.  Possible causes are missing google-services.json or com.google.gms.google-services gradle plugin.
06-05 13:49:27.991 15144-15144/? E/GMPM: Scheduler not set. Not logging error/warn.
06-05 13:49:28.005 15144-15158/? E/GMPM: Uploading is not possible. App measurement disabled

I was thinking that key to this problem may be to somehow provide data (appIds, SHAs etc.) from generated in the Google Developers console “google-services.json” file into Unity, but .aar library which was generated from android studio contains those informations in res/values/strings file as I think it should.

I was testing many probable solutions including:

exporting android project from unity and adding my library module to it

providing my library as .jar file and “google-services.json” separately

providing necessary data directly in Unity in res/values/strings file

adding it to exported project

Ended up with the same error as I mentioned above.

Am I doing something wrong, or maybe there is an entirely different approach to this problem?

Edit:

Android Manifest from Unity (Plugins/Android):

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="<UNITY APP PACKAGE NAME>" android:versionName="1.0" android:versionCode="1" android:installLocation="preferExternal">
  <supports-screens android:smallScreens="true" android:normalScreens="true" android:largeScreens="true" android:xlargeScreens="true" android:anyDensity="true" />

  <uses-permission android:name="android.permission.INTERNET" />
  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

  <application android:theme="@style/UnityThemeSelector" android:icon="@drawable/app_icon" android:label="@string/app_name" android:debuggable="true" android:isGame="true" android:banner="@drawable/app_banner">

    <activity android:name="<PLUGIN PACKAGE NAME + CLASS NAME>" android:label="@string/app_name" android:screenOrientation="fullSensor" android:launchMode="singleTask" android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|uiMode|screenSize|smallestScreenSize|fontScale">

      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
        <category android:name="android.intent.category.LEANBACK_LAUNCHER" />
      </intent-filter>

      <meta-data android:name="unityplayer.UnityActivity" android:value="true" />
    </activity>

  </application>

  <uses-sdk android:minSdkVersion="19" android:targetSdkVersion="23" />
  <uses-feature android:glEsVersion="0x00020000" />

  <uses-feature android:name="android.hardware.touchscreen" android:required="false" />
  <uses-feature android:name="android.hardware.touchscreen.multitouch" android:required="false" />
  <uses-feature android:name="android.hardware.touchscreen.multitouch.distinct" android:required="false" />
</manifest>


问:
C# How to use Directory White Spaces into process.arguements?
The program created utilizes a 3rd party tool to generate a log file.

However the arguments provided for the the tool requires various files from Directory locations as part of generating the logs. Therefore the main argument of @"-r C:\test\ftk\ntuser.dat -d C:\System Volume Information\" + restoreFolder.Name + " -p runmru"; would be used to generate the logs.

May someone advise on how to make the arguments of "C:\System Volume Information\" be processed by the system with the white spaces in placed? Thanks!

The codes:

```<code>            Process process = new Process();
            process.StartInfo.FileName = @"C:\test\ftk\ripxp\ripxp.exe";
            process.StartInfo.Arguments = @"-r C:\test\ftk\ntuser.dat -d C:\System Volume Information\" + restoreFolder.Name + " -p runmru";
            process.StartInfo.CreateNoWindow = false;
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardInput = true;
            process.StartInfo.RedirectStandardError = true;
            process.Start();
</code>```

答:
You need to escape the " by appending a \ to them (\") - for normal strings, or doubling them ("") for verbatim string literals (those starting with @):

```<code>process.StartInfo.Arguments = @"-r C:\test\ftk\ntuser.dat -d ""C:\System Volume Information\" + restoreFolder.Name + @""" -p runmru";
</code>```

Body:
The program created utilizes a 3rd party tool to generate a log file.

However the arguments provided for the the tool requires various files from Directory locations as part of generating the logs. Therefore the main argument of @"-r C:\test\ftk\ntuser.dat -d C:\System Volume Information\" + restoreFolder.Name + " -p runmru"; would be used to generate the logs.

May someone advise on how to make the arguments of "C:\System Volume Information\" be processed by the system with the white spaces in placed? Thanks!

The codes:

            Process process = new Process();
            process.StartInfo.FileName = @"C:\test\ftk\ripxp\ripxp.exe";
            process.StartInfo.Arguments = @"-r C:\test\ftk\ntuser.dat -d C:\System Volume Information\" + restoreFolder.Name + " -p runmru";
            process.StartInfo.CreateNoWindow = false;
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardInput = true;
            process.StartInfo.RedirectStandardError = true;
            process.Start();

Body:
You need to escape the " by appending a \ to them (\") - for normal strings, or doubling them ("") for verbatim string literals (those starting with @):

process.StartInfo.Arguments = @"-r C:\test\ftk\ntuser.dat -d ""C:\System Volume Information\" + restoreFolder.Name + @""" -p runmru";


问:
DirectX Screen Capture - Desktop Duplication API - limited frame rate of AcquireNextFrame
I'm trying to use Windows Desktop Duplication API to capture the screen and save the raw output to a video. I'm using AcquireNextFrame with a very high timeout value (999ms). This way I should get every new frame from windows as soon as it at has one, which naturally should be at 60fps anyway. I end up getting sequences where everything looks good (frame 6-11), and then sequences where things look bad (frame 12-14). If I check AccumulatedFrames

```<code>lFrameInfo.AccumulatedFrames
</code>```

the value is often 2 or higher. From my understanding, this means windows is saying "hey hold up, I don't have a frame for you yet", because calls to AcquireNextFrame take so long. But once windows does finally give me a frame, it is saying "hey you were actually too slow and ended up missing a frame". If i could somehow get these frames I think I would be getting 60hz.

This can be further clarified with logging:

```<code>I0608 10:40:16.964375  4196 window_capturer_dd.cc:438] 206 - Frame 6 start acquire
I0608 10:40:16.973867  4196 window_capturer_dd.cc:451] 216 - Frame 6 acquired
I0608 10:40:16.981364  4196 window_capturer_dd.cc:438] 223 - Frame 7 start acquire
I0608 10:40:16.990864  4196 window_capturer_dd.cc:451] 233 - Frame 7 acquired
I0608 10:40:16.998364  4196 window_capturer_dd.cc:438] 240 - Frame 8 start acquire
I0608 10:40:17.007876  4196 window_capturer_dd.cc:451] 250 - Frame 8 acquired
I0608 10:40:17.015393  4196 window_capturer_dd.cc:438] 257 - Frame 9 start acquire
I0608 10:40:17.023905  4196 window_capturer_dd.cc:451] 266 - Frame 9 acquired
I0608 10:40:17.032411  4196 window_capturer_dd.cc:438] 274 - Frame 10 start acquire
I0608 10:40:17.039912  4196 window_capturer_dd.cc:451] 282 - Frame 10 acquired
I0608 10:40:17.048925  4196 window_capturer_dd.cc:438] 291 - Frame 11 start acquire
I0608 10:40:17.058428  4196 window_capturer_dd.cc:451] 300 - Frame 11 acquired
I0608 10:40:17.065943  4196 window_capturer_dd.cc:438] 308 - Frame 12 start acquire
I0608 10:40:17.096945  4196 window_capturer_dd.cc:451] 336 - Frame 12 acquired
I0608 10:40:17.098947  4196 window_capturer_dd.cc:464] 1 FRAMES MISSED on frame: 12
I0608 10:40:17.101444  4196 window_capturer_dd.cc:438] 343 - Frame 13 start acquire
I0608 10:40:17.128958  4196 window_capturer_dd.cc:451] 368 - Frame 13 acquired
I0608 10:40:17.130957  4196 window_capturer_dd.cc:464] 1 FRAMES MISSED on frame: 13
I0608 10:40:17.135459  4196 window_capturer_dd.cc:438] 377 - Frame 14 start acquire
I0608 10:40:17.160959  4196 window_capturer_dd.cc:451] 399 - Frame 14 acquired
I0608 10:40:17.162958  4196 window_capturer_dd.cc:464] 1 FRAMES MISSED on frame: 14
</code>```

Frame 6-11 look good, the acquires are roughly 17ms apart. Frame 12 should be acquired at (300+17=317ms). Frame 12 starts waiting at 308, but doesn't get anything until 336ms. Windows didn't have anything for me until the frame after (300+17+17~=336ms). Okay sure maybe windows just missed a frame, but when I finally get it, I can check AccumulatedFrames and its value was 2 (meaning I missed a frame because I waited too long before calling AcquireNextFrame). In my understanding, it only makes sense for AccumulatedFrames to be larger than 1 if AcquireNextFrame returns immediately.

Furthermore, I can use PresentMon while my capture software is running. The logs show MsBetweenDisplayChange for every frame, which is fairly steady at 16.666ms (with a couple outliers, but much less than my capture software is seeing).

These people (1, 2) seem to have been able to get 60fps, so I'm wondering what I am doing incorrectly.

My code is based on this:

```<code>int main() {
    int FPS = 60;
    int video_length_sec = 5;

    int total_frames = FPS * video_length_sec;
    for (int i = 0; i < total_frames; i++) {
        if(!CaptureSingleFrame()){
            i--;
        }
    }
}

ComPtr<ID3D11Device> lDevice;
ComPtr<ID3D11DeviceContext> lImmediateContext;
ComPtr<IDXGIOutputDuplication> lDeskDupl;
ComPtr<ID3D11Texture2D> lAcquiredDesktopImage;
ComPtr<ID3D11Texture2D> lGDIImage;
ComPtr<ID3D11Texture2D> lDestImage;
DXGI_OUTPUT_DESC lOutputDesc;
DXGI_OUTDUPL_DESC lOutputDuplDesc;
D3D11_TEXTURE2D_DESC desc;

// Driver types supported
D3D_DRIVER_TYPE gDriverTypes[] = {
    D3D_DRIVER_TYPE_HARDWARE
};
UINT gNumDriverTypes = ARRAYSIZE(gDriverTypes);

// Feature levels supported
D3D_FEATURE_LEVEL gFeatureLevels[] = {
    D3D_FEATURE_LEVEL_11_0,
    D3D_FEATURE_LEVEL_10_1,
    D3D_FEATURE_LEVEL_10_0,
    D3D_FEATURE_LEVEL_9_1
};
UINT gNumFeatureLevels = ARRAYSIZE(gFeatureLevels);

bool Init() {
    int lresult(-1);

    D3D_FEATURE_LEVEL lFeatureLevel;

    HRESULT hr(E_FAIL);

    // Create device
    for (UINT DriverTypeIndex = 0; DriverTypeIndex < gNumDriverTypes; ++DriverTypeIndex)
    {
        hr = D3D11CreateDevice(
            nullptr,
            gDriverTypes[DriverTypeIndex],
            nullptr,
            0,
            gFeatureLevels,
            gNumFeatureLevels,
            D3D11_SDK_VERSION,
            &lDevice,
            &lFeatureLevel,
            &lImmediateContext);

        if (SUCCEEDED(hr))
        {
            // Device creation success, no need to loop anymore
            break;
        }

        lDevice.Reset();

        lImmediateContext.Reset();
    }

    if (FAILED(hr))
        return false;

    if (lDevice == nullptr)
        return false;

    // Get DXGI device
    ComPtr<IDXGIDevice> lDxgiDevice;
    hr = lDevice.As(&lDxgiDevice);

    if (FAILED(hr))
        return false;

    // Get DXGI adapter
    ComPtr<IDXGIAdapter> lDxgiAdapter;
    hr = lDxgiDevice->GetParent(
        __uuidof(IDXGIAdapter), &lDxgiAdapter);

    if (FAILED(hr))
        return false;

    lDxgiDevice.Reset();

    UINT Output = 0;

    // Get output
    ComPtr<IDXGIOutput> lDxgiOutput;
    hr = lDxgiAdapter->EnumOutputs(
        Output,
        &lDxgiOutput);

    if (FAILED(hr))
        return false;

    lDxgiAdapter.Reset();

    hr = lDxgiOutput->GetDesc(
        &lOutputDesc);

    if (FAILED(hr))
        return false;

    // QI for Output 1
    ComPtr<IDXGIOutput1> lDxgiOutput1;
    hr = lDxgiOutput.As(&lDxgiOutput1);

    if (FAILED(hr))
        return false;

    lDxgiOutput.Reset();

    // Create desktop duplication
    hr = lDxgiOutput1->DuplicateOutput(
        lDevice.Get(), //TODO what im i doing here
        &lDeskDupl);

    if (FAILED(hr))
        return false;

    lDxgiOutput1.Reset();

    // Create GUI drawing texture
    lDeskDupl->GetDesc(&lOutputDuplDesc);
    desc.Width = lOutputDuplDesc.ModeDesc.Width;
    desc.Height = lOutputDuplDesc.ModeDesc.Height;
    desc.Format = lOutputDuplDesc.ModeDesc.Format;
    desc.ArraySize = 1;
    desc.BindFlags = D3D11_BIND_FLAG::D3D11_BIND_RENDER_TARGET;
    desc.MiscFlags = D3D11_RESOURCE_MISC_GDI_COMPATIBLE;
    desc.SampleDesc.Count = 1;
    desc.SampleDesc.Quality = 0;
    desc.MipLevels = 1;
    desc.CPUAccessFlags = 0;
    desc.Usage = D3D11_USAGE_DEFAULT;

    hr = lDevice->CreateTexture2D(&desc, NULL, &lGDIImage);

    if (FAILED(hr))
        return false;

    if (lGDIImage == nullptr)
        return false;

    // Create CPU access texture
    desc.Width = lOutputDuplDesc.ModeDesc.Width;
    desc.Height = lOutputDuplDesc.ModeDesc.Height;
    desc.Format = lOutputDuplDesc.ModeDesc.Format;
    std::cout << desc.Width << "x" << desc.Height << "\n\n\n";
    desc.ArraySize = 1;
    desc.BindFlags = 0;
    desc.MiscFlags = 0;
    desc.SampleDesc.Count = 1;
    desc.SampleDesc.Quality = 0;
    desc.MipLevels = 1;
    desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ | D3D11_CPU_ACCESS_WRITE;
    desc.Usage = D3D11_USAGE_STAGING;

    return true;
}

void WriteFrameToCaptureFile(ID3D11Texture2D* texture) {

    D3D11_MAPPED_SUBRESOURCE* pRes = new D3D11_MAPPED_SUBRESOURCE;
    UINT subresource = D3D11CalcSubresource(0, 0, 0);

    lImmediateContext->Map(texture, subresource, D3D11_MAP_READ_WRITE, 0, pRes);

    void* d = pRes->pData;
    char* data = reinterpret_cast<char*>(d);

    // writes data to file
    WriteFrameToCaptureFile(data, 0);
}

bool CaptureSingleFrame()
{
    HRESULT hr(E_FAIL);
    ComPtr<IDXGIResource> lDesktopResource = nullptr;
    DXGI_OUTDUPL_FRAME_INFO lFrameInfo;
    ID3D11Texture2D* currTexture;

    hr = lDeskDupl->AcquireNextFrame(
        999,
        &lFrameInfo,
        &lDesktopResource);

    if (FAILED(hr)) {
        LOG(INFO) << "Failed to acquire new frame";
        return false;
    }

    if (lFrameInfo.LastPresentTime.HighPart == 0) {
        // not interested in just mouse updates, which can happen much faster than 60fps if you really shake the mouse
        hr = lDeskDupl->ReleaseFrame();
        return false;
    }

    int accum_frames = lFrameInfo.AccumulatedFrames;
    if (accum_frames > 1 && current_frame != 1) {
        // TOO MANY OF THESE is the problem
        // especially after having to wait >17ms in AcquireNextFrame()
    }

    // QI for ID3D11Texture2D
    hr = lDesktopResource.As(&lAcquiredDesktopImage);

    // Copy image into a newly created CPU access texture
    hr = lDevice->CreateTexture2D(&desc, NULL, &currTexture);
    if (FAILED(hr))
        return false;
    if (currTexture == nullptr)
        return false;

    lImmediateContext->CopyResource(currTexture, lAcquiredDesktopImage.Get());

    writer_thread->Schedule(
        FROM_HERE, [this, currTexture]() {
        WriteFrameToCaptureFile(currTexture);
    });
    pending_write_counts_++;

    hr = lDeskDupl->ReleaseFrame();

    return true;
}
</code>```

**EDIT - According to my measurements, you must call AcquireNextFrame() before the frame will actually appear by about ~10ms, or windows will fail to acquire it and get you the next one. Every time my recording program takes more than 7 ms to wrap around (after acquiring frame i until calling AcquireNextFrame() on i+1), frame i+1 is missed.

***EDIT - Heres a screenshot of GPU View showing what I'm talking about. The first 6 frames process in no time, then the 7th frame takes 119ms. The long rectangle beside "capture_to_argb.exe" corresponds to me being stuck inside AcquireNextFrame(). If you look up to the hardware queue, you can see it cleanly rendering at 60fps, even while I'm stuck in AcquireNextFrame(). At least this is my interpretation (I have no idea what I'm doing).

答:
"Current Display Mode: 3840 x 2160 (32 bit) (60hz)" refers to display refresh rate, that is how many frames can be passed to display per second. However the rate at which new frames are rendered is typically much lower. You can inspect this rate using PresentMon or similar utilities. When I don't move the mouse it reports me something like this:

As you can see when nothing happens Windows presents new frame only twice per second or even slower. However this is typically really good for video encoding because even if you are recording video at 60 fps and AcquireNextFrame reports that no new frame is available then it means that current frame is exactly the same as previous.

Body:
I'm trying to use Windows Desktop Duplication API to capture the screen and save the raw output to a video. I'm using AcquireNextFrame with a very high timeout value (999ms). This way I should get every new frame from windows as soon as it at has one, which naturally should be at 60fps anyway. I end up getting sequences where everything looks good (frame 6-11), and then sequences where things look bad (frame 12-14). If I check AccumulatedFrames

lFrameInfo.AccumulatedFrames

the value is often 2 or higher. From my understanding, this means windows is saying "hey hold up, I don't have a frame for you yet", because calls to AcquireNextFrame take so long. But once windows does finally give me a frame, it is saying "hey you were actually too slow and ended up missing a frame". If i could somehow get these frames I think I would be getting 60hz.

This can be further clarified with logging:

I0608 10:40:16.964375  4196 window_capturer_dd.cc:438] 206 - Frame 6 start acquire
I0608 10:40:16.973867  4196 window_capturer_dd.cc:451] 216 - Frame 6 acquired
I0608 10:40:16.981364  4196 window_capturer_dd.cc:438] 223 - Frame 7 start acquire
I0608 10:40:16.990864  4196 window_capturer_dd.cc:451] 233 - Frame 7 acquired
I0608 10:40:16.998364  4196 window_capturer_dd.cc:438] 240 - Frame 8 start acquire
I0608 10:40:17.007876  4196 window_capturer_dd.cc:451] 250 - Frame 8 acquired
I0608 10:40:17.015393  4196 window_capturer_dd.cc:438] 257 - Frame 9 start acquire
I0608 10:40:17.023905  4196 window_capturer_dd.cc:451] 266 - Frame 9 acquired
I0608 10:40:17.032411  4196 window_capturer_dd.cc:438] 274 - Frame 10 start acquire
I0608 10:40:17.039912  4196 window_capturer_dd.cc:451] 282 - Frame 10 acquired
I0608 10:40:17.048925  4196 window_capturer_dd.cc:438] 291 - Frame 11 start acquire
I0608 10:40:17.058428  4196 window_capturer_dd.cc:451] 300 - Frame 11 acquired
I0608 10:40:17.065943  4196 window_capturer_dd.cc:438] 308 - Frame 12 start acquire
I0608 10:40:17.096945  4196 window_capturer_dd.cc:451] 336 - Frame 12 acquired
I0608 10:40:17.098947  4196 window_capturer_dd.cc:464] 1 FRAMES MISSED on frame: 12
I0608 10:40:17.101444  4196 window_capturer_dd.cc:438] 343 - Frame 13 start acquire
I0608 10:40:17.128958  4196 window_capturer_dd.cc:451] 368 - Frame 13 acquired
I0608 10:40:17.130957  4196 window_capturer_dd.cc:464] 1 FRAMES MISSED on frame: 13
I0608 10:40:17.135459  4196 window_capturer_dd.cc:438] 377 - Frame 14 start acquire
I0608 10:40:17.160959  4196 window_capturer_dd.cc:451] 399 - Frame 14 acquired
I0608 10:40:17.162958  4196 window_capturer_dd.cc:464] 1 FRAMES MISSED on frame: 14

Frame 6-11 look good, the acquires are roughly 17ms apart. Frame 12 should be acquired at (300+17=317ms). Frame 12 starts waiting at 308, but doesn't get anything until 336ms. Windows didn't have anything for me until the frame after (300+17+17~=336ms). Okay sure maybe windows just missed a frame, but when I finally get it, I can check AccumulatedFrames and its value was 2 (meaning I missed a frame because I waited too long before calling AcquireNextFrame). In my understanding, it only makes sense for AccumulatedFrames to be larger than 1 if AcquireNextFrame returns immediately.

Furthermore, I can use PresentMon while my capture software is running. The logs show MsBetweenDisplayChange for every frame, which is fairly steady at 16.666ms (with a couple outliers, but much less than my capture software is seeing).

These people (1, 2) seem to have been able to get 60fps, so I'm wondering what I am doing incorrectly.

My code is based on this:

int main() {
    int FPS = 60;
    int video_length_sec = 5;

    int total_frames = FPS * video_length_sec;
    for (int i = 0; i < total_frames; i++) {
        if(!CaptureSingleFrame()){
            i--;
        }
    }
}

ComPtr<ID3D11Device> lDevice;
ComPtr<ID3D11DeviceContext> lImmediateContext;
ComPtr<IDXGIOutputDuplication> lDeskDupl;
ComPtr<ID3D11Texture2D> lAcquiredDesktopImage;
ComPtr<ID3D11Texture2D> lGDIImage;
ComPtr<ID3D11Texture2D> lDestImage;
DXGI_OUTPUT_DESC lOutputDesc;
DXGI_OUTDUPL_DESC lOutputDuplDesc;
D3D11_TEXTURE2D_DESC desc;

// Driver types supported
D3D_DRIVER_TYPE gDriverTypes[] = {
    D3D_DRIVER_TYPE_HARDWARE
};
UINT gNumDriverTypes = ARRAYSIZE(gDriverTypes);

// Feature levels supported
D3D_FEATURE_LEVEL gFeatureLevels[] = {
    D3D_FEATURE_LEVEL_11_0,
    D3D_FEATURE_LEVEL_10_1,
    D3D_FEATURE_LEVEL_10_0,
    D3D_FEATURE_LEVEL_9_1
};
UINT gNumFeatureLevels = ARRAYSIZE(gFeatureLevels);

bool Init() {
    int lresult(-1);

    D3D_FEATURE_LEVEL lFeatureLevel;

    HRESULT hr(E_FAIL);

    // Create device
    for (UINT DriverTypeIndex = 0; DriverTypeIndex < gNumDriverTypes; ++DriverTypeIndex)
    {
        hr = D3D11CreateDevice(
            nullptr,
            gDriverTypes[DriverTypeIndex],
            nullptr,
            0,
            gFeatureLevels,
            gNumFeatureLevels,
            D3D11_SDK_VERSION,
            &lDevice,
            &lFeatureLevel,
            &lImmediateContext);

        if (SUCCEEDED(hr))
        {
            // Device creation success, no need to loop anymore
            break;
        }

        lDevice.Reset();

        lImmediateContext.Reset();
    }

    if (FAILED(hr))
        return false;

    if (lDevice == nullptr)
        return false;

    // Get DXGI device
    ComPtr<IDXGIDevice> lDxgiDevice;
    hr = lDevice.As(&lDxgiDevice);

    if (FAILED(hr))
        return false;

    // Get DXGI adapter
    ComPtr<IDXGIAdapter> lDxgiAdapter;
    hr = lDxgiDevice->GetParent(
        __uuidof(IDXGIAdapter), &lDxgiAdapter);

    if (FAILED(hr))
        return false;

    lDxgiDevice.Reset();

    UINT Output = 0;

    // Get output
    ComPtr<IDXGIOutput> lDxgiOutput;
    hr = lDxgiAdapter->EnumOutputs(
        Output,
        &lDxgiOutput);

    if (FAILED(hr))
        return false;

    lDxgiAdapter.Reset();

    hr = lDxgiOutput->GetDesc(
        &lOutputDesc);

    if (FAILED(hr))
        return false;

    // QI for Output 1
    ComPtr<IDXGIOutput1> lDxgiOutput1;
    hr = lDxgiOutput.As(&lDxgiOutput1);

    if (FAILED(hr))
        return false;

    lDxgiOutput.Reset();

    // Create desktop duplication
    hr = lDxgiOutput1->DuplicateOutput(
        lDevice.Get(), //TODO what im i doing here
        &lDeskDupl);

    if (FAILED(hr))
        return false;

    lDxgiOutput1.Reset();

    // Create GUI drawing texture
    lDeskDupl->GetDesc(&lOutputDuplDesc);
    desc.Width = lOutputDuplDesc.ModeDesc.Width;
    desc.Height = lOutputDuplDesc.ModeDesc.Height;
    desc.Format = lOutputDuplDesc.ModeDesc.Format;
    desc.ArraySize = 1;
    desc.BindFlags = D3D11_BIND_FLAG::D3D11_BIND_RENDER_TARGET;
    desc.MiscFlags = D3D11_RESOURCE_MISC_GDI_COMPATIBLE;
    desc.SampleDesc.Count = 1;
    desc.SampleDesc.Quality = 0;
    desc.MipLevels = 1;
    desc.CPUAccessFlags = 0;
    desc.Usage = D3D11_USAGE_DEFAULT;

    hr = lDevice->CreateTexture2D(&desc, NULL, &lGDIImage);

    if (FAILED(hr))
        return false;

    if (lGDIImage == nullptr)
        return false;

    // Create CPU access texture
    desc.Width = lOutputDuplDesc.ModeDesc.Width;
    desc.Height = lOutputDuplDesc.ModeDesc.Height;
    desc.Format = lOutputDuplDesc.ModeDesc.Format;
    std::cout << desc.Width << "x" << desc.Height << "\n\n\n";
    desc.ArraySize = 1;
    desc.BindFlags = 0;
    desc.MiscFlags = 0;
    desc.SampleDesc.Count = 1;
    desc.SampleDesc.Quality = 0;
    desc.MipLevels = 1;
    desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ | D3D11_CPU_ACCESS_WRITE;
    desc.Usage = D3D11_USAGE_STAGING;

    return true;
}

void WriteFrameToCaptureFile(ID3D11Texture2D* texture) {

    D3D11_MAPPED_SUBRESOURCE* pRes = new D3D11_MAPPED_SUBRESOURCE;
    UINT subresource = D3D11CalcSubresource(0, 0, 0);

    lImmediateContext->Map(texture, subresource, D3D11_MAP_READ_WRITE, 0, pRes);

    void* d = pRes->pData;
    char* data = reinterpret_cast<char*>(d);

    // writes data to file
    WriteFrameToCaptureFile(data, 0);
}

bool CaptureSingleFrame()
{
    HRESULT hr(E_FAIL);
    ComPtr<IDXGIResource> lDesktopResource = nullptr;
    DXGI_OUTDUPL_FRAME_INFO lFrameInfo;
    ID3D11Texture2D* currTexture;

    hr = lDeskDupl->AcquireNextFrame(
        999,
        &lFrameInfo,
        &lDesktopResource);

    if (FAILED(hr)) {
        LOG(INFO) << "Failed to acquire new frame";
        return false;
    }

    if (lFrameInfo.LastPresentTime.HighPart == 0) {
        // not interested in just mouse updates, which can happen much faster than 60fps if you really shake the mouse
        hr = lDeskDupl->ReleaseFrame();
        return false;
    }

    int accum_frames = lFrameInfo.AccumulatedFrames;
    if (accum_frames > 1 && current_frame != 1) {
        // TOO MANY OF THESE is the problem
        // especially after having to wait >17ms in AcquireNextFrame()
    }

    // QI for ID3D11Texture2D
    hr = lDesktopResource.As(&lAcquiredDesktopImage);

    // Copy image into a newly created CPU access texture
    hr = lDevice->CreateTexture2D(&desc, NULL, &currTexture);
    if (FAILED(hr))
        return false;
    if (currTexture == nullptr)
        return false;

    lImmediateContext->CopyResource(currTexture, lAcquiredDesktopImage.Get());

    writer_thread->Schedule(
        FROM_HERE, [this, currTexture]() {
        WriteFrameToCaptureFile(currTexture);
    });
    pending_write_counts_++;

    hr = lDeskDupl->ReleaseFrame();

    return true;
}

**EDIT - According to my measurements, you must call AcquireNextFrame() before the frame will actually appear by about ~10ms, or windows will fail to acquire it and get you the next one. Every time my recording program takes more than 7 ms to wrap around (after acquiring frame i until calling AcquireNextFrame() on i+1), frame i+1 is missed.

***EDIT - Heres a screenshot of GPU View showing what I'm talking about. The first 6 frames process in no time, then the 7th frame takes 119ms. The long rectangle beside "capture_to_argb.exe" corresponds to me being stuck inside AcquireNextFrame(). If you look up to the hardware queue, you can see it cleanly rendering at 60fps, even while I'm stuck in AcquireNextFrame(). At least this is my interpretation (I have no idea what I'm doing).


问:
How to set month value based on count
How to get the correct month in javascript. I don't want to use any plugin for this.

var date = new Date();
var month = date.getMonth();
// value is 06 current month;

var month = date.getMonth() + 15;
// now value is 21```
</div>
</div>
</p>

<p>Here, if the getMonth() count more than 12 means how can I get the correct month.
If more than 12 means I need to increase the year also right. </p>

<p>For Example,</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// assume current month December
var month = date.getMonth()+3;  // value is 14</code>```

I want to show the month as "03" (MARCH). Please help me how can I do this

答:
var date = new Date();
var month = date.getMonth();

var monthNames = ["January", "February", "March", "April", "May", "June",
  "July", "August", "September", "October", "November", "December"
];

var month = date.getMonth() + 15;

var result = new Date(date.getYear(),month,date.getDay()).getMonth();

console.log(result, monthNames[result]);```

Title: How to set month value based on count

Body:
How to get the correct month in javascript. I don't want to use any plugin for this.

var date = new Date();
var month = date.getMonth();
// value is 06 current month;

var month = date.getMonth() + 15;
// now value is 21

Here, if the getMonth() count more than 12 means how can I get the correct month.
If more than 12 means I need to increase the year also right.

For Example,

// assume current month December
var month = date.getMonth()+3;  // value is 14

I want to show the month as "03" (MARCH). Please help me how can I do this


问:
Can I call a function inside a Lambda expression in python
I have a function with including if, else condition and for loop. I want to write this function inside a lambda expression. I tried from many ways to create this lambda function. But still I couldn't do it. This is my function with another rules.

```<code>negation ='no,not,never'.split(',')
list2 = 'miss,loss,gone,give up,lost'.split(',')

def f(sentence):
  s = sentence.split()
  l = [s.index(word) for word in s if word in list2]
# Will returns list of indices (of sentence) where word is in list2
   if len(l) > 0:
    for e in l:
        # Check previous word
        if s[e-1] not in negation:
            print 'sad'
</code>```

Can I express this function inside a lambda expression since I developing a rule based classifier for detect emotion from a sentence like happy, sad, angry. Following is my lambda function.

```<code>rules = [(lambda x: word_tokenize(x)[-1] == '?', "neutral"),
         (lambda x: word_tokenize(x)[0] in question, "neutral"),
         (lambda x: any(word in list2 for word in [WordNetLemmatizer().lemmatize(word,'v') for word in word_tokenize(x)]), "sad"),
     (lambda x: any(word in list1 for word in [WordNetLemmatizer().lemmatize(word,'v') for word in word_tokenize(x)]), "happy")]

         print classify("I miss you", rules)
</code>```

答:
Instead of cramming everything into a lambda expression, I would just create a function that did everything you need it to do (from your comment, it sounds like you want to apply certain rules to a sentence in a certain order). You can always use that function in list comprehension, map, reduce, etc. Since I don't know exactly what your rules are though, this is the best example I can give:</p>

```<code>a = ["This is not a sentence. That was false.",
     "You cannot play volleyball. You can play baseball.",
     "My uncle once ate an entire bag of corn chips! I am not lying!"]
def f(paragraph):
    sentences = paragraph.split(".")
    result = []
    for i in range(len(sentences)):
        //apply rules to sentences
        if "not" in sentences[i]:
            result.append("negative")
        else:
            result.append("positive")
    return result
my_result = [f(x) for x in a]
</code>```

Body:
I have a function with including if, else condition and for loop. I want to write this function inside a lambda expression. I tried from many ways to create this lambda function. But still I couldn't do it. This is my function with another rules.

negation ='no,not,never'.split(',')
list2 = 'miss,loss,gone,give up,lost'.split(',')

def f(sentence):
  s = sentence.split()
  l = [s.index(word) for word in s if word in list2]
# Will returns list of indices (of sentence) where word is in list2
   if len(l) > 0:
    for e in l:
        # Check previous word
        if s[e-1] not in negation:
            print 'sad'

Can I express this function inside a lambda expression since I developing a rule based classifier for detect emotion from a sentence like happy, sad, angry. Following is my lambda function.

rules = [(lambda x: word_tokenize(x)[-1] == '?', "neutral"),
         (lambda x: word_tokenize(x)[0] in question, "neutral"),
         (lambda x: any(word in list2 for word in [WordNetLemmatizer().lemmatize(word,'v') for word in word_tokenize(x)]), "sad"),
     (lambda x: any(word in list1 for word in [WordNetLemmatizer().lemmatize(word,'v') for word in word_tokenize(x)]), "happy")]

         print classify("I miss you", rules)

Body:
Instead of cramming everything into a lambda expression, I would just create a function that did everything you need it to do (from your comment, it sounds like you want to apply certain rules to a sentence in a certain order). You can always use that function in list comprehension, map, reduce, etc. Since I don't know exactly what your rules are though, this is the best example I can give:

a = ["This is not a sentence. That was false.",
     "You cannot play volleyball. You can play baseball.",
     "My uncle once ate an entire bag of corn chips! I am not lying!"]
def f(paragraph):
    sentences = paragraph.split(".")
    result = []
    for i in range(len(sentences)):
        //apply rules to sentences
        if "not" in sentences[i]:
            result.append("negative")
        else:
            result.append("positive")
    return result
my_result = [f(x) for x in a]


问:
Create ArrayList from array
Given an array of type Element[]:

```<code>Element[] array = {new Element(1), new Element(2), new Element(3)};
</code>```

How do I convert this array into an object of type ArrayList<Element>?

```<code>ArrayList<Element> arrayList = ???;
</code>```

答:
You can do it in java 8 as follows</p>

```<code>ArrayList<Element> list = (ArrayList<Element>)Arrays.stream(array).collect(Collectors.toList());
</code>```

OwnerDisplayName: Ron Tuffin

ContentLicense: CC BY-SA 4.0

Title: Create ArrayList from array

Body:
Given an array of type Element[]:

Element[] array = {new Element(1), new Element(2), new Element(3)};

How do I convert this array into an object of type ArrayList<Element>?

ArrayList<Element> arrayList = ???;

Body:
You can do it in java 8 as follows

ArrayList<Element> list = (ArrayList<Element>)Arrays.stream(array).collect(Collectors.toList());


问:
What is the dataweave expression to map an arraylist to a copybook?
I am building a copybook request for IBM MQ and in the request I have to send an arraylist of elements having values. I am getting the exception

too few values for 'IO-ARRAY' of segment COMMAREA at position 0 (com.mulesoft.flatfile.lexical.WriteException).

I am using mule 3.8 and configuring the output of Data transformer as 'Copybook'. PFB my configurations,

Data Transform: https://i.stack.imgur.com/2kO8c.png

Here is the copybook file I am using,

        01  COMMAREA.
           05  MQ-CNTL.
               10  MQ-MSGID          PIC X(08).
        05 INPUT-OUTPUT.
            10  ID1               PIC X(04).
         10  ID2               PIC X(08).
         10  IO-ARRAY  OCCURS 99 INDEXED BY IO-ARRAY.
           15  ELEMENT1        PIC X(03).
           15  ELEMENT2        PIC X(03).
           15  ELEMENT3        PIC X(01).
           15  ELEMENT4        PIC X(01).
           15  ELEMENT5        PIC X(02).```

Can you please help resolve this?

答:
My understanding is that this line:

```<code>       10  IO-ARRAY  OCCURS 99 INDEXED BY IO-ARRAY.
</code>```

indicates that there is a dependency on the IO-ARRAY field. For reference look into the below code snippet.

```<code>01 WS-TABLE.
  05 WS-A OCCURS 3 TIMES INDEXED BY I.
     10 WS-B PIC A(2).
     10 WS-C OCCURS 2 TIMES INDEXED BY J.
        15 WS-D PIC X(3).
</code>```

Body:
I am building a copybook request for IBM MQ and in the request I have to send an arraylist of elements having values. I am getting the exception

too few values for 'IO-ARRAY' of segment COMMAREA at position 0 (com.mulesoft.flatfile.lexical.WriteException).

I am using mule 3.8 and configuring the output of Data transformer as 'Copybook'. PFB my configurations,

Data Transform: https://i.stack.imgur.com/2kO8c.png

Here is the copybook file I am using,

        01  COMMAREA.
           05  MQ-CNTL.
               10  MQ-MSGID          PIC X(08).
        05 INPUT-OUTPUT.
            10  ID1               PIC X(04).
         10  ID2               PIC X(08).
         10  IO-ARRAY  OCCURS 99 INDEXED BY IO-ARRAY.
           15  ELEMENT1        PIC X(03).
           15  ELEMENT2        PIC X(03).
           15  ELEMENT3        PIC X(01).
           15  ELEMENT4        PIC X(01).
           15  ELEMENT5        PIC X(02).

Can you please help resolve this?

Body:
My understanding is that this line:

       10  IO-ARRAY  OCCURS 99 INDEXED BY IO-ARRAY.

indicates that there is a dependency on the IO-ARRAY field. For reference look into the below code snippet.

01 WS-TABLE.
  05 WS-A OCCURS 3 TIMES INDEXED BY I.
     10 WS-B PIC A(2).
     10 WS-C OCCURS 2 TIMES INDEXED BY J.
        15 WS-D PIC X(3).