text:
Q: What is the correct syntax for passing a static string with a select query? This is my query within a Yii controller.  I am trying to pass the name of the controller as a static string. This syntax throws the error

"Incorrect syntax near keyword LEFT."

If I use:
'Message' AS controllerName,

...then it works fine.
The full function:
/**
 * Datatable: Message
 *
 * @param $status
 */
public function actionMessage($status) {
    // only allow ajax requests to this action
    if (!Yii::app()->request->isAjaxRequest && !YII_DEBUG) {
        Yii::app()->end();
    }

    // start building the create command
    $command = Yii::app()->db->createCommand()
        ->select("
            {Yii::app()->controller->id} AS controllerName,
            Message.MessageID AS primaryKey,
            Message.Name AS messageName,
            Message.Code AS messageCode,
            Message.CloneOf AS messageCloneOf,
            Message.IsActive AS messageIsActive,
            Message.IsArchived,
            Client.Name AS clientName,
            Workflow.WorkflowID AS workflowID,
            Workflow.Name AS workflowName,
            Workflow.Color AS workflowColor,

            STUFF((
                SELECT CAST(',' + aprv AS VARCHAR(MAX))
                FROM
                    (
                        SELECT MessageID, mv.RowInsertDate AS inDate, CONCAT(REPLACE(SUBSTRING ( a.Options ,0 , PATINDEX('%\",\"required\"%', a.Options )),'{\"name\":\"',' '), ' - All - ', CONCAT(u.FirstName,' ',u.LastName), ' on ' , mv.RowInsertDate) AS aprv
                            FROM MessageApproval mv
                            JOIN [User] u ON u.UserID = mv.UserID
                            JOIN [Action] a ON a.ActionID = mv.ActionID
                            WHERE mv.IsApproved=1
                        UNION
                        SELECT MessageID, mvl.RowInsertDate AS inDate, CONCAT(REPLACE(SUBSTRING ( a.Options ,0 , PATINDEX('%\",\"required\"%', a.Options )),'{\"name\":\"',' '), ' - ', l.Code, ' - ', CONCAT(u.FirstName,' ',u.LastName), ' on ' , mvl.RowInsertDate) AS aprv
                            FROM MessageApprovalLocale mvl
                            JOIN [User] u ON u.UserID = mvl.UserID
                            JOIN Locale l ON l.LocaleID = mvl.LocaleID
                            JOIN [Action] a ON a.ActionID = mvl.ActionID
                            WHERE mvl.IsApproved=1
                    ) AS approvalData
                WHERE (Message.MessageID = approvalData.MessageID)
                ORDER BY inDate DESC
            FOR XML PATH ('')), 1, 1, '') AS Approvals,

            STUFF((SELECT CAST(',' + [Name] AS VARCHAR(MAX))
            FROM [Brand]
            JOIN MessageBrand ON Brand.BrandID = MessageBrand.BrandID
            WHERE (Message.MessageID = MessageBrand.MessageID)
            ORDER BY Brand.Name ASC
            FOR XML PATH ('')), 1, 1, '') AS brands,

            STUFF((SELECT CAST(',' + [Name] AS VARCHAR(MAX))
            FROM [Communication]
            JOIN CommunicationRegionMessage ON Communication.CommunicationID = CommunicationRegionMessage.CommunicationID
            WHERE (Message.MessageID = CommunicationRegionMessage.MessageID)
            ORDER BY Communication.Name ASC
            FOR XML PATH ('')), 1, 1, '') AS communications,

            STUFF((SELECT CAST(',' + [Name] AS VARCHAR(MAX))
            FROM [Track]
            JOIN TrackCommunication ON Track.TrackID = TrackCommunication.TrackID
            JOIN CommunicationRegionMessage ON TrackCommunication.CommunicationID = CommunicationRegionMessage.CommunicationID
            WHERE (Message.MessageID = CommunicationRegionMessage.MessageID)
            ORDER BY Track.Name ASC
            FOR XML PATH ('')), 1, 1, '') AS tracks,

            STUFF((SELECT CAST(',' + [Name] AS VARCHAR(MAX))
            FROM [Series]
            JOIN SeriesTrack ON Series.SeriesID = SeriesTrack.SeriesID
            JOIN TrackCommunication ON SeriesTrack.TrackID = TrackCommunication.TrackID
            JOIN CommunicationRegionMessage ON TrackCommunication.CommunicationID = CommunicationRegionMessage.CommunicationID
            WHERE (Message.MessageID = CommunicationRegionMessage.MessageID)
            ORDER BY Series.Name ASC
            FOR XML PATH ('')), 1, 1, '') AS series,

            STUFF((SELECT CAST(',' + [Name] AS VARCHAR(MAX))
            FROM [Campaign]
            JOIN CampaignSeries ON Campaign.CampaignID = CampaignSeries.CampaignID
            JOIN SeriesTrack ON CampaignSeries.SeriesID = SeriesTrack.SeriesID
            JOIN TrackCommunication ON SeriesTrack.TrackID = TrackCommunication.TrackID
            JOIN CommunicationRegionMessage ON TrackCommunication.CommunicationID = CommunicationRegionMessage.CommunicationID
            WHERE (Message.MessageID = CommunicationRegionMessage.MessageID)
            ORDER BY Campaign.Name ASC
            FOR XML PATH ('')), 1, 1, '') AS campaigns,

            STUFF((SELECT CAST(',' + [Name] AS VARCHAR(MAX))
            FROM [Program]
            JOIN MessageProgram ON Program.ProgramID = MessageProgram.ProgramID
            WHERE (Message.MessageID = MessageProgram.MessageID)
            ORDER BY Program.Name ASC
            FOR XML PATH ('')), 1, 1, '') AS programs,

            STUFF((SELECT '|' + Name + ';' + CAST(Template.RowUpdateDate AS VARCHAR)
            FROM [Template]
            JOIN MessageTemplate ON Template.TemplateID = MessageTemplate.TemplateID
            WHERE (Message.MessageID = MessageTemplate.MessageID)
            ORDER BY Template.Name ASC
            FOR XML PATH ('')), 1, 1, '') AS templates,

            STUFF((SELECT CAST(',' + [Code] AS VARCHAR(MAX))
            FROM [Template]
            JOIN MessageTemplate ON Template.TemplateID = MessageTemplate.TemplateID
            WHERE (Message.MessageID = MessageTemplate.MessageID)
            ORDER BY Template.Name ASC
            FOR XML PATH ('')), 1, 1, '') AS templateCodes,

            STUFF((SELECT DISTINCT ',' + CAST([Name] AS VARCHAR(MAX))
            FROM [Connector]
            JOIN PublishMessage ON Connector.ConnectorID = PublishMessage.ConnectorID
            WHERE (Message.MessageID = PublishMessage.MessageID)
            FOR XML PATH ('')), 1, 1, '') AS pubConnectors,

            PublishMessage.PublishStartDate AS pubStart,
            PublishMessage.PublishEndDate AS pubEnd,
            PublishMessage.PublishID AS pubID,

            STUFF((
                SELECT '|' + CAST(CONCAT(IsPublished,'.',Code,'.',SUBSTRING(PublishResponse, 0, 20)) AS VARCHAR)
                    FROM PublishMessage
                    JOIN (
                        SELECT MAX(Publish.PublishID) PublishID, MAX(PublishMessage.PublishMessageID) PublishMessageID, MAX(PublishMessage.MessageID) MessageID, Locale.Code, MAX(Publish.RowInsertDate) RowInsertDate
                        FROM Publish
                        JOIN Locale ON Locale.LocaleID=Publish.LocaleID
                        JOIN PublishMessage ON PublishMessage.PublishID = Publish.PublishID
                        WHERE MessageID=Message.MessageID
                        GROUP BY Locale.Code
                    ) AS latest ON latest.PublishMessageID=PublishMessage.PublishMessageID
                    ORDER BY IsPublished DESC, PublishMessage.RowInsertDate DESC
                FOR XML PATH ('')
            ), 1, 1, '') AS pubStatus,

            PublishMessage.PublishResponse AS pubResponse,
            STUFF((SELECT '|' + MetaName + ':=' + MetaValue FROM ConnectorDetail WHERE ConnectorID = Connector.ConnectorID AND Show = 1 FOR XML PATH('')), 1, 1, '') as pubMeta
        ")
        ->from('Message')
        ->leftJoin('PublishMessage', 'PublishMessage.PublishMessageID = (SELECT MAX(PublishMessageID) FROM PublishMessage WHERE PublishMessage.MessageID = Message.MessageID AND PublishStartDate IS NOT NULL)')
        ->leftJoin('Connector', 'Connector.ConnectorID = PublishMessage.ConnectorID')
        ->join('Workflow', 'Message.WorkflowID = Workflow.WorkflowID')
        ->join('Client', 'Client.ClientID = Message.ClientID')
        ->where(DBHelper::whereFilterUserClient())
        ->order('Message.Name ASC');

    // apply status filter
    switch ($status) {
        case 'all':
            $command->andWhere('Message.IsArchived = 0');
            break;
        case 'archive':
            $command->andWhere('Message.IsArchived = 1');
            break;
        default:
            Yii::app()->end(sprintf('Invalid Status: %s', $status));
    }

    // get the query result
    $data = $command->queryAll();

    // Add in unapproved locales to the approvals (I couldn't find an efficient way to include this in main query)
    $localeApprovalMsgIDs = array_keys(MessageApprovalLocale::usesLocaleApproval());
    $unapprovedLocales = MessageApprovalLocale::unApprovedLocales($localeApprovalMsgIDs);

    foreach ($data as &$message) {

        if ( isset($unapprovedLocales[$message['primaryKey']]) ) {
            $message['Approvals'] = trim($message['Approvals'] . ',' . $unapprovedLocales[$message['primaryKey']]['Locales'],',');
        }
    }

    TableHelper::actionDataTable($data, $status == 'all' ? $this->dataTableColumns() : array_slice($this->dataTableColumns(), 2));
}

A: You have to use parameter binding for this:
$command = Yii::app()->db->createCommand()
    ->select("
        :controllerid AS controllerName,

...
->order('Message.Name ASC')
->bindParam(':controllerid', Yii::$app->controller->id);


text:
Q: Explaining squid traffic usecase I see sometimes some traffic pattern which I don't fully understand, and I hope I can get some help.
Let's say I run a website. I look at the logs coming in for my http site and I see a request proxied by squid (header Via is telling me about squid). No problem there, someone is being proxied via squid.
But then I look at the IPs. The connecting IP (1.2.3.4) is consistent to where the end-user is actually physically located. However, the X-Forwarded-For header shows an IP which is -- for the sake of discussion -- EC2 (2.3.4.5).
So this could tell me that someone using 2.3.4.5 is being proxied to a squid running on 1.2.3.4. But this doesn't make sense because I know the person is located at 1.2.3.4.
So overall it looks like someone at 1.2.3.4 is using a squid on EC2, which does something (maybe security?) which adds a XFF and Via header and then tunnels back to 1.2.3.4 and goes out to the internet.
This last scenario seems convoluted (and very slow adding an extra "hop") but maybe I am missing some use-case or setup which some IT might decide to do.
Does anyone know what's going on? Thanks!
PS: let's assume none is spoofing headers! As this does happen regularly, although I would call it a corner-case.

A: I can think of two cases.

*

*you or your hosting provider is using a reverse proxy

*your client is behind a "corporate" proxy (or emulating a vpn exit node through a ec2 instance with squid -- aka a sophisticated poor man's vpn)

And a third, combining the two above:

*Someone is behind a corporate proxy connecting to your webserver through a reverse proxy.

The X-Forwarded-For may be displaying the client along with the proxies IP address, as in: X-Forwarded-For: client, proxy1, proxy2.
Usually, this header is useful for log analyzers and such, to have the origin IP for analytics or other purposes, if you have a reverse proxy you have to set it right so you don't log everything as coming from it. The last IP on that line should be the previous to-last proxy. If you are getting only one IP there, it's either badly configured or only one hop.
In case the request already comes from a corporate proxy (case 2), depending on configuration, it might arrive at your reverse proxy (case 1), and end with confusing headers (case 3) if the reverse proxy didn't clean the headers prior to adding it's own headers.
In my opinion, the most probable case might be that someone is using an EC2 instance (if you were referring to the Amazon service, but any VPS will do) as a proxy to avoid some kind of blocking.
Sources:

*

*https://en.wikipedia.org/wiki/X-Forwarded-For

*https://supporthandbook.wordpress.com/2011/01/10/using-squid-hosted-on-ec2-to-bypass-corporate-proxy/

*http://hackingonstuff.net/post/23929749838/setting-up-a-squid-proxy-on-aws

*http://blog.spench.net/2010/02/24/tips-for-setting-up-squid-in-reverse-proxy-web-accelerator-accel-mode/

A: After some digging, I can conclude that such scenario doesn't normally exist and it is due to a wrong network or squid configuration:

*

*squid always inserts a random XFF

*the network internal addressing is using public ip instead of private ips

redpajama_set_name: RedPajamaStackExchange


text: Q: Installing tekton encountered forbidden message I am trying to install Tekton. But upon trying to install the dashboard I have encountered an error "forbidden".  I would like to install task, pipeline, and triggers


text:
Q: Changing network request path of application using reverse engineering techniques I am debugging my own application, so please avoid legal advices,
I am new to reverse engineering. I want to know, if it is possible to change application network request path. Let's suppose, my application is making API call to this server https://example.com, can someone change it to https://fake.com by reverse engineering(without source code).
My application is written in C#/.Net WPF.
To prevent decompiling, I used .Net-Reactor to convert it to native code

A: It is possible, even without touching your code at all.
The hacker can hook Winsock APIs like connect() or gethostbyname() by various means. There is also a Windows feature called Layered Socket Providers (LSP) that allow doing the same. Finally, this can be done by routing means even on different machine through which the network traffic passes.
To verify that you have connected to authentic server you have to use cryptographic means, like SSL/TLS protocols.


text:
Q: Interesting results with duplicate columns in pandas.DataFrame Can anyone help to explain why I get errors in some actions and not others when there is a duplicate column in a pandas.DataFrame.
Minimal, Reproducible Example
import pandas as pd
df = pd.DataFrame(columns=['a', 'b', 'b'])

If I try and insert a list into column 'a' I get an error about dimension mis-match:
df.loc[:, 'a'] = list(range(5))

Traceback (most recent call last):
...
ValueError: cannot copy sequence with size 5 to array axis with dimension 0

Similar with 'b':
df.loc[:, 'b'] = list(range(5))

Traceback (most recent call last):
...
ValueError: could not broadcast input array from shape (5) into shape (0,2)

However if I insert into an entirely new column, I don't get an error, unless I insert into 'a' or 'b':
df.loc[:, 'c'] = list(range(5))
print(df)

     a    b    b  c
0  NaN  NaN  NaN  0
1  NaN  NaN  NaN  1
2  NaN  NaN  NaN  2
3  NaN  NaN  NaN  3
4  NaN  NaN  NaN  4

df.loc[:, 'a'] = list(range(5))

Traceback (most recent call last):
...
ValueError: Buffer has wrong number of dimensions (expected 1, got 0)

All of these errors disappear if I remove the duplicate column 'b'

Additional information
pandas==1.0.2

A: Why use loc and not just:
df['a'] = list(range(5))

This gives no error and seems to produce what you need:
a   b   b
0   NaN NaN
1   NaN NaN
2   NaN NaN
3   NaN NaN
4   NaN NaN

same for creating column c:
df['c'] = list(range(5))


text:
Q: Rewinding from VC2 presented Over Current Context not reloading original VC1 I have a PresentingViewController (VC1) and a PresentedViewController (VC2).
VC1 --Segue:Present Modally:Over Current Context-->  VC2
VC2 --RewindSegue --> VC1
The problem is that when I rewind from VC2 to VC1, it is not being "reloaded".  It is nil.
However if I present VC 2 modally: Full Screen, the rewind triggers a reload of VC1 and all is dandy.
Why does a rewind FROM a VC presented "Modally:Over Current Context" not reload the VC you are rewinding to?  How can I present over Current Context and also force a reload of VC1 when I rewind?
Any help would be much appreciated.  Thank you.

A: Solved the problem by adding the function I wanted to update in VC1 in the unwinding action
@IBAction func unwindToDetailViewControllerVC1(segue: UIStoryboardSegue) {

    println("Unwinding to DetailViewControllerVC1")
    rememberWhatSegmentIsPressed()

}

Also remember to tick the 'Defines Context' in the presentingViewController.
See: https://stackoverflow.com/a/27487057/4051036


text:
Q: What's holding up my ByteBuffer from freeing? I'm allocating a lot of byte buffers.  After I'm done with them I set all reference to null.  This is supposedly the "correct" way to release bytebuffers?  Dereference it and let the GC clean it up ?  I also call System.gc() to try and help it along.
Anyways, I create a bunch of buffers, deference them; but after "some time" I get all sorts of memory errors: java.lang.OutOfMemoryError: Direct buffer memory
I can increase the MaxDirectMemorySize but it just delays the above error.
I'm 99% positive I don't have anything referencing the old ByteBuffers.  Is there a way to check this to see what the heck still has a ByteBuffer allocated?

A: You can use a tool like MAT that's free with Eclipse to see what is keeping your byte buffer by letting it do some heapdump analysis.
Another way I can think of is to wrap your byte buffer with something else that has a finalizer method.
Also Systen.gc() does not guarantee that finalizers will be executed you need to do     System.runFinalization() to increase the likelihood.

A: Setting the references to null is the correct way to let the garbage collector that you are finished with that object.  There must still be some other dangling reference.  The best tool I have found for finding memory leaks is YourKit.  A free alternative that is also very good is Visual VM from the JDK.
Remember that the slice() operation creates a new byte buffer that references the first one.

A: This is a problem with older versions of Java.  The latest version of Java 6 will call System.gc() before throwing an OutOfMemoryError.  If you don't want to trigger a GC you can release the direct memory manually on the Oracle/Sun JVM with
((DirectBuffer) buffer).cleaner().clean();

However, it is a better approach to recycle the direct buffers yourself so doing this is not so critical. (Creating direct ByteBuffers is relatively expensive)

A: Direct java.nio.ByteBuffer is (by definition) stored outside of java heap space. It is not freed until GC runs on heap, and frees it. But you can imagine a situation where heap usage is low therefore it does not need GC, but non-heap memory gets allocated and runs out of bounds.
Based on very interesting read:
http://www.ibm.com/developerworks/library/j-nativememory-linux/

The pathological case would be that the native heap becomes full and
  one or more direct ByteBuffers are eligible for GC (and could be freed
  to make some space on the native heap), but the Java heap is mostly
  empty so GC doesn't occur.


text:
Q: How to run bash logical operators from python I'm trying to execute:
    actual = subprocess.run(['echo 123 | ./ft_ssl md5 -s ' + data + ' -p'], stdout=subprocess.PIPE)
    actual = actual.stdout.decode('utf-8')

and after that variable actual equals "123 | ./ft_ssl md5 -s fuck -p\n".
Python run only echo for all the input and ignore | operation.
Help, please, what i have to do to run two commands with this logical operation?

A: You can avoid echo altogether. Piping can be simulated here by passing the echo argument to the stdin of the call to ./ft_ssl
actual = subprocess.Popen(['./ft_ssl', 'md5', '-s', data, '-p'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
output = actual.communicate(b'123')

See the docs for more details about communicate


text:
Q: Java - Array List Cumulation I am working on a project where I have a user enter two values
1) Country of Birth (ISO Short Code, such as US, UK, IN, etc)
2) Current Age.
At the end of the program, I'd like to output a breakdown of age by country, such as :
US: 1 - 10 (5 people) 11 - 20 (10 people)
UK: 1 - 10 (2 people) 11 - 20 ( 15 people) etc
I'm not even sure where to start with this.
Right now I have user entries (via Scanner) for both age and country of birth going to individual ArrayLists -- but I have no idea how to get the cumulative output.
Any suggestions or ideas on where I can look?
Thanks!

A: I would suggest you not put the countries and ages into separate lists. Instead create a single class to store both. It will look something like:
class Person {
    private final String country;
    private final int age;
}

Then have a list of Person objects that are created as the user enters data:
List<Person> people;

Classifying into country and age groups can be done in lots of different ways. The simplest is to build a multi level map that stores the information:
Map<String, Map<String, Integer>> classification;

In this case the first string is the country, the second string is the age bucket and the third is the count. The count of UK people aged 11-20 would be classification.get("UK").get("11-20").
That should be enough to get you started.


text:
Q: Optimalizing Django's QuerySetSequences In one of my views I have problem, that going into this url makes CPU usage 100% for like 5-10 mins. It means that for the next 5-10 mins my webpage is useless.
My bet is that's because of how many database queries I am trying to send.
Views.py that gives me trouble:
def guild_details(request, guild_name):
    fixed_guild_name = urllib.parse.unquote(guild_name)
    players = Player.objects.filter(guild=fixed_guild_name)

    last_month = datetime.today() - timedelta(days=30)
    deaths = reduce(QuerySetSequence, [Deaths.objects.filter(killed=player, date__gte=last_month) for player in players])
    kills = reduce(QuerySetSequence, [Deaths.objects.filter(killer=player, date__gte=last_month) for player in players])

    return render(request, 'guild.html', {'players': players,
                                          'deaths': deaths.order_by('-date'),
                                          'kills': kills.order_by('-date'),
                                          'guild_name': guild_name})

It seems not that bad, but consider that:

*

*Database includes over 6000+ "Players". (and rising)

*Database includes over 26000+ "Deaths". (and rising)

At first, I was thinking about doing cache for this webpage, but it's deaths / kills might change every 30 mins or so, so I don't think that will help much - considering that I have trouble accessing this page for the first time if players count is high (10+). If player count is small, I have no trouble accessing this page.
Also, I'm running redis / celery with scrapping on same server.
Is there something I could optimalize to make it work? Or should I just simply put more CPU into this?
My "top" command:
    last pid: 69974;  load averages:  4.28,  4.78,  5.49                                                                                up 2+11:16:22  12:40:46
14 processes:  5 running, 9 sleeping
CPU: 33.1% user,  1.4% nice,  6.0% system,  0.0% interrupt, 59.4% idle
Mem: 8965M Active, 30G Inact, 112K Laundry, 82G Wired, 3594M Free
ARC: 64G Total, 41G MFU, 19G MRU, 17M Anon, 857M Header, 2934M Other
     55G Compressed, 97G Uncompressed, 1.76:1 Ratio
Swap:

  PID USERNAME       THR PRI NICE   SIZE    RES STATE   C   TIME    WCPU COMMAND
41281 xxxx             1 103    0 65500K 61516K CPU0    0  15:27 100.34% python3.6
42147 xxxx             1 103    0 52956K 48584K CPU1    1   6:33  99.98% python3.6
41637 xxxx             1 103    0 56284K 52352K CPU9    9  14:44  96.18% python3.6
44812 xxxx             1  35   15 65132K 57864K CPU3    3   0:05   0.05% python3.6
51296 xxxx             4  35   15 12444K  7880K kqread  3   0:03   0.03% redis-server
69122 xxxx             1  35   15  7920K  3236K CPU5    5   0:00   0.02% top
40866 xxxx             1  35   15 13192K  8336K select  5   0:00   0.00% sshd
44823 xxxx             1  35   15 73836K 66868K select  2   1:03   0.00% python3.6
93909 xxxx             1  35   15 62060K 55860K select  5   0:04   0.00% python3.6
44811 xxxx             1  35   15  7668K  3688K select  4   0:01   0.00% screen
66149 xxxx             1  21    0  4691M    98M accept  3   0:00   0.00% php-fpm
93908 xxxx             1  35   15  7668K  3708K select  3   0:00   0.00% screen
40867 xxxx             1  35   15  8056K  4336K wait    3   0:00   0.00% bash
51295 xxxx             1  35   15  7668K  3656K select  1   0:00   0.00% screen

The first 3 are passenger_wsgi which turns manage.py ON.

A: You can use the __in [Django-doc] lookup and pass a list of Players here:
def guild_details(request, guild_name):
    fixed_guild_name = urllib.parse.unquote(guild_name)
    players = Player.objects.filter(guild=fixed_guild_name)

    last_month = datetime.today() - timedelta(days=30)
    deaths = Deaths.objects.filter(killed__in=players, date__gte=last_month)
    kills = Deaths.objects.filter(killer__in=players, date__gte=last_month)

    return render(request, 'guild.html', {'players': players,
                                          'deaths': deaths.order_by('-date'),
                                          'kills': kills.order_by('-date'),
                                          'guild_name': guild_name})
We thus make a query that also performs the ORDER BY in the same query.


text:
Q: MongoDB Group By query How I can implement on MongoDb this SQL Query
SELECT TOP 100 * FROM Tracks
WHERE ID IN (SELECT MAX(ID) FROM Tracks WHERE UserID IN ([UserIDs...]) GROUP BY UserID)

Tracks structure:
Tracks[{_id, userId, {lat, lon},  dateCreate, ...}, ...]

Thanks!

A: You'd want to use the aggregation framework for this:
db.Tracks.aggregate( [
    { $match: { 'UserID': { $in: [ UserIDs ] } } },
    { $group: { _id: '$UserID', max: { $max: '$_id' } },
    { $sort: { $max: -1 } },
    { $limit: 100 }
] );

First we match against the wanted UserIDs, then we group depending on UserID and also put the maximum _id value in the new max field. Then we sort by max descendently to get the highest max numbers first and then we limit by the top 100.


text:
Q: Facebook iFrame application -- IE7 not allowing cookies I know this topic has been covered extensively, but I am totally stuck and in need of some direction and new opinions.  I have a Facebook iFrame application that works perfectly in IE6,8, Safari, Chrome, FF, etc.  Only IE7 gives me grief.
I have created a P3P policy file, and its associated XML file.  The policy fully validates with the P3P policy validator.
As soon as the iFrame loads from within Facebook, the red eye icon appears and when I click it, it reports that cookies from the iFrame's domain are blocked.  I have confirmed that the default 'medium' privacy setting is set on IE7.  Interestingly I've found that by removing Google Analytics, the page will load initially without blocking the cookies, but as soon as the page reloads, or the user logs in, cookies are then blocked again even though the P3P header is sent immediately from every page.  All assets are sent via S3, so there shouldn't be any issues there.
FYI, here's my P3P file; I've tried absolute paths, relative paths, switching order of CP and policyref, and separated the two into separate header calls with no luck.
header('P3P: CP="NON DSP TAIa PSAa PSDa OUR IND UNI", policyref="/w3c/p3p.xml"');

I have confirmed that the P3P Header is being sent and received by the browser.  I have added a META p3p tag to the HTML page.  I have removed all redirects.  Still the issue persists.  I've spent so much time looking into this, and I am now out of ideas.  Any thoughts or ideas about how to approach this from a fresh perspective would be greatly appreciated.  I'm using PHP 5.3.5 over NGINX.  No framework being used...

A: I had the same problem. Facebook iframe app worked great in all browsers except IE7. When you first went to the app it loaded fine. But then when you clicked a link it would load the page okay but then after a second or so would refresh and redirect the browser. In the end you just got a blank page. I also had the red eye icon blocking the cookies.
The culprit turned out to be the javascript code which loads the facebook javascript lib:
FB.init({
            appId  : '<?=FACEBOOK_APP_ID?>',
            status : true, // check login status
            cookie : true, // enable cookies to allow the server to access the session
            xfbml  : true  // parse XFBML
        });

To fix the problem I changed status : true, to status : false. Now when clicking links the page loads and doesn't refresh.
So whats really going on here I am not sure but I have a guess...The redirect was being caused by the FB javavascript checking the login status and for some reason thinking the user was logged out and so redirecting to a login page. The server side login script I guess would then see that you had indeed logged in and redirect you back to the app. So on and so on.
So the problem of IE7 not setting the cookies set inside the iframe still exists, the evil eye remains. But as long as the links inside your iframe reference the parent window target="_top" pointing at the facebook canvas page it seems you don't need the cookie anyway. The PHP SDK looks for the session in a number of places starting with $_REQUEST. I am guessing that when facebook loads the iframe it includes the session param in the query string. So even though the cookies don't work in IE7 through the iframe your server scripts will still get them from the query param.
Hope that makes some sort of sense, I don't totally get it but it fixed my app.

A: i don't know but maybe this will help, it worked like a charm on my app.
header('P3P: CP="CAO PSA OUR"');
ob_start();
session_start();


text:
Q: .net core assembly can not concurrently run on linux I wrote an dotnet core app for running on linux.
published a single executable file with self-contained enabled.
dotnet publish -c Release -r linux-x64 -o ${dst_path} -v n /p:PublishTrimmed=true /p:PublishSingleFile=true

But strangely it can only run a single instance.
Because when it's running, it will remove the execute permission of the file.
$ ./Test
10/21/2020 11:50:27 AM [Info] Server started at ws://0.0.0.0:12500 (actual port 12500)
$ ls -l Test  <---------Test is running, ls -l is executed in another terminal
-rw-rw-rw- 1 root root 53081298 10月 21 11:50 Test

And execute permission is added back after the runnning process exited.
$ ls -l Test  <------------Test is not running.
-rwxrwxrwx 1 root root 53081298 10月 21 11:50 Test

So I can not start more than one process.
I am really confused with this problem.
Could anyone help?

A: Sorry for bothering, I found the root reason.
Just in case other may encount the same stupid situation,  leave a message here.
My problem is caused by virutalBox.
Because I put my published assembly Test in the shared directory of my host between shared virtual machine.
After move my file Test to virtual machine's home directory, it works well.
And thank you for your help @jdoer1997


text:
Q: Why does my app keep crashing when I use  in android layout? I have a fragment that holds a google map.
  <fragment xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:map="http://schemas.android.com/apk/res-auto"
            xmlns:tools="http://schemas.android.com/tools"
            android:id="@+id/map"
            android:name="com.google.android.gms.maps.SupportMapFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_alignParentStart="true"
            android:layout_below="@+id/relativeLayout"
            tools:context="com.xxxxx.MapsActivity" />

I would like to create a view that is approx 250 x 300 that sits on the map.
Initially I used a ViewFlipper and then a RelativeLayout. That seemed to work but I realised ViewFlipper isn't used for this purpose.
So I changed ViewFlipper to View and RelativeLayout to constraintlayout but the app keeps crashing.
Under the map fragment I have the following:
 <android.support.constraint.ConstraintLayout
        android:id="@+id/view"
        android:layout_width="250dp"
        android:layout_height="300dp"

        <View
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_width="250dp"
            android:layout_height="300dp">

         <Button>
            .....................
            ....................
         </Button>

        </View>
    </android.support.constraint.ConstraintLayout>

But after doing a bit of reading is there no simple customisable  component that can be used like in iOS?
Thanks.


text:
Q: Connect to MySQL database w/ C# as non-root user? Let me start by saying I'm completely new to databases, but have been reading through the MySQL tutorial they have.
Right now, I'm trying to make an app that allows unprivileged users (non-root) to connect and do some commands on a database through a C# GUI app. The users will login to the database using windows authentication.
Now, I was able to to make a quick GUI where the person running the program can connect to the database on a local host using "root" and get whatever content is in it.
My question is, how exactly do I allow users to connect w/ non-root privileges? The only things I've been able to find all deal w/ using the connection string w/ "root" as the user.
Edit: The database is already made. I won't personally be able to connect to it as a root user and give other users permissions.

A: You could use the grant syntax, as root to grant permissions to other users. E.g.:
GRANT ALL PRIVILEGES ON mydatabase.* TO pfinferno

A: Well, first of all, you have to realize that this "root" (from MySQL) is different from the "root" user (from your computer).
When you log on MySQL database (as root firstly), you can create another user with least privileges. (Creating user: https://dev.mysql.com/doc/refman/5.1/en/create-user.html)
After that, you can give (grant) some privileges to this specific user. (Granting privileges: https://dev.mysql.com/doc/refman/5.1/en/grant.html)
You can, for instance, allow that some user will only select data from the tables. Another user can insert/update. And so on.
So, in your application, you can specify another user instead of root, as you can normally see.

A: Some important concepts too are the rows in the table shown here:
select user,host,password from mysql.user where user='pfinferno';

Important takeaways, users can have multiple hostnames or wildcard. Each have their own rights and passwords. Though the password from the above is hashed, at least you can quickly eyeball it so see if all the passwords match (such as root with 3 accounts).
The host column is populated by the following values, mostly:
Specimen A:

*

*localhost

*127.0.0.1

*%

*common names such md21.newyork.comcastbusiness.net and the like

The % value is the wildcard. It is for flexibility, but it can be highly dangerous when used with users like 'root'@'%'. Keeping root as the 1st two only in Specimen A is highly advised. Also, the first two are quite different in different tools. What I recommend is having a root user row for the first two, and keeping the passwords the same. There are pros and cons to this approach. But remember that when you can't connect that something else out there was relying on the connection, be it an agent, phpmyadmin, a tool, the my.conf settings, etc. You will be revisiting this a lot.
In the example given by Mureinik it grants privileges to the user with the wildcard host = %. This means it is banking on a user created as such. Note that it is typical to have user accounts setup that way. Though there is nothing restricting you to locking it down tighter.

When a user attempts to connect to the server, the user he is ultimately connected as can be resolved to a different user/host combo, as can be seen in the case where there is no localhost (host) user or common-name, but rather one with a host value of wildcard %. This can be seen with this query:
Specimen B:
select current_user(),user();

The latter is the user presented by the connection attempt, the former is the one that was resolved and actual. The implications can cause one to waste days in debugging, as can be seen in these forums. Some people can't connect for days, I am serious.
Specimen C:
create user 'pfinferno'@'localhost' identified by 'thePassword';
create user 'pfinferno'@'127.0.0.1' identified by 'thePassword';
create user 'pfinferno' identified by 'thePassword';
create user 'pfinferno'@'md21.newyork.comcastbusiness.net' identified by 'thePassword';

-- note #3 above is same as 'pfinferno'@'%'
Now granted, the host name may be wildcard for normal users, and host name may be localhost and 127.0.0.1 for root only. But in the attempt to lock down security, admins often create user accounts based on hostname coming in (such as Specimen C, line 4), and vary security with grants based on that. Managing it can be a bit overwhelming. So they often just say screw it, I will create the wildcard user. That may be fine for a new user, say Susie, but for Secimen C line 4, if that is who you are coming in, you can have grants on line 3 user that you won't pick up. So the resolving of what user your are actuallity (See Specimen B), goes from most specific hostname to fallback to more general, until it finds one such as wildcard.
Unfortunately, users don't connect with hostname specified per se, they just are what they are. They try to connect. So you don't say hey I want to be this thing @hostname, you just are what you are. You are 'pfinferno'@'md21.newyork.comcastbusiness.net', but may fallback to wildcard.
If users are dropped in Specimen C except for wildcard %, well you better have the grants that went with them that you expect, because you are now a new user.
Try to limit the use of wildcards on the grant statement to not do *.* as in the lazy approach, which would just grant rights to all databases and tables. In Mureinik's example, it was for all tables in one database. Not too shabby. Try to fine tune rights, such as granting SELECT privileges on tables or not at all, to users that don't need them. Be careful with WITH GRANT OPTION as seen on the net with cut and paste from it. If you use it, you just granted the user rights to grant other users rights.
SSH Tunnels
One reason you might not want to use Secimen A host = % wildcard (other than the obvious We are Risk Averse) is that
create user 'pfinferno'@'localhost' identified by 'thePassword';

is perfect for SSH Tunnels. You would be connecting through a cryptographically secure channel with PKI, and present yourself as if you are @ localhost. This drastically reduces security exposure.

Why Can't I Connect?
Hopefully the below visual with little commentary can show why I named this section as I did.
drop user 'pfinferno'@'localhost';
drop user 'pfinferno'@'127.0.0.1';
drop user 'pfinferno'@'%';
drop user 'pfinferno'@'md21.newyork.comcastbusiness.net';
flush privileges; -- some say this is not necessary, I have found otherwise

create user 'pfinferno'@'localhost' identified by 'thePassword';
create user 'pfinferno'@'127.0.0.1' identified by 'thePassword';
create user 'pfinferno' identified by 'thePassword';
create user 'pfinferno'@'md21.newyork.comcastbusiness.net' identified by 'thePassword';

...
select user,host,password from mysql.user where user='pfinferno';

grant all on so_gibberish.* to 'pfinferno'@'%'; -- grant all rights on so_gibberish db

flush privileges; -- some say this is not necessary, I have found otherwise

Look at some grants.
show grants for 'pfinferno'@'localhost';    -- sandboxed. Can just log in and sit there
+-----------------------------------------------------------------------------------------+
| Grants for pfinferno@localhost                                                          |
+-----------------------------------------------------------------------------------------+
| GRANT USAGE ON *.* TO 'pfinferno'@'localhost' IDENTIFIED BY PASSWORD '*74692AE70C53...' |
+-----------------------------------------------------------------------------------------+

show grants for 'pfinferno'@'127.0.0.1';    -- sandboxed. Can just log in and sit there
same as above

show grants for 'pfinferno'; -- wildcard % user, has all rights on so_gibberish;
+-----------------------------------------------------------------------------------------+
| Grants for pfinferno@%                                                                  |
+-----------------------------------------------------------------------------------------+
| GRANT USAGE ON *.* TO 'pfinferno'@'%' IDENTIFIED BY PASSWORD '*74692AE70C53...'         |
| GRANT ALL PRIVILEGES ON `so_gibberish`.* TO 'pfinferno'@'%'                             |
+-----------------------------------------------------------------------------------------+

Note above that GRANT USAGE means at least you have the rights to log in and sit (sandboxed). But the wildcard %user also has all rights on so_gibberish db in its entirety.
Now I go to mysql prompt via mysql -u pfinferno -pthePassword
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
+--------------------+

mysql> select current_user(),user();
+---------------------+---------------------+
| current_user()      | user()              |
+---------------------+---------------------+
| pfinferno@localhost | pfinferno@localhost |
+---------------------+---------------------+

The attempted user (user()) was resolved to the same (current_user()). I was  sandboxed, able to do basically nothing, except select now() til bored to death.
mysql> use so_gibberish;
ERROR 1044 (42000): Access denied for user 'pfinferno'@'localhost' to database 'so_gibberish'

quit mysql CLI as that user.
Now
drop user 'pfinferno'@'localhost';
drop user 'pfinferno'@'127.0.0.1';
drop user 'pfinferno'@'md21.newyork.comcastbusiness.net';

I just dropped three out of four of my pfinferno users
Go to mysql prompt via mysql -u pfinferno -pthePassword
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| so_gibberish       |
+--------------------+

mysql> select current_user(),user();
+----------------+---------------------+
| current_user() | user()              |
+----------------+---------------------+
| pfinferno@%    | pfinferno@localhost |
+----------------+---------------------+

mysql> use so_gibberish;
Database changed

This shows that @ the CLI (or any program) from any host, that the attempt to connect is first as presented by user and then as resolved to actual ( see the output from user() and current_user(), respectively).
So, perhaps oddly, as I dropped users, the EFFECTIVE RIGHTS increased as the user was resolved to a different one. This can be the subject of hours/days/weeks of debugging. Users can have no clue who they are really logged in as (resolved to), or why they can't, as each, by the way, can have a different password ! This is especially true with user root with several rows in mysql.user ... and considering that probably 50% of all mysql users connect with it, initially, as developers. Just a guestimate.


text:
Q: Is there a visual modeling tool / language or style which supports Scala profile?
[Similarly sounding question currently active on SO is " Is there a visual modeling language or style for the functional programming paradigm? " which is different then this question because another is focusing only on Functional programming paradigm and my question is looking for a modeling tool which supports combination of Object Oriented Paradigm (which independently has many well established visual modeling UML tools) and Functional Programming Paradigm together.

Is there a visual modeling tool / language or style which supports Scala profile (provides and includes all Scala language artifacts) or can say that it supports the object oriented programming paradigm and the functional programming paradigm, together.
For an Enterprise scale Scala project, with what modeling tool - the business analyst prepare Visual Models or any other type of model(s) for Logical (conceptual) view and Development view?

*

*The logical view is concerned with the functionality that the system provides to the end-users.

*The development view illustrates a system from a programmer's perspective and is concerned with software management.

In certain circles of software development, formal modeling is a requirement, no matter how bureaucratic you consider this to be. There are several levels of involvement from different teams on the conclusion of a project and many of the people involved have no idea about the code. They don't need to have, it'd be a major hassle if that was asked of them. The formal modeling is there to assure that they'll get a better view of how things work so that they can perform their roles in the development.
  (This paragraph is taken from: https://stackoverflow.com/users/166802/codnik)

A: Unfortunately there doesn't seem to be one available.
I have a PhD student friend who is working on formalising modelling techniques, however he is not building a PoC.


text:
Q: Developing on android-based device via wireless One known way to develop your android application directly onto the device is using the usb connector and install the driver using eclipse. As such, is there a known way to do this wireless?
EDIT:
Ideally this shouldn't require rooted device.

A: UPDATE: This is now natively supported with recent SDKs. Look here under "Wireless Usage".
In short:

*

*Connect to your device via USB

*Enter "adb tcpip 5555"

*Unplug your device

*Look up your device's IP in the system settings

*Enter "adb connect [ip address]:5555"

*That's it!

For the record, here is the old version of the answer:
Install the wireless ADB app. Details here: http://www.androidcentral.com/android-quick-app-adb-wireless
EDIT: Okay, that one requires root. If you don't have root, it's going to be a bit more cumbersome. Off the top of my head, here's what you can do:

*

*Use any means of wireless transfer (Bluetooth or FTP, there are lots of apps for either on the market) to transfer the APK file from your computer to the phone.

*Use a file manager (OI File Manager, for example) to navigate to the file and open it.

Step 1 can be automated through the command line if you're using FTP (and, at least on Unix-based systems, most likely via Bluetooth as well).
Step 2, well, cannot be simplified THAT easily. But you could write an installer app that simply does an ACTION_VIEW on the APK file on your phone.
Obviously, this will go through the package installer, so you'll have to confirm the installation process and everything. But hey, it's wireless :)
(Side note: There are several telnetd and sshd solutions on Android, but none that I could find are for non-rooted phones. If you can get a telnet/ssh connection going, you may be able to make this process more comfortable.)

A: Are you sure there isn't some form of adb already running?  Look in settings for anything about enabling debugging.  Get a terminal emulator app such as connectbot, start it up and do 'ps' to see what is running.
If you post the name of the tablet (and google it!) there might be some known solutions already

A: For those who have a rooted phone can use an app from Google Play which simplifies very much making a wireless connection. Try this one https://play.google.com/store/apps/details?id=com.ttxapps.wifiadb&hl=en. It worked for me.


text:
Q: How to choose correct linspace sample data to obtain correct dominant frequency result I have a Python snippet of code I found. I used it to create useful Python code to extract the dominate frequency. I know the code works because I have used it with the default N and Nev values on some runs and received the same Strouhal number (St) as the sinusoidal method.
I am evaluating the frequency of a vortex street, so I don't have DC frequency, but I am getting "0.0". I tested the values of N and Nev when the code was working. I noticed the final result of the dominate frequency is very dependent on N.
I have looked at suggested posts, but they fall short. Here is the code. How do I adjust sample for linspace as my lift data increases?
#1/usr/bin/env python

import sys
import numpy as np
import scipy.fftpack as fftpack
import matplotlib.pyplot as plt

print("Hello World!")

N = 2500
Nev = 1000

data = np.loadtxt('CoefficientLiftData.dat', usecols= (0,3))

times = data[:,0]
length = int(len(times)/2)

forcez= data[:,1]
t = np.linspace(times[length], times[-1], N)
forcezint = np.interp(t, times, forcez)

fourier = fftpack.fft(forcezint[Nev-1:N-1])
frequencies = fftpack.fftfreq(forcezint[Nev-1:N-1].size, d=t[1]-t[0])
#print(frequencies)
freq = frequencies[np.argmax(np.abs(fourier))]

print(freq)

A: Did you have a look at this answer on how to choose the correct frequency scale? Additionally you should have a look on window functions, like the Tukey window to get the correct frequencies of your signal, if the signal is not equal at the interval boundaries.
Edit: And you could also have a look at this answer that gives detailed explanation on how to get proper results for an FFT analysis.


text:
Q: Why Hibernate re-update when querying objects causes Batch update returned unexpected row count? I am writing a Test class to test my DAO (ProjectDao). Only one table in the database (for Project) and no association in persistence object.
Here is my base test class (for @Before and @After methods):
@TransactionConfiguration
@Transactional
public class DaoTestBase extends AbstractTransactionalJUnit4SpringContextTests {

@Autowired
protected ProjectDao projectDao;

@Autowired
protected List<Project> dummyProjects;

@Before
public void initTestData() throws Exception {
    projectDao.deleteAll();

    for (Project project : dummyProjects) {
        projectDao.saveOrUpdate(project);
    }
}

@After
public void clearTestData() throws Exception {
    projectDao.deleteAll();
}
}

And here is the actual Test class with 2 test methods:
@ContextConfiguration(locations = {
    "classpath*:database/dummy-beans-test.xml",
    "classpath*:springcontext/*test.xml"})
public class ProjectDaoTest extends DaoTestBase {

private static final Comparator<Project> PROJECT_COMPARATOR =
        new Comparator<Project>() {
    public int compare(Project o1, Project o2) {
        if (o1.getNumber() < o2.getNumber()) {
            return -1;
        } else if (o1.getNumber() == o2.getNumber()) {
            return 0;
        } else {
            return 1;
        }
    };
};

@Test
public void shouldQueryTheSameAsDummyObjects() throws Exception {
    List<Project> projects = projectDao.getAll();
    Assert.assertEquals(dummyProjects.size(), projects.size());

    Set<Project> preProjects = new TreeSet<Project>(PROJECT_COMPARATOR);
    preProjects.addAll(dummyProjects);

    for (Project project : projects) {
        if (preProjects.contains(project)) {
            preProjects.remove(project);
        }
    }

    Assert.assertEquals(0, preProjects.size());
}

@Test
public void deleteSomeProjectsShouldRemoveThem() throws Exception {
    List<Project> projects = projectDao.getAll();
    Assert.assertEquals(3, projects.size());

    for (Project toDeleteProject : projects) {
        projectDao.delete(toDeleteProject);

        List<Project> remainProjects = projectDao.getAll();
        for (Project project : remainProjects) {
            if (project.getNumber() == toDeleteProject.getNumber()) {
                Assert.assertTrue(false);
            }
        }
    }
}
}

The problem is when i ignore one of the test method above, everything is tested fine but when i test both of them, it will cause:
Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1

Inspecting the Log i see that when executing first test, Hibernate do these SQL:
Hibernate:
delete
from
    project_table
Hibernate:
insert
into
    project_table
    (pro_customer, pro_end_date, pro_name, pro_number, pro_start_date, pro_status)
values
    (?, ?, ?, ?, ?, ?)
Hibernate:
insert
into
    project_table
    (pro_customer, pro_end_date, pro_name, pro_number, pro_start_date, pro_status)
values
    (?, ?, ?, ?, ?, ?)
Hibernate:
insert
into
    project_table
    (pro_customer, pro_end_date, pro_name, pro_number, pro_start_date, pro_status)
values
    (?, ?, ?, ?, ?, ?)
Hibernate:
select
    this_.id as id0_0_,
    this_.pro_customer as pro2_0_0_,
    this_.pro_end_date as pro3_0_0_,
    this_.pro_name as pro4_0_0_,
    this_.pro_number as pro5_0_0_,
    this_.pro_start_date as pro6_0_0_,
    this_.pro_status as pro7_0_0_
from
    project_table this_
Hibernate:
delete
from
    project_table

And when executing second test, they do:
Hibernate:
delete
from
    project_table
Hibernate:
update
    project_table
set
    pro_customer=?,
    pro_end_date=?,
    pro_name=?,
    pro_number=?,
    pro_start_date=?,
    pro_status=?
where
    id=?
Hibernate:
update
    project_table
set
    pro_customer=?,
    pro_end_date=?,
    pro_name=?,
    pro_number=?,
    pro_start_date=?,
    pro_status=?
where
    id=?
Hibernate:
update
    project_table
set
    pro_customer=?,
    pro_end_date=?,
    pro_name=?,
    pro_number=?,
    pro_start_date=?,
    pro_status=?
where
    id=?
Hibernate:
delete
from
    project_table

Before and after these Hibernate actions in each test, i noticed that Hibernate opened and closed Session (and rolled back transaction). So my questions are:
1/ Why in the @Before method of second test, Hibernate did not insert data (the data they inserted in the first method have been rolled back?!).
2/ Why in the second test method i only getAll (using criteria) and Hibernate updated the data?!
3/ Why is the Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1 is this case?
In the DAO's implementation i retrieved current Session from SessionFactory, do query using criteria. E.g. for getAll() method:
sessionFactory.getCurrentSession()
                .createCriteria(type)
                .list()

A: If I understand correctly, your project entities are in fact Spring beans coming from the Spring context. The Spring context, by default, is shared between tests.
The first test attaches these entities to the session using saveOrUpdate() and thus generates an ID for them. Then it deletes them from the database.
The second test then calls saveOrUpdate() with these exact same Project instances as argument. Since they already have an ID, Hibernate considers that they're detached Project instances that should already exist in the database, and uses update queries to update them. But since they don't exist in the database anymore, the query fails.
You should not reuse Project entity instances between tests. Create the instances from scratch in your @Before method instead of getting them from the Spring context.


text:
Q: Function to swap array elements by reference I'm trying passing an array to change its elements by reference.
Example:
Input element 1 = 4 / element 2 = 5 / element 3 = 6
Output element 1 = 6 / element 2 = 4 /element 3 = 5
Inside the swap function, the swapping is working but when I print the array in the main function, it prints the original array without swapping it.
Code bellow:
    void swap1(int *n1, int *n2, int *n3)
{
    int temp = *n3;
    *n3 = *n2;
    *n2 = *n1;
    *n1 = temp;

}

int main(int argc, char** argv) {

    int arr[3];

    for(int i = 0; i<3; i++)
    {
        printf("Input %d:", i+1);
        scanf("%d", arr+i);

    }

    swap1(arr, arr+1, arr+2);

    for( int i =1; i <=3; i++)
    {
        printf("After swap element %d - %d\n", i, arr[i] );
    }

    return (EXIT_SUCCESS);
}

Thank you in advance for your help.

A: Your problem is here:
for( int i =1; i <=3; i++)
{
    printf("After swap element %d - %d\n", i, arr[i] );
}

this code should be:
for( int i =0; i <3; i++)
{
    printf("After swap element %d - %d\n", i+1, arr[i] );
}

Remember that on C arrays start at 0.


text:
Q: Phantomjs wont let me use jQuery ajax POST So I'm trying to get the source of a page with phantomjs and then use jquery to post that source to a php page for further processing.
Heres my First PHP page
    <?php
$output = shell_exec("sudo /usr/local/bin/phantomjs --proxy=127.0.0.1:8118 --web-security=false ./test.js");
?>

And it fires test.js just fine!
I'm running phantomjs on Linux CentOS 64bit
Below is Test.js where I want to go to a git hub page then once its loaded, i want to evaluate the page, get the html for the page, inject jQuery make sure there is no conflicts and then send that page source to post-put-or-get.php.
I've tested jquery and it is being injected and basic dom manipulation is working, I can change the font size of the git hub page etc
I've tried post, put and get, everything on the Test.js page works but not the Jquery Ajax call?
I've tried async on and off, different content types but its like the jQuery.ajax is being ignored for some reason?
Ive even tried ditching jquery and using just javascript to try and post but still nothing, I just cant post?
Am I doing something crazy or is something broke that should be fixed?
    var page = require('webpage').create();

page.onConsoleMessage = function(msg) {
    console.log(msg);

};
page.open("https://github.com/logxen/SmoothieBoard/tree/feature/5driver", function(status) {

    if ( status === "success" ) {

    page.evaluate(function() {
    data = document.body.innerHTML;
    console.log(data);

    page.injectJs('jquery-1.7.2.min.js');
    jQuery.noConflict();
    jQuery.ajax({
      type:'POST',
      async: false ,
      url:'post-put-or-get.php',
      contentType: 'application/x-www-form-urlencoded',
      data:'htmlsource='+data,
      success:function(datafeed) {
        if(datafeed) {
            console.log(datafeed);
        } else {
            console.log("no joy");
        }
      }
   });

    });
    phantom.exit();

    }
});


text:
Q: Wrap text in div with ellipses (+ drop wrapping of floating div) Ok been banging my head against the desk for awhile with this one .. want to achieve the following
1) Header (nav) should be on one line with no wrapping (this includes nav-back, nav-title & nav-next)
2) when you shrink the window nav-title should shrink AND when the window doesn't allow the ability to show all the text it should be cut off with ellipses (eg 'This is way too lon..')
Here is what I'm working from:

<

Want this no-wrap with ellipses

Same here

>

with styling on jsfiddle

A: You're applying the ellipses overflow properties to the .nav container instead of the titles.
JSFiddle
CSS
.nav .nav-main-title, .nav .nav-sub-title {
    white-space:nowrap;
    overflow:hidden;
    text-overflow:ellipsis;
    width: inherit;
}


text:
Q: Filter rows in a pandas DataFrame I am looking for a way to filter rows in a DataFrame. I have the following data:
data = [
    {'year':2015, 'v1':'str1', 'v2':'str2', 'v3':'str3', 'val': 6},
    {'year':2016, 'v1':'str1', 'v2':'str2', 'v3':'str3', 'val': 5},
    {'year':2017, 'v1':'str1', 'v2':'str2', 'v3':'str3', 'val': 3},
    {'year':2015, 'v1':'str11', 'v2':'str2', 'v3':'str3', 'val': 4},
    {'year':2016, 'v1':'str11', 'v2':'str2', 'v3':'str3', 'val': 9},
    {'year':2017, 'v1':'str12', 'v2':'str2', 'v3':'str3', 'val': 1},
    {'year':2016, 'v1':'str1', 'v2':'str21', 'v3':'str3', 'val': 9},
    {'year':2017, 'v1':'str1', 'v2':'str21', 'v3':'str3', 'val': 7},
    {'year':2018, 'v1':'str1', 'v2':'str21', 'v3':'str3', 'val': 8},
    {'year':2015, 'v1':'str1', 'v2':'str2', 'v3':'str31', 'val': 6},
    {'year':2016, 'v1':'str1', 'v2':'str2', 'v3':'str31', 'val': 5},
    {'year':2016, 'v1':'str1', 'v2':'str2', 'v3':'str31', 'val': 6},
    {'year':2017, 'v1':'str1', 'v2':'str2', 'v3':'str31', 'val': 3},
    {'year':2018, 'v1':'str1', 'v2':'str2', 'v3':'str31', 'val': 4}
]

The filtering rule: if there are not at least three subsequent years, starting with 2015, with rows which match in v1, v2 and v3, then those rows should be removed. The rows which match in v1, v2 and v3 for at least three subsequent years from 2015 on, should be kept.
The expected output after filtering for the example above is:
import pandas as pd
df = pd.DataFrame(data)
# filtering step
print(df)

    year     v1     v2     v3  val
0   2015   str1   str2   str3    6
1   2016   str1   str2   str3    5
2   2017   str1   str2   str3    3
3   2015   str1   str2  str31    6
4   2016   str1   str2  str31    5
5   2016   str1   str2  str31    6
6   2017   str1   str2  str31    3
7   2018   str1   str2  str31    4

Any ideas?

A: You can chain two groupby+filter
v = ['v1', 'v2', 'v3']

(df.groupby(v).filter(lambda s: 2015 in s['year'].values)
   .groupby(v).filter(lambda s: s.year.nunique() >= 3) and s.year.diff().isin([0, 1, np.nan]).all())

   year    v1    v2     v3  val
0  2015  str1  str2   str3    6
1  2016  str1  str2   str3    5
2  2017  str1  str2   str3    3
3  2015  str1  str2  str31    6
4  2016  str1  str2  str31    5
5  2016  str1  str2  str31    6
6  2017  str1  str2  str31    3
7  2018  str1  str2  str31    4

A: I feel like we can short the filter as below
df.groupby(['v1','v2','v3']).filter(lambda x : pd.Series([2015,2016,2017]).isin(x['year']).all())
Out[142]:
    year    v1    v2     v3  val
0   2015  str1  str2   str3    6
1   2016  str1  str2   str3    5
2   2017  str1  str2   str3    3
9   2015  str1  str2  str31    6
10  2016  str1  str2  str31    5
11  2016  str1  str2  str31    6
12  2017  str1  str2  str31    3
13  2018  str1  str2  str31    4


text:
Q: MySQL - phpmyadmin alert message CREATE TABLE `projekt_ti_cdv`.`offer` ( `offer_id` INT(2) NOT NULL AUTO_INCREMENT , `offer_type` VARCHAR(256) NOT NULL , `offer_price` INT(256) NOT NULL , `offer_realization` INT(256) NOT NULL , `offer_any_daw` VARCHAR(100) NOT NULL , `offer_vst` VARCHAR(256) NOT NULL , PRIMARY KEY (`offer_id`)) ENGINE = InnoDB;

I tried to create table on my database and i got an alert message from localhost 'Please enter a valid length'. I don't know how to fix that.
BR,
Chris

A: The maximum length allowed for the INT datataype is 255. You need to fix that in your statement.
I am unsure that you do want to specify a length anyway. The INT size is always 4 bytes, regardless of the specified length - the length is just here to specify the padding that is used when displaying the values in the command line client.
I would recommend:
CREATE TABLE `projekt_ti_cdv`.`offer` (
    `offer_id` TINYINT NOT NULL AUTO_INCREMENT ,
    `offer_type` VARCHAR(256) NOT NULL ,
    `offer_price` INT NOT NULL ,
    `offer_realization` INT NOT NULL ,
    `offer_any_daw` VARCHAR(100) NOT NULL ,
    `offer_vst` VARCHAR(256) NOT NULL ,
    PRIMARY KEY (`offer_id`)
) ENGINE = InnoDB;

I changed the datatype of column offer_id to TINYINT, since you seem to want a smaller number for this: it can store values up to 127 (or 255 when unsigned). See the documentation for more about integer datatypes storage and ranges.


text:
Q: How to extract first element from a JSON structure in KQL? I have a JSON data structure like this stored in a column:
{
  "Attributes": "[\"AnAttribute\"]",
  "WorkItems": "[\"674746\"]",
  "AuthorAliases": "[\"AnAlias\"]"
}

I want to extract the first element from one of the arrays. I try the below, but it doesn't work. What am I misunderstanding here?
Query
let t = datatable (data:string) [
   @'{"Attributes": "[\"AnAttribute\"]","WorkItems": "[\"674746\"]","AuthorAliases": "[\"AnAlias\"]"}'
];
t
| extend asDyn = todynamic(data)
| extend WorkItems = asDyn["WorkItems"]
| extend WorkItem = WorkItems[0]

Result

data
asDyn
WorkItems
WorkItem

{"Attributes": "["AnAttribute"]","WorkItems": "["674746"]","AuthorAliases": "["AnAlias"]"}
{"Attributes": "["AnAttribute"]", "WorkItems": "["674746"]",  "AuthorAliases": "["AnAlias"]"}
["674746"]

A: let t = datatable (data:string) [
   @'{"Attributes": "[\"AnAttribute\"]","WorkItems": "[\"674746\"]","AuthorAliases": "[\"AnAlias\"]"}'
];
t
| extend asDyn = parse_json(data)
| extend WorkItems = parse_json(tostring(asDyn["WorkItems"]))
| extend WorkItem = WorkItems[0]

data
asDyn
WorkItems
WorkItem

{"Attributes": "["AnAttribute"]","WorkItems": "["674746"]","AuthorAliases": "["AnAlias"]"}
{"Attributes":"["AnAttribute"]","WorkItems":"["674746"]","AuthorAliases":"["AnAlias"]"}
["674746"]
674746

Fiddle


text:
Q: std::map default value (move only types) How to solve std::map default value for move-only types? It seems like the problem is who owns the object

*

*If the value exists, the map stays owner, and a T const& must be returned

*If the value does not exits, the caller will be the owner, and a T (move-constructed from the default value) must be returned.

But the return-type of the function must be the same regardless of where the return value came from. Thus it is impossible to take the default value from a temporary. Am I correct?
You could use std::shared_ptr but that would be cheating.

A: This can be achieved with a proxy object.
template <typename T>
class PossiblyOwner
{
public:
    struct Reference {};

    PossiblyOwner(const PossiblyOwner & other)
       : m_own(other.m_own),
         m_ref(m_own.has_value() ? m_own.value() : other.m_ref)
    {}
    PossiblyOwner(PossiblyOwner && other)
       : m_own(std::move(other.m_own)),
         m_ref(m_own.has_value() ? m_own.value() : other.m_ref)
    {}

    PossiblyOwner(T && val) : m_own(std::move(val)), m_ref(m_own.value()) {}
    PossiblyOwner(const T & val) : m_own(val), m_ref(m_own.value()) {}
    PossiblyOwner(Reference, const T & val) : m_ref(val) {}
    const T& value () const { return m_ref; }
    operator const T& () const { return m_ref; }

    // convenience operators, possibly also define ->, +, etc.
    // but they are not strictly needed
    auto operator *() const { return *m_ref; }
private:
    std::optional<T> m_own;
    const T & m_ref;
};

// Not strictly required
template <typename T>
std::ostream & operator<<(std::ostream & out,
              const PossiblyOwner<T> & value)
{
    return out << value.value();
}
template <typename Container, typename Key, typename ...DefaultArgs>
auto GetOrDefault(const Container & container, const Key & key,
                  DefaultArgs ...defaultArgs)
    -> PossiblyOwner<decltype(container.find(key)->second)>
{
    auto it = container.find(key);
    using value_type = decltype(it->second);
    using ret_type = PossiblyOwner<value_type>;
    if (it == container.end())
        return {value_type(std::forward<DefaultArgs>(defaultArgs)...)};
    else
        return {typename ret_type::Reference{}, it->second};
}

Then the usage can be:
int main()
{
    std::map<int, std::unique_ptr<std::string>> mapping;
    mapping.emplace(1, std::make_unique<std::string>("one"));
    mapping.emplace(2, std::make_unique<std::string>("two"));
    mapping.emplace(3, std::make_unique<std::string>("three"));
    std::cout << *GetOrDefault(mapping, 0,
                 std::make_unique<std::string>("zero")) << "\n";
    std::cout << *GetOrDefault(mapping, 1,
                 std::make_unique<std::string>("one1")) << "\n";
    std::cout << *GetOrDefault(mapping, 3,
                 new std::string("three1")) << "\n";
}

Edit
I have noticed that the default copy constructor of PossiblyOwner<T> causes undefined behavior, so I had to define a non-default copy and move constructors.


text:
Q: LFS: Git credentials for..XXXX..not found. Your user name must be of the form DOMAIN\user So we are trying to setup GIT LFS with on premises TFS and we are having a couple of errors. The errors and setup are described below:
Setup:
1) On-premises TFS 2017 w/Update 1
2) Visual Studio 2015 w/Update 3
3) Atlassian SourceTree (Git Client)
4) GIT LFS is installed on the developer's system
5) The Git Credential Manager for Windows (GCM)
Errors:

*

*Going to Tools->Options->[Git Tab] in SourceTree and selecting [Use System Git] and trying to checkout a version of the file from history results in the following error:

git-lfs/2.0.1 (GitHub; windows amd64; go 1.8; git 678cdbd4) git
  version 2.12.1.windows.1
$ git-lfs.exe filter-process Error downloading object: Framework4.dll
  (ef57f778c9fd50b27144784cd1df55b1b014d564ad6d8d726b156748219b8e5f)
Smudge error: Error downloading Framework4.dll
  (ef57f778c9fd50b27144784cd1df55b1b014d564ad6d8d726b156748219b8e5f):
  batch response: Your user name must be of the form DOMAIN\user. It is
  currently USR123

*Going to Tools->Options->[Git Tab] in SourceTree and selecting [Use Embedded Git] and trying to checkout a version of the file from history results in the following error:

git-lfs/1.5.2 (GitHub; windows 386; go 1.7.3; git 547a06aa) git
  version 2.10.2.windows.1
$ git-lfs.exe smudge -- Framework4.dll Error downloading object:
  Framework4.dll
  (ef57f778c9fd50b27144784cd1df55b1b014d564ad6d8d726b156748219b8e5f)
Smudge error: Error downloading
  ef57f778c9fd50b27144784cd1df55b1b014d564ad6d8d726b156748219b8e5f: LFS:
  Git credentials for
  http://localhost:8080/tfs/DefaultCollection/Common/_git/Common%20References
  not found.: LFS: Git credentials for
  http://localhost:8080/tfs/DefaultCollection/Common/_git/Common%20References
  not found.

What I have researched and tried:

*

*Folks recommended using "The Git Credential Manager for Windows (GCM)" to store and manage credentials. This was installed with the latest git version. But the errors still persists.

*Tried it without having installed "The Git Credential Manager for Windows (GCM)" still the error happens.

*Updated Git versions to the latest. Tried git-lfs/1.5.2 and git-lfs/2.0.1. But no go.

*Additional error info on the Environment:

ENV:
LocalWorkingDir=C:\Users\USR123\Documents\GitCloneTest\Common\References2
  LocalGitDir=C:\Users\USR123\Documents\GitCloneTest\Common\References2.git
  LocalGitStorageDir=C:\Users\USR123\Documents\GitCloneTest\Common\References2.git
  LocalMediaDir=C:\Users\USR123\Documents\GitCloneTest\Common\References2.git\lfs\objects
  LocalReferenceDir=
  TempDir=C:\Users\USR123\Documents\GitCloneTest\Common\References2.git\lfs\tmp
  ConcurrentTransfers=1 TusTransfers=false BasicTransfersOnly=false
  BatchTransfer=true SkipDownloadErrors=false FetchRecentAlways=false
  FetchRecentRefsDays=7 FetchRecentCommitsDays=0
  FetchRecentRefsIncludeRemotes=true PruneOffsetDays=3
  PruneVerifyRemoteAlways=false PruneRemoteName=origin
  AccessDownload=ntlm AccessUpload=ntlm DownloadTransfers=basic
  UploadTransfers=basic GIT_CONFIG_PARAMETERS='color.branch=false'
  'color.diff=false' 'color.status=false' 'diff.mnemonicprefix=false'
  'core.quotepath=false' GIT_DIR=.git GIT_LFS_PATH=C:\Program Files\Git
  LFS GIT_PAGER=cat GIT_PREFIX=

Any ideas on how to fix the credential / authentication errors above?
Thank you.

A: This error comes from LFS extension if you have logged in to TFS without specifying domain name, and you are trying to push a large file.
Go to Control Panel\User Accounts\Credential Manager, Windows Credentials tab and remove credentials stored for TFS server.
When you git push again from command line, you will be prompted for your credentials. Specify your user name with the domain: DOMAIN\USER

A: Since version 2.4.0 Git-Lfs comes with NTLM support. With this you no longer need to use the basic authentication fallback by setting the credentials in the Windows Credential Manager and Git-Lfs should work out of the box with TFS on-prem.


text:
Q: Check if an SDK is installed on Mobile (Vitamtio and .m3u8) I'm Using Vitamio Lib to play (.m3u8) in my android application,,can i check if the user has the sdk on his mobile phone,,and if not give him the link to Download it?

A: You can do something like bellow before starting your player
public boolean checkVitamioInstallation(final Context context) {
    try {
        VitamioInstaller.checkVitamioInstallation(context
                .getApplicationContext());

        return true;
    } catch (VitamioNotCompatibleException e) {
        TGLogger.e(this, "Not compatible", e);
        TGLogger.i(this, "Not compatible");
        OnClickListener listener = new OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                Uri marketUri = Uri.parse("market://details?id="
                        + VitamioInstaller.getCompatiblePackage());
                Intent marketIntent = new Intent(Intent.ACTION_VIEW,
                        marketUri);
                context.startActivity(marketIntent);

            }
        };
        Builder dialog = getDialog(context.getResources().getString(
                R.string.not_compatible_plugin), context.getResources()
                .getString(R.string.install_plugin_msg), context
                .getResources().getString(R.string.install_msg), context,
                listener);
        dialog.show();
    } catch (VitamioNotFoundException e) {
        TGLogger.e(this, "plugin not found", e);
        OnClickListener listener = new OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                Uri marketUri = Uri.parse("market://details?id="
                        + VitamioInstaller.getCompatiblePackage());
                Intent marketIntent = new Intent(Intent.ACTION_VIEW,
                        marketUri);
                context.startActivity(marketIntent);

            }
        };
        Builder dialog = getDialog(context.getResources().getString(
                R.string.plugin_not_found), context.getResources()
                .getString(R.string.fresh_plugin_install), context
                .getResources().getString(R.string.install_msg), context,
                listener);
        dialog.show();

    }
    return false;
}

A: If you use a current version of the Vitamio library in your app - when invoked the library will check itself whether Vitamio is installed and if not will prompt the user to download the relevant library APK from either the Android Marketplace or from the Vitamio website directly (if they don't have access to the Marketplace).


text:
Q: UWP How to detect pen button press I am developing an app in UWP for Windows 10.
I would like to perform some action when the user presses a button on the Pen (e.g. eraser or barrel button).
Ideally, I would like to have an app-wide listener that is fired when the user presses e.g. the eraser button, even when the pen is "far" from the screen (e.g. 30 cm / 1 foot distance between the pen and the screen).
Is there any way to achieve this in UWP / C#?
Thanks!

A: You could check the PenButtonListener Class which is newly added in the build 19041.

A: On latest windows 10, Windows.Devices.Input.PenButtonListener was added for this.


text:
Q: onActivityResult() is not being called I've been trying for a while now to get this to work but to no avail. I am attempting to retrieve data from my DetailActivity and return it to my MainActivity. Can any one assist.
 @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.v(LOG_TAG, "KJHVLERHVRHOGVINORWUI " + MY_CHILD_ACTIVITY + " " + resultCode +" "+Activity.RESULT_OK);
        switch(requestCode) {
            case (MY_CHILD_ACTIVITY) : {
                if (resultCode == Activity.RESULT_OK) {
                    System.out.println("LOG_TAG"+ "MainActivity.EXTRA_SEARCH" + data.getStringExtra(MainActivity.EXTRA_SEARCH));
                }
                break;
            }
        }
    }

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

        setContentView(R.layout.activity_main);

        artistsAlbums = new ArrayList<>();
        tempAlbums = new ArrayList<>();

        final RestAdapter adapter = new RestAdapter.Builder()
                .setEndpoint(END_POINT)
                .build();
        service = adapter.create(APIService.class);

        EditText tview = (EditText) findViewById(R.id.artist_field);
        tview.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
                Log.v("LOG_TAG", s + " onTextChanged() " + " start: " + start + " count: " + count + " after: " + after);
            }

            @Override
            public void afterTextChanged(Editable s) { //aftertextchanged{
                Log.v("LOG_TAG", s + " afterTextChanged()");
                if (listViewRefresh) {
                    if (mAdapter != null) {
                        //mAdapter.clear();
                        //mAdapter.notifyDataSetChanged();
                        artistsAlbums.clear();
                        displayItems();
                    }
                }
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                name = s.toString();
                Log.v("LOG_TAG", s.length() + " onTextChanged() " + " start: " + start + " before: " + before + " count:" + count);
                //listViewRefresh = (start == 0) && (before == 1) && (count == 0);
                listViewRefresh = name.length() == 0;
                    //======================================A R T I S T S=====================================m============
                    service.searchArtists(name, new Callback<ArtistsPager>() {
                                @Override
                                public void success(ArtistsPager artistsPager, Response response) {
                                    Image image;
                                    if (artistsPager.artists.items != null) { //for .. 6
                                        artistsAlbums.clear(); //this line doesn't work!!
                                        //artistsAlbums = new ArrayList<ArtistsAlbum>(); //this line works but is wrong!!

                                        for (int i = 0; i < artistsPager.artists.items.size(); i++) { //for .. 1
                                            try {  // try .. 1
                                                mName = artistsPager.artists.items.get(i).name;         //Breakpoint here!!
                                                mId = artistsPager.artists.items.get(i).id;
                                                int size = artistsPager.artists.items.get(i).images.size();

                                                if (size == 0) {
                                                    //------------------------------------------
                                                    album = new ArtistsAlbum();
                                                    album.setName(mName);
                                                    album.setId(mId);
                                                    artistsAlbums.add(album);
                                                    //------------------------------------------
                                                } else {
                                                    for (int j = 0; j < size; j++) {
                                                        if ((300 <= artistsPager.artists.items.get(i).images.get(j).width) &&
                                                            (650 >= artistsPager.artists.items.get(i).images.get(j).width)){
                                                            mUrl = artistsPager.artists.items.get(i).images.get(j).url;
                                                            album = new ArtistsAlbum();
                                                            album.setUrl(mUrl);
                                                            album.setName(mName);
                                                            album.setId(mId);
                                                            artistsAlbums.add(album);
                                                            break;
                                                        }
                                                    }
                                                }
                                            } catch (IndexOutOfBoundsException e) { //try .. 1
                                                e.printStackTrace();
                                            }
                                        }// for .. 1

                                        if (!listViewRefresh )
                                            displayItems();
                                        else {
                                            artistsAlbums.clear();
                                            displayItems();
                                        }

                                        //displayItems(artistsAlbums);

                                        Log.v(LOG_TAG, "======================================= TOP ================================================");
                                        for (ArtistsAlbum obj : artistsAlbums)
                                            System.out.println("LOG_TAG" + "name: " + obj.getName() + " id: " + obj.getId() + " Url: " + obj.getUrl());
                                        Log.v(LOG_TAG, "====================================== BOTTOM ==============================================");

                                        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                            @Override
                                            public void onItemClick(final AdapterView<?> parent, final View view,
                                                                    int position, long id) {
                                                final ArtistsAlbum item = (ArtistsAlbum) parent.getItemAtPosition(position);
                                                // System.out.println("LOG_TAG" + "name: " + item.getName() + " id: " + item.getId() + " Url: " + item.getUrl());
                                                //sendMessage(item.getId());
                                                intent = new Intent(MainActivity.this, DetailActivity.class);
                                                intent.putExtra(EXTRA_MESSAGE, item.getId());
                                                intent.putExtra(EXTRA_SEARCH, name);
                                                startActivityForResult(intent, MY_CHILD_ACTIVITY);

                                            }
                                        });
                                    } //for..6
                                }

                                @Override
                                public void failure(RetrofitError error) {

                                }
                    });
            } //onTextChanged
        });
}

Within DetailActivity I have my SetResult() within onPause() callback:
@Override
    protected void onPause   () {
        super.onPause();
        Log.v(LOG_TAG, "onPause()");
        Intent in = getIntent();
        in.putExtra(MainActivity.EXTRA_SEARCH, searchStr);
        setResult(Activity.RESULT_OK, in);
        Log.v(LOG_TAG, "Activity.RESULT_OK" + in);
        finish();
    }

And for completeness I have supplied the AndroidManifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.richard.webapitest" >

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme"
        >
        <activity
            android:name="com.example.richard.webapitest.MainActivity"
            android:label="@string/app_name"
           >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".DetailActivity"
            android:label="@string/title_activity_detail"
            android:parentActivityName=".MainActivity">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.example.richard.webapitest.MainActivity" />
        </activity>
    </application>
</manifest>

Many thank
addendum:
My Log Cat is as followed once run:
07-27 08:40:49.091    2080-2080/com.example.richard.webapitest V/LOG_TAG﹕ onTextChanged()  start: 0 count: 0 after: 1
07-27 08:40:49.091    2080-2080/com.example.richard.webapitest V/LOG_TAG﹕ 1 onTextChanged()  start: 0 before: 0 count:1
07-27 08:40:49.127    2080-2080/com.example.richard.webapitest V/LOG_TAG﹕ e afterTextChanged()
07-27 08:40:49.515    2080-2294/com.example.richard.webapitest D/dalvikvm﹕ GC_FOR_ALLOC freed 318K, 4% free 9195K/9540K, paused 7ms, total 8ms
07-27 08:40:49.519    2080-2294/com.example.richard.webapitest W/dalvikvm﹕ VFY: unable to find class referenced in signature (Ljava/nio/file/Path;)
07-27 08:40:49.523    2080-2294/com.example.richard.webapitest W/dalvikvm﹕ VFY: unable to find class referenced in signature ([Ljava/nio/file/OpenOption;)
07-27 08:40:49.523    2080-2294/com.example.richard.webapitest I/dalvikvm﹕ Could not find method java.nio.file.Files.newOutputStream, referenced from method okio.Okio.sink
07-27 08:40:49.523    2080-2294/com.example.richard.webapitest W/dalvikvm﹕ VFY: unable to resolve static method 17524: Ljava/nio/file/Files;.newOutputStream (Ljava/nio/file/Path;[Ljava/nio/file/OpenOption;)Ljava/io/OutputStream;
07-27 08:40:49.523    2080-2294/com.example.richard.webapitest D/dalvikvm﹕ VFY: replacing opcode 0x71 at 0x000a
07-27 08:40:49.523    2080-2294/com.example.richard.webapitest W/dalvikvm﹕ VFY: unable to find class referenced in signature (Ljava/nio/file/Path;)
07-27 08:40:49.523    2080-2294/com.example.richard.webapitest W/dalvikvm﹕ VFY: unable to find class referenced in signature ([Ljava/nio/file/OpenOption;)
07-27 08:40:49.523    2080-2294/com.example.richard.webapitest I/dalvikvm﹕ Could not find method java.nio.file.Files.newInputStream, referenced from method okio.Okio.source
07-27 08:40:49.523    2080-2294/com.example.richard.webapitest W/dalvikvm﹕ VFY: unable to resolve static method 17523: Ljava/nio/file/Files;.newInputStream (Ljava/nio/file/Path;[Ljava/nio/file/OpenOption;)Ljava/io/InputStream;
07-27 08:40:49.523    2080-2294/com.example.richard.webapitest D/dalvikvm﹕ VFY: replacing opcode 0x71 at 0x000a
07-27 08:40:49.767    2080-2080/com.example.richard.webapitest V/MainActivity﹕ in displayItems0
07-27 08:40:49.767    2080-2080/com.example.richard.webapitest V/MainActivity﹕ ======================================= TOP ================================================
07-27 08:40:49.767    2080-2080/com.example.richard.webapitest V/MainActivity﹕ ====================================== BOTTOM ==============================================
07-27 08:40:50.255    2080-2304/com.example.richard.webapitest D/dalvikvm﹕ GC_FOR_ALLOC freed 390K, 5% free 9319K/9736K, paused 5ms, total 5ms
07-27 08:40:50.275    2080-2304/com.example.richard.webapitest D/dalvikvm﹕ GC_FOR_ALLOC freed 25K, 4% free 9352K/9736K, paused 6ms, total 6ms
07-27 08:40:50.275    2080-2304/com.example.richard.webapitest I/dalvikvm-heap﹕ Grow heap (frag case) to 10.036MB for 921612-byte allocation
07-27 08:40:50.283    2080-2094/com.example.richard.webapitest D/dalvikvm﹕ GC_FOR_ALLOC freed <1K, 4% free 10252K/10640K, paused 7ms, total 7ms
07-27 08:40:50.951    2080-2314/com.example.richard.webapitest D/dalvikvm﹕ GC_FOR_ALLOC freed 75K, 4% free 10257K/10640K, paused 7ms, total 7ms
07-27 08:40:50.959    2080-2314/com.example.richard.webapitest I/dalvikvm-heap﹕ Grow heap (frag case) to 11.604MB for 1638412-byte allocation
07-27 08:40:50.967    2080-2314/com.example.richard.webapitest D/dalvikvm﹕ GC_FOR_ALLOC freed 0K, 4% free 11857K/12244K, paused 7ms, total 7ms
07-27 08:40:51.431    2080-2098/com.example.richard.webapitest D/dalvikvm﹕ GC_FOR_ALLOC freed 75K, 4% free 11859K/12244K, paused 6ms, total 6ms
07-27 08:40:51.435    2080-2098/com.example.richard.webapitest I/dalvikvm-heap﹕ Grow heap (frag case) to 12.535MB for 974412-byte allocation
07-27 08:40:51.443    2080-2098/com.example.richard.webapitest D/dalvikvm﹕ GC_FOR_ALLOC freed 0K, 3% free 12810K/13196K, paused 7ms, total 7ms
07-27 08:40:51.723    2080-2099/com.example.richard.webapitest D/dalvikvm﹕ GC_FOR_ALLOC freed 75K, 3% free 12811K/13196K, paused 6ms, total 6ms
07-27 08:40:51.727    2080-2099/com.example.richard.webapitest I/dalvikvm-heap﹕ Grow heap (frag case) to 13.668MB for 1188552-byte allocation
07-27 08:40:51.743    2080-2099/com.example.richard.webapitest D/dalvikvm﹕ GC_FOR_ALLOC freed 0K, 3% free 13972K/14360K, paused 6ms, total 6ms
07-27 08:40:51.975    2080-2295/com.example.richard.webapitest D/dalvikvm﹕ GC_FOR_ALLOC freed 149K, 3% free 15041K/15448K, paused 7ms, total 7ms
07-27 08:40:52.187    2080-2295/com.example.richard.webapitest D/dalvikvm﹕ GC_FOR_ALLOC freed 74K, 3% free 16641K/17052K, paused 5ms, total 5ms
07-27 08:40:59.359    2080-2080/com.example.richard.webapitest W/EGL_genymotion﹕ eglSurfaceAttrib not implemented
07-27 08:41:05.459    2080-2080/com.example.richard.webapitest V/DetailActivity﹕ onPause()
07-27 08:41:05.459    2080-2080/com.example.richard.webapitest V/DetailActivity﹕ Activity.RESULT_OKIntent { cmp=com.example.richard.webapitest/.DetailActivity (has extras) }
07-27 08:41:05.539    2080-2080/com.example.richard.webapitest W/EGL_genymotion﹕ eglSurfaceAttrib not implemented

A: @Override
protected void onPause()
{
   Log.v(LOG_TAG, "onPause()");
   Intent data = new Intent();
   data.putExtra(MainActivity.EXTRA_SEARCH, searchStr);
   if (getParent() == null) {
      setResult(Activity.RESULT_OK, data);
   } else {
      getParent().setResult(Activity.RESULT_OK, data);
   }
   Log.v(LOG_TAG, "Activity.RESULT_OK" + in);
   super.onPause();
}

check also that https://stackoverflow.com/a/2621390/2401265


text:
Q: Listing customers using the go stripe api client I am trying to list all my customers in stripe and I am getting this error:

2018/08/14 19:14:21 Requesting GET api.stripe.com/v1/customers
2018/08/14 19:14:21 http: proxy error: dial tcp [::1]:3001:
getsockopt: connection refused

The code snippet I am using is:
stripe.Key = "sk_test_abc123"

params := &stripe.CustomerListParams{}
params.Filters.AddFilter("limit", "", "3")
i := customer.List(params)
for i.Next() {
    c := i.Customer()
    fmt.Printf("customer is..\n %v", c)
}

I removed my stripe private test key ofcourse in the above snippet.
Why would I be getting this type of error?  Is it my laptops firewall or something?
Update
It seems the issue is because I am using https://github.com/codegangsta/gin for live reloading.
Is there a way to get this to work?
I just ran my go project by doing:
go build
./proj-name

And the API called worked fine.


text:
Q: How to retrieve the data from Eloquent or raw Query in Laravel? I need to retrieve data from DB Week of the month and dates
am able to get data from MYSQL Query
SELECT cnt, `creationdate`, week, weekname,
DATE_ADD(firstOfMonth,INTERVAL (week-1) WEEK) as 'Week Start',
 IF(DATE_ADD(firstOfMonth,INTERVAL ((week-1)*7+6) DAY) > eom,
 eom, DATE_ADD(firstOfMonth,INTERVAL ((week-1)*7+6) DAY)) as 'Week End'
FROM (
 SELECT COUNT(`firstname`) AS 'cnt', `creationdate`,
FLOOR((DAYOFMONTH(`creationdate`) - 1) / 7 +1) AS week,
CONCAT('Week ',FLOOR((DAYOFMONTH(`creationdate`) - 1) / 7) +1) AS weekname, DATE_ADD(`creationdate`,interval -DAY(`creationdate`)+1 DAY) AS firstOfMonth,
LAST_DAY(`creationdate`) as 'eom'
FROM `UserDetails` WHERE DATE_FORMAT(`creationdate`,'%m/%Y')='06/2017' GROUP BY week ) a

Am converting to laravel Raw Query was
$monthOfWeaks = DB::table("UserDetails")
            ->select(DB::raw('cnt, creationdate, week, weekname,
DATE_ADD(firstOfMonth,INTERVAL (week-1) WEEK) as WeekStart,
DATE_ADD(firstOfMonth,INTERVAL ((week-1)*7+6) DAY) > eom, eom, DATE_ADD(firstOfMonth,INTERVAL ((week-1)*7+6) DAY)) as WeekEnd'))
->select(DB::raw('COUNT(`firstname`) as cnt, creationdate,
 FLOOR((DAYOFMONTH(creationdate) - 1) / 7 +1) as week,
 CONCAT(Week,FLOOR((DAYOFMONTH(creationdate) - 1) / 7) +1) as weekname,
 DATE_ADD(creationdate,interval -DAY(creationdate)+1 DAY) as firstOfMonth,
 LAST_DAY(creationdate) as eom'))
            ->whereRaw("DATE_FORMAT(creationdate,'%m/%Y')='06/2017')")
            ->groupBy(DB::raw("WEEK(creationdate)"))
            ->get();

It seems like some error but I could not fix in laravel
please give some input to get solve my issues?
Thanks.

A: you can use
DB::select("
SELECT cnt, `creationdate`, week, weekname,
DATE_ADD(firstOfMonth,INTERVAL (week-1) WEEK) as 'Week Start',
 IF(DATE_ADD(firstOfMonth,INTERVAL ((week-1)*7+6) DAY) > eom,
 eom, DATE_ADD(firstOfMonth,INTERVAL ((week-1)*7+6) DAY)) as 'Week End'
FROM (
 SELECT COUNT(`firstname`) AS 'cnt', `creationdate`,
FLOOR((DAYOFMONTH(`creationdate`) - 1) / 7 +1) AS week,
CONCAT('Week ',FLOOR((DAYOFMONTH(`creationdate`) - 1) / 7) +1) AS weekname, DATE_ADD(`creationdate`,interval -DAY(`creationdate`)+1 DAY) AS firstOfMonth,
LAST_DAY(`creationdate`) as 'eom'
FROM `UserDetails` WHERE DATE_FORMAT(`creationdate`,'%m/%Y')='06/2017' GROUP BY week ) a
");

if you don't have any parameter to add to the query that comes from the request/other third party (and so there is no SQL injection risk)


text:
Q: Creating .exe from c project with built in SDL2 library I've created a SDL2 based project, that after the building proccess creates a prog.exe file.
Sending the project to other systems creates an error: ERROR: The program can't start because SDL2.dll is missing from your computer. Which makes sense, because they didn't install sdl to begin with.
Is there a way for me to send them the .exe file that already has all the needed libraries, without making them to install SDL by themselves?
Thanks.

A: You can take sdl2.dll from your computer and copy that to the same directory on the other computer as you have the .exe in.
Typically an installer for your application would handle this.


text:
Q: Enter password only once for three "git clone"s in a script I want to create a bash script in Linux with clone repositories from git.
I want to write the script in the way that I want need to type the username and password.
My script looks:
#!/bin/bash
git clone http://xxx
git clone http://yyy
git clone http://zzz

When I'm running this script, I need manually to insert the username and the password 3 times (for 3 repository: xxx, yyy, zzz).
Is it possible to  update the script so the username and password will be inserted automatically ?

A: You should create ssh key pair, deploy ssh-public key to these three repositories and clone them using ssh url instead of http.
In this way you won't be prompted for username or password.
Command to create ssh key pair:
ssh-keygen -t rsa -b 4096
Keys will be created at ~/.ssh by default. Public key will be saved as id_rsa.pub
Find more details about creating and adding ssh keys to github repo here.


text:
Q: Assign all the Order to related Customers on database My website got hacked and all the customers were deleted, but the orders are still here.
I imported back the customers by CSV, but the orders are no longer assigned/linked to them. The only commun point is the email address in the orders details and the email address in customers accounts.
I need to know how I can assign again orders to customers in the database. Is it possible to find a way to link them again using the email?

A: Here is the solution.
In case of multiple deletion, use those 2 sql queries. First sql query will link orders to customers, and second query will show the orders in the customers account (orders tab)
UPDATE sales_flat_order as SFO
INNER JOIN customer_entity as C
ON C.email = SFO.customer_email
SET SFO.customer_id = C.entity_id
WHERE SFO.customer_is_guest = 0

UPDATE sales_flat_order_grid as SFOG
INNER JOIN sales_flat_order as SFO
ON SFO.entity_id = SFOG.entity_id
SET SFOG.customer_id = SFO.customer_id

A: It looks like this query worked, and I can see the client in the order and click on his name to go see his info.
UPDATE sales_flat_order as SFO INNER JOIN customer_entity as C on C.email = SFO.customer_email SET SFO.customer_id = C.entity_id WHERE SFO.customer_is_guest = 0

But when I go to the client's info, Orders Tab, there are no orders.

A: it's return the  Error in query (1064): Syntax error near 'FOR sales_flat_order_grid Table' at line 6strong text


text:
Q: tried to connect mongodb with my app getting an error The error is "MongooseError: The uri parameter to openUri() must be a string, got "undefined". Make sure the first parameter to mongoose.connect() or mongoose.createConnection() is a string."
I'm attaching ss of the file and the error error image
the code in db.js(suubed in config folder) is
const mongoose = require('mongoose')

const connectDB = async () => {
    try {
        const conn = await mongoose.connect(process.env.MONGO_URI, {
            useNewUrlParser: true,
            useUnifiedTopology: true,
            useFindAndModify: false
        })

        console.log(`${conn.connection.host}`)
    } catch (err) {
        console.log(err)
    }
}

module.exports = connectDB

A: Please don't attach external links and/or screenshots - put the code right here.
As the error says, the "uri" (first parameter) to mongoose.connect is undefined, and needs to be a string -- make sure you're loading your environment variables successfully and make sure you didn't make a typo in the process.env.MONGO_URI variable name, since it currently evaluates to undefined.