问:
jQuery click event fires the first time, but not the second
This is the HTML I'm working with:

```<code><ul id="categories">
  <li><a href="#cargo">Cargo Trailers</a></li>
  <div class="dropdown">
    <ul>
      <li><a href="#utility">Utility Trailers</a></li>
    </ul>
  </div>
</ul>
</code>```

I have written a jQuery script to hide the dropdown div. The dropdown div appears the first time the click event is fired. Once the li in the dropdown div is selected and switches places with the first li in the #categories ul, clicking on the li will not bring up the dropdown div.

Here is the jQuery:

```<code>jQuery(document).ready(function($) {

// hide the dropdown div
$('#categories > div').hide();

/*
    Click the drop down arrow function
*/
var $listHeader = $('#categories > li');

$listHeader.click(function() {

    if ( $('#categories > div:hidden') ) {
        //show the drop down
        $('#categories > div').show();
    } else {
        //hide the drop down
        $('#categories > div').hide();
    }
});

/*
    Click a list-item in the drop down function
*/
$('#categories > div a').click(function() {

    /* actions to change the title to the newly selected item */
    // hide the ul
    $('#categories > div').hide();

    // move the clicked item to the header
    $(this).prependTo('#categories > li');

    // move the previous title to the dropdown and sort
    $('#categories > li > a:eq(1)').prependTo('#categories > div > ul > li:empty');

    // Reset the listHeader variable
    $listHeader = $('#categories > li');

    // cancel default browser action
    return false;

});
});
</code>```

答:
this $('#categories > div:hidden') will always return jQuery object (which evaluates to true), even if there are no elements matching selector. Use jQuery's .toggle() instead of if...else:

```<code>$('#categories > div').toggle();
</code>```

here's an example to play with

Update in response to your comment: Updated example - http://jsfiddle.net/Etkjr/1/

You are correct, event handlers are unbound on DOM change. To prevent, that you would need to use 2 jQuery functions: .live() and .delegate. Both of them monitor DOM changes and rebind events to selectors when the DOM is changed.

You want click on a first li to expand dropdown menu - use

```<code>$('#categories li:first').live('click', function() {})
</code>```

this way clicking on a first li will trigger your handler, even if your li was just now moved to first position.

```<code>$('#categories').delegate('.dropdown a', 'click', functon(evt) {})
</code>```

This is an example of .delegate(). This means that when someone clicks element matching .dropdown a inside the #categories this handler will be called.

Here you can use .live() instead, but .delegate makes more sense. Instead of assigning (copying) event handler to all matching elements, we delegate all clicks to a single event handler.

I also updated "moving" code. Interesting side effect here, is that you don't need to .hide() dropdown inside the second handler. You see, when you click on a link inside dropdown, the link gets moved into first position. .live() detects that and assigns a click() handler to the link you just clicked. But event is still propagating, so after your second handler is finished, event bubbles up to li, and $('.li').live('click', ...) executes, hiding your dropdown div.

Hope this makes sense.

Body:
This is the HTML I'm working with:

Cargo Trailers

Utility Trailers

I have written a jQuery script to hide the dropdown div. The dropdown div appears the first time the click event is fired. Once the li in the dropdown div is selected and switches places with the first li in the #categories ul, clicking on the li will not bring up the dropdown div.

Here is the jQuery:

jQuery(document).ready(function($) {

// hide the dropdown div
$('#categories > div').hide();

/*
    Click the drop down arrow function
*/
var $listHeader = $('#categories > li');

$listHeader.click(function() {

    if ( $('#categories > div:hidden') ) {
        //show the drop down
        $('#categories > div').show();
    } else {
        //hide the drop down
        $('#categories > div').hide();
    }
});

/*
    Click a list-item in the drop down function
*/
$('#categories > div a').click(function() {

    /* actions to change the title to the newly selected item */
    // hide the ul
    $('#categories > div').hide();

    // move the clicked item to the header
    $(this).prependTo('#categories > li');

    // move the previous title to the dropdown and sort
    $('#categories > li > a:eq(1)').prependTo('#categories > div > ul > li:empty');

    // Reset the listHeader variable
    $listHeader = $('#categories > li');

    // cancel default browser action
    return false;

});
});

Body:
this $('#categories > div:hidden') will always return jQuery object (which evaluates to true), even if there are no elements matching selector. Use jQuery's .toggle() instead of if...else:

$('#categories > div').toggle();

here's an example to play with

Update in response to your comment: Updated example - http://jsfiddle.net/Etkjr/1/

You are correct, event handlers are unbound on DOM change. To prevent, that you would need to use 2 jQuery functions: .live() and .delegate. Both of them monitor DOM changes and rebind events to selectors when the DOM is changed.

You want click on a first li to expand dropdown menu - use

$('#categories li:first').live('click', function() {})

this way clicking on a first li will trigger your handler, even if your li was just now moved to first position.

$('#categories').delegate('.dropdown a', 'click', functon(evt) {})

This is an example of .delegate(). This means that when someone clicks element matching .dropdown a inside the #categories this handler will be called.

Here you can use .live() instead, but .delegate makes more sense. Instead of assigning (copying) event handler to all matching elements, we delegate all clicks to a single event handler.

I also updated "moving" code. Interesting side effect here, is that you don't need to .hide() dropdown inside the second handler. You see, when you click on a link inside dropdown, the link gets moved into first position. .live() detects that and assigns a click() handler to the link you just clicked. But event is still propagating, so after your second handler is finished, event bubbles up to li, and $('.li').live('click', ...) executes, hiding your dropdown div.

Hope this makes sense.


来源: stackexchange

问:
Can Firebase Crashlytics show events from Analytics?
I set up Firebase Analytics and Firebase Crashlytics for my project.

Can I view Analytics events and user properties in Firebase Crashlytics reports (including automatically collected events)?

Should I log events for Analytics and Crashlytics independently?

Should I set user properties for Analytics and customs keys for Crashlytics independently?

It looks like duplication.

答:
EDIT: Crashlytics is now able to show Analytics events.

ORIGINAL ANSWER:
Firebase Crash Reporting and Firebase Crashlytics are fully independent products, so you will have to deal with them separately.

Crashlytics currently is not able to show Analytics events in crash reports.  That is something the team would like to add in the future.

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
Can't install Nuget package "RestSharp"
I have to install the RestSharp NuGet package. But everytime i try to, these error shows up:

Installing via Console:

Or installing via the NuGet UI:

I need RestSharp for openALPR API.

Thanks for reading my question and maybe even anwsering it!

With best regards
Fabian Maurhart

答:
I don't think that this is an error specific to the Package... looks like you could be running a buggy version of NuGet or have a broken cache, found this as a reference, maybe the hints will help, even if this is a bit older.

Excerpt

Downloads:

https://dist.nuget.org/win-x86-commandline/latest/nuget.exe (or check here: https://dist.nuget.org/index.html)

You can run this from anywhere using command prompt or powershell.

Then you can run the following commands:

```<code>nuget.exe locals -clear global-packages
nuget.exe locals -clear packages-cache
nuget.exe locals -clear http-cache
</code>```

Thanks Seeker1437

Title: Can't install Nuget package "RestSharp"

Body:
I don't think that this is an error specific to the Package... looks like you could be running a buggy version of NuGet or have a broken cache, found this as a reference, maybe the hints will help, even if this is a bit older.

Excerpt

Downloads:

https://dist.nuget.org/win-x86-commandline/latest/nuget.exe (or check here: https://dist.nuget.org/index.html)

You can run this from anywhere using command prompt or powershell.

Then you can run the following commands:

nuget.exe locals -clear global-packages
nuget.exe locals -clear packages-cache
nuget.exe locals -clear http-cache

Thanks Seeker1437


问:
Want a Mysql SELECT query to returns string instead of numbers
I HAVE THIS QUERY

```<code>mysql> select suppliers.valid AS 'Supplier Status' from suppliers;
+-----------------+
| Supplier Status |
+-----------------+
|               0 |
|               0 |
|               0 |
|               0 |
|               0 |
|               0 |
|               1 |
|               1 |
|               1 |
|               1 |
|               1 |
|               1 |
|               1 |
|               1 |
|               1 |
+-----------------+
</code>```

I want the returned results to be  Supplier status is "valid" where "suppliers.valid > 0" and "invalid" where "suppliers.valid = 0".
Can someone  give me ideas  how to achieve this with mysql SQL query?

答:
You can use a CASE statement.

```<code>SELECT
    CASE
       WHEN `valid` > 0 THEN 'Valid'
       WHEN `valid` = 0 THEN 'Invalid'
       ELSE 'Error'
   END AS `Supplier_Status`
FROM
    `suppliers`;
</code>```

I would strongly advise against columns with spaces in them, so I added an underscore, but you can rename that to whatever you'd like.

Body:
I HAVE THIS QUERY

mysql> select suppliers.valid AS 'Supplier Status' from suppliers;
+-----------------+
| Supplier Status |
+-----------------+
|               0 |
|               0 |
|               0 |
|               0 |
|               0 |
|               0 |
|               1 |
|               1 |
|               1 |
|               1 |
|               1 |
|               1 |
|               1 |
|               1 |
|               1 |
+-----------------+

I want the returned results to be  Supplier status is "valid" where "suppliers.valid > 0" and "invalid" where "suppliers.valid = 0".
Can someone  give me ideas  how to achieve this with mysql SQL query?

Body:
You can use a CASE statement.

SELECT
    CASE
       WHEN `valid` > 0 THEN 'Valid'
       WHEN `valid` = 0 THEN 'Invalid'
       ELSE 'Error'
   END AS `Supplier_Status`
FROM
    `suppliers`;

I would strongly advise against columns with spaces in them, so I added an underscore, but you can rename that to whatever you'd like.


问:
How to use PHP function include_once() for form submission in other directory?
Please provide a temporary solution and depth related answer for my understanding.
I have a directory called /users/ with signup.html and /users/js/signup.js and /users/signup.php

On my home page i use php: include_once(signup.html) and then when I click the sign up button it uses the directory from the index.php directory.

Is there a function that would effectively include in path for the signup.html file?

/public_html/index.php

/public_html/users/signup.html

```<code><!DOCTYPE html>

<html>

<head>

    <title>Sign Up</title>

    <meta charset="UTF-8"><br>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>

</head>

<div class="container py-5">
    <div class="row">
        <div class="col-md-12">
            <h2 class="text-center text-white mb-4">Bootstrap 4 Login Form</h2>
            <div class="row">
                <div class="col-md-6 mx-auto">
                    <span class="anchor" id="formLogin"></span>

                    <div id="signupStatus"></div>
                <!--Card Sign Up !-->
                <div class="card rounded-0">
                    <div class="card-header">
                        <h3 class="mb-0">Sign Up</h3>
                    </div>
                    <div class="card-body">

                        <form id="signupForm" class="form" role="form" autocomplete="off" style="overflow: hidden">

                            <div class="signup form-group">
                                <label for="username">Username</label>
                                <input type="text" id="username" class="form-control form-control-lg rounded-0" name="username" placeholder="username"/>
                            </div>

                            <div class="signup form-group">
                                <label for="email">Email</label>
                                <input id="email" class="form-control form-control-lg rounded-0"  type="email" name="email" placeholder="email"/>
                            </div>

                            <div class="signup form-group">
                                <label for="password">Password</label>
                                <input id="password" class="form-control form-control-lg rounded-0"  type="password" name="password" placeholder="password"/>
                            </div>

                            <div class="signup"><input class="btn btn-success btn-lg float-right" type="button" id="signup" value="Sign up"/></div>

                            <div class="signup"><a href="http://woofwarrior.com/users/login.html">...already a user?</a></div>

                        </form>
                    </div>
                </div>
            </div>

</div>
        </div>
    </div>
</div>

<script type="text/javascript">

    users_dir = 'http://'+window.location.hostname+'/users/';

document.getElementById("signup").onclick = function(){

    var httpRequest;

    httpRequest = new XMLHttpRequest();

    if (!httpRequest) {

        console.log('Cannot create an XMLHTTP instance');

        return false;

    }else{

        httpRequest.onreadystatechange = alertContents;

        var formElement = document.getElementById('signupForm');

        var formData = new FormData(formElement);

        httpRequest.open("POST", users_dir+'signup.php');

        //console.log(formData);

        httpRequest.send(formData);

    }

    function alertContents() {

        if (httpRequest.readyState === XMLHttpRequest.DONE) {
            //console.log(httpRequest.status);

            if (httpRequest.status === 200) {

                //console.log("test123");

                var data = JSON.parse(httpRequest.responseText);

                //console.log(data);

                document.getElementById('signupStatus').innerHTML = data;

            }else{

                console.log('There was a problem with the request.');

            }

        }

    }

}
</code>```

答:
```<code><a href="<? $_SERVER['DOCUMENT_ROOT'].'/users/signup.html' ?>">click</a>
</code>```

Is this what you are asking?

Body:
Please provide a temporary solution and depth related answer for my understanding.
I have a directory called /users/ with signup.html and /users/js/signup.js and /users/signup.php

On my home page i use php: include_once(signup.html) and then when I click the sign up button it uses the directory from the index.php directory.

Is there a function that would effectively include in path for the signup.html file?

/public_html/index.php

/public_html/users/signup.html

<!DOCTYPE html>

    <title>Sign Up</title>

    <meta charset="UTF-8">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

Bootstrap 4 Login Form

Sign Up

                        <form id="signupForm" class="form" role="form" autocomplete="off" style="overflow: hidden">

                                Username
                                <input type="text" id="username" class="form-control form-control-lg rounded-0" name="username" placeholder="username"/>

                                Email
                                <input id="email" class="form-control form-control-lg rounded-0"  type="email" name="email" placeholder="email"/>

                                Password
                                <input id="password" class="form-control form-control-lg rounded-0"  type="password" name="password" placeholder="password"/>

<input class="btn btn-success btn-lg float-right" type="button" id="signup" value="Sign up"/>

...already a user?

                        </form>

Body:
<a href="<? $_SERVER['DOCUMENT_ROOT'].'/users/signup.html' ?>">click</a>

Is this what you are asking?


问:
Getting error " Attempted to read or write protected memory"
This is what is in the header file.

```<code>/// Creates a new file geodatabase in the specified location.
/// @param[in]    path The location where the geodatabase should be created.
/// @param[out]   geodatabase A reference to the newly-created geodatabase.
/// @return       A long integer indicating whether the method finished successfully.
EXT_FILEGDB_API long CreateGeodatabase(const std::wstring& path, Geodatabase& geodatabase);
</code>```

This is what my dllimport looks like.

```<code>[DllImport("FileGDBAPI.dll", EntryPoint = "#49", SetLastError=true, CallingConvention=CallingConvention.Winapi)]
        public static extern int CreateGeodatabase([MarshalAs(UnmanagedType.LPStr)]string path, ref IntPtr geodatabase);
</code>```

..and this is the code thats using it.

```<code>IntPtr Geodatabase = IntPtr.Zero;
                FileGDBAPI_wrapper.CreateGeodatabase("c:\temp\testGDB.gdb", ref Geodatabase);
</code>```

What am I doing wrong?

答:
If you are using .NET 4.0, try passing parameters without the ref keyword.

i.e.

FileGDBAPI_wrapper.CreateGeodatabase("c:\temp\testGDB.gdb", /ref/ Geodatabase);

and let me know if this works for you.

EDIT

Forget about my previous answer, I was typically ignorant.

I think you need to mark the Geodatabase as out instead of ref in both the declaration and invocation of the function; in this case you will NOT need to initialize your IntPtr before passing it to CreateGeodatabase()

I guess -and may be I am still ignorant - the problem related to declaring the Geodatabase argument in your library as a reference not as a pointer, that is, you can't pass null (IntPtr.Zero) to it, and typically, you don't need so, you need it as an out parameter.

ContentLicense: CC BY-SA 2.5

Body:
This is what is in the header file.

/// Creates a new file geodatabase in the specified location.
/// @param[in]    path The location where the geodatabase should be created.
/// @param[out]   geodatabase A reference to the newly-created geodatabase.
/// @return       A long integer indicating whether the method finished successfully.
EXT_FILEGDB_API long CreateGeodatabase(const std::wstring& path, Geodatabase& geodatabase);

This is what my dllimport looks like.

[DllImport("FileGDBAPI.dll", EntryPoint = "#49", SetLastError=true, CallingConvention=CallingConvention.Winapi)]
        public static extern int CreateGeodatabase([MarshalAs(UnmanagedType.LPStr)]string path, ref IntPtr geodatabase);

..and this is the code thats using it.

IntPtr Geodatabase = IntPtr.Zero;
                FileGDBAPI_wrapper.CreateGeodatabase("c:\temp\testGDB.gdb", ref Geodatabase);

What am I doing wrong?


问:
How to do a right unit test for the Presenter in MVP
I'm using the MVP pattern. And faced with a problem of covering the Presenter with unit testing.

Behavior:
View(Form) has two buttons on it - Ok and Apply.

If Ok button is pressed then the Data must be validated and in a case of success the Data must be saved and View must be closed.

If Apply button is pressed then the Data must be validated and in a case of success the Data must be saved then the Data must be reloaded and the View must be refreshed.

Presenter has two methods which are called by the View in case of Ok and Apply buttons are pressed. They are OkButtonPressed and ApllyButtonPressed respectively.

This is a pseudo code of the Presenter

```<code>private
  // view intreface
  View : IView;
  function TrySaveChanges: boolean {
    //Validate data by calling Model's methods
    //Save data by calling Model's methods
    // In case of any error call View to show an error message
  }
  function RefreshData: boolean {
    //Load data by calling Model's methods
  };
  function RefershView: boolean {
    //Call View's methods to refresh the data on it
  };

public
  procedure OkButtonPressed {
    if TrySaveChanges {
      View.Close;
    }
  }
  procedure ApplyButtonPressed {
    If TrySaveChanges {
      RefreshData;
      RefershView;
    }
  }
</code>```

How cover such code with unit test?
Roy Osherove says to test public methods as public methods call private ones. So via tests for public the behavior of private can be tested.
But in the example above few Presenter's public methods call the same private method.
What should exact be tested for the OkButtonPressed and ApplyButtonPressed methods?
Regarding to Roy behavior of TrySaveChanges must be tested in tests for OkButtonPressed and ApplyButtonPressed methods. But will this produce tests "duplicates"?
If I do not test the TrySaveChanges methods behavior in tests for OkButtonPressed and ApplyButtonPressed methods then where I should test it?
Maybe the problem is in the Presenter itself?

答:
I think you have a couple of options here:

extract TrySaveChanges into its own class / move that logic to the model.

accept that extracting common code into private methods will sometimes lead to executing those methods more than once in your tests.

To me, both would be perfectly fine.

Body:
I'm using the MVP pattern. And faced with a problem of covering the Presenter with unit testing.

Behavior:
View(Form) has two buttons on it - Ok and Apply.

If Ok button is pressed then the Data must be validated and in a case of success the Data must be saved and View must be closed.

If Apply button is pressed then the Data must be validated and in a case of success the Data must be saved then the Data must be reloaded and the View must be refreshed.

Presenter has two methods which are called by the View in case of Ok and Apply buttons are pressed. They are OkButtonPressed and ApllyButtonPressed respectively.

This is a pseudo code of the Presenter

private
  // view intreface
  View : IView;
  function TrySaveChanges: boolean {
    //Validate data by calling Model's methods
    //Save data by calling Model's methods
    // In case of any error call View to show an error message
  }
  function RefreshData: boolean {
    //Load data by calling Model's methods
  };
  function RefershView: boolean {
    //Call View's methods to refresh the data on it
  };

public
  procedure OkButtonPressed {
    if TrySaveChanges {
      View.Close;
    }
  }
  procedure ApplyButtonPressed {
    If TrySaveChanges {
      RefreshData;
      RefershView;
    }
  }

How cover such code with unit test?
Roy Osherove says to test public methods as public methods call private ones. So via tests for public the behavior of private can be tested.
But in the example above few Presenter's public methods call the same private method.
What should exact be tested for the OkButtonPressed and ApplyButtonPressed methods?
Regarding to Roy behavior of TrySaveChanges must be tested in tests for OkButtonPressed and ApplyButtonPressed methods. But will this produce tests "duplicates"?
If I do not test the TrySaveChanges methods behavior in tests for OkButtonPressed and ApplyButtonPressed methods then where I should test it?
Maybe the problem is in the Presenter itself?


问:
Eclipse keyboard command to add import statement
I am a C# developer who is doing some Android development in Eclipse. One of my favorite keyboard shortcuts in Visual Studio is CTRL + . which brings up the SmartTag menu. This is incredibly useful for adding using statements on the fly.

As an example if I don't have an import statement for System.Xml.Linq but create a variable of type XDocument I can quickly add the appropriate using with the keyboard command.

Is there a similar keyboard command available in Eclipse?

答: In Preferences->General->Key, you can have your bindings for shortcut key. This article: Eclipse Short Cut Keys lists some useful shortcuts. </p>


问:
How to Select ABS(Value) when a condition is being met in SQL Server 2014?

When an Account is 'PrePaid' (PlanCode = P0100) then the balance owing is in negative (eg; -100 if they are owing $100.

When an Account is 'PostPaid' (PlanCode = P0200) then the balance owing is positive (eg; 100 if they are owing $100)

Some PrePaid accounts are owed money to and hence show balance as positive (eg;  50 would mean that we owe them $50)

Some PostPaid Accounts are owed money too (as in they overpaid) and show balance as negative (eg; -50 would mean that we owe them $50)

I want to generate a report that shows all accounts that owe us $5 or more.

My code is wrong, but perhaps my logic is right?

```<code>SELECT A.[AccountId]
      ,A.[AccountNumber]
      ,CASE WHEN P.PlanCode = 'P0100' THEN 'PrePaid'
        WHEN P.PlanCode = 'P0200' THEN 'PostPaid'
       END PlanType
      ,CASE WHEN P.PlanCode = 'P0100' THEN (Select ABS(CurrentBalance) FROM Account WHERE CurrentBalance < 0)
        WHEN P.PlanCode = 'P0200' THEN (Select [CurrentBalance] FROM Account WHERE CurrentBalance > 0)
       END [CurrentBalance]

FROM [GEB_DWH].[dbo].[Account] A
INNER JOIN AccountPlan P ON A.AccountId = P.AccountId

WHERE A.CurrentBalance >= 5

ORDER BY CurrentBalance DESC
</code>```

EDIT:

I've also tried:

```<code>SELECT A.[AccountId]
      ,A.[AccountNumber]
      ,CASE WHEN P.PlanCode = 'P0100' THEN 'PrePaid'
        WHEN P.PlanCode = 'P0200' THEN 'PostPaid'
       END PlanType
      ,ABS([CurrentBalance])[CurrentBalance]
      --,CASE WHEN P.PlanCode = 'P0100' THEN (Select ABS(CurrentBalance) FROM Account WHERE CurrentBalance < 0)
        --WHEN P.PlanCode = 'P0200' THEN (Select [CurrentBalance] FROM Account WHERE CurrentBalance > 0)
      -- END [CurrentBalance]

FROM [GEB_DWH].[dbo].[Account] A
INNER JOIN AccountPlan P ON A.AccountId = P.AccountId

WHERE ((P.PlanCode = 'P0100' AND (A.CurrentBalance)  < 0) OR (P.PlanCode = 'P0200' AND (A.CurrentBalance)  > 0))
  AND A.CurrentBalance > 5

ORDER BY CurrentBalance DESC
</code>```

答:
If I understand correctly:</p>

```<code>WHERE (A.PlanCode = P0100 AND A.CurrentBalance >= 5) OR
      (A.PlanCode = P0200 AND A.CurrentBalance <= -5)
</code>```

Body:
When an Account is 'PrePaid' (PlanCode = P0100) then the balance owing is in negative (eg; -100 if they are owing $100.

When an Account is 'PostPaid' (PlanCode = P0200) then the balance owing is positive (eg; 100 if they are owing $100)

Some PrePaid accounts are owed money to and hence show balance as positive (eg;  50 would mean that we owe them $50)

Some PostPaid Accounts are owed money too (as in they overpaid) and show balance as negative (eg; -50 would mean that we owe them $50)

I want to generate a report that shows all accounts that owe us $5 or more.

My code is wrong, but perhaps my logic is right?

SELECT A.[AccountId]
      ,A.[AccountNumber]
      ,CASE WHEN P.PlanCode = 'P0100' THEN 'PrePaid'
        WHEN P.PlanCode = 'P0200' THEN 'PostPaid'
       END PlanType
      ,CASE WHEN P.PlanCode = 'P0100' THEN (Select ABS(CurrentBalance) FROM Account WHERE CurrentBalance < 0)
        WHEN P.PlanCode = 'P0200' THEN (Select [CurrentBalance] FROM Account WHERE CurrentBalance > 0)
       END [CurrentBalance]

FROM [GEB_DWH].[dbo].[Account] A
INNER JOIN AccountPlan P ON A.AccountId = P.AccountId

WHERE A.CurrentBalance >= 5

ORDER BY CurrentBalance DESC

EDIT:

I've also tried:

SELECT A.[AccountId]
      ,A.[AccountNumber]
      ,CASE WHEN P.PlanCode = 'P0100' THEN 'PrePaid'
        WHEN P.PlanCode = 'P0200' THEN 'PostPaid'
       END PlanType
      ,ABS([CurrentBalance])[CurrentBalance]
      --,CASE WHEN P.PlanCode = 'P0100' THEN (Select ABS(CurrentBalance) FROM Account WHERE CurrentBalance < 0)
        --WHEN P.PlanCode = 'P0200' THEN (Select [CurrentBalance] FROM Account WHERE CurrentBalance > 0)
      -- END [CurrentBalance]

FROM [GEB_DWH].[dbo].[Account] A
INNER JOIN AccountPlan P ON A.AccountId = P.AccountId

WHERE ((P.PlanCode = 'P0100' AND (A.CurrentBalance)  < 0) OR (P.PlanCode = 'P0200' AND (A.CurrentBalance)  > 0))
  AND A.CurrentBalance > 5

ORDER BY CurrentBalance DESC

Body:
If I understand correctly:

WHERE (A.PlanCode = P0100 AND A.CurrentBalance >= 5) OR
      (A.PlanCode = P0200 AND A.CurrentBalance <= -5)


问:
Create array from mixed floats and arrays Python
Let's say that I have an array x = np.random.normal(size=(300, 300)) and that I wish to create a diagonal matrix of size (2, 2, 300, 300) using x. My first approach was to just do

```<code>import numpy as np

x = np.random.normal(size=(300, 300))

array = np.array([
    [x, 0.],
    [0., x]
])
</code>```

However, when doing so I get an array of size (2, 2). Is there a numpy function for recasting the elements to the same size? Given that all the arrays of the list are the same shape, and that all other elements are floats.

Edit
I might add that just defining an empty array and setting the diagonal to x is not a solution.

Edit 2
Here's a sample

```<code>import numpy as np

x = np.random.normal(size=(3, 3))

array = np.zeros((2, 2, *x.shape))

array[0, 0] = array[1, 1] = x

print(array)
</code>```

Yielding

```<code>[[[[-1.57346701 -1.00813871 -0.72318135]
   [ 0.11852539  1.144298    1.38860739]
   [ 0.64571669  0.47474236  0.294049  ]]

  [[ 0.          0.          0.        ]
   [ 0.          0.          0.        ]
   [ 0.          0.          0.        ]]]

 [[[ 0.          0.          0.        ]
   [ 0.          0.          0.        ]
   [ 0.          0.          0.        ]]

  [[-1.57346701 -1.00813871 -0.72318135]
   [ 0.11852539  1.144298    1.38860739]
   [ 0.64571669  0.47474236  0.294049  ]]]]
</code>```

答:
For the case of first two dimension of the output having lengths as 2, the posted solution with -
 array[0, 0] = array[1, 1] = x would be fast and readable.

I would try to solve for generic lengths.

Approach #1 : Here's one approach with masking -

```<code>m = 2 # length along first two axes of o/p
out = np.zeros((m,m) + x.shape)
out[np.eye(m,dtype=bool)] =  x
</code>```

Approach #2 : Using assignment on first two axes merged view and thus avoiding the creation of any mask and leveraging fast sliced assignment -

```<code>out = np.zeros((m,m) + x.shape)
out.reshape((-1,) + x.shape)[::m+1] = x
</code>```

Generic pattern case

We would leverage np.broadcast_to to solve for such a case -

```<code>def resizer(tup):
    shp = x.shape
    out_shp = (len(tup), -1) + shp
    list_arrs = [np.broadcast_to(j, shp) for i in tup for j in i]
    return np.asarray(list_arrs).reshape(out_shp)
</code>```

Sample run -

```<code>In [121]: x
Out[121]:
array([[55, 58, 75],
       [78, 78, 20],
       [94, 32, 47]])

In [122]: array0 = [
     ...:     [x, 0, 1, 2],
     ...:     [1, 2, 0, x]
     ...: ]

In [123]: resizer(array0)
Out[123]:
array([[[[55, 58, 75],
         [78, 78, 20],
         [94, 32, 47]],

        [[ 0,  0,  0],
         [ 0,  0,  0],
         [ 0,  0,  0]],

        [[ 1,  1,  1],
         [ 1,  1,  1],
         [ 1,  1,  1]],

        [[ 2,  2,  2],
         [ 2,  2,  2],
         [ 2,  2,  2]]],
        .....

        [[55, 58, 75],
         [78, 78, 20],
         [94, 32, 47]]]])
</code>```

Body:
Let's say that I have an array x = np.random.normal(size=(300, 300)) and that I wish to create a diagonal matrix of size (2, 2, 300, 300) using x. My first approach was to just do

import numpy as np

x = np.random.normal(size=(300, 300))

array = np.array([
    [x, 0.],
    [0., x]
])

However, when doing so I get an array of size (2, 2). Is there a numpy function for recasting the elements to the same size? Given that all the arrays of the list are the same shape, and that all other elements are floats.

Edit
I might add that just defining an empty array and setting the diagonal to x is not a solution.

Edit 2
Here's a sample

import numpy as np

x = np.random.normal(size=(3, 3))

array = np.zeros((2, 2, *x.shape))

array[0, 0] = array[1, 1] = x

print(array)

Yielding

[[[[-1.57346701 -1.00813871 -0.72318135]
   [ 0.11852539  1.144298    1.38860739]
   [ 0.64571669  0.47474236  0.294049  ]]

  [[ 0.          0.          0.        ]
   [ 0.          0.          0.        ]
   [ 0.          0.          0.        ]]]

 [[[ 0.          0.          0.        ]
   [ 0.          0.          0.        ]
   [ 0.          0.          0.        ]]

  [[-1.57346701 -1.00813871 -0.72318135]
   [ 0.11852539  1.144298    1.38860739]
   [ 0.64571669  0.47474236  0.294049  ]]]]

Body:
For the case of first two dimension of the output having lengths as 2, the posted solution with -
 array[0, 0] = array[1, 1] = x would be fast and readable.

I would try to solve for generic lengths.

Approach #1 : Here's one approach with masking -

m = 2 # length along first two axes of o/p
out = np.zeros((m,m) + x.shape)
out[np.eye(m,dtype=bool)] =  x

Approach #2 : Using assignment on first two axes merged view and thus avoiding the creation of any mask and leveraging fast sliced assignment -

out = np.zeros((m,m) + x.shape)
out.reshape((-1,) + x.shape)[::m+1] = x

Generic pattern case

We would leverage np.broadcast_to to solve for such a case -

def resizer(tup):
    shp = x.shape
    out_shp = (len(tup), -1) + shp
    list_arrs = [np.broadcast_to(j, shp) for i in tup for j in i]
    return np.asarray(list_arrs).reshape(out_shp)

Sample run -

In [121]: x
Out[121]:
array([[55, 58, 75],
       [78, 78, 20],
       [94, 32, 47]])

In [122]: array0 = [
     ...:     [x, 0, 1, 2],
     ...:     [1, 2, 0, x]
     ...: ]

In [123]: resizer(array0)
Out[123]:
array([[[[55, 58, 75],
         [78, 78, 20],
         [94, 32, 47]],

        [[ 0,  0,  0],
         [ 0,  0,  0],
         [ 0,  0,  0]],

        [[ 1,  1,  1],
         [ 1,  1,  1],
         [ 1,  1,  1]],

        [[ 2,  2,  2],
         [ 2,  2,  2],
         [ 2,  2,  2]]],
        .....

        [[55, 58, 75],
         [78, 78, 20],
         [94, 32, 47]]]])


问:
Scala, Either[_, Seq[Either[_, T]] to Either[_, Seq[T]]
Here's the scaste for the code below: https://scastie.scala-lang.org/bQMGrAKgRoOFaK1lwCy04g

I've a two JSON API endpoints. First, items.cgi, returns list of item objects in the following format

```<code>$ curl http://example.com/items.cgi
[
    ...
    { sn: "KXB1333", ownerId: 3, borrowerId: 0 },
    { sn: "KCB1200", ownerId: 1, borrowerId: 2 },
    ...
]
</code>```

borrowerId == 0 means item has no borrower.

Second, users.cgi, returns user specified by id query parameter

```<code>$ curl http://example.com/user.cgi?id=1
{ id: 1, name: "frank" }
</code>```

The API may be bad but I have to deal with it. Now in Scala I'd like to work with this nice data model

```<code>case class User(id: Int, name: String)
case class Item(sn: String, owner: User, borrower: Option[User])
</code>```

I also have the following for doing HTTP requests

```<code>case class ApiFail(reason: String)
def get[T](url: String): Either[ApiFail, T] = ??? /* omitted for brevity */
</code>```

The get() function uses some magic to fetch a JSON from an URL and construct a T out of it (it uses some libraries). On IO failure or bad HTTP status it returns Left.

I'd like to write the following function

```<code>def getItems: Either[ApiFail, Seq[Item]]
</code>```

It should fetch the list of items, for each item fetch the linked users and return a new list of Items or fail on any HTTP request failure. (There may be redundant requests for users with a same ID but I don't care about memoization/caching yet.)

So far I only managed to write this function

```<code>def getItems: Either[ApiFail, Seq[Either[ApiFail, Item]]]
</code>```

where a failure to retrieve some user is fatal only for the corresponding item and not the whole result. Here's the implementation

```<code>def getItems: Either[ApiFail, Seq[Either[ApiFail, Item]]] = {
    case class ItemRaw(sn: String, ownerId: Int, borrowerId: Int)

    get[List[ItemRaw]]("items.cgi").flatMap(itemRawList => Right(
        itemRawList.map(itemRaw => {
            for {
                owner <- get[User](s"users.cgi?id=${itemRaw.ownerId}")
                borrower <-
                    if (itemRaw.borrowerId > 0)
                        get[User](s"users.cgi?id=${itemRaw.borrowerId}").map(Some(_))
                    else
                        Right(None)
            } yield
                Item(itemRaw.sn, owner, borrower)
        })
    ))
}
</code>```

This seems like a request for a homework but it occurs to me frequently that I want to switch from one wrapper thing (m-monad?) to another and I'm a bit puzzled as to how to do it with wrapper functions (c-combinators?) only. I could of course switch to an imperative implementation. I'm just curious.

答:
There is a word for doing exactly this in the FP world - "Traverse" (link to cats implementation). It's used when you have an F[A] and a function A => G[B] and you want a G[F[B]]. Here, F is List, A is ItemRaw, G is Either[ApiFail, _], and B is Item. Of course there are some constraints on what F and G can be.

Using cats, you can change your method very slightly:

```<code>import cats._, cats.implicits._

def getItems: Either[ApiFail, Seq[Item]] = {
  case class ItemRaw(sn: String, ownerId: Int, borrowerId: Int)

  get[List[ItemRaw]]("items.cgi").flatMap(itemRawList =>
    itemRawList.traverse[({type T[A]=Either[ApiFail, A]})#T, Item](itemRaw => {
      for {
        owner <- get[User](s"users.cgi?id=${itemRaw.ownerId}")
        borrower <-
          if (itemRaw.borrowerId > 0)
            get[User](s"users.cgi?id=${itemRaw.borrowerId}").map(Some(_))
          else
            Right(None)
      } yield
        Item(itemRaw.sn, owner, borrower)
    })
  )
}
</code>```

With that said, I can certainly understand being hesitant to go fully down that route. cats (and scalaz) are a lot to take in - though I recommend you do at some point!

Without them, you can always write your own utility methods for manipulating your commonly-used containers:

```<code>def seqEither2EitherSeq[A, B](s: Seq[Either[A, B]]): Either[A, Seq[B]] = {
  val xs: Seq[Either[A, Seq[B]]] = s.map(_.map(b => Seq(b)))
  xs.reduce{ (e1, e2) => for (x1 <- e1; x2 <- e2) yield x1 ++ x2 }
}

def flattenEither[A, B](e: Either[A, Either[A, B]]): Either[A, B] = e.flatMap(identity)
</code>```

Then the result you want would be:

```<code>val result: Either[ApiFail, Seq[Item]] = flattenEither(getItems.map(seqEither2EitherSeq))
</code>```

Body:
Here's the scaste for the code below: https://scastie.scala-lang.org/bQMGrAKgRoOFaK1lwCy04g

I've a two JSON API endpoints. First, items.cgi, returns list of item objects in the following format

$ curl http://example.com/items.cgi
[
    ...
    { sn: "KXB1333", ownerId: 3, borrowerId: 0 },
    { sn: "KCB1200", ownerId: 1, borrowerId: 2 },
    ...
]

borrowerId == 0 means item has no borrower.

Second, users.cgi, returns user specified by id query parameter

$ curl http://example.com/user.cgi?id=1
{ id: 1, name: "frank" }

The API may be bad but I have to deal with it. Now in Scala I'd like to work with this nice data model

case class User(id: Int, name: String)
case class Item(sn: String, owner: User, borrower: Option[User])

I also have the following for doing HTTP requests

case class ApiFail(reason: String)
def get[T](url: String): Either[ApiFail, T] = ??? /* omitted for brevity */

The get() function uses some magic to fetch a JSON from an URL and construct a T out of it (it uses some libraries). On IO failure or bad HTTP status it returns Left.

I'd like to write the following function

def getItems: Either[ApiFail, Seq[Item]]

It should fetch the list of items, for each item fetch the linked users and return a new list of Items or fail on any HTTP request failure. (There may be redundant requests for users with a same ID but I don't care about memoization/caching yet.)

So far I only managed to write this function

def getItems: Either[ApiFail, Seq[Either[ApiFail, Item]]]

where a failure to retrieve some user is fatal only for the corresponding item and not the whole result. Here's the implementation

def getItems: Either[ApiFail, Seq[Either[ApiFail, Item]]] = {
    case class ItemRaw(sn: String, ownerId: Int, borrowerId: Int)

    get[List[ItemRaw]]("items.cgi").flatMap(itemRawList => Right(
        itemRawList.map(itemRaw => {
            for {
                owner <- get[User](s"users.cgi?id=${itemRaw.ownerId}")
                borrower <-
                    if (itemRaw.borrowerId > 0)
                        get[User](s"users.cgi?id=${itemRaw.borrowerId}").map(Some(_))
                    else
                        Right(None)
            } yield
                Item(itemRaw.sn, owner, borrower)
        })
    ))
}

This seems like a request for a homework but it occurs to me frequently that I want to switch from one wrapper thing (m-monad?) to another and I'm a bit puzzled as to how to do it with wrapper functions (c-combinators?) only. I could of course switch to an imperative implementation. I'm just curious.

Body:
There is a word for doing exactly this in the FP world - "Traverse" (link to cats implementation). It's used when you have an F[A] and a function A => G[B] and you want a G[F[B]]. Here, F is List, A is ItemRaw, G is Either[ApiFail, _], and B is Item. Of course there are some constraints on what F and G can be.

Using cats, you can change your method very slightly:

import cats._, cats.implicits._

def getItems: Either[ApiFail, Seq[Item]] = {
  case class ItemRaw(sn: String, ownerId: Int, borrowerId: Int)

  get[List[ItemRaw]]("items.cgi").flatMap(itemRawList =>
    itemRawList.traverse[({type T[A]=Either[ApiFail, A]})#T, Item](itemRaw => {
      for {
        owner <- get[User](s"users.cgi?id=${itemRaw.ownerId}")
        borrower <-
          if (itemRaw.borrowerId > 0)
            get[User](s"users.cgi?id=${itemRaw.borrowerId}").map(Some(_))
          else
            Right(None)
      } yield
        Item(itemRaw.sn, owner, borrower)
    })
  )
}

With that said, I can certainly understand being hesitant to go fully down that route. cats (and scalaz) are a lot to take in - though I recommend you do at some point!

Without them, you can always write your own utility methods for manipulating your commonly-used containers:

def seqEither2EitherSeq[A, B](s: Seq[Either[A, B]]): Either[A, Seq[B]] = {
  val xs: Seq[Either[A, Seq[B]]] = s.map(_.map(b => Seq(b)))
  xs.reduce{ (e1, e2) => for (x1 <- e1; x2 <- e2) yield x1 ++ x2 }
}

def flattenEither[A, B](e: Either[A, Either[A, B]]): Either[A, B] = e.flatMap(identity)

Then the result you want would be:

val result: Either[ApiFail, Seq[Item]] = flattenEither(getItems.map(seqEither2EitherSeq))


问:
Qulatrics Help: loop and merge once, and then never present this loop again
I have run into an issue with the loop and merge function in Qualtrics. I have 8,000 loops set up, and I am presenting one of those loops randomly to each participant.

When this one loop is presented, I need Qualtrics to NEVER present this loop again. I am not sure how to accomplish this?

I know I can simply separate my 8,000 loops into individual questions and randomize and evenly present in the block options, however 8,000 questions is a lot to compile.

I believe there is a way of doing this in Qualtrics perhaps using javascript?

Can anyone help?

I have also thought of embedding data, and keeping a counter of the question that was presented, but this seemed to be more complex than I originally thought.

All help is appreciated!

答:
JavaScript isn't going to help select your choices.  Here is the easiest approach...

Before your Loop & Merge block set up an MC question with your 8,000 choices, then use Advanced Randomization to randomly insert a subset of 1 from the 8,000 choices, and check the "Evenly Present Elements" box. Use JavaScript to hide the MC question. If it is on the same page as another question, you can hide it with one line of JavaScript since you won't need to automatically click the Next button:

```<code>$(this.questionId).hide();
</code>```

Set up your Loop & Merge block to loop based on the displayed options in the hidden MC question.

Body:
JavaScript isn't going to help select your choices.  Here is the easiest approach...

Before your Loop & Merge block set up an MC question with your 8,000 choices, then use Advanced Randomization to randomly insert a subset of 1 from the 8,000 choices, and check the "Evenly Present Elements" box. Use JavaScript to hide the MC question. If it is on the same page as another question, you can hide it with one line of JavaScript since you won't need to automatically click the Next button:

$(this.questionId).hide();

Set up your Loop & Merge block to loop based on the displayed options in the hidden MC question.


问:
MyBatis and SQL, best performance query
I would know that is the best way to do a query linke the following. I need to optimize performances and to avoid useless operation in the DB (postgresql).

User will input a series of filters, which are a couple of values ("id_meta" and "value"), which will reduce the numbers of rows I exctract from "meta" table. Those fields are not PK.

Here is an example, the table has more column, but those are the interested ones.

```<code>| id_meta | value      | id_ud |
| ------- |:----------:| -----:|
| 1       | pippo      | 45    |
| 2       | 10         | 45    |
| 3       | 21/05/2010 | 45    |
| 1       | pluto      | 35    |
| 2       | 14         | 35    |
| 3       | 22/05/2010 | 35    |
</code>```

and so on... if users inputs the couple (1:pippo) and (2:14) the query will return 0 rows, because there is not a (2:14) for the id_ud returned by the first filter (45).

it can't give different values for the same id_meta at the same time, things like (1:pippo) AND (1:pluto) are not possible

So basically every couple of filters is a nested subqueries, which reduce the numbers of the first result set. If user will give 3 filters, I would do 3 subqueries

```<code>select id_ud
from meta
where id_meta = 12
      and value = '45'
      and id_ud in (select id_ud
                    from meta
                    where id_meta = 10
                    and value = 1000
                    and id_ud in (select id_ud
                                  from meta
                                  where id_meta = 6
                                  and value = 'll'
                                 )
                   )
</code>```

I need to count the number of the returned rows AND I have another condition

```<code>select count(id_ud)
from meta
where id_ud in (select ID_UD
                from documento
                where stato = 'ACHIVIATO'
                and id_cat_doc = 2)
and value= '2010'
and id_meta = 12 and id_ud in (select id_ud
                               from meta
                               where id_meta = 10
                               and value = 1000
                               and id_ud in (select id_ud
                                             from meta
                                             where id_meta = 6
                                             and value = 'll'
                                             )
                              );
</code>```

So basically I have to dinamically create a nested subqueries with MyBatis and count the returned values, as the last example above. Is there a way to avoid all that subqueries, pheraps using ANY, ALL, UNION or other SQL constructs ?

Thanks, please feel free to add more detail, I'm not sure i explained clearly my problem...

UPDATE

I'm trying to build this query with mybatis

```<code>    select
        count (id_ud)
    from
        documento
    where
        stato = 'ARCHIVIATO'
        and id_categoria_documentale = #{param2, jdbcType=BIGINT}
        <foreach item="value" index="key" collection="param1.entrySet()" open=" and id_ud in ("
            separator=" and id_ud in (" close="))">
            select
                id_ud
            from
                meta
            where
                id_meta = #{key, jdbcType=INTEGER}
                and value = #{value, jdbcType=VARCHAR}
        </foreach>
</code>```

Where param1 is the map object containing all the user filters. I have problems adding the correct numbers of closing )... Any Ideas ?

答:
Your query is more or less identical to tag search, fulltext search, or dating search. Therefore it makes sense to use a search method already optimized for such cases.

Fulltext, which fortunately postgres supports, seems a good match.

I suggest coalescing the whole "meta" table into a column in the table "documento" which would represent the tags. Let's name this column... "tags."

It would contain "1=pippo 2=14 3=21/05/2010" for id_ud=45

You will probably have to use something other than a ":", disable lexing and other fancy options etc, in order to convince the full text search engine to consider your tokens as "words".

This should be quite fast.

Another option, since you have dates, is to give these dates real columns in the table "documento". For example if you have a publication date, why not put it in a column with an index on it? This will also allow range (date BETWEEN ... AND ...) searches. Relational databases like to have their data in columns... it's the standard, and also the most efficient... "meta" tables like you have are always cumbersome.

Multiple independent column indexes can be combined using a bitmap index scan, which is quite fast.

Another approach is to put the tags inside the "documento" table, but inside a hstore. This way all the tags for one record are on the same line, and you can use partial index on the keys in the hstore.

Title: MyBatis and SQL, best performance query

Body:
I would know that is the best way to do a query linke the following. I need to optimize performances and to avoid useless operation in the DB (postgresql).

User will input a series of filters, which are a couple of values ("id_meta" and "value"), which will reduce the numbers of rows I exctract from "meta" table. Those fields are not PK.

Here is an example, the table has more column, but those are the interested ones.

| id_meta | value      | id_ud |
| ------- |:----------:| -----:|
| 1       | pippo      | 45    |
| 2       | 10         | 45    |
| 3       | 21/05/2010 | 45    |
| 1       | pluto      | 35    |
| 2       | 14         | 35    |
| 3       | 22/05/2010 | 35    |

and so on... if users inputs the couple (1:pippo) and (2:14) the query will return 0 rows, because there is not a (2:14) for the id_ud returned by the first filter (45).

it can't give different values for the same id_meta at the same time, things like (1:pippo) AND (1:pluto) are not possible

So basically every couple of filters is a nested subqueries, which reduce the numbers of the first result set. If user will give 3 filters, I would do 3 subqueries

select id_ud
from meta
where id_meta = 12
      and value = '45'
      and id_ud in (select id_ud
                    from meta
                    where id_meta = 10
                    and value = 1000
                    and id_ud in (select id_ud
                                  from meta
                                  where id_meta = 6
                                  and value = 'll'
                                 )
                   )

I need to count the number of the returned rows AND I have another condition

select count(id_ud)
from meta
where id_ud in (select ID_UD
                from documento
                where stato = 'ACHIVIATO'
                and id_cat_doc = 2)
and value= '2010'
and id_meta = 12 and id_ud in (select id_ud
                               from meta
                               where id_meta = 10
                               and value = 1000
                               and id_ud in (select id_ud
                                             from meta
                                             where id_meta = 6
                                             and value = 'll'
                                             )
                              );

So basically I have to dinamically create a nested subqueries with MyBatis and count the returned values, as the last example above. Is there a way to avoid all that subqueries, pheraps using ANY, ALL, UNION or other SQL constructs ?

Thanks, please feel free to add more detail, I'm not sure i explained clearly my problem...

UPDATE

I'm trying to build this query with mybatis

    select
        count (id_ud)
    from
        documento
    where
        stato = 'ARCHIVIATO'
        and id_categoria_documentale = #{param2, jdbcType=BIGINT}
        <foreach item="value" index="key" collection="param1.entrySet()" open=" and id_ud in ("
            separator=" and id_ud in (" close="))">
            select
                id_ud
            from
                meta
            where
                id_meta = #{key, jdbcType=INTEGER}
                and value = #{value, jdbcType=VARCHAR}
        </foreach>

Where param1 is the map object containing all the user filters. I have problems adding the correct numbers of closing )... Any Ideas ?


问:
Configure list of servers for devpi
I am running a devpi-server locally in my laptop, so that I can work offline whenever I have no internet connection (this only works if devpi has had the chance to locally cache the packages that I need, of course)

Currently I have the devpi-server configured with default settings, so that it is looking for packages in the standard PyPi.

I would like to configure the devpi-server to use a list of servers to find packages:

a private PyPi server, where we are publishing our internal libraries: http://xx.xx.xx.xx:yyyyy/simple/

the standard PyPi servers, for the usual Python ecosystem: https://www.python.org/pypi

Question: is it possible to configure devpi with a list of servers to try?

I do not find this option in the devpi documentation.

Packages should be search in the list of servers: if a package is not found in the first server, it should look for it in the second, until the end of the list is reached and a "not found" message is replied.

答:
You can do this by combining Devpi's index mirroring and the index inheritance feature.

Assuming you have a user bob on your Devpi server,

create an index mirroring your private server: devpi index -c private type=mirror mirror_url=http://xx.xx.xx.xx:yyyyy/simple/.

Create an index inheriting from /root/pypi and the newly created mirror: devpi index -c all bases=/bob/all,/root/pypi

Afterwards you should be able to get all packages from /bob/all.

Title: Configure list of servers for devpi


问:
Disabled input still focusable in Firefox
Minimal example

let input = document.createElement("input");
input.id = "input";
input.type = "number";
input.className = "number-input";
input.disabled = true;
document.body.appendChild(input);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.number-input:focus {
  background: yellow;
}
.number-input {
  -moz-appearance: textfield;
} </code>```

<button onClick="document.getElementById('input').disabled = false">
Enable
</button>

<button onClick="document.getElementById('input').disabled = true">
Disable
</button>```

The created input is semi-disabled on start, i. e. you can click on it and it turns yellow (gets focus), but you can't write a number into it. However after clicking Enable followed by Disable button, it is as disabled as expected. It seems to be a bug that involves the input.type = "number" and the browser specific -moz-appearance: textfield, that I use to hide the up and down buttons.

Any ideas how to really disable the input field, when the page is loaded?

答:
In Firefox it helps me to set disabled as input.disabled. Don't ask me why :-)

let input = document.createElement("input");
input.id = "input";
input.type = "number";
input.className = "number-input";
input.disabled; // here instead of input.disabled = true
document.body.appendChild(input);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.number-input:focus {
  background: yellow;
}
.number-input {
  -moz-appearance: textfield;
} </code>```

<button onClick="document.getElementById('input').disabled = false">
Enable
</button>

<button onClick="document.getElementById('input').disabled = true">
Disable
</button>```

Body:
Minimal example

let input = document.createElement("input");
input.id = "input";
input.type = "number";
input.className = "number-input";
input.disabled = true;
document.body.appendChild(input);

.number-input:focus {
  background: yellow;
}
.number-input {
  -moz-appearance: textfield;
}

<button onClick="document.getElementById('input').disabled = false">
Enable
</button>

<button onClick="document.getElementById('input').disabled = true">
Disable
</button>

The created input is semi-disabled on start, i. e. you can click on it and it turns yellow (gets focus), but you can't write a number into it. However after clicking Enable followed by Disable button, it is as disabled as expected. It seems to be a bug that involves the input.type = "number" and the browser specific -moz-appearance: textfield, that I use to hide the up and down buttons.

Any ideas how to really disable the input field, when the page is loaded?

Body:
In Firefox it helps me to set disabled as input.disabled. Don't ask me why :-)

let input = document.createElement("input");
input.id = "input";
input.type = "number";
input.className = "number-input";
input.disabled; // here instead of input.disabled = true
document.body.appendChild(input);

.number-input:focus {
  background: yellow;
}
.number-input {
  -moz-appearance: textfield;
}

<button onClick="document.getElementById('input').disabled = false">
Enable
</button>

<button onClick="document.getElementById('input').disabled = true">
Disable
</button>


问:
Flex datagrid component problem
Guys I've a grid view in flex,

one of the columns is rendered like this:

```<code><mx:DataGridColumn headerText="Cancel"  >
      <mx:itemRenderer>
       <fx:Component>
        <mx:Box width="100%" height="100%" horizontalAlign="center" verticalAlign="middle">
         <mx:Button label="Download" width="100%"  >
          <mx:click>someFunction();</mx:click>
         </mx:Button>
        </mx:Box>
       </fx:Component>
      </mx:itemRenderer>
      </mx:DataGridColumn>
</code>```

now I've a problem that the function in button click is not being recognized. It says "call to a possibly undefined function" even though it was defined. What is wrong with this? How do i make a button in a grid call a function in the same mxml file??

thanks

答:
Your itemRenderer is considered its own encapsulated component so it's looking for someFunction() within the itemRenderer itself. To call a function you have defined in the mxml file that contains your DataGrid, try calling the function using outerDocument.someFunction();.

If you would like to define the function at the itemRenderer level, you could do something like this:

```<code><mx:itemRenderer>
  <fx:Component>
    <mx:VBox>
      <fx:Script>
      <![CDATA[

        public function someFunction():void
        {
          // Do Something
        }

      ]]>
      </fx:Script>

      <mx:Button click="someFunction();"/>
    </mx:VBox>
  </fx:Component>
</mx:itemRenderer>
</code>```

Title: Flex datagrid component problem

Body:
Guys I've a grid view in flex,

one of the columns is rendered like this:

<mx:DataGridColumn headerText="Cancel"  >
      <mx:itemRenderer>
       <fx:Component>
        <mx:Box width="100%" height="100%" horizontalAlign="center" verticalAlign="middle">
         <mx:Button label="Download" width="100%"  >
          <mx:click>someFunction();</mx:click>
         </mx:Button>
        </mx:Box>
       </fx:Component>
      </mx:itemRenderer>
      </mx:DataGridColumn>

now I've a problem that the function in button click is not being recognized. It says "call to a possibly undefined function" even though it was defined. What is wrong with this? How do i make a button in a grid call a function in the same mxml file??

thanks

Body:
Your itemRenderer is considered its own encapsulated component so it's looking for someFunction() within the itemRenderer itself. To call a function you have defined in the mxml file that contains your DataGrid, try calling the function using outerDocument.someFunction();.

If you would like to define the function at the itemRenderer level, you could do something like this:

<mx:itemRenderer>
  <fx:Component>
    <mx:VBox>
      <fx:Script>
      <![CDATA[

        public function someFunction():void
        {
          // Do Something
        }

      ]]>
      </fx:Script>

      <mx:Button click="someFunction();"/>
    </mx:VBox>
  </fx:Component>
</mx:itemRenderer>


问:
Shiny dashboard and DT table not showing
I have a dashboard where I would like to show a table, but I cant figure out why my table is not showing. If I replace the table for example with some text, h2(....) it does show. I would like to click on "Species" and have the table show on the right when clicking it.

```<code>library(shiny)
library(shinydashboard)
library(shinyWidgets)
library(DT)

ui <- dashboardPage(
  dashboardHeader(title = "Basic dashboard"),
  dashboardSidebar(sidebarMenu(
    menuItem(
      "Species",
      tabName = "Species",
      icon = NULL,
      switchInput(
        inputId = "long1",
        onLabel = "Go",
        offLabel = "NoGo",
        value = T
      ),
      actionButton("Gobtn", "Get data"),
      menuItem("Specs", tabName = "Specs", icon = NULL)
    )
  )),

  dashboardBody(tabItems(
    tabItem(tabName = "Species",
            DT::renderDataTable("Table1")),
    tabItem(tabName = "Specs",
            h2("Hi"))
  ))
)
</code>```

server.r

```<code>  server <- shinyServer(function(input, output, session) {
  output$Table1 <- DT::renderDataTable({
    iris
  })
})

shinyApp(ui, server)
</code>```

答:
You need to change/add some part of the dashboardBody, see Using shiny modules and shinydashboard: shiny.tag error

```<code>library(shiny)
library(shinydashboard)
library(shinyWidgets)
library(DT)

ui <- dashboardPage(
  dashboardHeader(title = "Basic dashboard"),
  dashboardSidebar(sidebarMenu(
    menuItem(
      "Species",
      tabName = "Species",
      icon = NULL,

      switchInput(
        inputId = "long1",
        onLabel = "Go",
        offLabel = "NoGo",
        value = T
      ),
      actionButton("Gobtn", "Get data")
    )
  )),

  dashboardBody(tags$div(
    tabName = "Species",
    fluidRow(box(DT::dataTableOutput("Table1"))), class = "tab-content"
  ))
  )
</code>```

server.r

```<code>server <- shinyServer(function(input, output, session) {
  output$Table1 <- DT::renderDataTable({
    iris
  })
})

shinyApp(ui, server)
</code>```

Body:
I have a dashboard where I would like to show a table, but I cant figure out why my table is not showing. If I replace the table for example with some text, h2(....) it does show. I would like to click on "Species" and have the table show on the right when clicking it.

library(shiny)
library(shinydashboard)
library(shinyWidgets)
library(DT)

ui <- dashboardPage(
  dashboardHeader(title = "Basic dashboard"),
  dashboardSidebar(sidebarMenu(
    menuItem(
      "Species",
      tabName = "Species",
      icon = NULL,
      switchInput(
        inputId = "long1",
        onLabel = "Go",
        offLabel = "NoGo",
        value = T
      ),
      actionButton("Gobtn", "Get data"),
      menuItem("Specs", tabName = "Specs", icon = NULL)
    )
  )),

  dashboardBody(tabItems(
    tabItem(tabName = "Species",
            DT::renderDataTable("Table1")),
    tabItem(tabName = "Specs",
            h2("Hi"))
  ))
)

server.r

  server <- shinyServer(function(input, output, session) {
  output$Table1 <- DT::renderDataTable({
    iris
  })
})

shinyApp(ui, server)

Body:
You need to change/add some part of the dashboardBody, see Using shiny modules and shinydashboard: shiny.tag error

library(shiny)
library(shinydashboard)
library(shinyWidgets)
library(DT)

ui <- dashboardPage(
  dashboardHeader(title = "Basic dashboard"),
  dashboardSidebar(sidebarMenu(
    menuItem(
      "Species",
      tabName = "Species",
      icon = NULL,

      switchInput(
        inputId = "long1",
        onLabel = "Go",
        offLabel = "NoGo",
        value = T
      ),
      actionButton("Gobtn", "Get data")
    )
  )),

  dashboardBody(tags$div(
    tabName = "Species",
    fluidRow(box(DT::dataTableOutput("Table1"))), class = "tab-content"
  ))
  )

server.r

server <- shinyServer(function(input, output, session) {
  output$Table1 <- DT::renderDataTable({
    iris
  })
})

shinyApp(ui, server)


问:
In Python 3.6, how can I convert an unknown string to a set?

I want the program to read an input. Unless the input is "HELP", it consists of several integers separated by spaces. I don't know the number of integers provided.

I want the integers to be placed in a set.

This is the code I am currently using, but it takes a long time and I am looking for a faster method.

```<code>nextInput = input()
while nextInput != "HELP":
    testString = set()
    testString1 = nextInput.split()
    for j in range(0, len(testString1)):
        k = int(testString1[j])
        testString.add(k)
    nextInput = input()
</code>```

答:
Notice that set() accepts an iterable as parameter, so you can replace the whole body of your while with

```<code>testString = set(nextInput.split())
</code>```

Edit: If you need to have a set of numbers (which wasn't clear in the original question, specially as the variable name was "testString"; I will change the name of the variable for my own sanity) replace that line with

```<code>numset = set(int(_) for _ in nexInput.split())
</code>```

Below that, of course, you should add the line to ask for the next input.

Of course, if you want to be fully pythonic you would ask the input only once, you would do:

```<code>while True:
  nextInput = input()
  if nextInput == 'HELP':
    break
  numset = set(int(_) for _ in nexInput.split())
</code>```

Body:
I want the program to read an input. Unless the input is "HELP", it consists of several integers separated by spaces. I don't know the number of integers provided.

I want the integers to be placed in a set.

This is the code I am currently using, but it takes a long time and I am looking for a faster method.

nextInput = input()
while nextInput != "HELP":
    testString = set()
    testString1 = nextInput.split()
    for j in range(0, len(testString1)):
        k = int(testString1[j])
        testString.add(k)
    nextInput = input()

Body:
Notice that set() accepts an iterable as parameter, so you can replace the whole body of your while with

testString = set(nextInput.split())

Edit: If you need to have a set of numbers (which wasn't clear in the original question, specially as the variable name was "testString"; I will change the name of the variable for my own sanity) replace that line with

numset = set(int(_) for _ in nexInput.split())

Below that, of course, you should add the line to ask for the next input.

Of course, if you want to be fully pythonic you would ask the input only once, you would do:

while True:
  nextInput = input()
  if nextInput == 'HELP':
    break
  numset = set(int(_) for _ in nexInput.split())


问:
How can I force an HTML5 audio element to buffer an entire song?
I'm developing a local server that will stream a user's audio files so they can access them via web browsers using the HTML5 audio object. Since these files are on the user's computer, I expect the files to be buffered completely when they are loaded, but for certain large files, the songs get buffered part of the way, then stop, and resume buffering some time later.

My question is: how can I force the audio object to buffer the entire song at once? Can I do this from javascript, do I have to set an attribute on the audio object, or is there anything else I can do?

答: You could set the preload="auto" attribute. It's not guaranteed to do anything, but it's supposed to tell the user agent to buffer as much as it wants without concern for the remote end. http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html#attr-media-preload</p>


问:
SQL Error - The multi-part identifier "CF.OBJ" could not be bound
Im getting an error on multi part identifier for Sub query join. Please help. Following is the code I have written

```<code>SELECT CORE.BC_NUMBER AS BC,SEG.BC_NUMBER AS SEGBC,XREF.BC_NUMBER AS XREFBC,CF.OBJ
-- Table CORE
From CORE

-- join seg and core
LEFT JOIN SEG
ON CORE.BC_NUMBER= SEG.BC_NUMBER

-- Join XREF to go from BCNbr to GBC
LEFT JOIN
XREF
ON XREF.BUNL=SEG.BC_NUMBER;

-- GEN JOIN GBC
LEFT JOIN

(SELect JID,P,Obj, JT
From Gen) AS CF

ON CF.Obj=XREF.BC_NUMBER

;
</code>```

sqlfiddle.com/#!6/29f643/15

答:
As you have used CF alias inside the parentheses and taking reference outside of it. Here CF alias is not created yet, please use CF alias outside the parentheses to use it as a reference</p>

```<code>SELECT CORE.BC_NUMBER AS BC,SEG.BC_NUMBER AS SEGBC,XREF.BC_NUMBER AS XREFBC,CF.OBJ
-- Table CORE
From CORE

-- join seg and core
LEFT JOIN SEG
ON CORE.BC_NUMBER= SEG.BC_NUMBER

-- Join XREF to go from BCNbr to GBC
LEFT JOIN
XREF
ON XREF.BUNL=SEG.BC_NUMBER;

-- GEN JOIN GBC
LEFT JOIN

(SEL JID,P,Obj, JT
From Gen
) AS CF
ON CF.Obj=XREF.BC_NUMBER
;
</code>```

Body:
Im getting an error on multi part identifier for Sub query join. Please help. Following is the code I have written

SELECT CORE.BC_NUMBER AS BC,SEG.BC_NUMBER AS SEGBC,XREF.BC_NUMBER AS XREFBC,CF.OBJ
-- Table CORE
From CORE

-- join seg and core
LEFT JOIN SEG
ON CORE.BC_NUMBER= SEG.BC_NUMBER

-- Join XREF to go from BCNbr to GBC
LEFT JOIN
XREF
ON XREF.BUNL=SEG.BC_NUMBER;

-- GEN JOIN GBC
LEFT JOIN

(SELect JID,P,Obj, JT
From Gen) AS CF

ON CF.Obj=XREF.BC_NUMBER

;

sqlfiddle.com/#!6/29f643/15

Body:
As you have used CF alias inside the parentheses and taking reference outside of it. Here CF alias is not created yet, please use CF alias outside the parentheses to use it as a reference

SELECT CORE.BC_NUMBER AS BC,SEG.BC_NUMBER AS SEGBC,XREF.BC_NUMBER AS XREFBC,CF.OBJ
-- Table CORE
From CORE

-- join seg and core
LEFT JOIN SEG
ON CORE.BC_NUMBER= SEG.BC_NUMBER

-- Join XREF to go from BCNbr to GBC
LEFT JOIN
XREF
ON XREF.BUNL=SEG.BC_NUMBER;

-- GEN JOIN GBC
LEFT JOIN

(SEL JID,P,Obj, JT
From Gen
) AS CF
ON CF.Obj=XREF.BC_NUMBER
;


问:
Is it possible to have scala Future execute a mapping action in the same thread, like Java CompletableFuture?
In Java it is possible to do:

```<code>CompletableFuture<Integer> e = new CompletableFuture<Integer>();
e = e.thenApply(x -> x * 2);
e.complete(12);
</code>```

in this scenario the function in thenApply will run in the thread that is calling e.complete see thenApply

In Scala I noticed that all manipulation functions for the future have an ExecutionContext as argument, so I assume map (that does the same as thenApply) will send another task to the execution context.

How can I get the same behaviour of a Java CompletableFuture with non Async methods?

答:
Thanks @rethab, after having a look at your pointers, and looking the default implementation of ExecutionContext, I found a very simple solution:

```<code>object MyExCont extends ExecutionContext {
    override def execute(runnable: Runnable): Unit = runnable.run()

    override def reportFailure(cause: Throwable): Unit = cause.printStackTrace()
  }

  def main(args: Array[String]): Unit = {
    val p = Promise[String]()
    val e = p.future

    val t = new Thread(()=>{
      LOGGER.info("Completing")
      p.complete(Try {
        "hello"
      })
    })

    val f = e.map(x => {
      LOGGER.info("Adding...")
      x + ";"
    }, MyExCon)

    Thread.sleep(10)
    t.start()
    LOGGER.info(Await.result(f, Duration.Inf))
  }
</code>```

this will result in either:

If the future is not complete at the time of e.map(...), then the thread when Promise.complete is called will run the mapping operation

If the futures is complete at the time of e.map(...), then it is the thrad where e.map is run that will undertake the work.

Body:
In Java it is possible to do:

CompletableFuture<Integer> e = new CompletableFuture<Integer>();
e = e.thenApply(x -> x * 2);
e.complete(12);

in this scenario the function in thenApply will run in the thread that is calling e.complete see thenApply

In Scala I noticed that all manipulation functions for the future have an ExecutionContext as argument, so I assume map (that does the same as thenApply) will send another task to the execution context.

How can I get the same behaviour of a Java CompletableFuture with non Async methods?

Body:
Thanks @rethab, after having a look at your pointers, and looking the default implementation of ExecutionContext, I found a very simple solution:

object MyExCont extends ExecutionContext {
    override def execute(runnable: Runnable): Unit = runnable.run()

    override def reportFailure(cause: Throwable): Unit = cause.printStackTrace()
  }

  def main(args: Array[String]): Unit = {
    val p = Promise[String]()
    val e = p.future

    val t = new Thread(()=>{
      LOGGER.info("Completing")
      p.complete(Try {
        "hello"
      })
    })

    val f = e.map(x => {
      LOGGER.info("Adding...")
      x + ";"
    }, MyExCon)

    Thread.sleep(10)
    t.start()
    LOGGER.info(Await.result(f, Duration.Inf))
  }

this will result in either:

If the future is not complete at the time of e.map(...), then the thread when Promise.complete is called will run the mapping operation

If the futures is complete at the time of e.map(...), then it is the thrad where e.map is run that will undertake the work.


问:
How to get Months between two dates
I'm trying to get All the months between two dates.

for e.g if the user posted an article on 21-10-2012 and today date is 5-12-2017. Now i want to get all the month and Year between this period like shown below

```<code>10-2012
11-2012
01-2013
02-2014
03-2015
04-2015
05-2015
06-2015
07-2015 // and so on
.......
.......
.......
12-2017 // Till Today Date
</code>```

Till Now i was only able to calculate the difference.

```<code>$article_date= date("d-m-Y", $article['date']);
$year = date("Y");
$month = date("m");
$day = date("d");
$date1 = new DateTime($article_date);
$date2 = new DateTime("$day-$month-$year");

$diff = $date1->diff($date2);

echo (($diff->format('%y') * 12) + $diff->format('%m')) . " full months difference";
</code>```

How can i get all the months?

答:
```<code>function list_months($date_from,$date_to, $return_format){
        $arr_months = array();
        $a =  new \DateTime($date_from);
        $x =  new \DateTime($date_to);

        $start = $a->modify('first day of this month');
        $end = $x->modify('first day of next month');

        $interval = \DateInterval::createFromDateString('1 month');
        $period = new \DatePeriod($start, $interval, $end);

        foreach ($period as $dt) {
            $arr_months[] = $dt->format($return_format);
        }

        return $arr_months ;
    }
</code>```

Example: $new_list = list_months('11-10-2012','11-10-2017', 'm-Y');

Title: How to get Months between two dates

Body:
I'm trying to get All the months between two dates.

for e.g if the user posted an article on 21-10-2012 and today date is 5-12-2017. Now i want to get all the month and Year between this period like shown below

10-2012
11-2012
01-2013
02-2014
03-2015
04-2015
05-2015
06-2015
07-2015 // and so on
.......
.......
.......
12-2017 // Till Today Date

Till Now i was only able to calculate the difference.

$article_date= date("d-m-Y", $article['date']);
$year = date("Y");
$month = date("m");
$day = date("d");
$date1 = new DateTime($article_date);
$date2 = new DateTime("$day-$month-$year");

$diff = $date1->diff($date2);

echo (($diff->format('%y') * 12) + $diff->format('%m')) . " full months difference";

How can i get all the months?

Body:
function list_months($date_from,$date_to, $return_format){
        $arr_months = array();
        $a =  new \DateTime($date_from);
        $x =  new \DateTime($date_to);

        $start = $a->modify('first day of this month');
        $end = $x->modify('first day of next month');

        $interval = \DateInterval::createFromDateString('1 month');
        $period = new \DatePeriod($start, $interval, $end);

        foreach ($period as $dt) {
            $arr_months[] = $dt->format($return_format);
        }

        return $arr_months ;
    }

Example: $new_list = list_months('11-10-2012','11-10-2017', 'm-Y');


问:
Why does an image is distorted when I set it using GroundOverlay in my Google Map?
I am trying to set a screenshot of a map into another map using GroundOverlay provided by Google Maps.

First I save the bounds of the map when I take the screenshot. I get them using

```<code>borders = GoogleMap.getProjection().getVisibleRegion().latLngBounds;
</code>```

After when I set the screenshot to the GroundOverlay image using that bounds, the image appears distorted. I did it like this

```<code>GroundOverlayOptions offlineMap = new GroundOverlayOptions()
                            .image(BitmapDescriptorFactory.fromBitmap(myBitmap))
                            .transparency(0)
                            .positionFromBounds(borders);
                    imageOverlay = map.addGroundOverlay(offlineMap);
</code>```

Here is a screenshot of the problem:
Screenshot of the image overlay distorted

Why is happening this? How can I set the image correctly?

EDITED

I could set the image without distorsion passing the LatLng coordinates of the center of the image and the width of the image, but the thing is that the GroundOverlayOptions object needs the width in kilometers, and I calculated using the distance between the two bot points of the image in the moment that is captured.

My problem is, the image is set with correct proportions, but in the wrong place.
How can I save the attributes to set the image in the exactly same position on the map as when it was taken?

答:
Try this code, which gets screenshot on mScreenshotButton press, than add it as overlay on mAddOverlayButton press:

```<code>public class MainActivity extends AppCompatActivity implements OnMapReadyCallback {

    private GoogleMap mGoogleMap;
    private MapFragment mMapFragment;
    private Button mAddOverlayButton;
    private Button mScreenshotButton;
    private Bitmap mScreenshot;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mScreenshotButton = (Button) findViewById(R.id.get_screenshot_button);
        mScreenshotButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getMapScreenshot();
            }
        });

        mAddOverlayButton = (Button) findViewById(R.id.add_overlay_button);
        mAddOverlayButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                LatLngBounds borders = mGoogleMap.getProjection().getVisibleRegion().latLngBounds;

                GroundOverlayOptions overlay = new GroundOverlayOptions()
                        .image(BitmapDescriptorFactory.fromBitmap(mScreenshot))
                        .transparency(0f)
                        .positionFromBounds(borders);

                mGoogleMap.addGroundOverlay(overlay);
            }
        });

        mMapFragment = (MapFragment) getFragmentManager()
                .findFragmentById(R.id.map_fragment);
        mMapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mGoogleMap = googleMap;
    }

    public void getMapScreenshot()
    {
        GoogleMap.SnapshotReadyCallback callback = new GoogleMap.SnapshotReadyCallback() {
            Bitmap bitmap;

            @Override
            public void onSnapshotReady(Bitmap snapshot) {
                mScreenshot = snapshot;
            }
        };

        mGoogleMap.snapshot(callback);
    }

}
</code>```

And there is no any distortion.  Seems you didn't get borders properly.

Body:
I am trying to set a screenshot of a map into another map using GroundOverlay provided by Google Maps.

First I save the bounds of the map when I take the screenshot. I get them using

borders = GoogleMap.getProjection().getVisibleRegion().latLngBounds;

After when I set the screenshot to the GroundOverlay image using that bounds, the image appears distorted. I did it like this

GroundOverlayOptions offlineMap = new GroundOverlayOptions()
                            .image(BitmapDescriptorFactory.fromBitmap(myBitmap))
                            .transparency(0)
                            .positionFromBounds(borders);
                    imageOverlay = map.addGroundOverlay(offlineMap);

Here is a screenshot of the problem:
Screenshot of the image overlay distorted

Why is happening this? How can I set the image correctly?

EDITED

I could set the image without distorsion passing the LatLng coordinates of the center of the image and the width of the image, but the thing is that the GroundOverlayOptions object needs the width in kilometers, and I calculated using the distance between the two bot points of the image in the moment that is captured.

My problem is, the image is set with correct proportions, but in the wrong place.
How can I save the attributes to set the image in the exactly same position on the map as when it was taken?

Body:
Try this code, which gets screenshot on mScreenshotButton press, than add it as overlay on mAddOverlayButton press:

public class MainActivity extends AppCompatActivity implements OnMapReadyCallback {

    private GoogleMap mGoogleMap;
    private MapFragment mMapFragment;
    private Button mAddOverlayButton;
    private Button mScreenshotButton;
    private Bitmap mScreenshot;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mScreenshotButton = (Button) findViewById(R.id.get_screenshot_button);
        mScreenshotButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getMapScreenshot();
            }
        });

        mAddOverlayButton = (Button) findViewById(R.id.add_overlay_button);
        mAddOverlayButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                LatLngBounds borders = mGoogleMap.getProjection().getVisibleRegion().latLngBounds;

                GroundOverlayOptions overlay = new GroundOverlayOptions()
                        .image(BitmapDescriptorFactory.fromBitmap(mScreenshot))
                        .transparency(0f)
                        .positionFromBounds(borders);

                mGoogleMap.addGroundOverlay(overlay);
            }
        });

        mMapFragment = (MapFragment) getFragmentManager()
                .findFragmentById(R.id.map_fragment);
        mMapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mGoogleMap = googleMap;
    }

    public void getMapScreenshot()
    {
        GoogleMap.SnapshotReadyCallback callback = new GoogleMap.SnapshotReadyCallback() {
            Bitmap bitmap;

            @Override
            public void onSnapshotReady(Bitmap snapshot) {
                mScreenshot = snapshot;
            }
        };

        mGoogleMap.snapshot(callback);
    }

}

And there is no any distortion.  Seems you didn't get borders properly.


问:
What is the cheapest Google Compute Engine architecture for sharded MongoDB development setup?
After weeks of developing my various microservices, GC Pub/Sub and GC Functions using a basic MongoDB server, I would like to test the entire data flow using what I would use in production: a sharded MongoDB cluster. I've never used these and would like to get myself familiar with setting them up, updating, etc.

Costs are an issue at this stage, especially for testing. Therefore, what is the most cost-effective way to setup a (test) MongoDB sharded cluster on Google Compute Engine?

答:
The easiest approach for you is to use Cloud Launcher for your deployment. It will let you choose the number of nodes and the machine types. In that way you can deploy something that suits your budget. You will get billed according to the resources you deploy and can use this online calculator to have an estimate. A drawback is that there does not seems to be a direct way to increase nodes or change machine types without manual reconfiguration.

While configuring your deployment the appropriate number of nodes and an arbitre will be created. Once you have tested, you might want to think about using more complex architectures that will be redundant against failures in one region (Those will certainly increase your cost since it will mean having additional nodes).

You can also consider running Mongo on GKE, it would be easier to escale but it will require that you get familiar with Kubernetes. Kubernetes Engine is also charged according to the resources used by the cluster.


问:
Where to check custom webapplication logs in wso2 carbon
Need help here..
I have developed a java application and configured logs using log4j. I have deployed this application in wso2 carbon. Can anyone tell me where to check my application logs in wso2 carbon??
I can see only carbon logs wso2carbon.log..
Where can i check my application specific logs??</p>

答:
If you have your own log4j.properties file in your webapp, you can configure the location in it.

See this for more details.

https://docs.wso2.com/display/AS530/Customize+Logging+for+Web+Applications


问:
Convert Array of Dictionaries into Array of Values from NSFetchRequest
I have a dictionary that is being returned from a NSFetchRequest using the fetchRequest.resultType = .dictionaryResultType  the dictionary returned is [Any] and looks like the folowing:

```<code>teams [{
    team = Canadiens;
}, {
    team = "Maple Leafs";
}, {
    team = Penguins;
}]
</code>```

I would like just an array of the values, like this [Canadiens, "Maple Leafs", Penguins"], how can I convert the array of dictionaries into an array only containing the values?

Full fetch

```<code>func teamNames(managedContext: NSManagedObjectContext) {
    //print("\(self) -> \(#function)")

    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Players")

    fetchRequest.fetchBatchSize = 8
    fetchRequest.propertiesToGroupBy = [#keyPath(Players.team)]
    fetchRequest.propertiesToFetch   = [#keyPath(Players.team)]
    fetchRequest.resultType          = .dictionaryResultType

    do {

        let fetchTeamNamesDictionary = try managedContext.fetch(fetchRequest)
        print("fetchTeamNamesDictionary \(fetchTeamNamesDictionary)")

    } catch let error as NSError {

        print("GoFetch|teamNames: Could not fetch. \(error), \(error.userInfo)")
    }

}
</code>```

Alternate to accepted answer:

```<code>do {

    let fetchTeamNamesArray = try managedContext.fetch(fetchRequest)

    for array in fetchTeamNamesArray {

        let teamName = (array as AnyObject).value(forKey: "team") as! String

        teamNameArray.append(teamName)

    }
</code>```

答:
As you clearly know that the keys and values of the result are strings force-downcast the result to [[String:String]]

```<code>let teamArray = try managedContext.fetch(fetchRequest) as! [[String:String]]
</code>```

Then map the dictionaries to its value for key team

```<code>let teamNames = teamArray.map { $0["team"]! }
</code>```

Body:
I have a dictionary that is being returned from a NSFetchRequest using the fetchRequest.resultType = .dictionaryResultType  the dictionary returned is [Any] and looks like the folowing:

teams [{
    team = Canadiens;
}, {
    team = "Maple Leafs";
}, {
    team = Penguins;
}]

I would like just an array of the values, like this [Canadiens, "Maple Leafs", Penguins"], how can I convert the array of dictionaries into an array only containing the values?

Full fetch

func teamNames(managedContext: NSManagedObjectContext) {
    //print("\(self) -> \(#function)")

    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Players")

    fetchRequest.fetchBatchSize = 8
    fetchRequest.propertiesToGroupBy = [#keyPath(Players.team)]
    fetchRequest.propertiesToFetch   = [#keyPath(Players.team)]
    fetchRequest.resultType          = .dictionaryResultType

    do {

        let fetchTeamNamesDictionary = try managedContext.fetch(fetchRequest)
        print("fetchTeamNamesDictionary \(fetchTeamNamesDictionary)")

    } catch let error as NSError {

        print("GoFetch|teamNames: Could not fetch. \(error), \(error.userInfo)")
    }

}

Alternate to accepted answer:

do {

    let fetchTeamNamesArray = try managedContext.fetch(fetchRequest)

    for array in fetchTeamNamesArray {

        let teamName = (array as AnyObject).value(forKey: "team") as! String

        teamNameArray.append(teamName)

    }

Body:
As you clearly know that the keys and values of the result are strings force-downcast the result to [[String:String]]

let teamArray = try managedContext.fetch(fetchRequest) as! [[String:String]]

Then map the dictionaries to its value for key team

let teamNames = teamArray.map { $0["team"]! }


问:
How to add existing folder to android and use them?
I am developing a mobile application by using Lucene. I have a folder which includes index files. In the application, I want to use these index files for searching. Lucene Library expects path of this folder to read. I placed this folder in the assets folder. But I can't get this folder's path. I checked Android Storage Documentation. But I could not find any solution to add existing folder to external storage. If I would add them to external storage, I can get the path with getExternalFilesDir(). I am working by using emulator.

```<code>Directory dir = FSDirectory.open(Paths.get("path of index folder"));
IndexReader reader = DirectoryReader.open(dir);
searcher = new IndexSearcher(reader);
</code>```

Above code section works well in a Java SE application since I can give the path of folder directly. But In android I am working by using emulator. How can give path of index folder in android? Where should I place this folder to reach in the application?

答:
You put them into the folder into your assets, then copy the assets to the file system on first run.  Then you can pass the location you wrote them to to Lucene.

Fair warning:  I tried to use Lucene and couldn't a year ago, because it was using IO functions that weren't ported to Android.  Now that Java 1.8 exists on Android maybe they have been, but if not you're going to have additional problems to solve.

Body:
I am developing a mobile application by using Lucene. I have a folder which includes index files. In the application, I want to use these index files for searching. Lucene Library expects path of this folder to read. I placed this folder in the assets folder. But I can't get this folder's path. I checked Android Storage Documentation. But I could not find any solution to add existing folder to external storage. If I would add them to external storage, I can get the path with getExternalFilesDir(). I am working by using emulator.

Directory dir = FSDirectory.open(Paths.get("path of index folder"));
IndexReader reader = DirectoryReader.open(dir);
searcher = new IndexSearcher(reader);

Above code section works well in a Java SE application since I can give the path of folder directly. But In android I am working by using emulator. How can give path of index folder in android? Where should I place this folder to reach in the application?


问:
SQL- how to retrieve by similar dates
Okay, so I have a table with a user_id column and a submitted_dtm column.

I want to find instances where users submitted multiple records within 1 day of each other, and count how many times that has happened.

I've tried something like

```<code>select * from table_t t where
(select count(*) from table_t t2 where
t.user_id = t2.user_id and
t.pk!=t2.pk and
t.submitted_dtm between t2.submitted_dtm-.5 and t2.submitted_dtm+.5)>0;
</code>```

The problem is that this query returns a result for each record in a date group.  Instead, I just want a result per date group. Ideally, I'd just get the count in that group.

That is, if I have 6 records:

```<code>user_id     submitted_dtm
--------------------------
1            12/04/2017 1:15
1            12/04/2017 5:50
2            11/25/2017 2:00
2            11/25/2017 3:25
2            11/25/2017 6:05
2            10/06/2017 4:00
</code>```

I want 2 results, a count of 2 and a count of 3.

Is it possible to do this in sql?

答:
I don't have data to test it but I suspect something like this would do the trick :</p>

```<code>SELECT user_id,To_char(t.submitted_dtm, 'dd/mm/yyyy'), COUNT(*)
  FROM table_t t
 INNER JOIN table_t t2
    ON t.user_id = t2.user_id
   AND t.pk != t2.pk
   AND t.submitted_dtm BETWEEN t2.submitted_dtm - .5 AND
       t2.submitted_dtm + .5
 GROUP BY user_id,To_char(t.submitted_dtm, 'dd/mm/yyyy')
HAVING COUNT(*) > 1
</code>```

Title: SQL- how to retrieve by similar dates

Body:
Okay, so I have a table with a user_id column and a submitted_dtm column.

I want to find instances where users submitted multiple records within 1 day of each other, and count how many times that has happened.

I've tried something like

select * from table_t t where
(select count(*) from table_t t2 where
t.user_id = t2.user_id and
t.pk!=t2.pk and
t.submitted_dtm between t2.submitted_dtm-.5 and t2.submitted_dtm+.5)>0;

The problem is that this query returns a result for each record in a date group.  Instead, I just want a result per date group. Ideally, I'd just get the count in that group.

That is, if I have 6 records:

user_id     submitted_dtm
--------------------------
1            12/04/2017 1:15
1            12/04/2017 5:50
2            11/25/2017 2:00
2            11/25/2017 3:25
2            11/25/2017 6:05
2            10/06/2017 4:00

I want 2 results, a count of 2 and a count of 3.

Is it possible to do this in sql?

Body:
I don't have data to test it but I suspect something like this would do the trick :

SELECT user_id,To_char(t.submitted_dtm, 'dd/mm/yyyy'), COUNT(*)
  FROM table_t t
 INNER JOIN table_t t2
    ON t.user_id = t2.user_id
   AND t.pk != t2.pk
   AND t.submitted_dtm BETWEEN t2.submitted_dtm - .5 AND
       t2.submitted_dtm + .5
 GROUP BY user_id,To_char(t.submitted_dtm, 'dd/mm/yyyy')
HAVING COUNT(*) > 1


问:
PHP: replacement for DateTime object
The server that I have my sited hosted is on PHP5.12.14, and I have an error when I run the DateTime object from PHP5.3

```<code># DateTime::add — Adds an amount of days, months, years, hours, minutes and seconds to a DateTime object
$date = new DateTime($item_user['mem_updated']);

# add a day to the object
$date -> add(new DateInterval('P1D'));
</code>```

the error,

```<code>Fatal error: Call to undefined method DateTime::add() in /homepages/xxx.php on line xx
</code>```

So, I have look for the other solutions rather than sticking to PHP5.3's DateTime object. How can I write the code to replace the code above?

basically I have this date and time data (for instance - 2011-01-21 02:08:39) from the mysql database, and I just need to add 1 day or 24 hours to that date/time, then passing it into a function below,

```<code>$time_togo = time_togo($date -> format('Y-m-d H:i:s'));
</code>```

thanks.

答:
Here's an example:

```<code>$date = date('Y-m-d H:i:s');

$new_tstamp = strtotime($date.'+1WEEK');
$new_date = date('Y-m-d H:i:s', $new_tstamp);
</code>```

In other words, strtotime lets you use date expressions like +1DAY, +1MONTH and so on.

The above will work for date string (e.g.: 2010-01-01). If your original date is a Unix timestamp, you can still use strtotime, although a bit differently:

```<code>$new_tstamp = strtotime('+1WEEK', $timestamp);
</code>```

Title: PHP: replacement for DateTime object

Body:
The server that I have my sited hosted is on PHP5.12.14, and I have an error when I run the DateTime object from PHP5.3

# DateTime::add — Adds an amount of days, months, years, hours, minutes and seconds to a DateTime object
$date = new DateTime($item_user['mem_updated']);

# add a day to the object
$date -> add(new DateInterval('P1D'));

the error,

Fatal error: Call to undefined method DateTime::add() in /homepages/xxx.php on line xx

So, I have look for the other solutions rather than sticking to PHP5.3's DateTime object. How can I write the code to replace the code above?

basically I have this date and time data (for instance - 2011-01-21 02:08:39) from the mysql database, and I just need to add 1 day or 24 hours to that date/time, then passing it into a function below,

$time_togo = time_togo($date -> format('Y-m-d H:i:s'));

thanks.

Body:
Here's an example:

$date = date('Y-m-d H:i:s');

$new_tstamp = strtotime($date.'+1WEEK');
$new_date = date('Y-m-d H:i:s', $new_tstamp);

In other words, strtotime lets you use date expressions like +1DAY, +1MONTH and so on.

The above will work for date string (e.g.: 2010-01-01). If your original date is a Unix timestamp, you can still use strtotime, although a bit differently:

$new_tstamp = strtotime('+1WEEK', $timestamp);