text:
Q: Upload zip to hockeyapp with VSTS fails Outline: when uploading a generated zip file to hockeyapp, the step fails with nothing in the log.
In VSTS I have this build setup

The build step look like this

The arguments sent to msbuild is

/p:AppxBundlePlatforms="$(BuildPlatform)" /p:AppxPackageDir="$(build.artifactstagingdirectory)\AppxPackages\" /p:AppxBundle=Always /p:UapAppxPackageBuildMode=StoreUpload

It builds fine, and creates my artifacts:

Nothing wrong here. It is like i want it.
But something goes wrong when I try to release the _Test folder to HokeyApp. This is how my release setup

The zip step is doing the zip fine. Creates the zip file, but when it reaches the HokeyApp step, it fails after 10-15 seconds. Here is how I have setup the hockeyapp step:

I have tried to upload the appxupload artifact, and it allows me to do so, but I dont want that. I want the zipped _Test artifact uploaded. The hokeyapp step log gives me nothing
2016-11-30T21:43:07.6949753Z ##[section]Starting: Upload to HockeyApp

2016-11-30T21:43:07.6969757Z ==============================================================================

2016-11-30T21:43:07.6969757Z Task         : HockeyApp

2016-11-30T21:43:07.6969757Z Description  : Deploy your alpha and beta builds of mobile apps to HockeyApp

2016-11-30T21:43:07.6969757Z Version      : 1.0.0

2016-11-30T21:43:07.6969757Z Author       : Microsoft Corporation

2016-11-30T21:43:07.6969757Z Help         :

2016-11-30T21:43:07.6969757Z ==============================================================================

2016-11-30T21:43:09.0241255Z c1cc894e-c665-4c94-b6d1-a0fe5164fabd exists true

2016-11-30T21:43:12.5465049Z ##[section]Finishing: Upload to HockeyApp

How is this possible? Shouldnt I be able to upload the .zip file to HokeyApp? I can upload the _Test zip file, if I do it through VS.
I am doing something wrong here? I have used quite some time on this, so any suggestions would be appreciated!!
Here is the whole release log , just in case
2016-11-30T21:42:47.5913557Z ##[section]Starting: Release

2016-11-30T21:42:47.6113574Z Current agent version: '2.109.1'

2016-11-30T21:42:48.4311090Z Downloading task: ArchiveFiles

2016-11-30T21:42:50.1468654Z Downloading task: HockeyApp

2016-11-30T21:42:53.1334019Z ##[section]Starting: Download Artifacts

2016-11-30T21:42:53.1454012Z ReleaseId=16, TeamProjectId=44db8ed4-94b4-4e35-8cd8-205881b9686c, ReleaseDefinitionName=Tweed

2016-11-30T21:42:53.1614017Z Release folder: C:\a\r1\a

2016-11-30T21:42:53.1754004Z Environment variables available are below.  Note that these environment variables can be referred to in the task (in the ReleaseDefinition) by replacing "_" with "." e.g. AGENT_NAME environment variable can be referenced using Agent.Name in the ReleaseDefinition:

                [AGENT_ID] --> [1]

                [BUILD_BUILDID] --> [46]

                [RELEASE_ARTIFACTS_BUILD_CI_PACKAGE_BUILDURI] --> [vstfs:///Build/Build/46]

                [RELEASE_ARTIFACTS_BUILD_CI_PACKAGE_REQUESTEDFORID] --> [582f0e68-9531-4663-8559-e6a12e3f8f4c]

                [REQUESTEDFORID] --> [582f0e68-9531-4663-8559-e6a12e3f8f4c]

                [BUILD_REQUESTEDFORID] --> [582f0e68-9531-4663-8559-e6a12e3f8f4c]

                [AZURE_HTTP_USER_AGENT] --> [VSTS_f43ace1e-817e-4992-b28c-756a83e50efd_release_1_16_16_1]

                [RELEASE_ARTIFACTS_BUILD_CI_PACKAGE_SOURCEBRANCHNAME] --> [master]

                [RELEASE_RELEASENAME] --> [Release-16]

                [AGENT_VERSION] --> [2.109.1]

                [BUILD_BUILDURI] --> [vstfs:///Build/Build/46]

                [SYSTEM_HOSTTYPE] --> [release]

                [SYSTEM_CULTURE] --> [en-US]

                [BUILD_SOURCEVERSION] --> [dc3c85c0df5e4b130fad22f4ce7dbf7471a2500f]

                [SYSTEM_ARTIFACTSDIRECTORY] --> [C:\a\r1\a]

                [RELEASE_ARTIFACTS_BUILD_CI_PACKAGE_DEFINITIONID] --> [4]

                [AGENT_JOBSTATUS] --> [Succeeded]

                [RELEASE_DEFINITIONNAME] --> [Tweed]

                [RELEASE_RELEASEID] --> [16]

                [RELEASE_ARTIFACTS_BUILD_CI_PACKAGE_REPOSITORY_PROVIDER] --> [TfsGit]

                [MSDEPLOY_HTTP_USER_AGENT] --> [VSTS_f43ace1e-817e-4992-b28c-756a83e50efd_release_1_16_16_1]

                [RELEASE_ARTIFACTS_BUILD_CI_PACKAGE_REQUESTEDFOR] --> [Martin Slot]

                [SYSTEM_TOTALJOBSINPHASE] --> [1]

                [RELEASE_REQUESTEDFORID] --> [...]

                [RELEASE_RELEASEDESCRIPTION] --> []

                [SYSTEM_TEAMPROJECT] --> [Tweed]

                [RELEASE_RELEASEWEBURL] --> [...]

                [SYSTEM_JOBID] --> [...]

                [AGENT_RELEASEDIRECTORY] --> [C:\a\r1\a]

                [BUILD_DEFINITIONNAME] --> [Build CI package]

                [SYSTEM_TEAMFOUNDATIONSERVERURI] --> [https://martinslot.vsrm.visualstudio.com/]

                [RELEASE_RELEASEURI] --> [vstfs:///ReleaseManagement/Release/16]

                [BUILD_BUILDNUMBER] --> [...]

                [AGENT_HOMEDIRECTORY] --> [C:\LR\Mms\Services\Mms\TaskAgentProvisioner\Tools\agents\2.109.1]

                [SYSTEM_WORKFOLDER] --> [C:\a]

                [RELEASE_DEFINITIONID] --> [1]

                [BUILD_SOURCEBRANCH] --> [refs/heads/master]

                [AGENT_MACHINENAME] --> [TASKAGENT5-0007]

                [BUILD_REPOSITORY_PROVIDER] --> [TfsGit]

                [RELEASE_DEFINITIONENVIRONMENTID] --> [1]

                [RELEASE_ENVIRONMENTS_BETA_STATUS] --> [InProgress]

                [AGENT_WORKFOLDER] --> [C:\a]

                [BUILD_TYPE] --> [Build]

                [SYSTEM_PARALLELEXECUTIONTYPE] --> [None]

                [SYSTEM_TIMELINEID] --> [5bd0571c-c6d6-4fb7-aeeb-8cb6c84badd6]

                [RELEASE_ARTIFACTS_BUILD_CI_PACKAGE_DEFINITIONNAME] --> [Build CI package]

                [RELEASE_ARTIFACTS_BUILD_CI_PACKAGE_BUILDNUMBER] --> [20161130.8]

                [AGENT_ROOTDIRECTORY] --> [C:\a]

                [RELEASE_ARTIFACTS_BUILD_CI_PACKAGE_REPOSITORY_NAME] --> [Tweed]

                [AGENT_JOBNAME] --> [Release]

                [RELEASE_DEPLOYPHASEID] --> [16]

                [BUILD_DEFINITIONID] --> [4]

                [AGENT_NAME] --> [Hosted Agent]

                [SYSTEM_JOBPOSITIONINPHASE] --> [1]

                [RELEASE_ENVIRONMENTID] --> [16]

                [BUILD_SOURCEBRANCHNAME] --> [master]

                [SYSTEM_ENABLEACCESSTOKEN] --> [False]

                [SYSTEM_DEFAULTWORKINGDIRECTORY] --> [C:\a\r1\a]

                [RELEASE_DEPLOYMENTID] --> [16]

                [RELEASE_ARTIFACTS_BUILD_CI_PACKAGE_TYPE] --> [Build]

                [BUILD_REQUESTEDFOR] --> [...]

                [SYSTEM_TEAMFOUNDATIONCOLLECTIONURI] --> [https://martinslot.visualstudio.com/]

                [BUILD_REPOSITORY_NAME] --> [...]

                [SYSTEM] --> [release]

                [RELEASE_ARTIFACTS_BUILD_CI_PACKAGE_SOURCEVERSION] --> [dc3c85c0df5e4b130fad22f4ce7dbf7471a2500f]

                [AGENT_SERVEROMDIRECTORY] --> [C:\LR\Mms\Services\Mms\TaskAgentProvisioner\Tools\agents\2.109.1\externals\vstsom]

                [SYSTEM_TASKDEFINITIONSURI] --> [https://martinslot.visualstudio.com/]

                [RELEASE_REQUESTEDFOR] --> [Martin Slot]

                [RELEASE_ENVIRONMENTNAME] --> [Beta]

                [SYSTEM_COLLECTIONID] --> [f43ace1e-817e-4992-b28c-756a83e50efd]

                [RELEASE_ENVIRONMENTURI] --> [vstfs:///ReleaseManagement/Environment/16]

                [RELEASE_ARTIFACTS_BUILD_CI_PACKAGE_BUILDID] --> [46]

                [RELEASE_ARTIFACTS_BUILD_CI_PACKAGE_SOURCEBRANCH] --> [refs/heads/master]

                [RELEASE_SKIPARTIFACTSDOWNLOAD] --> [False]

                [RELEASE_ATTEMPTNUMBER] --> [1]

                [SYSTEM_PLANID] --> [fccff008-3e4a-4d57-872f-35994d5c28f9]

                [SYSTEM_TEAMPROJECTID] --> [44db8ed4-94b4-4e35-8cd8-205881b9686c]

2016-11-30T21:42:53.1754004Z Downloading artifact

2016-11-30T21:42:54.0592894Z Cleaning artifacts directory: C:\a\r1\a

2016-11-30T21:42:54.0592894Z Cleaned artifacts directory: C:\a\r1\a

2016-11-30T21:42:54.0712858Z Starting artifacts download...

2016-11-30T21:42:54.1053041Z Downloading linked artifact Build CI package of type Build...

2016-11-30T21:42:54.1053041Z Created artifact folder C:\a\r1\a\Build CI package

2016-11-30T21:42:54.1875602Z Preparing to get the list of available artifacts from build

2016-11-30T21:42:54.7212893Z Preparing to download artifact: drop

2016-11-30T21:42:54.7292887Z Artifact Type: ServerDrop

2016-11-30T21:42:55.3570619Z Caching items under 'drop' in the file container...

2016-11-30T21:42:55.5149683Z Caching complete. (157 ms)

2016-11-30T21:43:00.9780683Z 10 downloads remaining.

2016-11-30T21:43:05.2739672Z Download complete.

2016-11-30T21:43:05.2759665Z 29 placed file(s): 29 downloaded, 0 empty

2016-11-30T21:43:05.2759665Z 29 MB downloaded at 2983 KB/sec. Download time: 00:00:09.7433696. Parallel download limit: 4.

2016-11-30T21:43:05.2759665Z Downloaded linked artifact Build CI package

2016-11-30T21:43:05.2759665Z Finished artifacts download

2016-11-30T21:43:05.2809727Z ##[section]Finishing: Download Artifacts

2016-11-30T21:43:05.3604337Z ##[section]Starting: Archive files

2016-11-30T21:43:05.4024556Z ==============================================================================

2016-11-30T21:43:05.4024556Z Task         : Archive Files

2016-11-30T21:43:05.4024556Z Description  : Archive files using a variety of compression formats such as .7z, .rar, .tar.gz, and .zip.

2016-11-30T21:43:05.4024556Z Version      : 1.0.9

2016-11-30T21:43:05.4024556Z Author       : Microsoft Corporation

2016-11-30T21:43:05.4034557Z Help         : [More Information](http://go.microsoft.com/fwlink/?LinkId=809083)

2016-11-30T21:43:05.4034557Z ==============================================================================

2016-11-30T21:43:06.2792624Z [command]C:\a\_tasks\ArchiveFiles_d8b84976-e99a-4b86-b885-4849694435b0\1.0.9\7zip\7z.exe a -tzip C:\a\r1\a\Build CI package\drop\Tweed_1.1.1.0_Test.zip Tweed_1.1.1.0_Test

2016-11-30T21:43:07.6809768Z

2016-11-30T21:43:07.6809768Z 7-Zip [64] 16.00 : Copyright (c) 1999-2016 Igor Pavlov : 2016-05-10

2016-11-30T21:43:07.6809768Z

2016-11-30T21:43:07.6809768Z Scanning the drive:

2016-11-30T21:43:07.6809768Z 20 folders, 28 files, 22367999 bytes (22 MiB)

2016-11-30T21:43:07.6809768Z

2016-11-30T21:43:07.6809768Z Creating archive: C:\a\r1\a\Build CI package\drop\Tweed_1.1.1.0_Test.zip

2016-11-30T21:43:07.6809768Z

2016-11-30T21:43:07.6809768Z Items to compress: 48

2016-11-30T21:43:07.6809768Z

2016-11-30T21:43:07.6809768Z

2016-11-30T21:43:07.6809768Z Files read from disk: 28

2016-11-30T21:43:07.6809768Z Archive size: 21992428 bytes (21 MiB)

2016-11-30T21:43:07.6809768Z Everything is Ok

2016-11-30T21:43:07.6939754Z ##[section]Finishing: Archive files

2016-11-30T21:43:07.6949753Z ##[section]Starting: Upload to HockeyApp

2016-11-30T21:43:07.6969757Z ==============================================================================

2016-11-30T21:43:07.6969757Z Task         : HockeyApp

2016-11-30T21:43:07.6969757Z Description  : Deploy your alpha and beta builds of mobile apps to HockeyApp

2016-11-30T21:43:07.6969757Z Version      : 1.0.0

2016-11-30T21:43:07.6969757Z Author       : Microsoft Corporation

2016-11-30T21:43:07.6969757Z Help         :

2016-11-30T21:43:07.6969757Z ==============================================================================

2016-11-30T21:43:09.0241255Z c1cc894e-c665-4c94-b6d1-a0fe5164fabd exists true

2016-11-30T21:43:12.5465049Z ##[section]Finishing: Upload to HockeyApp

2016-11-30T21:43:12.5475064Z ##[section]Finishing: Release

Even if i specify the zip file directly, not using the *.zip, in the hockeyapp step, it gives me the same result.
What really annoys me is the that HockeyApp task step log shows me NOTHING :) Maybe I am building it wrong? Or? Am I doing something that is not possible yet with the hockeyapp task?
I really hope someone can help me.

A: Solved. The problem was the zip task. This task created a zip file with a the folder inside, instead of just taking all the files from the source and put in the zip. I installed "zip directories" from the market place, and it did the job.


text:
Q: What will be effect of removing sh file in Ubuntu? i have removed my sh file by mistake. I want to know is it impact on executing a
    application program? or is it fine? If it effects, then what will be the ways to
    recover it?

A: The command to fix this is cd /bin && sudo ln -s dash /bin/sh

redpajama_set_name: RedPajamaStackExchange


text:
Q: firstElementChild doesn't work in Internet Explorer 7...what are my options? Consider the JavaScript below:
var v;
if (this.children.length > 0) {
    v = this.firstElementChild.value;
}

This works in modern versions of FireFox and Chrome but this.firstElementChild.value throws an exception in Internet Explorer 7-8.  Is there another way for me to get this to work for all browsers?
UPDATE -- FINAL SOLUTION
I went with the following:
v = (this.firstElementChild || this.children[0] || {}).value --Thanks to all.

A: this.firstElementChild should work in every significant browser bar IE <=9 and Firefox 3 (QuirksMode).
this.children[0] will work in every significant browser bar Firefox 3, except that IE <=9 counts comment nodes as element nodes (QuirksMode). This may or may not be an issue for you.
The catch-all system is this:
var node = this.firstChild,
    firstElementChild = null;

for ( ; node; node = node.nextSibling) {
    if (node.nodeType === 1) {
        firstElementChild = node;
        break;
    }
}

firstElementChild will then be the first element child if one exists, null otherwise. It would be best to see if this.firstElementChild exists before doing the loop, for performance reasons.

A: I don't know, maybe this.children[0].value?

A: If your code is in an event handler and the function is bound with "attachEvent" the "this" keyword is bound to the "window" object and not the HTMLElement.
Try:
function doSomething(e) {
    var targ;
    if (!e) var e = window.event;
    if (e.target) targ = e.target;
    else if (e.srcElement) targ = e.srcElement;
    if (targ.nodeType == 3) // defeat Safari bug
        targ = targ.parentNode;
}

Check http://www.quirksmode.org/js/events_properties.html.

A: try the following :
var v;
if (this.children.length > 0) {
    v = this.firstChild;
}

althogh in modern browsers first child will usually will be text segment

A: We ran into this problem with IE11 and discovered that .firstChild() is a reliable fix across all browsers.


text:
Q: Loop Analysis (find Vo in the circuit) My working:
I1 = 2mA,
I2 = 4mA,
I3 = 4mA
Loop for I4,
2k(I4 - I3) + 1k(I1 + I4 - I3) + 1k(I2 + I4) = 0
2k(I4 - 4m) + 1k(2m + I4 - 4m) + 1k(4m + I4) = 0
2k(I4) + 1k(I4) + 1k(I4) - 8 - 2 + 4 = 0
4k(I4) - 6 = 0
I4 = 6/4k = 1.5m
Vo = 1k (I1 + I4 - I3)
Vo = 1k (2m + 1.5m - 4m)
     = -0.50V
May I know where did I do wrong?

A: Don't make I4 flow across two meshes; I4 should only flow around the lower right mesh. Your equation for the supermesh will include terms for I3 and I4, and you will get the final equation by inspection at the current source inside the supermesh.

A: The correct loop 4 equation looks like this :
$$ (I_4 - I_3)2\textrm{k}\Omega + (I_4 + I_1 -I_3)1\textrm{k}\Omega +(I_4+I_2)1\textrm{k}\Omega - 12V = 0  $$
And the solution is \$I_4 = 4.5\textrm{mA}\$ and \$V_O = (4.5\textrm{mA} + 2\textrm{mA}- 4\textrm{mA})1\textrm{k}\Omega = 2.5V\$

A: You went wrong when you said I3=4mA. That 4mA is shared between two loops. So, if I3=4mA there cannot be any current flowing in the other loop--which wouldn't make sense.
I think you realized this and tried to compensate by make I4 something other than the current in the 4th loop, but as you found, that still doesn't work out.


text:
Q: What is the meaning of true value and uncertainty from a measurement? I am taking the following example:

Lengths of an object are measured as : 5cm , 5.2cm , 5.1cm , 5.5 cm. Calculate the true value and the error .
The answer is True value = 5.2 cm error = 0.15 cm.

I am unable to interpret the answer. I have the following two explanations.

*

*If the length of the object is measured again , it is likely to lie between 5.2 +-  0.15 cm i.e. between 5.05 cm and 5.35 cm.

*The "actual length " of the object is somewhere between  5.05 cm and 5.35 cm.
I also cannot understand whether the error of 0.15 is the same as the uncertainty.
I don't know which of the explanations is correct or there is some other correct explanation.
Please provide me the correct explanation.

A: There are two kinds of errors, systematic and random. Both deviate your measurements from the "true value", which you can never reach. Systematic errors deviate always the same way the measurement (like parallax for example, you might be measuring always 1mm more) and random errors deviate the measurements from the true value like a gaussian function.
So, to discuss your interpretations. 1) is correct, even though it's convenient to talk on more mathematical terms (statistical certainty and sigmas, look those up). Basically, as you make your confidence interval bigger, the probability of the next measurement falling there increases. 2) is correct only if there are no systematic errors, which might or might not happen, thats something that needs to be studied for each individual experiment.


text:
Q: Change items in a  onchange of another  element So basically I have 2 <select> elements, and what I want is that the user selects a option in the first <select> and then the second <select> changes its options depending on what is selected. The second <select> is empty, and when the first<select> get changed it needs to add <options> to the second <select>.
HTML 1st select :
<select name="roof_width" onChange="getWidth(this.selectedIndex)" value="3" class="content_selectinput" id="select_width">
    <?php
        $i = 0;
        $x = 2;
        while(isset($dak_breedte[$i]))
        {
            if(isset($roof_width_index) && $roof_width_index == $i)
            {
                echo"<option value='$i' id='$i' selected='Selected'>".$dak_breedte[$i]." Meter </option>";
                $i++;
            }
            else
            {
                echo"<option value='$x'>".$dak_breedte[$i]." Meter</option>";
                $i++;
            }
        }
    ?>
</select>

HTML 2nd select :
<select name="NokBreedte" onClick="ridgeCheck()" value="3" class="content_selectinput" id="select_ridge" >
</select>

JavaScript :
function getWidth(index)
{
    ridge_min = index - 10;
    ridge_max = index + 10
    ridge_select = document.getElementById("select_ridge");
    for(i = 0; i <= 99; i++)
    {
        if(i < ridge_min || i > ridge_max)
        {
            ridge_select.add(ridge_values[i]);
        }
    }
}

The text values for the second <select> are stored in an array. I searched the web for a while and also tried it with jQuery, but nothing works.
To be clear, what I need is :
When a user changes the first <select> the second <select> needs to change directly.

A: if you are using jquery replace your function with this one
function getWidth(){
    var index = $('#select_width').val();
    ridge_min = index - 10;
    ridge_max = index + 10

    var options = '';

    for(i = 0; i <= 99; i++)
    {
        if(i > ridge_min || i < ridge_max)
        {
            options += "<option>" + ridge_values[i] + "</option>";
        }
     }

     $('#select_ridge').html(options);
}

Also change
getWidth(this.selectedIndex)

to
getWidth()

Update
Sorry modified again but you have used the following condition wrong.
if(i < ridge_min || i > ridge_max)

should be
if(i > ridge_min || i < ridge_max)

A: At first you need to delete all old values (all code you should use in onChange's function)
//Clear the HTML Select DropdownList
$('#select_ridge option').empty();

});
after you need to add new values
    var listvalues= new Array();
    listvalues[0] = { Text: "val1", Value: "1" };
    listvalues[1] = { Text: "val2", Value: "2" };
    listvalues[2] = { Text: "val3", Value: "3" };

    $.each(listvalues, function (index) {
            $("#select_ridge").append(GetOption(listvalues[index].Text, listvalues[index].Value));
            });
    });
    function GetOption(text, value) {
            return "<option value = '" + value + "'>" + text + "</option>"
    }


text:
Q: node.js ncp | fs.readdir | missing files | use of callback I´ve tried to copy a lot of files in folder by "ncp", but every time I check if the files are copied, not all of them are there. There are always some files are missing.
I´ve tried to use fs.readdir to check that are all files there but fs gives me the same result there are some files are missing
my ncp code
ncp(path.join(req.body.uploadPath,req.body.packageName,resourceDirectoryName), path.join(req.body.uploadPath,req.body.packageName),  (err) => {
    if (err) {
     //devmode report
     devMode.report('**error** '+err);
    }
})

my fs code
fs.readdir(path.join(req.body.uploadPath,req.body.packageName,resourceDirectoryName), (err, files)=>{
              console.log('####', files)
})

And this is the fs.readdir result

This is the folder with all files that I want to copy

This is the list of files it didn't copy

A: *

*CLUE 1:

Check the order reported on your fs.readdir

*CLUE 2:

Now, as it´s alphabetical order, look for the next ocurrence in your list (alphabetically)

*CLUE 3:

Check for special characters on it´s name.

*CLUE 4 - TEST A POSSIBLE SOLUTION*

As you can see, there is a space on the name of `new dictionary.json". Remove the spaces on this name and try again.

*CLUE 5 - Change your call, and add StopOnError

Add an StopOnError option to show if it stops there and why

ncp (
  path.join(req.body.uploadPath, req.body.packageName,   resourceDirectoryName),
  path.join(req.body.uploadPath,req.body.packageName),
  {stopOnErr: true},
  (err) => {
        if (err)
        {
          return console.error(err);
        }
      console.log("ok");
   }
)

SOLUTION

After dealing with this for a little of time, the problem was located:
  The user was executing the fs.readdir right after the execution of
  NCP. As NCP is asyncronous, fs.readdir was not reading the whole bunch
  of copied files, as they were still not copied.
Then, just a delay before fs.readdir was the solution to see all of them. Not a Spaces or special characters thing.

FINALLY, A REAL SOLUTION

As async programming has a first-day-of-school where everybody learns
  how to deal with callbacks, there is an example to deal with
  callbacks, and solve the question.

var ncp = require('ncp').ncp;
var fs = require('fs');

ncp.limit = 16;
var source="dir1"
var destination="dir2"
console.log('Starting');
console.log(new Date().toISOString());

ncp(source, destination, mycallback );

function mycallback(err)
{
 //here we are inside a callback declared in an outer function
 if (err) {
   return console.log(err);
 }
 console.log('done!');
 console.log(new Date().toISOString());
 fs.readdir(destination, function (err, files){
            console.log("Files Copied to Dir2 "+ files.length);
            //here we are inside fs.readdir callback
            copyTwo();
              });
 //as fs.readdir is also async, I cannot execute copyTwo() here, and I must execute inside fs.reddir callback
}

function copyTwo()
{
console.log('Starting CopyTwo');
console.log(new Date().toISOString());
source="dir2"
destination="dir3"
  //This function uses an embedded callback
  ncp(source, destination, function (err)
  {
   // here we are inside the function declared (with-no-name) to use directly asembedded  callback
   if (err) {
     return console.log(err);
   }
   console.log('done!');
   console.log(new Date().toISOString());
   fs.readdir(destination, function (err, files){
              console.log("Files Copied to Dir3 "+ files.length);
                });
  });
}

[admin-sp@localhost pruebaApp]$ ls dir1 | wc -l
7777
[admin-sp@localhost pruebaApp]$ ls dir2 | wc -l
0
[admin-sp@localhost pruebaApp]$ ls dir3 | wc -l
0
[admin-sp@localhost pruebaApp]$ node index.js
Starting
2018-05-01T00:55:50.683Z
done!
2018-05-01T00:55:57.063Z
Files Copied to Dir2 7777
Starting CopyTwo
2018-05-01T00:55:57.069Z
done!
2018-05-01T00:56:03.030Z
Files Copied to Dir3 7777
[admin-sp@localhost pruebaApp]$


text:
Q: How to store a color label in Xcode 10.2.1 from iOS 9.3 I'm making a game, and I want to save that when I pass the level, the background of the button changes color. Is it correct to use UserDefaults?
For example, the button "level 1" the background is gray and when the level is completed the color changes to orange but when I close the app, the button "level 1" returns to its gray color.
How do I save the color of the button in this case orange when the level is completed?
I've tried to use userDefaults but when defining it it tells me "UIColor cannot be converted to String"
@IBAction func continuarAccion(_ sender: Any) {

    animateOut(desireView: vistaNivel1).  //Remove the view, in this case I have a blur, is where the level is shown

    botonNivel1.backgroundColor = UIColor.white

}

By default, the background button "level 1", is white
when the level is complete the "level 1 button" changes the background to orange.
I would like to know how I can save that orange color so that when I close the app, the background of the "level 1" button remains orange.
Is it correct for me to use Userefaults?
I'm using xcode 10.1.2, compatibility from iOS 9.3

A: save hex value to userdefaults:
 UserDefaults.standard.set( hexValue as? String, forKey: "color")

// get value
    let strColor = UserDefaults.standard.object(forKey: "color") as? String

//   To convert hex value to UIColor:
   func hexStringToUIColor (hex:String) -> UIColor {
    var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()

    if (cString.hasPrefix("#")) {
        cString.remove(at: cString.startIndex)
    }

    if ((cString.count) != 6) {
        return UIColor.gray
    }

    var rgbValue:UInt32 = 0
    Scanner(string: cString).scanHexInt32(&rgbValue)

    return UIColor(
        red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
        green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
        blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
        alpha: CGFloat(1.0)
    )
}


text:
Q: Query exceeded resource limits in Bigquery In order to find the country for a specific IP address, I'm using the Maxmind IP address database. I've downloaded the database and imported it into Google BigQuery, so I can query it. In a separate table, I'm capturing IP-addresses from certain events in our systems. I would now like to join those two data sources.
The columns in the Maxmind database are as follows:

*

*start_ip_range   STRING  NULLABLE

*end_ip_range STRING  NULLABLE

*start_ip_num STRING  NULLABLE

*end_ip_num   STRING  NULLABLE

*country_code STRING  NULLABLE

*country_name

The columns in my event table are:

*

*request_id STRING    NULLABLE

*ip_address STRING    NULLABLE

As documented here (https://dev.maxmind.com/geoip/legacy/csv/) there is a way to get an integer representation of the ip address, so I can use it to query the ip address and retrieve the country_code or country_name.
I have now constructed the following query:
SELECT
  p.*,
  g.country_code AS country_code
FROM
  `dev.event_v1` p
INNER JOIN
  `dev.geo_ip_countries` g
ON
  SAFE_CAST(SPLIT(p.ip_address, ".")[OFFSET(0)] AS NUMERIC)*16777216 +
  SAFE_CAST(SPLIT(p.ip_address, ".")[OFFSET(1)] AS NUMERIC)*65536 +
  SAFE_CAST(SPLIT(p.ip_address, ".")[OFFSET(2)] AS NUMERIC)*256 +
  SAFE_CAST(SPLIT(p.ip_address, ".")[OFFSET(3)] AS NUMERIC)
BETWEEN
  SAFE_CAST(g.start_ip_num AS INT64)
AND
  SAFE_CAST(g.end_ip_num AS INT64)
LIMIT 100

And however this works when using a limit, it doesn't for constructing a view.
Two questions:
1. Is there a way to simplify the query
2. Google BigQuery throws an error when I try to return a large result set:
Error: Query exceeded resource limits. 28099.974050246612 CPU seconds were used, and this query must use less than 5600.0 CPU seconds.

Any help is appreciated!
Solution
Rewriting the query to the following worked and solved the resource limit issue too:
SELECT
  p.*,
  g.country_code
FROM
  `dev.event_v1` p
INNER JOIN
  `dev.geo_ip_countries` g
ON
  NET.IP_TRUNC(NET.SAFE_IP_FROM_STRING(p.ip_address),16) = NET.IP_TRUNC(NET.SAFE_IP_FROM_STRING(g.start_ip_range),16)
WHERE
  NET.SAFE_IP_FROM_STRING(p.ip_address)
  BETWEEN
    NET.SAFE_IP_FROM_STRING(g.start_ip_range)
  AND
    NET.SAFE_IP_FROM_STRING(g.end_ip_range)

A: Try below (BigQuery Standard SQL)
#standardSQL
SELECT
  p.* EXCEPT(ip_address_num),
  g.country_code AS country_code
FROM (
  SELECT *,
    SAFE_CAST(SPLIT(p.ip_address, ".")[OFFSET(0)] AS NUMERIC)*16777216 +
    SAFE_CAST(SPLIT(p.ip_address, ".")[OFFSET(1)] AS NUMERIC)*65536 +
    SAFE_CAST(SPLIT(p.ip_address, ".")[OFFSET(2)] AS NUMERIC)*256 +
    SAFE_CAST(SPLIT(p.ip_address, ".")[OFFSET(3)] AS NUMERIC) ip_address_num
  FROM `dev.event_v1`
) p
INNER JOIN (
  SELECT
    SAFE_CAST(g.start_ip_num AS INT64) start_ip_num,
    SAFE_CAST(g.end_ip_num AS INT64) end_ip_num,
    country_code
  FROM `dev.geo_ip_countries`
) g
ON ip_address_num BETWEEN g.start_ip_num AND g.end_ip_num

A: So you're joining everything in dev.event_v1 with dev.geo_ip_countries to get dev.geo_ip_countries.country_code for each row in dev.event_v1. I think you'd be interested in a left join.
You might be interested in testing if the conversions in the net functions can replace your math portion.
I don't know much about the contents of event_v1 requests or ip_addresses which could divide it, but I'm willing to bet there's a lot more rows there than there are in the geo_ip_countries. It's likely the bulk of your query time. Lets say you need to reduce that time about 6 fold. You should probably select a 6th of it to join and insert into a staging table, and repeat for the next 6ths in sequence.
I think using the NTILE(6) would help you; maybe OVER (ROWS UNBOUNDED PRECEDING) as nt, not sure really. Then with a nt = 1 in the where or join on clause.


text:
Q: RxJava Alternate to CompletableFuture I am new to Rx java and trying to find a solution to my problem. I want to return a Single to caller but the data is not available when that method is called, it will get filled either before that call is made or after that call is made. A naive example of what I am trying to do is below. CompletableFuture partially solves it but I am looking for Rx solution, possibly with backpressure.
val receiver = Receiver()

class Receiver {
    var data = ""

    // this returns a single but does not have data, but will be available after call to onComplete
    request(): Single<Data> {
        return Single.fromFuture(completableFuture)
    }

    onNext(data: String) {
        data.append(data)
    }

    onComplete() {
        completableFuture.complete(data)
    }
}

class Processor {
    fun process() {
        receiver.onNext("1")
        receiver.onNext("2")
        receiver.onComplete()
    }
}

class Caller {
    fun call() {
        // This should get "12" result
        // Processor().process() can be called before or after caller subscibe
        receiver.request()..subscribe(...)
    }
}

A: Instead of CompletableFuture, you can use PublishSubject. In order to be able to supply the value either before or after the subscribe call, you should also used .cache() on the Single. Put it all together like this:
class Receiver {
    var data = ""
    val subject = PublishSubject.create<Data>()
    val single = Single.fromObservable(subject).cache()
    // this ensures there is at least one subscription when the event is published - otherwise because there is no subscriber, the event is lost, despite cache().
    val dummyObserver = single.subscribe()

    // this returns a single but does not have data, but will be available after call to onComplete
    fun request(): Single<Data> {
        return single
    }

    fun onNext(data: String) {
        // as before
    }

    fun onComplete() {
        subject.onNext(data)
        subject.onComplete(data)
    }
}


text:
Q: Jenkins Windows Slave Disappears on restart I have a Jenkins master setup which has 2 linux slaves and a windows slave. I have a configuration where all boxes are switched off in the night and restarted in the morning. The Jenkins master shows 2 linux nodes in the morning however it does not show windows slave (it just disappears and not even shown offline). The Jenkins version I am using : 2.73.

A: The problem was related to swarm configuration which was resolved after putting together correct configuration files and enable on machine startup (to handle a situation if the machine goes down).


text:
Q: Transaction propagation when calling methods inside the same EJB I have a simple EJB stateless class with two methods, both without @TransactionAttribute. The first method saves beer and invokes another one which saves other beer and throws an exception.
@Stateless
public class EJBContainer {

    @PersistenceContext
    EntityManager em;

    public void testTransaction() {
        em.persist(getBeer("Corona"));
        try {
            saveAndThrowException();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void saveAndThrowException() {
        em.persist(getBeer("Heineken"));
        throw new RuntimeException();
    }

    //getBeer() definition
}

I assumed that both methods would use default transaction type (required) - so a new transaction will be created in the first method and it will be used in the second method. So throwing an exception should rollback this transaction and no beers will be saved by EntityManager. But it turned out that both beers have been saved. Where am I wrong?
When I moved a second method to the other stateless EJB it worked as I had supposed - the first EJB created new transaction, the second used it, exception caused a rollback and no beers had been saved.
The EJB is called from this JAX-RS client:
@ApplicationScoped
public class BeerController {

    @Inject
    private EJBContainer ejbContainer;

    @POST
    public void addBeer() {
        ejbContainer.testTransaction();
    }
}

A: As you are using a no interface view, may be the injection is not working correctly. I would try to use the @EJB annotation instead of @Inject.
@EJB
private EJBContainer ejbContainer;

@POST
public void addBeer() {
    ejbContainer.testTransaction();
}

This way you should get the expected results. But one of your assumptions is not exactly correct. When you call saveAndThrowException from testTransacion is not an EJB invocation, it's just a local method invocation, if your declared a different @TransactionAttribute for saveAndThrowException if would not matter.
If you need to call a transactional method from another transactional method of your EJB you can do it adding a reference to the EJB itself, and call it like you would do if it was another EJB:
@Stateless
public class EJBContainer {

    @PersistenceContext
    EntityManager em;

    @EJB
    private EJBContainer ejbContainer;

    public void testTransaction() {
        em.persist(getBeer("Corona"));
        try {
            ejbContainer.saveAndThrowException();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void saveAndThrowException() {
        em.persist(getBeer("Heineken"));
        throw new RuntimeException();
    }

    //getBeer() definition
}

A: Can't comment yet, not enough reputation. Therefore a separate post.
Areus has the point. The way you call it is just a local invocation, therefore all the interceptors around saveAndThrowException which are executed when you call it from outside are omitted by the application server. You throw the exception and directly catch it before returning control to the application server. The application server does not know anything about the exception, ergo erverything is fine and the transaction gets commited.


text:
Q: Redis with wsl2 podman - connection refused I'm running Ubuntu 20.04 within WSL2 on Windows 10.
I installed podman.
>podman -v
 podman version 3.

I tried starting a container with
podman run --name some-redis -d -p 6379:6379 redis

The container is starting. No errors in the log.
If I tried
redis-cli

From Ubuntu it's working.
From dos/powershell it is not working
rdcli -h localhost
localhost:6379> (error) Redis connection to localhost:6379 failed - connect ECONNREFUSED 127.0.0.1:6379

And also it is not working with my SpringBoot application.
I'm also using a portainer container with port mapping 9000:9000 and I can access it from ubuntu, dos, powershell.
So what's the problem with redis.  Is it coming from redis or from wsl2/podman ?
What can I do.
ps : The same container on the same machine with docker desktop was working fine.

A: You probably run into this WSL2 issue: https://github.com/microsoft/WSL/issues/4851
Solution:

*

*option 1: use [::1]:6379 instead of localhost:6379 from Windows side

*option 2: use -p 127.0.0.1:6379:6379 instead of -p 6379:6379 with podman run.


text:
Q: Moving a Physics Sprite in Unity How do I move a physics sprite in Unity? Do I apply force to the body like in farseers physics, or do I move the character sprite? This is how I'm currently trying to move it and im getting:

NullReferenceException: UnityEngine.Rigidbody2D.get_velocity()

    _position.x = Input.GetAxis ("Horizontal");
    _position.y = Input.GetAxis ("Vertical");

    if (Input.GetKeyDown(KeyCode.Space))
    {
        _rig.AddForce(new Vector2(_rig.velocity.x, _jumpHeight));
        _rig.velocity = new Vector2(Mathf.Clamp(_rig.velocity.x, -_clampValue.x, _clampValue.x), Mathf.Clamp(_rig.velocity.y, -_clampValue.y, _clampValue.y));
    }

    if (Input.GetKey(KeyCode.D))
    {
        //_rig.AddForce(new Vector2(_moveSpeed, _rig.velocity.x));
        //_rig.velocity = new Vector2(Mathf.Clamp(_rig.velocity.x, -_clampValue.x, _clampValue.x), Mathf.Clamp(_rig.velocity.y, -_clampValue.y, _clampValue.y));
        _rig.velocity = new Vector2(_position.x * _moveSpeed, _rig.velocity.y);
    }

    if (Input.GetKey(KeyCode.A))
    {
        _rig.AddForce(new Vector2(-_moveSpeed, _rig.velocity.y));
        _rig.velocity = new Vector2(Mathf.Clamp(_rig.velocity.x, -_clampValue.x, _clampValue.x), Mathf.Clamp(_rig.velocity.y, -_clampValue.y, _clampValue.y));
    }

A: It simply seems that you didn't assign RigidBody2D to your sprite.
I suppose that _rig is assigned this way in your Start or Awake method :
_rig = GetComponent<Rigidbody2D>();

But if you don't have assign a Rigidbody2D to your GameObject, it will return a null reference. That is the reason of the exception.
Go in the Editor, select your GameObject in Hierarchy panel, then add a component Rigidbody2D to it in the Inspector panel.
The way you add forces is also false. You need to pass a Vector2 that represent the direction of the move. By the way, you can't clamp a velocity in negative value because velocity is always positive.
To conclude, you made a mistake in the way you handled the inputs. You use Input.GetAxis to get the axis value and the A and D keys to launch the move. Maybe it can work because A and D are the keys use for Horizontal and Vertical axis by default but it can cause errors later.
For all these reasons, I suggest that you to edit your code this way :
float horizontal = Input.GetAxis ("Horizontal");

if (Input.GetKeyDown(KeyCode.Space))
    _rig.AddForce(new Vector2(0, _jumpHeight));

if (horizontal < 0)
    _rig.AddForce(new Vector2(-_moveSpeed, 0));
if (horizontal > 0)
    _rig.AddForce(new Vector2(_moveSpeed, 0));

if (_rig.velocity.x > _clampValue.x)
    _rig.velocity = new Vector2(_clampValue.x, _rig.velocity.y);
if (_rig.velocity.y > _clampValue.y)
    _rig.velocity = new Vector2(_rig.velocity.x, _clampValue.y);


text:
Q: is there a count_if function for a gsl_vector? C/C++ I am using the gnu scientific library (GSL).
Say I have a gsl_vector like this:
7  0  -6  5  8  0  10  -2
That's a vector containing positive numbers, negative numbers, and zeros as elements.
I want to count the number of non-zero elements or zero elements in this gsl_vector.
I know there is a function called count_if for a C++ Vector. But I search through the gsl_vector.h and gsl_blas.h, there is no function equal to that.
I can go though all the elements by assessing them though gsl_vector_get() and then ask the if question.
int counter = 0;

for(int i = 0;i<length_of_the_gsl_vector;++i){
  if(fabs(gsl_vector_get(y,i))<0.5) ++counter;
}

return counter;

But I have been wondering for almost a day whether there is such a function already in GSL that is much more efficient.
Or maybe there is a count_if function for gsl_array ?

A: You can get hold of the data pointer by using gsl_vector_ptr, then use std::count_if on pointers:
struct Predicate{
    inline bool operator()(double x) const {
        return fabs(x) < 0.5 ;
    }
} ;

int res = std::count_if(
    gsl_vector_ptr(y,0), gsl_vector_ptr(y,0) + size,
    Predicate()
) ;

A: They state that GSL implements std::valarray model, I read such statement as authorizing me to use something like:
gsl_block vec;
/* initialize ... */
std::valarray<double> a(vec.data, vec.size);
/* use std:: galore */


text:
Q: How to getDuration() with/without MediaPlayer I have two Fragments in my ViewPager. The 1st fragment lists down all the mp3 files that are available and the second one actually does the playing (implements the MediaPlayer logic).
In my 1st fragment I would like to list out the duration of the mp3 files. Because all the mp3 files are being loaded from media files how do I get the duration of them files ?
I tried the following:
Initial declaration:
MediaPlayer mediaPlayer;

Code Implementation:
mediaPlayer.setDataSource(mp3URL);
totalDuration = utils.milliSecondsToTimer(mediaPlayer.getDuration());

MilliSecondsToTimer converts the milliseconds string to 3:40 format.
Final Application:
duration.setText(totalDuration);

Doing this gives me the following error:
10-08 03:38:03.341: E/MediaPlayer(2586): Attempt to call getDuration without a valid mediaplayer
10-08 03:38:03.361: E/MediaPlayer(2586): error (-38, 0)
10-08 03:38:03.461: E/MediaPlayer(2586): Error (-38,0)

How do I just extract the total duration from the URL ?? Help please.

A: You might be calling getDuration before the file is fully loaded. See if the solution to this question works for you.
final VideoView video = (VideoView) findViewById(R.id.videoplayer);
            final MediaController controller = new MediaController(this);

            video.setVideoURI(Uri.parse(getIntent().getStringExtra("url")));
            video.setMediaController(controller);
            controller.setMediaPlayer(video);
            video.setOnPreparedListener(new OnPreparedListener() {

                   public void onPrepared(MediaPlayer mp) {
                       int duration = video.getDuration();
                       video.requestFocus();
                       video.start();
                       controller.show();

                   }
               });

A: You are trying to get mediaPlayer.getDuration() before the preparation is complete. Use the setOnPreparedListener() method to set a preparation listener and call the getDuration() method only after the preparation is complete.
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
  public void onPrepared(MediaPlayer mp) {
      totalDuration = utils.milliSecondsToTimer(mediaPlayer.getDuration());
  }
});


text:
Q: Dynamic URL in Codeigniter I am having trouble to dynamic the url using codeigniter.
I need to display dynamic URL look like below.
http://example.com/[store-url]
I did that. But when i try to view non-dynamic url like
http://example.com/blog. It accesssing store page only.
So i have wrote in my routes like below and it is working.
$route['blog'] = "blog";
But here my problem is i am having lot pages such as /blog. all pages are pointing the stores pages only including admin control panel
There any solution for that without setting the routes

A: In the routes.php
First wirte the coding of Dynamic URL
like
include_once (APPPATH . 'helpers/inflector_helper.php');

$path = explode('/', $_SERVER['REQUEST_URI']);
if ($_SERVER['HTTP_HOST'] == 'www.expample.com') {
    $controller = $path[1];
} else {
   $controller = $path[2];
}

$route[$controller] = plural($controller) . "/view" . ucwords($controller);
$route[$controller . '/list'] = plural($controller) . "/view" . ucwords($controller);
$route[$controller . '/view/(:num)'] = plural($controller) . "/view" . ucwords($controller) . "/$1";
$route[$controller . '/view/(:num)/(:any)'] = plural($controller) . "/view" . ucwords($controller) . "/$1/$2";

I write my static url
$route['login'] = "authenticate_user/index";
$route['validate'] = "authenticate_user/validateUser";
$route['logout'] = "authenticate_user/logout";

I hope this should work.


text:
Q: Workaround for content_for use in conjunction with fragment caching I'm trying to insert content into the head of my page on an per element basis, so I'd like to be able to specify something like this in a partial:
# _partial.html.erb
<%= content_for :style %>
  .element {
    background-color: red;
  }
<% end %>

And place that in the head of my page:
# application.html.erb
<head>
  <style>
    <%= content_for(:style) %>
  </style>
</head>

But the element partials are fragment cached, content_for is ignored in caches.
It's stated in Rails documentation that content_for will not for work elements that are fragment cached:
WARNING: content_for is ignored in caches. So you shouldn't use it for elements that will be fragment cached.
http://api.rubyonrails.org/classes/ActionView/Helpers/CaptureHelper.html#method-i-content_for
Is there currently a way to get content_for to work with fragment caching on Rails 5.1? No ones seems to have really touched this issue for a while. Does anyone know if there's a reason why?

There are some older mentions here:
Is there a workaround for ignored content_for blocks with caches_action and :layout => false?
content_for works in development but not production?
https://gist.github.com/stackng/891895
https://rails.lighthouseapp.com/projects/8994/tickets/3409-content_for-and-fragment-caching

A: There's Rails pull request for this open now: https://github.com/rails/rails/pull/39600
Hopefully this will "just work" in Rails soon...
Disclaimer: I submitted this pull request

A:
Is there currently a way to get content_for to work with fragment caching on Rails 5.1?

By design, the partial is not evaluated at all when the cache is used, so the only solution would be to cache the content_for result along with the 'real' content, as the linked historical patch did. The only work-around is to move the content_for block outside the partial -- which is understandably easier said than done, and undermines the point of using it in the first place.

No ones seems to have really touched this issue for a while. Does anyone know if there's a reason why?

It looks like the issue just fell off the radar many years ago: I see no relevant PR in GitHub at all. (I actually have a note about this in my personal todo list, but had no idea it had previously been worked on.)
No, there is no reason why this functionality hasn't been implemented (if there was a reason 8 years ago, it's been lost to the sands of time -- and may no longer apply anyway). If someone's interested in pursuing a PR: please do.


text:
Q: Burninate [slides] slides has no tag wiki, and no clearly defined purpose, being currently used for:

*

*JavaScript slideshow plugin thingies {1, 2, 3, 4} -> slidesjs

*Sliding movements on a touchscreen

*Sliding movement of <div>s

*Anything related to PowerPoint {1, 2, 3, 4} -> aspose-slides

*"trackbars with more than one slide" (???)

*Whatever this is...
Given that it seems to be an information-free meta-tag, I vote burninate.
Update: See above list for possible replacement tags.

A: It's gone.


text:
Q: Not all rows outputting PHP Mysql in this code I am trying to output all images with the tag I searched. I created 2 images with the same tag 'hi'.
The program is only outputting one of the images though. But when I echo the $rows number it equals 2. When I ran the query in MYSQL it also returned 2 rows. I do not see why ALL the images are being shown.
 $input = ($_GET['input']);
$query = "SELECT * FROM `photo`.`photo` WHERE `tags` LIKE '%$input%'";
$result = mysql_query($query);
$data = mysql_fetch_array($result) or die (mysql_error());
$rows = mysql_num_rows($result);
$image = $data['image'];
     header('Content-type: image/jpeg');
     echo $image;

This isn't all my code but it is all that I think is necessary. Here is what is being shown in another page.
echo "<img src='photolarge.php?input=$input'>"

When I echo $rows it outputs the number 2 so I know the query is working.

A: You need to use a loop to iterate through the result array.
$query = "SELECT * FROM `photo`.`photo` WHERE `tags` LIKE '%$input%'";
$result = mysql_query($query);
while($rows = mysql_fetch_array($result)) {
    echo $rows[image];
}

As I mentioned in the comments, please don't use mysql_ functions. You also need to sanitize your parameter as your code is vulnerable to SQL injection.

A: You need to fetch all returned rows in line 4, not only the first one.

A: try this
   $query = "SELECT * FROM `photo`.`photo` WHERE `tags` LIKE '%$input%'";
   $result = mysql_query($query);
   while($row = mysql_fetch_array($result)) {
   echo $row['image'];
   }

tips: try to change to MYSQLI or PDO ,MYSQL is no longer maintained


text:
Q: each of which or all of which + respectively I want to combine the following sentences into one sentence.

Nokia was followed by Motorola and Ericsson.
  Motorola was on the second rank and Ericsson was on the third rank.

How should I construct the sentence? Mentioned below are the possible choices that I thought.
a. Nokia was followed by Motorola and Ericsson, all of which were on the second and the third rank, respectively.
b. Nokia was followed by Motorola and Ericsson, all of which was on the second and the third rank, respectively.
c. Nokia was followed by Motorola and Ericsson, each of which were on the second and the third rank, respectively.
d. Nokia was followed by Motorola and Ericsson, each of which was on the second and the third rank, respectively.
I have searched in Google but I have not found any answer yet. I just guess the answer is A.
Any suggestion regarding this issue?
Thank you

A: You are probably German. Respectively is a much rarer word in English than beziehungssweise is in German, and if you find yourself using it, you should probably think twice. (Furthermore, if you are tempted to abbreviate respectively as resp. you will instantly give away your identity as a German while also not being well understood by native English speakers)
In this case, it is better not to use either "each of which" or "all of which", and you can simply say:

Nokia, Motorola, and Ericsson were ranked first, second, and third, respectively.

In less-technical contexts or if you just want to sound more like a native speaker, you'll be better understood if you just say

Nokia, Motorola, and Ericsson were ranked first, second, and third.

or if you must be absolutely clear about the order of the rankings,

Nokia ranked first, Motorola came second, and Ericsson third.


text:
Q: UIPopoverViewController does not resize properly on iOS 8 I have UIPopoverController in my application. It contains UINavigationController. When I show UIPopoverController it uses correct content size of top view controller. When I push view controller UIPopoverController is getting resized (that is what I expect). But when I pop back to previous view controller, it does not getting resized.
I used code from here. But it does not help.
Everything works fine for iOS 7.
Can anyone help me?

A: I found one solution, but still looking for more elegant one.
Add @property (nonatomic, weak) UIPopoverController *popover; to first controller in navigation stack and call [self.popover setPopoverContentSize:self.preferredContentSize animated:YES]; in place where popover should be resized.


text:
Q: django dynamic model object in query api I have 5 model class with geometric data and other different parameters.  In a search I need to query the data in all these five model classes based on the user selection i.e. dynamically change model class in query.   For that in django 1.4 I used models.__dict__[layer] and based on the select the layer field  varies.  But now I am working in django 1.11 and this is not working.
In django 1.4 I used,
 data =  models.__dict__[layer].objects.filter(name__icontains=keyWd).values('name').order_by('name')

In django 1.11, I tried the same but failed.
what is the best method for the solution.


text:
Q: Eclipse: copy the Java Build Path to a different workspace In Eclipse how do I copy the Java Build Path to a different workspace?
Somebody somewhere wrote that if you copy the project then you have copied the build path also. This doesn't seem to be the case.
I've tried copying the entire workspace to a new directory. Opening Eclipse and pointing it to the new directory has all the projects and source files but the build path for my project is empty. It doesn't even have the basic Java source files to build against (java.lang.Object).
Eclipse 3.3.0 (Europa)
Any ideas?

A: The build path is stored in a file named .classpath in the project's root directory. I don't know of any different way, and copying the directory should also copy that file, of course. How do you copy the project? What OS?

A: Be very careful...
The workspace itself is just metadata in eclipse that points to your project folders. If the projects are not actually in the workspace directory, you aren't actually copying them, just references to them.
This can happen if you use "Import existing projects into workspace" that are folders in the file system without the "copy into workspace" checkbox checked, or if you create a project using an existing directory.
If you copy that workspace to a different machine, the projecs won't be there.
If you want to share projects, your best bet would be to use source/version control (subversion, for example) and have everyone hook up to the same repository.
Another note on the build paths -- if you have a java project reference an external jar, the absolute path of that jar is stored in the build path. This can be bad if other people who are sharing that project have the jar in a different location on their machine. If this happens, you should look into using Classpath variables or user libraries in eclipse.
Can you comment more on what you're attempting to do when you do the copy?


text:
Q: How can I get the RabbitMQ queue acknowledge statistics I am using pika and want to know how to get the acknowledge statistics.
I have installed management plugin from which I can see the acknowledge statistics, but I want to access it directly through a library; such as pika.

A: Edit:
Today I would use the inbuilt Prometheus plugin to gather detailed statistics instead.

If you want to get the data you can simply use a HTTP client in Python and use the RabbitMQ Management API to retrieve the data for your own usage.
The api is pretty easy to use, but this particular feature is not necessarily well documented. You can however easily map the information you need and use it to generate the kind of information you need.
You simply call the queue information like this:

*

*http://127.0.0.1:15672/api/queues/%2F/Test
Simply replace Test with the name of the queue you need to collect data from.
You then add a couple of options to get more detailed information:

*

*?lengths_age=60&lengths_incr=5&msg_rates_age=60&msg_rates_incr=5

*e.g. http://127.0.0.1:15672/api/queues/%2F/queue_name?lengths_age=60&lengths_incr=5&msg_rates_age=60&msg_rates_incr=5
The output would look something like this:
{"memory": 21816,
 "message_stats":
     {
         "publish": 4,
         "publish_details":
             {
              "rate": 0.0,
              "samples": [....]
         },
         "messages": 4,
         "messages_details":
             {
                 "rate": 0.0,
                 "samples": [....],
                 "avg_rate": 0.0,
                 "avg": 4.0},
         "messages_ready": 4,
         "messages_ready_details": {
             "rate": 0.0,
             "samples": [....],
             "avg_rate": 0.0,
             "avg": 4.0
         },
.....

If you are looking for an overview of the RabbitMQ server, rather than a specific queue you can use this api call.

*

*http://127.0.0.1:15672/api/overview?lengths_age=60&lengths_incr=5&msg_rates_age=60&msg_rates_incr=5
General documentation on the API is available here.


text:
Q: Android: how to encode a stream of images to h264 with hardware acceleration? I am currently working on an app, to read the camera images and process them using OpenCV.
I would like to store the original images as a "normal" video and to drop the processed images after processing (after the information is extracted).
For this I basically need to encode the image stream to h264.
It will not be possible to use ffmpeg or other solutions wich do it on the general cpu. It has to be done using the internal hardware acceleration.
Because of this I have actually three questions:

*

*Does somebdy know how to achieve h264 encoding using the internal hw-modules to encode videos?

*Or does ffmpeg really support this on Android?

*Or is there a way access the image stream during the "usual" encoding process?
Thanks alot!

A: You can run the MediaRecorder to create the video using h264 hardware encoder (if available) and at the same time register your preview frame handler. I cannot guarantee that all preview frames will go in both directions, though.
Alternatively, you can compile ffmpeg with libstagefright, and it will use hardware avc encoder.
Alternatively, you can use stagefright directly from your app (via JNI).
Finally, you can follow the approach of libstreaming to find the optimal recording API for your platform (be it MediaRecorder API, or MediaCodec buffer-to-buffer method which requires Android 4.1, or MediaCodec surface-to-buffer method which requires Android 4.3.


text:
Q: Turtle Graphics - Extract Color from onscreenclick I am using Turtle Graphics in Python for a larger program. I am able to return the point that the user clicks on using turtle.onscreenclick
However, I would like to extract the RGB color of the point that the user clicks on. Can this even be done in turtle graphics and how can this be accomplished? Thank you!
import turtle

# Global variables specifying the point clicked

xclick = 0
yclick = 0

# Draw a rectangle that is red

height = float(50)
length = height *(1.9)
length = round(length,2)
turtle.begin_fill()
turtle.color("red")
turtle.down()
turtle.forward(length)
turtle.right(90)
turtle.forward(height)
turtle.right(90)
turtle.forward(length)
turtle.right(90)
turtle.forward(height)
turtle.right(90)
turtle.end_fill()

# Gets the click

def getcoordinates():
    turtle.onscreenclick(turtle.goto)
    turtle.onscreenclick(modifyglobalvariables)

# Modifies the global variables

def modifyglobalvariables(rawx,rawy):
    global xclick
    global yclick
    xclick = int(rawx//1)
    yclick = int(rawy//1)
    print(xclick)
    print(yclick)

getcoordinates()
turtle.done()

A: turtle doesn't have function to get pixel color. It uses tkinter (and widget tkinter.Canvas - turtle.getcanvas()) to display everything but it doesn't have function to get pixel color too.
Canvas keeps all as objects and second answer for "Get pixel colors of tkinter canvas" shows how to get color of object in position (x,y). Maybe it will work for you.

EDIT: I made working example
canvas uses different coordinates - it needed to change y = -y
import turtle

# --- functions --- (lower_case_names)

def get_pixel_color(x, y):

    # canvas use different coordinates
    y = -y

    canvas = turtle.getcanvas()
    ids = canvas.find_overlapping(x, y, x, y)

    if ids: # if list is not empty
        index = ids[-1]
        color = canvas.itemcget(index, "fill")
        if color != '':
            return color.lower()

    return "white" # default color

def modify_global_variables(rawx,rawy):
    global xclick
    global yclick

    xclick = int(rawx)
    yclick = int(rawy)

    print(get_pixel_color(xclick, yclick))

def draw_rect(x1, y1, width, height, color):
    y1 = -y1
    canvas = turtle.getcanvas()
    canvas.create_rectangle((x1, y1, x1+width, y1+height), fill=color, width=0)

# --- main ---

# Global variables specifying the point clicked

xclick = 0
yclick = 0

# Draw a rectangle that is red

height = 50.0 # now it is float
length = height * 1.9
length = round(length, 2)

turtle.down()
turtle.color("RED")

turtle.begin_fill()

for _ in range(2):
    turtle.forward(length)
    turtle.right(90)
    turtle.forward(height)
    turtle.right(90)

turtle.end_fill()

# Use tkinter.Canvas to draw rectangle

draw_rect(100, 100, length, height, 'green')

# Gets the click & Modifies the global variables

turtle.onscreenclick(modify_global_variables)

turtle.done()


text:
Q: Keep footer visible except when virtual keyboard is open on Android web? I need to have a footer which is always visible on the screen, except when the virtual keyboard is open. This is the default behaviour on iOS, however on Android the footer rises up above the keyboard. Can this be prevented?

  <input />
  <input />

Footer

.cont {
  display: flex;
  flex-direction: column;
  margin-bottom: 60px;
}
.footer {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: blue;
  color: white;
  text-align: center;
  height: 50px;
  line-height: 50px;
}

https://codepen.io/adsfdsfhdsafkhdsafjkdhafskjds/pen/qBbROeG

A: here is a demo by using Jquery:  https://codepen.io/nomi9995/pen/ZEQLyyy
here is a demo by using Javascript:  https://codepen.io/nomi9995/pen/eYJgLbo
Actually when keyboard opens. it resize the screen. we can detect resize screen and give bottom to auto when keyboard open and give bottom to 0when keyboard close
Jquery
if(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
            var sumedges = $(window).width() + $(window).height();
    $(window).resize(function () {
      if ($(window).width() + $(window).height() < sumedges) {
        $(".footer").css("bottom", "auto");
      } else {
        $(".footer").css("bottom", "0");
      }
    });
}

Javascript
if(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
            var sumedges = window.innerWidth + window.innerHeight;
            window.onresize = function () {
                if (window.innerWidth + window.innerHeight < sumedges) {
                    const footerArr = document.getElementsByClassName("footer");
                    for (let i = 0; i < footerArr.length; i++) {
                        footerArr[i].style.bottom = "auto";
                    }
                } else {
                    const footerArr = document.getElementsByClassName("footer");
                    for (let i = 0; i < footerArr.length; i++) {
                        footerArr[i].style.bottom = "0";
                    }
                }
            };
        }


text:
Q: accessing a file in windows7 using C# Code by providing administrative credentials How could i access a file of Windows folder in windows 7 using C# code.
i want to access that file using administrator username password, instead of asking user to access file "AS ADMINISTRATOR".

A: Are you looking for something similar to this: A small C# Class for impersonating a User
P.S. Think about consequences of hardcoding an admin password in the code.


text:
Q: Error in Windows 10 with use of Sparklyr in R ("Error in validate_java_version_line(master, version)...": Similar questions have been asked-and-answered, but always for non-Windows systems and most were years old, so I was hoping for guidance that was more current and intelligible. The installation and loading of Sparklyr was successful.
Error occurs after defining SparkContext object as follows:
sc <- spark-connect(master = "local")

The error returned is:

Error in validate_java_version_line(master, version) :
Java version detected but couldn't parse version from: java version "14" 2020-03-17

Previous questions have suggested installing an older version of Java. Is this still the right strategy for a Windows machine? Some have referenced that it necessary to reset the JAVA_HOME environment variable  is that still necessary - if so, how? Also, I wonder which version should I download and will installation of an older version of Java screw-up other applications that depend on the latest version?


text:
Q: Missing rows when ordering by nested field using Criteria Api I've encounterd weird behaviour of JPA (provider: EclipseLink) using order by functionality. I have TransactionData class, which has reference to CustomerData class:
@Entity
public class TransactionData {
    //...
    @ManyToOne
    @JoinColumn(name = "CUSTOMER_ID")
    private CustomerData customer;
    //...
}

@Entity
public class CustomerData {
    //...
    @Column(name = "LAST_NAME")
    private String lastName;
    //...
}

In my project, there are some specific cases, where there are transactions, which are not assigned to any customer (called non-customer transactions).
I try to get list of all registered transactions (both cusotmer transactions and non-customer transactions) and sort them by customer's last name. To acheive this I've written following Criteria Api
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<TransactionData> criteriaQuery = criteriaBuilder.createQuery(TransactionData.class);
Root<TransactionData> from = criteriaQuery.from(TransactionData.class);
criteriaQuery.orderBy(criteriaBuilder.asc(from.get("customer").get("lastName"));
TypedQuery<TransactionData> query = entityManager.createQuery(criteriaQuery);
return query.getResultList();

I think I should get list of all transactions, of course, with those, where customer field is set to NULL value. But JPA behaviour is different, because it cut out all transactions, where reference to customer is empty.

A: from.get("customer").get("lastName") will do implicitly an INNER JOIN. If some transactions have no customer assigned then what you need is a LEFT JOIN:

Join<TransactionData , CustomerData> customer = from.join("customer", JoinType.LEFT);
criteriaQuery.orderBy(criteriaBuilder.asc(customer.get("lastName"));


text:
Q: Why would my Win7 laptop seem to page if it has 6GB RAM? I use Uniblue and Norton 360 to check on my system and I'm not using all the RAM, but it sure seems to act that way. I have cleaned, checked, defragged, anit-virused, polished it, patted it on the head, nothing seems to improve this thing. It all started a couple of days ago. Very frustrating. Original symptoms were "Not Responding" and having to wait for a minute or so to recover. Now its 10 minutes to an hour, or it locks up completely.

*

*Windows 7

*Office 2010

*6GB RAM

*500 GB Drive (20% used)

*Chrome/IE

A: Run ProcessHacker and go to Tools->Pagefiles.

Here you see the actual and peak usage of the pagefile.

A: I agree with @ChristopherN.Boisjoli - get rid of Norton and Uniblue and all the other rubbish that the vendor installs too!
Check what is still running and look carefully for anything using CPU when nothing is happening or reading/writing to disk.
Use the performance monitor tool and install Process Explorer from Sysinternals (part of Microsoft these days) to see what is happening under the covers.
When things are stable, consider a lighter weight security tool.
Note that software is often designed to allow parts to be dumped from RAM to disk and this is normal even when plenty of RAM is available.
Also, are you using 64bit Windows? I assume you are but if not, you won't be making best use of that 6GB.

A: If you are only asking 'why would the OS page if I am not using all my RAM?' That is normal and it depends on what programs you are using.

A: Find some uninstallers try to be their official and clean your computer from  Uniblue and Norton 360 for good. Clean temporary files after that.
Install some nice free antivirus that you can find on download.com , this is good download source.


text:
Q: Python & Redis - Flask API that sets/reads values from Redis problem The situation is the following: I have a Flask web server, and I need to develop a new API endpoint for it (POST/GET), which would update/read a server status.
My POST API requires an input like this:
{
    "name": <name_of_the_server>,
    "serverUrl" <url_of_the_server>,
    "available": true/false
}

I want to save this information in Redis for a week. I save the whole JSON from the API request as a dictionary value in Redis. I dump and load it with pickle. The key is the "name" paramater.
I also have a GET API endpoint, in which I can specify the name of the server, and get the status information about it. Hence, Python checks in Redis for the key, containing the name of the server (given by the user through the API), and returns the value (the dictionary with all of the information that was saved previously).
This is all good, and works as intended. However, through the GET API, I should also be able to search for server status with the server URL (as well as the server name).
So far my solution is like this:
// Redis is a class, I previously instantiated
redis.set(server_name, server_data, ex=time_to_live)
redis.set(server_url, server_data, ex=time_to_live)

I set two keys, containing the exact same information. Through the GET endpoint, this gives me the chance to check server status by using either the server name or the server URL, as they return the same value. Also, they have the same expiry date, and are always updated together.
This works, however I feel this is more of a "cheat" solution, so I would want to ask for an advice if I should keep it that way, or if there is a better way to achieve the same functionality. Thank you in advance!


text:
Q: is there a way to set variable type in PUG mixin? I have a warning in my pug file (ideaj ide)
I like typing... ;)
But I can't reach any information how to accomplish typing in the PUG syntax.
I tried few syntaxes jsdoc, typescript, flowtype, c, java like - all ends with hard error.


text:
Q: How to create a floating widget hovering other widgets on Windows? Assume we have a wxWebView control in both window hierarchy and sizer hierarchy. How do we create a static text "loading" hovering above the wxWebView on Windows? Thanks.
It's straightforward on Linux. Create a wxStaticText of which the parent/owner is the same as the wxWebView and that's all. Unfortunately, it won't work on Windows. The wxStaticText is invisible because it is covered by the wxWebView. I've tried many ways, including calling their method Lower and Raise to adjust their z-orders, but in vain.
I also tried putting the text into a wxFrame and use samples/shaped/ as an example, but on the second thought, the new top-level frame may cover the GUI of other processes. So it isn't a good design.
Any suggestion? Thanks.

A: wxWidgets doesn't support overlapping child controls, so you would need to use a different top level window for your floating control, typically a wxPopupWindow -- then you could either draw your text in it or make wxStaticText its child.


text:
Q: Recalculating Apex Managed Sharing I am studying "Apex Managed Sharing" but I have a problem with "Recalculating Apex Managed Sharing".
The Apex Developer Guide says:

Every time a custom object's organization-wide sharing default access
  level is updated, any Apex recalculation classes defined for
  associated custom object are also executed.

I have created an Apex Class implementing Database.Batch interface and I have assigned this class for my Custom Object.
If I start the Recalculation from UI the code run correctly but if I change OWD the code is not executed.

A: To associate an Apex managed sharing recalculation class with a custom object:

*

*From the management settings for the custom object, go to Apex Sharing Recalculations.

*Choose the Apex class that recalculates the Apex sharing for this object. The class you choose must implement the Database.Batchable interface. You cannot associate the same Apex class multiple times with the same custom object.

*Click Save.

To run an Apex sharing recalculation, from the management settings for a custom object, go to Apex Sharing Recalculation, and then click New.
When working with Apex sharing recalculations, note the following.

*

*The Apex code that extends the sharing recalculation can process a maximum of five million records. If thisApex code affects more than five million records, the job fails immediately.

*You can monitor the status of Apex sharing recalculations in the Apex job queue.

*You can associate a maximum of five Apex sharing recalculations per custom object.

*You cannot associate Apex sharing recalculations with standard objects.

A: I think I finnaly found the solution, you will only be able to see the apex sharing reasons and apex sharing Recalcultation categories if you switch to classic and navigate to your object in setup.


text:
Q: How to save data in state or cache in getServerSideProps? I am building a Next.js app it is supposed to be SSR.
So I have some common data, e.g Navigation and a few other things which I do need to be server rendered and I need it on every page. But loading it on every page from my REST API in getServerSideProps when I move between pages doesn't seem right.
So I am looking for a way to save this information in some local cache or state and I don't load it the second time when I move to another page in the browser.
Is there a way to do so?

A: You can set the Cache-Control header inside getServerSideProps to cache its response.
Example from the Caching with Server-Side Rendering documentation:

// This value is considered fresh for ten seconds (s-maxage=10).
// If a request is repeated within the next 10 seconds, the previously cached value will still be fresh.
// If the request is repeated before 59 seconds, the cached value will be
// stale but still render (stale-while-revalidate=59).
// In the background, a revalidation request will be made to populate the
// cache with a fresh value. If you refresh the page, you will see the new value.
export async function getServerSideProps({ req, res }) {
    res.setHeader(
        'Cache-Control',
        'public, s-maxage=10, stale-while-revalidate=59'
    )

    return {
        props: {}
    }
}

You can configure the Cache-Control header value as you see fit. Note that setting a Cache-Control value only works in production mode, as the header will be overwritten in development mode.


text:
Q: Custom Rewrite Rule for Custom Post Type with URL Param I am trying to create a custom rewrite rule for a custom post type where
This:
http://test.loc/products/directory/?c=some-value

Should become this:
http://test.loc/products/directory/some-value

Minimal code:
function create_post_type() {
  register_post_type( 'acme_product',
    array(
      'labels' => array(
        'name' => __( 'Products' ),
        'singular_name' => __( 'Product' )
      ),
      'show_ui' => false,
      'public' => true,
      'has_archive' => true,
      'rewrite' => array("slug" => "products/directory")
    )
  );
  add_rewrite_rule(
      '^products/directory/([A-Za-z0-9-]+)/?$',
      'index.php?post_type=acme_product&c=$1',
      'top'
  );
}

I also tried like this:
add_rewrite_rule(
    '^products/directory/?([^/]*)/?',
    'index.php?post_type=acme_product&c=$matches[1]',
    'top'
);

I simply can't get the value of 'c'. Is there something in the rewrite rule that should be different? I can't seem to get this to work.
By the way I CAN retrieve 'some-value' of 'c' from this:
 http://test.loc/index.php?post_type=acme_product&c=some-value

To retrieve the value in the template I tried both:
get_query_var( 'c' );

and
$_GET['c'];

I get nothing back...

A: SOLUTION:
I am answering my own question here since no responses were given and I presume this might be helpful to someone and in the mean while I found a solution..
I had to use the second version of 'add_rewrite_rule':
add_rewrite_rule(
  '^products/directory/?([^/]*)/?',
  'index.php?post_type=acme_product&c=$matches[1]',
  'top'
);

I needed to register a query var,, since external query params aren't recognizable to WordPress
function 123wp_query_vars( $query_vars ){
  $query_vars[] = 'c';
  return $query_vars;
}
add_filter( 'query_vars', '123wp_query_vars' );

Then retrieve the value in the template using:
get_query_var( 'c' );

A: If you just want a redirect with regex, use Yoast SEO and select Redirects and choose option Regex.
For a url go from http://example.com/products/?c=some-value to http://example.com/products/some-value use this regex expression and paste on Yoast redirect regex page:

Type: 301 Moved Permanently
Regex Expression: products/?c=/?([^/]*)/?
URL: products/$1

I hope it helps another people who wants to redirect not just add and rewrite_rule
Best,


text:
Q: Memory usage of the current Flex/Actionscript application System.totalMemory shows the memory usage of the all instances of all flash/AIR applications in the system. Is there a way to find the memory usage of only the current application? Also even if I have only one instance of an application, and I close/relaunch it several times, System.totalMemory increases almost exponentially.

A: If you have access to Flex Builder Professional you can do this with the profiler.
I Flex Builder, click Profile > Profile External Application. Cĺick 'New' and browse to the application, select the application and click 'Launch'. When the application starts, Flex Builder will pop up a dialog, check "Enable memory profiling" and uncheck "Enable performance profiling". There will be a tab called "Memory Usage" with a graph of the memory usage for the application over time.

A: As Markus said the Flex Profiler offers a really great way to profile your applications. If you don't have Flex Builder... if you're on a mac I would suggest the system profiler, and if you're on windows i would suggest process explorer.


text:
Q: What is the correct way to export named components? Is there a difference between exporting like this:
export const Foo ...

and this
const Foo ...
export { Foo }

A: There is not really a difference, with the second approach you could just export a list of names:

After the export keyword, you can use let, const, and var declarations, as well as function or class declarations. You can also use the export { name1, name2 } syntax to export a list of names declared elsewhere. Note that export {} does not export an empty object — it's a no-op declaration that exports nothing (an empty name list). - mdn web docs


text:
Q: Base UIViewController for entire app with views inside I want to create base view controller for my app, all other view controllers will subclass it. It will contain some controls inside.
How I can achieve that? For creating design, should I drag new View controller on storyboard and don't connect it anywhere (then You have warning all the time). i Would like to create outlets and make some base implementation. If I use xib file it don't have all guidelines, like one below status bar.


text:
Q: How to alert and redirect using sweet alert in asp.net ScriptManager.RegisterStartupScript(this, this.GetType(),
"alert",
"alert('User details saved successfully');window.location ='frmDisplayUsers.aspx';",
true);

A: You need to add a referene to the SweetAlert library in the head section of the page:
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>

Then you need to change your code to this:
ScriptManager.RegisterStartupScript(this, this.GetType(),
"alert",
"swal('User details saved successfully').then((value) => { window.location ='frmDisplayUsers.aspx'; });",
true);

A: ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "swal('Done !!!','User details saved successfully','success').then((value) => { window.location ='frmDisplayUsers.aspx'; });", true);

this was what i wanted.....


text:
Q: How to Modify Custom Attribute X of all users/groups in an OU? I need to change Custom Attribute 1 and 2 for ~500 mailboxes in Exchange.
The user accounts linked with mailboxes are spread over 10-15 OU's within AD and each different OU needed different custom attributes.
Ideally, I dont want to run the following command twice for each mailbox
Set-Mailbox user@domain.com -CustomAttribute1 "X"

SUDO
Get a list of all users, email groups, contacts, rooms in a given OU in AD
Change each Custom attribute 1 to X
Change each Custom attribute 2 to X

A: Use an LDAP filter:
(|
  (objectCategory=person)
  (&
    (objectCategory=group)
    (!
      (groupType:1.2.840.113556.1.4.803:=2147483648)
    )
  )
  (msExchResourceMetaData=ResourceType:Room)
)

The above matches the following object types:

*

*users and contacts: (objectCategory=person)

*distribution groups: (&(objectCategory=group)(!(groupType:1.2.840.113556.1.4.803:=2147483648))) (technically this means: groups that are not security groups)

*room resources: (msExchResourceMetaData=ResourceType:Room)
You can select the AD objects matching that filter with Get-ADObject and modify their properties with Set-ADObject:
$ou   = 'OU=some unit,DC=example,DC=com'
$fltr = '(|(objectCategory=person)' +
          '(&(objectCategory=group)' +
            '(!(groupType:1.2.840.113556.1.4.803:=2147483648)))' +
          '(msExchResourceMetaData=ResourceType:Room))'

Get-ADObject -LDAPFilter $fltr -SearchBase $ou -SearchScope Subtree |
  Set-ADObject -Replace @{
    'extensionAttribute1' = 'X'
    'extensionAttribute2' = 'X'
  }

I'm not entirely sure about the attribute names, since I don't have an Exchange at hand. You must use their LDAP names here, not any fancy alias.


text:
Q: In SNMP, Can we remove .0 from the end of a Scalar OID? I have a situation, I have defined a scalar OID in my MIB but when I try to get value of the OID from the Agent using SNMP Get, it says "No OID exists" but when I append .0 at the end of the OID it replies with the value. I need to know can I make sure that this .0 at the end of the OID should not be required?

A: The OID convention (.0 for scalar objects) is part of SNMP standards, so cannot be altered for you alone.


text:
Q: how to change scheduler header text? iam  using devexpress scheduler. in my form iam using
   schedulerControl1.ActiveViewType = DevExpress.XtraScheduler.SchedulerViewType.WorkWeek;
   schedulerControl1.WorkWeekView.WorkTime.Start = System.TimeSpan.FromHours(7);
   schedulerControl1.WorkWeekView.WorkTime.End = System.TimeSpan.FromHours(22);
   schedulerControl1.WorkWeekView.ShowWorkTimeOnly = true;
   schedulerControl1.WorkWeekView.ShowAllDayArea = false;

as you can see iam using workweek view, the start week setting properties was monday, but the header is displaying 10 october, 11 octoberand so on. the thing is how do i change the scheduler header to day name like monday, tuesday and so on.
n.b : if its duplicate please refer it

A: you can use formatting services (see Formatting Services - an example of use) for this purpose.
See Also:
Work Week View without specific dates
Refer these for the alternative way to implement this:
How to: Display Custom Day Headers
SchedulerControl.CustomDrawDayOfWeekHeader Event
How to: Custom Paint Day Headers
CustomDrawDayHeader, how to use custom captions with default background ?
Hope this help.


text:
Q: shorcuts in a window manager-independent way I am thinking of abandoning fluxbox (or at least trying some alternatives)
My many configured keys are holding me back. I have a shortcut to open xterm, a shortcut to make a window half the screen size, to maximize, to send a window to another workspace...
I am wondering: is there a non-window manager program that just does keyboard shortcuts? Can such a program meet the use cases above? If so, I could use it to slowly transition away from fluxbox, and change WM many times until I find a better one.


text:
Q: Identity Column values jumps to 1000 in SQL Server Identity value jumps to 1000 on my client's computer.
I have searched a lot. I  know that I have to use trace flag -T272 but client's computer doesn't have SQL Server Configuration Manager. How to set trace flag on .MDF files?


text:
Q: iOS error reading from input stream I have a function which reads bytes from network input stream using
long count = [inputstream read:buffer maxlength:no_of_bytes_to_read];

I m calling this function two times. first time it is working but for second time my buffer has some unreadable characters at end replacing my original data.
but when i put a breakpoint over this reading function and step over slowly then it reads the accurate data
what may be the reason??


text:
Q: How to run alternative where condition if row is zero Suppose i have a table
table
+-------------+
| id  |  name |
+-------------+
|  1  |  xabx |
|  2  |  abxd |
|  3  |  axcd |
|  4  |  azyx |
|  5  |  atyl |
|  6  |  aksd |
|  7  |  baabc|
|  8  |  aabcd|
+-------------+

first i have to get data if matches first some char like :
if name = aab
then have to run select * from table where name like 'aab%'
then it returns
+-------------+
|  8  | aabcd |
+-------------+

which execatlly i want
but if i have only abc
then the above query return 0 row
then i have to search from middle like :
select * from table where name like '%abc%'
then it returns which is the alternative
+-------------+
|  7  |  baabc|
|  8  |  aabcd|
+-------------+

i have no much knowledge about mysql is there any query which can do like if first where condition don't have row then run alternative where condition
i have tried this but didn't work as i want.
select * from table where name like 'abc%' or name like '%abc%'
fiddle
thanks in advance

A: This is somewhat your desired result:
select *from t
where (case
           when name like 'abc' then 1
           when name like 'bc%' then 1
           when name like '%bc' then 1
           when name like '%bc%' then 1
           else null
           end)
order by name
  limit 1;

I just put all the combinations as conditions.
You can interchange their sequence or remove unnecessary condition.
limit 1 makes only 1 row visible for whichever condition satisfies.
Here is the answer from your fiddle. Check it out
Hope it helps!

A: This is a possible solution:
Left joining the table on itself, where the table is initially filtered by the more inclusive %bx% and then the join is filtered by the more restrictive bx%.
This allows you to use the joined name if it exists, but revert to the original if not:
SELECT t1.id, IF(t2.name IS NULL, t1.name, t2.name) name
FROM test t1
LEFT JOIN test t2 ON t2.id = t1.id AND t1.name like 'bx%'
WHERE t1.name LIKE '%bx%'

This may/may not be ideal depending on the size or your dataset.

A: COUNT checking may work
select *
from table
where name like 'aab%' or
      ((select count(*) from table where name like 'aab%') = 0 and name like '%abc%')

I guess that it would be a good idea to compute the count value into a variable first, however, the optimizer may recognize independent subquery anyway and run it once.


text:
Q: Black Navigation Bar covering image view in collection view header I have a collection view header who's background contains an image. What I am trying to do is allow for the image to be the background of the navigation controller.

What I have now

This is what I am trying to achieve

I have tried a lot of things so far. I made the navigation bar translucent. I adjusted the edges for extended layout, and I have set the property of navigation controller to be under opaque bars.
override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(true)
    navigationController?.navigationBar.isHidden = false
    navigationController?.navigationBar.isTranslucent = true
    tabBarController?.tabBar.isHidden = false
    tabBarController?.tabBar.barTintColor = UIColor.white
    tabBarController?.tabBar.tintColor = UIColor.lightWetAsphalt
    self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
    self.navigationController!.navigationBar.shadowImage = UIImage()
    self.navigationController?.navigationBar.backgroundColor = UIColor.clear
    self.edgesForExtendedLayout = []
    collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentBehavior.never
}

Note: If i hide the navigation controller, the image view goes under the status bar perfectly fine. For some reason, when I don't hide the navigation bar, thats when it brings up this black view


text: Q: Spring Data Neo4j findAll() for depth>1 takes long time By default findAll() method finds nodes for depth = 1. If I try to find nodes for depth greater than 1. For example findAll(2) it takes long time to compute the result. There are thousands of child nodes at level 2. I need an efficient way to get result for depth = 2.


text:
Q: Vue 3 Composition Api , Vue-router 4 Naigation guards throw an Error when using it When I try to use navigation guard from Vue-router 4, my code is no longer working it show a errors with undefined (push) from Pinia store router.push('/'). Here is my code:
import { createRouter, createWebHistory } from "vue-router";
import manageStaffRoutes from "./manage.staff.js";
import authRoutes from "./login.js";

import { useAuthStore } from "@/stores/auth.store.js";

const routes = [...manageStaffRoutes, ...authRoutes];

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes,
});

router.beforeEach(async (to, from) => {
    const auth = await useAuthStore();
    const publicPages = ["/login", "/super-admin-login"];
    const authRequired = !publicPages.includes(to.path);
    if (authRequired && !auth.user) {
        return "/";
    }
});
export default router;

then in my  store I have this code , where I am trying to redirect the user after successfully login
import { defineStore } from "pinia";
import { ref, computed } from "vue";
import axios from "axios";
import { useRouter } from "vue-router";

export const useAuthStore = defineStore("userAuth", () => {
    const router = useRouter();
    const userData = ref(null);
    const errorMessages = ref(null);

    const user = computed(() => {
        return JSON.parse(localStorage.getItem("user"));
    });

    if (user.value) {
        axios.defaults.headers.common["Authorization"] = `${user.value.token}`;
    }

    async function login(email, password) {
        try {
            const data = await axios.post("api/v1/users/login", {
                email: email,
                password: password,
            });
            if (data.status === 200) {
                userData.value = data.data;
                localStorage.setItem(
                    "user",
                    JSON.stringify(userData.value.data)
                );
                await router.push("/"); // the error

            }
        } catch (error) {
            console.log(error);
            return (errorMessages.value = error.response.data.errorsToSend);
        }
    }

    const logout = async () => {
        try {
            const data = await axios.post("api/v1/users/logout");
            console.log(data);
            if (data.status === 201) {
                user.value = null;
                localStorage.removeItem("user");
                await router.push({ name: "login" }); // the error

            }
        } catch (error) {
            console.log(error);
            // return (errorMessages.value = error.response.data.message);
        }
    };
    return { login, user, errorMessages, logout };
});

Here is the error:

A: Following the single responsability principle I suggest you to change the login() function on the store, remove the router push to let the store only authenticate your user. By doing this the redirection is handled by the calling funcion an not by the login.
AuthStore
import { defineStore } from "pinia";
import { ref, computed } from "vue";
import axios from "axios";

export const useAuthStore = defineStore("userAuth", () => {

    // ....

    async function login(email, password) {
        try {
            const data = await axios.post("api/v1/users/login", {
                email: email,
                password: password,
            });

            if (data.status === 200) {
                userData.value = data.data;
                localStorage.setItem(
                    "user",
                    JSON.stringify(userData.value.data)
                );
            }
        } catch (error) {
            console.log(error);
            return (errorMessages.value = error.response.data.errorsToSend);
        }
    }
};

Router
import { useAuthStore } from "@/stores/auth.store.js";

// ...

router.beforeEach(async (to, from) => {
    const authStore = useAuthStore();
    const publicPages = ["/login", "/super-admin-login"];
    const authRequired = !publicPages.includes(to.path);

    if (authRequired && !auth.user) {
        return "/";
    }
});