Q:

Getting BASH command PID

I have this piece of code
#!/bin/bash
streamURL=http://devimages.apple.com/iphone/samples/bipbop/gear4/prog_index.m3u8

(
    echo "Debugging for stream: $streamURL";
    echo "Starting debugging...";
    vlc -vvv --color $streamURL --file-caching=10000 2>&1 | sed "s/^/ `date`/";

) | tee  debug.txt &
PROCESS_PID=$!

ps -e | grep $PROCESS_PID
echo " killing process pid: "
echo $PROCESS_PID;
kill -9 $PROCESS_PID
ps -e | grep vlc #still there

My problem is I can't manage to save the "vlc ..." command PID into a variable in order to kill it later. If I move "PROCESS_PID=$!" right after it, it will be empty. Also need the pipe after it for sed. Any suggestions?

A:

You can get the pid by twiddling file descriptors, but it's painful.  For example:
{ PID=$({ (
   echo foo;
   echo bar;
   sh -c 'echo $$ >&5; exec echo baz' ) |
   tr a o; } 5>&1 1>&3 ); } 3>&1

will assign the pid of 'echo baz' to PID.  Replace that echo with your vlc and replace the tr with your sed and you should have a solution.
To try an provide a somewhat simplified explanation of what's going on here, first notice that we are using process substitution to make the assignment to PID.  The $() syntax simply takes the command inside the parentheses and assigns to the variable the output of the command.  It is important to remember that "output" here means "whatever is printed to file descriptor 1".  Inside the sh command, we print a pid to file descriptor 5 and then exec echo.  By using exec, that echo has the same pid that the previous echo wrote.  Now the echo foo, bar and baz are all writing into  the pipe that goes to tr.  The output of tr is being redirected to fd 3 (before the edit, this was fd 2. Which file descriptor to use is mostly arbitrary, but modifying 2 is a bad idea in case any errors are generated) and file descriptor 5 is being redirected to fd 1, so that it becomes the "output" of the process substitution that is assigned to PID.  Then outside the process substitution, we assign fd 3 to give output where it was originally desired.  Hopefully, this paragraph is more explanatory than obfuscating: if confused, look at the code for clarification!
Unfortunately, it gets uglier if you want to run in the background:
{ PID=$({ (
   echo foo;
   echo bar;
   sh -c 'echo $$ >&5; exec 5>&-; exec echo baz' >&3 & ) |
   tr a o; } 5>&1 1>&3 ); } 3>&1

Here, you need to close file descriptor 5 to ensure that the process substitution completes.


Q:

Seg Fault 11 when inserting element into binary search tree

I am writing a program in C++ and I can't figure out why I keep getting a segmentation fault. Here is the part of the code I am currently working with that is causing me trouble:
In my main function:
Tree* myTree;
myTree = CreateBST();

const Element a = 23;
InsertBST(myTree, a);

const Element b = 8;   //If I get rid of this line and the next one, the error goes away.
InsertBST(myTree, b);  //But I need to be able to insert data into my tree beyond just the root!

And then the insertBST function itself and its helper function:
void InsertBST(Tree * rTree, const Element nData){
    rTree->root = InsertNodeBST(rTree->root, nData);
}

//========================================================================================
TreeNode* InsertNodeBST(TreeNode* rNode, const Element nData)
{
    if(rNode->data == -999)   //A new tree's root->data will always be initialized to -999
   {
       TreeNode* rNew = new TreeNode;
       rNew->data = nData;
       rNew->left = NULL;
       rNew->right = NULL;
       return rNew;
   }
   else if(rNode == NULL)
   {
       TreeNode* rNew = new TreeNode;
       rNew->data = nData;
       rNew->left = NULL;
       rNew->right = NULL;
       return rNew;
   }
   else if(nData == rNode->data)
   {
       return rNode;
   }
   else if(nData < rNode->data)
   {
       rNode->left = InsertNodeBST(rNode->left, nData);
       return rNode;
   }
   else
   {
       rNode->right = InsertNodeBST(rNode->right, nData);
       return rNode;
   }

}

The structures we are required to use are as follows:
struct TreeNode {
  Element data;
  TreeNode *left;
  TreeNode *right;
};

struct Tree{
    TreeNode *root;
};

Does anyone see what I am clearly missing that could be causing my segmentation fault? I'm new to CS and I am taking my first CS class in 7 years, so I apologize if it is a glaringly obvious mistake. Thanks.

A:

if (rNode->data == -999)
{
    ...
}
else if (rNode == NULL)
{
    ...
}

If rNode is NULL, rNode->data crashes. Did you mean to put these ifs in the reverse order?


Q:

PHP & json_decode - how to get property of object

CONTEXT
I'm using json_decode to convert the contents of an Facebook open graph call into a php object.
EDIT to add code
My code looks like this:
$json = json_decode(file_get_contents("http://graph.facebook.com/http://example.com"),true);
var_dump($json);

A var_dump of the resulting object looks like this:
ARRAY(3) { ["ID"]=> STRING(18) "HTTP://EXAMPLE.COM" ["SHARES"]=> INT(14604317) ["COMMENTS"]=> INT(11300) }

PROBLEM
I would like to get the 12 from this object. I assumed that $json->shares would return 12, but instead it returns null. Any idea what the correct syntax for retrieving the 12 would be?

A:

Your array doesn't look right. Check out http://graph.facebook.com/http://example.com in a browser, notice how the keys and values are all lowercase, not uppercase like you have.
If you really are testing http://graph.facebook.com/http://example.com, then this will just work:
$array = json_decode(file_get_contents('http://graph.facebook.com/http://example.com'), true);
echo $array['shares'];

This gives me 14604317 which I can see in my browser is the correct result.
Note you have an array, not an object. So use array notation:


Q:

Unexpected observation: var_dump() of an array is flagging referenced elements... since when?

I've just been running some simple debug tests against arrays, and noticed that when I do a var_dump() of an array, the output is flagging any element in the array that is referenced by another variable. As a simple experiment, I ran the following code:
$array = range(1,4);

var_dump($array);
echo '
';

foreach($array as &$value) {
}

var_dump($array);
echo '
';

$value2 = &$array[1];

var_dump($array);
echo '
';

which gives the following output:
array(4) { [0]=> int(1) [1]=> int(2) [2]=> int(3) [3]=> int(4) }
array(4) { [0]=> int(1) [1]=> int(2) [2]=> int(3) [3]=> ∫(4) }
array(4) { [0]=> int(1) [1]=> ∫(2) [2]=> int(3) [3]=> ∫(4) }

Note the ∫ symbol alongside element 3 and subsequently element 1. Note also that those entries don't show the entry's datatype.
Following some experimentation, I don't see this if I var_dump a scalar type, or with objects or resources. If the array contains string data, the symbol is a & (and it does still show the datatype), likewise with float, boolean and object entries.
This is running against PHP 5.2.8
First question: When did this behaviour start, or is it something that I simply haven't noticed before now?
Second question: If referenced elements can be flagged in this way by var_dump(), is there any function in core PHP that will allow me to identify if an array element is referenced by another variable; or that will return the refcount or ref flag from a _zval_struct?

A:

Not sure if this answers your question, but you can use
debug_zval_dump($array);

to get the refcount:
array(4) refcount(2){
    [0]=> long(1) refcount(1)
    [1]=> &long(2) refcount(2)
    [2]=> long(3) refcount(1)
    [3]=> &long(4) refcount(2)
}

Also see this Article by Derick Rethans (PHP Core Dev) about Refcounting.


Q:

Subversion merging changes from a different repository

I'm really confused. I want to do something that a) seems like it should be pretty simple, and b) other people must do all the time, but I cant find out the best way to do it anywhere.
There's an external repository that contains some 3rd party code. I want to take a copy of version 1 of the code and put it in my own repository, and then customise it for my own needs. When version 2 of that code is released I want to be able to upgrade my customised version with all of the version 2 changes, retaining my customisations.
I've read about vendor branches (http://svnbook.red-bean.com/en/1.5/svn.advanced.vendorbr.html) but I don't understand why merging the previous copy of the vendor code and the new copy of the vendor code needs to be so complicated (ie. svn_load_dirs.pl). Surely, if the 3rd party code is stored in an SVN repository, all of the history regarding which files have moved/been deleted is known, so why do you need to tell it what's changed manually?
Quote:

For example, you will have the opportunity to tell the script that you know that the file math.c in version 1.0 of libcomplex was renamed to arithmetic.c in libcomplex 1.1.

I've also read (http://svn.haxx.se/users/archive-2006-04/0285.shtml) that it is possible to simply run a merge between different repositories, but I didn't think that was possible, and whenever I've tried it it's failed (though I could have been doing something wrong).
Can anyone clarify this for me, and suggest the best solution?

A:

I've just tried a brief experiment with TortoiseSVN:
Creating the test repositories

create two new repositories in rep1 and rep2
check out rep1 into co1
add a text file to co1 and check it in
export rep1 to ex1
import ex1 into rep2

At this stage you will be in the state of having created your local 'branch' in a new repository. The last two steps are all you need for an existing project.
To simulate some changes to the original repo, modify the text file in co1 and commit the changes.
Merging Changes
Now, to create your own working copy, check out rep2 into co2.
We should be ready to try merging from rep1 into co2.
Open the merge dialog for co2 and point it at rep1.
For the 'from' revision select the revision at which you exported your copy (in this case revision 1), or the revision that you last updated your local copy to.
For the 'to' revision select the HEAD or the latest update you want to apply.
Results
This seems to work as expected, with the modifications from rep1 being applied to the working copy of rep2 in co2. These then need to be committed back to your local repository.

A:

The vendor branches link you provided does effectively describe the process of what you want to do. It is a perfect solution relative to allowing you to do a straight update (import) of the vendor branch, and then as you allude to, will then allow you to merge the vendor's updates in with your changes in the main development branch.
The problem is that Subversion really doesn't provide direct support for file renames and moves of files between directories for the successive update from the vendor code because you are just getting snapshots of the source files' content....something needs to run the commands into the version system to indicate what changes are being made to the tree of file names that make up the new version. This is the purpose of the svn_load_dirs.pl script process. It helps you to get your version history manipulated around to match up the branches so that you can then proceed with the merge. If the vendor didn't rename and/or move files around between versions you imported, you would not have this problem.
In any case, the process described there is what you/need to do.


Q:

Where are trace files saved in PeopleSoft?

In PeopleSoft Enterprise, there is an option to enable tracing options from the signon screen. (Tracing options are also accessible after logon from PeopleTools > Utilities > Debug)
I've enabled tracing for SQL statements for debugging purposes. However, I can't figure out where to find my trace logs on the server once the session is complete.
Where are trace logs saved in PeopleSoft when trace flags are enabled?

A:

Typically they are on the Application Server under the directory for your environment.
e.g.

<PS_HOME>/appserv/<domain>/LOGS (quoted from article)
/opt/test/psft/pt/8.53/appserv/prd/LOGS/PSAPPSRV.10742/process_state.txt (quoted from blog entry)
$PS_CFG_HOME/appserv/<DOMAIN>/LOGS (quoted from blog entry)


Q:

rotating cogs in java

First of all my english is rubbish, so please understand.
I have been asked to do a little simulation/animation in java.
I have a few cog on board one of the cogs rotates all the time on its axis. when I move any other cog close to the rotating one it has to start rotating  and teeth can not overlap each other.
I think this link describes it quite well
http://www.csharphelper.com/howto_animate_gear.gif
I don't know how to make this cogs interact together, i will be really happy if some can show some code example
Many thanks for any help

A:

If you know how to rotate the kog, you could cheat a bit, and hard-code the timing so that they rotate at the right time :P

A:

This is a classic LCM (Least Common Multiple) problem: try to formulate a solution from the dimensions (radius or diameter or circumference) of the cogs.


Q:

Google Chrome Stable crashing at launch

After a recent update in Ubuntu 16.04 chrome refused to launch with the following output to terminal:
~$ google-chrome-stable
[5525:5562:0327/115046.503718:ERROR:nss_util.cc(724)] After loading Root   Certs, loaded==false: NSS error code: -8018
[5525:5550:0327/115046.527819:ERROR:in_progress_cache_impl.cc(93)] Could  not read download entries from file because there was a read failure.
--2018-03-27 11:50:46--  https://clients2.google.com/cr/report
Resolving clients2.google.com (clients2.google.com)... 216.58.213.110,  2a00:1450:4009:811::200e
Connecting to clients2.google.com   (clients2.google.com)|216.58.213.110|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: unspecified [text/html]
Saving to: ‘/dev/fd/4’

Crash dump id: 77bf82c7db6d1e8e

     0K                                                         602K=0s

Bus error (core dumped)

I tried purging chrome with sudo apt purge google-chrome-stable and reinstalling but it still wouldn't launch even after a reboot.

A:

The only thing that worked was purging both google-chrome-stable and chromium-browser with sudo apt purge google-chrome-stable and sudo apt purge chromium-browser and then deleting any files and folders which point to chrome or chromium under ~./cache/ and ~./config/. eg. rm -r ~/.cache/google-chrome/ etc.


Q:

Testing Ember Data

Anyone have any good examples of testing Ember data in your own app?
I'm starting to build an app using the Fixtures adapter, which is great. But I want to test my models and make sure everything works properly as I build.
I have QUnit setup and running, but I don't want to write the server side in order to verify that the Data Model makes a call. I'd like to mock out the Adapter and just see if the find method is called and return a new object from it. I'll worry about the server side implementation later.
Any ideas?
This is what I have so far (that doesn't work):
test('MyModel should call find', 1, function(){
  App.TestAdapter = DS.Adapter.extend({
    find: function(store, type, id){
      ok(true, 'calls the find method');
      console.log('find: ', type, id);
    }
  });

  App.Store = DS.Store.extend({
    adapter: 'App.TestAdapater'
  });

  myModel = App.MyModel.createRecord({
    name: 'Test',
    period: 0
  });

  // method that should call .find
  myModel.currentObject();

});

A:

I ended up going with Konacha.
The biggest part was:
before(function() {
  Ember.run(function() {
    App.initialize();
  });
});

afterEach(function() {
  Ember.run(function() {
    App.reset();
  });
});


Q:

How to call this curl API request to get the highest 'likelihood' json field name?

I'm trying to use this API from this site fullcontact for normalizing a number of possible names into 'likelihood values' for name extraction.
Tried the following code but it can't run Undefined offset: 2 error: $index_name = $possible_names[$n];. Moreover, I'm was stuck with the logic of extracting the name. Can someone help? Thanks
$possible_names = array("Jimmy Frank", "Wall Street"); // In this case Jimmy Frank should be the output person name

if (count($possible_names) > 1)
{
     for ($n = 0; $n <= count($possible_names); $n++)
     {
         $index_name = $possible_names[$n];
         $ch = curl_init();
         curl_setopt($ch, CURLOPT_URL, "https://api.fullcontact.com/v2/name/normalizer.json?q=$index_name");
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
         curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");

         $headers = array();
         $headers[] = "X-Fullcontact-Apikey: APIKEY";
         curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

         $namenormalizer_result = curl_exec($ch);

         if (curl_errno($ch)) {
            echo 'Error:' . curl_error($ch);
         }
         else
         {
            $namejson_result = json_decode($namenormalizer_result, true);
            $namejson_array[] = $namejson_result['likelihood'];
         }
         curl_close ($ch);
     }
}

A:

$possible_names is an array of size 2. Arrays are indexed from 0 so you need to remove the last index 2 which doesn't exist :
for ($n = 0; $n <= count($possible_names) - 1; $n++) {

}

or use strict condition :
for ($n = 0; $n < count($possible_names); $n++) {

}

For the extraction, you can use $namejson_result->nameDetails->fullName to extract fullName and $namejson_result->likelihood for likelihood :
$namejson_result = json_decode($result);

echo "likelihood for $index_name on " .
    $namejson_result->nameDetails->fullName . " : " .
    $namejson_result->likelihood . "\n";


Q:

Out of range error when reading from vector

After reading integers from a txt file and push_back them to a vector for different txt files (all of same structure) i dont get the right result every time.
the first line (first number of the vector) show how many graphs are to be implemented from this file.
Then the first number of the second line (second number of the vector) gives the nodes and the second number of the second line (third number of the vector) the edges. After there are the edges number pairs, then again number of nodes and number of edges and so on.
For the first vector my code works. This is what i have written:
int main(int argc, char** argv)  {
vector<int> read_ints = {2,9,9,6,3,7,1,8,9,6,4,5,1,1,9,2,5,1,4,5,4,9,9,4,6,8,1,3,4,2,8,6,7,9,3,4,7,1,5,4,9};
vector<int> read_ints2 = {10,25, 18,5 ,19,4 ,23,13, 25,4 ,7,2 ,18,11, 4,15, 25,16, 12,2 ,23,5 ,23,24, 19,14, 11,2 ,24,19, 2,14, 16,20, 24,19, 8,18, 3,15, 15,14, 10,15, 4,8 ,10,2 ,3,6 ,11,13, 9,8 ,1,7 ,13,5 ,12,3 ,9,12, 7,1 ,5,15, 2,14, 11,4 ,6,17, 17,9 ,1,10, 17,5 ,11,5 ,14,14, 13,7 ,4,14, 4,10, 8,17, 4,9 ,3,5 ,16,6 ,16,10, 3,2 ,14,1 ,13,15, 17,16, 13,16, 16,6 ,1,13, 5,5 ,8,16, 1,7 ,13,13, 10,10, 3,8 ,14,3 ,2,7 ,5,11, 12,7 ,12,7 ,10,15, 4,13, 15,11, 16,22, 22,11, 13,17, 6,10, 7,8 ,10,10, 21,20, 5,2 ,20,14, 4,3 ,22,7 ,1,4 ,19,2 ,16,11, 8,15, 1,1 ,4,16, 19,9 ,16,11, 3,12, 5,6 ,22,9 ,2,17, 5,18, 18,10, 4,10, 13,3 ,10,17, 12,15, 6,11, 2,6 ,17,7 ,5,14, 16,8 ,2,7 ,8,3 ,1,16, 9,16, 1,14, 12,9 ,5,14, 9,18, 11,20, 20,11, 8,9 ,11,1 ,19,7 ,15,5 ,12,1 ,6,10, 4,2 ,19,20, 7,3 ,8,11, 13,5 ,9,20, 18,10, 16,4 ,6,17, 14,18, 19,17, 5,8 ,10,17, 15,12, 12,6 ,4,12, 2,12, 8,7 ,4,7 ,5,10, 8,1 ,5,1 ,2,10, 6,10, 3,8 ,9,9 ,11,8 ,8,5 ,3,7 ,8,6 ,4,7 ,1,2 ,6,8 ,2,3 ,4,5 ,1,20, 20,6 ,15,14, 7,4 ,17,13, 3,8 ,15,17, 8,12, 18,14, 18,18, 7,9 ,15,11, 5,9 ,8,2 ,20,16, 20,4 ,1,3 ,2,20, 3,14, 10,1 ,5,19, 13};
vector<int>::iterator ints_iter;
int counter = 0; // to count the edges, for testing purposes.
int num_of_graphs = read_ints.at(0);
int num_vertices = read_ints.at(1) + 1; // + 1 because of the code i wrote for implementing the graph's vertices
int num_edges = read_ints.at(2);
read_ints.erase(read_ints.begin(), read_ints.begin() + 3); // deleting the first line (number of graphs) and the first graph's info, so it is easier to add edge's pairs.
for (int i = 0; i < num_of_graphs; i++){
    Graph g(num_vertices); // Graph is the class i made
    for (int i = 0; i < num_edges * 2; i += 2) {
        cout << read_ints.at(i) << " " << read_ints.at(i + 1) << endl; // printing the pairs line by line
        counter++;
    }
    read_ints.erase(read_ints.begin(), read_ints.begin() + (num_edges * 2)); // delete the pairs of the i'th graph every time from the vector to add the new edges on the next graph
    if (read_ints.empty()) // error handling for the last graph (which doesnt work)
        break;
    else
        int num_vertices = read_ints.at(0) + 1; // after deleting the previous graph info and the previous graphs edges from the vector, i change the i values for next graph's nodes and edges
        int num_edges = read_ints.at(1);
        read_ints.erase(read_ints.begin(), read_ints.begin() + 2); // since the vector is not empty i erase the last elements
}
cout << counter;

return 0;

For the first vector it works but for a bigger one like the second it says "terminate called after throwing an instance of 'std::out_of_range'
what():  vector::_M_range_check: __n (which is 8) >= this->size() (which is 8)"
after printing out all the edges.

A:

This
    else
        int num_vertices = read_ints.at(0) + 1;
    int num_edges = read_ints.at(1);
    read_ints.erase(read_ints.begin(), read_ints.begin() + 2);

declares two local variables named num_vertices and num_edges.  These are different from the local variables of the same name declared earlier in main, so the values used on the next iteration of the loop are from the first block of data.
Note that I've also adjusted the indentation to show the how the statements interact with the else.  In this case it is harmless because the other branch of the if is a break but you need to be careful that you don't misread your code due to misleading indentation.


Q:

Why admin menu and some styles working after modifying class Symlink -> Copy?

I have installed Magento ver. 2.1.2, Admin menu is not working and some of the front end styles are not coming properly.
After I replace (app/etc/di.xml) as in the below code, everything is working fine. I have been facing this issue with all Magento 2 versions.
Magento\Framework\App\View\Asset\MaterializationStrategy\Symlink

To
Magento\Framework\App\View\Asset\MaterializationStrategy\Copy

I got followed Solution for Inactive Admin Links in Magento 2 (Windows)
Can anybody tell me

Why the class replacement is necessary ?
Is this an internal bug ?
Am I missing something ?

A:

Officially Magento 2, as well as many other web application, is supposed to be installed and run in the native environment. The native environment means LAMP or LEMP + Unix compatible filesystem. On Windows you can easily have LAMP or LEMP but not fully Unix compatible filesystem (sure, you can try to emulate it in different ways but the emulation does not guarantee the system will work properly).
You need to change the Symlink materialisation strategy to the Copy statagy (Magento 2 using both for different cases) because your XAMPP installation does not support UNIX symlinks properly.
The symlinks in Windows (and XAMPP as well) are not the same as in the Unix based system. That's why you might have troubles using symlinks in Windows system.
No, it's not a bug since Magento is being developed and tested using the native (Unix) environment. Obviously, there's no reason to make the system compatible with different kinds of emulations. So, in order to be sure your system works correctly, it's strongly recommended to perform all development processes in the native environment as well (until you are going to run Magento 2 using Windows in production). It's achievable by using VirtualBox, Vagrant, Docker or other tools that allow you to run your web applications in Unix environment.


Q:

Replace HTTPS to HTTPS of XML

I need to get an image url from a XML file, but my server got some errors because this url uses https. How can I read the https link and relace it to http? Please help me, I don't understand programming...
function api_lastfm( $artist, $api_key ) {
        $data = xml2array( get( "http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=" . urlencode( $artist ) . "&api_key={$api_key}", false, false, false, 6 ) );
        return ( isset( $data[ 'artist' ][ 'image' ][ 4 ] ) && !empty( $data[ 'artist' ][ 'image' ][ 4 ] ) ) ? $data[ 'artist' ][ 'image' ][ 4 ] : $data[ 'artist' ][ 'image' ][ 3 ];
    }

Thanks!

A:

Like I mentioned in my comment, use  str_replace() for this.
My example assumes that the get() method returns a string with the xml:
function api_lastfm( $artist, $api_key )
{
    $data = get( "http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=" . urlencode( $artist ) . "&api_key={$api_key}", false, false, false, 6 );

    // Replace all image urls using https to http
    $data = str_replace('https://lastfm-img2', 'http://lastfm-img2', $data);

    $data = xml2array($data);
    return ( isset( $data[ 'artist' ][ 'image' ][ 4 ] ) && !empty( $data[ 'artist' ][ 'image' ][ 4 ] ) ) ? $data[ 'artist' ][ 'image' ][ 4 ] : $data[ 'artist' ][ 'image' ][ 3 ];
}

This should change all image URL's from https to http. It does mean that the images must be available without https as well, though.


Q:

How to free memory from a list of classes

Say I have two classes created work and workItem.
        CWorker *work = new CWorker();
        CWorkItem *workItem = new CWorkItem();

The work class has a public list m_WorkList and I add the work item to it.
work->m_WorkList.push_back(workItem);

If I just delete work
if(work != NULL)
delete work;

Do I need to loop through the list in the destructor like the following? Any better way to do this? Could I use clear instead?
while(m_WorkList.size())
{
    CWorkItem *workItem = m_WorkList.front();
    m_WorkList.pop_front();
    if(workItem)
        delete workItem;
}

A:

Yes you need to delete each item.  If you call new N times, then you need to call delete exactly N times as well.  There is no shortcut for bulk deleting items.
Also when you're done with it you need to call delete on work.
You can use new[] and delete[] if you want to create an array of items on the heap and release the items on the heap respectively at once.   But in your case this isn't what you're looking for.
You can look to boost::shared_ptr if you don't want to manually do these delete calls.

A:

as said in the other responses, you need to loop over your list and delete each elements. if you call clear, it will just remove pointers from the list not pointed objects.
if you need a list with the notion of ownership you can use boost pointer container. it will ensure that your objects are destroyed when you destroy your list


Q:

Paging/Sorting not working on web grid used in Partial View

I have a partial view where I am showing a web grid depending upon a value selected from a page.
For drop down I have used
 @Html.DropDownListFor(
x => x.ItemId,
new SelectList(Model.Items, "Value", "Text"),
new {
    id = "myddl",
    data_url = Url.Action("Foo", "SomeController")
}
)

For drop down item select I have used
$(function() {
$('#myddl').change(function() {
   var url = $(this).data('url');
   var value = $(this).val();
   $('#result').load(url, { value: value })
});
});

and below is my action
public ActionResult Foo(string value)
 {
  SomeModel model = ...
return PartialView(model);
 }

everything works good, but when I try doing a paging or sorting on my webgrid which is on my partial view I am showing a new window with the web grid.
I wanted to be able to sort and page on the same page without postback
Please help

A:

The following example works fine for me.
Model:
public class MyViewModel
{
    public string Bar { get; set; }
}

Controller:
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult Foo(string value)
    {
        var model = Enumerable.Range(1, 45).Select(x => new MyViewModel
        {
            Bar = "bar " + value + " " + x
        });
        return PartialView(model);
    }
}

Index.cshtml view:
<script type="text/javascript">
    $(function () {
        $('#myddl').change(function () {
            var url = $(this).data('url');
            var value = $(this).val();
            $.ajax({
                url: url,
                type: 'GET',
                cache: false,
                data: { value: value },
                success: function (result) {
                    $('#result').html(result);
                }
            });
        });
    });
</script>

@Html.DropDownList(
    "id",
    new[] {
        new SelectListItem { Value = "val1", Text = "value 1" },
        new SelectListItem { Value = "val2", Text = "value 2" },
        new SelectListItem { Value = "val3", Text = "value 3" },
    },
    new {
        id = "myddl",
        data_url = Url.Action("Foo", "Home")
    }
)

<div id="result">
    @Html.Action("Foo")
</div>

Foo.cshtml partial:
@model IEnumerable<MyViewModel>
@{
    var grid = new WebGrid(
        canPage: true,
        rowsPerPage: 10,
        canSort: true,
        ajaxUpdateContainerId: "grid"
    );
    grid.Bind(Model, rowCount: Model.Count());
    grid.Pager(WebGridPagerModes.All);
}

@grid.GetHtml(
    htmlAttributes: new { id = "grid" },
    columns: grid.Columns(
        grid.Column("Bar")
    )
)

Notice that I have used a GET request to refresh the grid instead of POST because this way the value query string parameter selected in the dropdown is preserved for future sorting and paging.


Q:

IOServiceGetMatchingServices returning empty iterator in OSX 10.11 El Capitan

I have a small program to find out the Vendor ID and Product ID of all the USB CDC devices connected to Mac. The program uses the IOServiceNameMatching and IOServiceGetMatchingServices to get the matching dictionary and service iterator respectively as shown in the code snippet below:
matchingDictionary = IOServiceNameMatching("AppleUSBCDC");
IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDictionary, &serviceIterator);

I then iterate through serviceIterator to enumerate and extract the IDs of all the connected USB CDC devices. This used to perfectly work fine until OSX 10.10 but the IOServiceGetMatchingServices is returning empty iterator in OSX 10.11. Why is it returning empty iterator only on OSX 10.11 even though the USB CDC devices are connected? Is there an alternate way to get the device list in OSX 10.11?

A:

El Capitan changed the underlying names/architecture of the USB stack, I assume the service name is now different but I don't have a USB CDC device handy to check.
Use IORegistryExplorer (included with the Hardware IO Tools) to look at the device nubs you want to match against, and see what properties they have (and what you can try to search for with IOServiceNameMatching or IOServiceMatching).


Q:

Data structure with at least O(ln N) on random access and at least O(ln N) on delete [NOT DUPLICATE]

There is no standard container which gives such guarantees out from the box, some additional manipulation are required (for instance, like Jerry Coffin suggested), it is NOT duplicate.

Are there any ready data structure/container with at least O(ln N) on random access and O(ln N) on delete? (stl/boost/etc)
Ordering of elements within container is not important.
Such operations may happen in series, like:

random access by index ( index is random too, rand()%size() )
delete this item
random access by index ( index is random too, rand()%size() )
delete this item

etc...

A:

Since you say ordering doesn't matter, you can do both in constant time using a vector.
Random access is (obviously) constant time.
Deletion in constant time can be done by swapping the element to delete with the last element, then deleting the last element.


Q:

What is the difference between ::: and :::.() in scala

In the scala list class it is shown that:
List(1, 2) ::: List(3, 4) = List(3, 4).:::(List(1, 2)) = List(1, 2, 3, 4).
Shouldn't:
List(1,2) ::: List(3,4) = List(1,2).:::(List(3,4)) = List(3,4,1,2)
( method ::: prefixes the list)

A:

From the docs:
def :::(prefix: List[A]): List[A]

[use case]
Adds the elements of a given list in front of this list.
Example:
List(1, 2) ::: List(3, 4) = List(3, 4).:::(List(1, 2)) = List(1, 2, 3, 4)

In Scala, operators that end in : are right associative and the invoking object appears on the right side of the operator. Because it is right associative, the prefix method will be called on the object "to the right", which is List(3, 4).
Then it will do what its name says, it will prefix List(3, 4) with List(1, 2), and that's why you get List(1, 2, 3 ,4). Not the most intuitive thing in the world but it's like this:
a ::: b
// ending in :, so flip the argument order, call the method on b.
b .:: a // :: = prefix b with a
result = a(concatenated) with b

Now let's look at the right hand side:
List(3, 4).:::(List(1, 2))

The . dot is performing an inversion of the ::: prefixed invocation, so it will simply invert the two List objects before performing the ::: prefix operation.
List(3, 4).:::(List(1,2)) = List(1, 2) ::: List(3, 4) // exactly as the above.
// and now you it's the same story.

The . dot is a simply way to invert associative operators. a ::: b is the same as b .::: a


Q:

How to make vscode show type info for exported function from another .js file?

Showing type information in vscode for Typescript files is pretty simply via the /// <reference path ... comment. However, I have the case where I use exported functions from one js file in another. The exported functions have been annotated to contain type information. Here's an example (lib/index.js):
/**
 * Put the executing thread to sleep for the given amount of milliseconds.
 * @param {number} milliseconds
 */
exports.sleep = function (milliseconds) {
    var end = new Date().getTime() + milliseconds;
    while (new Date().getTime() < end) { }
}

In my main.js file I do:
var lib = require("lib");
lib.sleep(500);

Unfortunately, vscode does not provide the call signature of that sleep function nor can I use cmd/ctrl+click to navigate to it.
I also created a typings file and referenced that in main.js, which works almost like I want, except that it doesn't take me to the original source, but instead to the typings file when I cmd/ctrl+click on the function name.
Is it possible and how to let vscode recognize exports in other JS files and provide call information and code navigation for them?

A:

Change require path to ./lib
var lib = require("./lib");
lib.sleep(500);


Q:

Does the sqlite 'file change counter' overflow when it exceeds the maximum size?

According to http://www.sqlite.org/fileformat.html SQLite3 maintains a 4-byte big-endian integer file change counter in byte 24..27 of the database file.
Does the file change counter overflow when it exceeds the maximum size?
(I feel the answer is: yes, it does overflow)

I ask because I wanted something akin to checksum for the sqlite file, and found file change counter through another StackOverflow question:
Checksum for a SQLite database?

A:

The actual value of the file change counter does not have any meaning (it is not a version number); the only important thing is that it is different from all other recent values.
A quick test shows that the value wraps around:
$ sqlite3 test.db 'create table t(x);'
$ od --skip-bytes 24 --read-bytes 4 -tx1 test.db | cut -c9-
00 00 00 01
(lots of changes ...)
$ od --skip-bytes 24 --read-bytes 4 -tx1 test.db | cut -c9-
ff ff ff ff
$ sqlite3 test.db 'drop table t;'
$ od --skip-bytes 24 --read-bytes 4 -tx1 test.db | cut -c9-
00 00 00 00


Q:

Camunda Timer event unexpected delay in timing

I have a process in which I have used a timer event. The timer event is of type
Duration and has wait time of 30 minutes(PT30M). This timer event is expected to end exactly after 30 minutes, but it takes additional 15 or 30 seconds.
This behavior is observed and the delay is exactly 15 or 30 seconds every time even if I change (increase or decrease) the duration of timer event. I would like to know why does it take 15 seconds extra then required to execute.

A:

A timer in a BPMN process is persisted as a job in Camunda. The job executor component repeatedly polls the job table for any jobs that are due. In case there are no due jobs, the polling applies exponential backoff, by default sleeping up to 60 seconds between polling attempts. So if your system has little load, this kind of delay is to be expected. You can use the job executor configuration property maxWait to change the maximum sleeping period.
Relevant documentation:

Job executor in general: https://docs.camunda.org/manual/7.10/user-guide/process-engine/the-job-executor/#job-executor-activation
Job executor configuration properties: https://docs.camunda.org/manual/7.10/reference/deployment-descriptors/tags/job-executor/


Q:

How can i have no error when press Cancel Button on openFileDialog?

before ask, i have done a lot of search on internet but have no found an answer to my problem.
I have one Form with a button and two Classes.
When i press the Button on the Form, a Dialog opens to select a file.txt from the disk.
If i press the Open Button, the program goes on correctly doing what is write on the code.
If i press the Cancel Button, the program rise an error: System.NullReferenceException: ‘Reference to an object not set on an object instance.' Path was Nothing.    (On Class FilePan     nomeFilePan = path.Replace("1319", "panasonic\") + _nomeFile + ".pan")
What can i do to send the program back to the Form, were i can press again the button to open a file or close the program?
Imports System
Public Class Form1
    Dim _fileTxt As FileTxt = New FileTxt()
    Dim CreaPan As FilePan = New FilePan()

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        _fileTxt.SetFileTxt()
        CreaPan.SetFilePan(_fileTxt.GetNomeFile(), _fileTxt.GetPath())
    End Sub
End Class

Public Class FileTxt
    Dim path As String
    Dim nomeFile As String
    Dim nomeFileTxt As String

    Public Sub SetFileTxt()
        Dim openFileDialog1 As New OpenFileDialog() With
            {
                .InitialDirectory = "",
                .Filter = "Txt file|*txt",
                .FilterIndex = 1,
                .RestoreDirectory = True,
                .Title = "Seleziona file"
            }
        If openFileDialog1.ShowDialog() = DialogResult.OK Then
            path = IO.Path.GetDirectoryName(openFileDialog1.FileName)
            nomeFile = IO.Path.GetFileNameWithoutExtension(openFileDialog1.FileName)
            nomeFileTxt = IO.Path.GetFileName(openFileDialog1.FileName)
        Else
            ' How can go back the program start (Form1 with the button)???
        End If
    End Sub

    Public Function GetNomeFile() As String
        Return nomeFile
    End Function

    Public Function GetPath() As String
        Return path
    End Function

End Class

Imports System.IO
Public Class FilePan
    Dim path As String
    Dim nomeFilePan As String

    Public Sub SetFilePan(ByVal _nomeFile As String, ByVal _path As String)

        path = _path
        nomeFilePan = path.Replace("1319", "panasonic\") + _nomeFile + ".pan"

        If File.Exists(nomeFilePan) Then
            File.Delete(nomeFilePan)
        End If
    End Sub
End Class

A:

There are many ways to do what you want. If you want to do it with your current structure you could try:
Public Function SetFileTxt() as Boolean
    Dim openFileDialog1 As New OpenFileDialog() With
        {
            .InitialDirectory = "",
            .Filter = "Txt file|*txt",
            .FilterIndex = 1,
            .RestoreDirectory = True,
            .Title = "Seleziona file"
        }
    If openFileDialog1.ShowDialog() = DialogResult.OK Then
        path = IO.Path.GetDirectoryName(openFileDialog1.FileName)
        nomeFile = IO.Path.GetFileNameWithoutExtension(openFileDialog1.FileName)
        nomeFileTxt = IO.Path.GetFileName(openFileDialog1.FileName)
        return True
    Else
        return False
    End If
End Function

This will return a bool of false if OK is not clicked on the dialog.
Then put .SetFileTxt() in an if statment.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    If _fileTxt.SetFileTxt() Then
        CreaPan.SetFilePan(_fileTxt.GetNomeFile(), _fileTxt.GetPath())
    End If
End Sub


Q:

Setting tag on imageview mono for android C#

I'm trying to add a tag to a imageview for comparison reasons. But unfortunately, I'm getting an illegal argument exception. The exception takes place on my code when trying to add the tag. Here's how I do it.
mainImage.SetTag(1, "circle");

Am I doing it wrong? It seems pretty simple, a key and and object value. I thought of using content description value, but mono doesn't seem to support getting content descriptions. Any ideas? Thanks!

A:

To avoid conflicts, you have to use a known Resource Id for the Tag - you can't just pick your own value.
Try adding an AndroidResource XML file in Resources/Values with content:
<?xml version="1.0" encoding="utf-8"?>
<resources>
  <item type="id" name="MyUniqueTag"/>
</resources>

then you should be able to use
 mainImage.SetTag(Resource.Id.MyUniqueTag, "circle");


Q:

Starting Asp.Net Website Automatically on windows startup

I want to start my asp.net application when my windows 7 x64 starts.
I have manually start IIS to start my asp.net website.
Please suggest me to way to do this task.

A:

Follow the path..

Start>Control Panel>Administrative Tools>Services>World Wide Web Publishing Service>Right click on that service>Properties> Set startup type =Automatic >OK

Done!! you will get your localhost site in start up!!


Q:

TinyMCE - load whole html content without altering meta head JavaScript tags

When I load file.html to TinyMCE, just content in body tag is available. I would like to be able to edit whole html site content with TinyMCE without striping html, head, meta, script tags, or other tags. How is this possible please?

A:

There is a plugin called fullpage that will allow you to do what you want:
https://www.tiny.cloud/docs/plugins/fullpage/


Q:

Photoshop CC2019 auto-update all linked smart objects including nested ones

I have Photoshop CC2019 PSD document containing several smart objects that contains other smart objects that contains other smart objects. Some of these have linked layers. Normally, such images are not updated automatically (which is extremely annoying, Adobe!) but you have to manually update each of them once the linked image content has changed.
There is a .jsx script file named "Update All Modified Content.jsx" which auto-updates linked layers (PNG image in my case) but only if the smart object is in the top most document - that is no nested smart objects with linked layers are updated automatically.
My question is: does anyone know how to update the content of the above mentioned .jsx file so that it would auto-update all linked images across all the smart objects in PSD document including nested ones?
For those who care or would be willing to help updating the code here it is:
// Update all modified content
var idplacedLayerUpdateAllModified = stringIDToTypeID( "placedLayerUpdateAllModified" );
executeAction( idplacedLayerUpdateAllModified, undefined, DialogModes.NO );

A:

So, after spending half a day with it I finally solved it myself. Here is the code:
#target photoshop

// SET INITIAL ACTIVE DOCUMENT
var mainDocument = app.activeDocument;

// SAVE THE DOCUMENT NAME FOR FUTURE USE
var mainDocName = mainDocument.name;

// RUN THE MAIN UPDATE FUNCTION
mainDocument.suspendHistory("processAllSmartObjects", "autoupdateAllSmartObjects(mainDocument, 0)");

// FINALLY SAVE THE MAIN DOCUMENT
mainDocument.save();

function autoupdateAllSmartObjects(theParent, prevVal) {

    // FUNCTION TO TEST IF SMARTOBJECT IS LINKED
    function isLinkedSO(obj) {

        var localFilePath = "";
        var ref = new ActionReference();
        ref.putIdentifier(charIDToTypeID('Lyr '), obj.id);
        var desc = executeActionGet(ref);
        var smObj = desc.getObjectValue(stringIDToTypeID('smartObject'));
        var isLinked = false;

        // TEST IF IT HAS LINKED FILE
        try {
            var localFilePath = smObj.getPath(stringIDToTypeID('link'));
            isLinked = true;

        } catch(e) {
            //
        }

        return isLinked;
    }

    // FUNCTION TO UPDATE LINKED SMART OBJECT
    function doTheUpdate(LYR, stackNr) {

        // SET ACTIVE LAYER TO ACTUALY ITERATED ONE
        app.activeDocument.activeLayer = LYR;

        // RUN IN "SILENT" MODE
        app.displayDialogs = DialogModes.NO;
        var layer = app.activeDocument.activeLayer;

        // IF ACTIVE LAYER IS SMARTOBJECT
        if (layer.kind == "LayerKind.SMARTOBJECT") {

            //alert(layer);

            // OPEN THE SMARTOBJECT
            app.runMenuItem(stringIDToTypeID('placedLayerEditContents'));

            // DO THE ACTUAL FILE UPDATE
            var idplacedLayerUpdateAllModified = stringIDToTypeID( "placedLayerUpdateAllModified" );
            executeAction( idplacedLayerUpdateAllModified, undefined, DialogModes.NO);

            // IF IT IS NOT THE "CORE/MAIN" DOCUMENT
            if(stackNr > 0) {

                // SAVE CHANGES (UPDATE) AND CLOSE IT
                app.activeDocument.close(SaveOptions.SAVECHANGES);
            }

            // CONTINUE INSIDE THIS ACTIVE SMARTOBJECT
            autoupdateAllSmartObjects(app.activeDocument, stackNr);
        }

        return;
    }

    // FUNCTION TO PARSE GROUPS
    function parseGroup(LYR) {

        var groupLayers = LYR.layers;

        // IF GROUP IS NOT EMPTY
        if(groupLayers.length > 0) {

            // PARSE ALL LAYERS IN THE GROUP
            for (var i = groupLayers.length - 1; i >= 0; i--) {

                var lyr = groupLayers[i];

                // IF NOT LOCKED = NOT EDITABL:E
                if(!lyr.allLocked) {

                    // YET ANOTHER GROUP?
                    if (lyr.typename == "LayerSet") {

                        // IF IT IS NOT EMPTY
                        if (lyr.layers.length > 0) {

                            // RE-RUN THE SCRIPT ANEW WITH THE SELECTED GROUP AS LAYERS SOURCE
                            autoupdateAllSmartObjects(lyr, 0);
                        }

                    // LAYERS
                    } else if (lyr.typename == "ArtLayer") {

                        // IF THE LAYER IS SMARTOBJECT
                        if (lyr.kind == LayerKind.SMARTOBJECT) {

                            // IF THE LAYER IS SET TO "visible" (THAT IS: NOT DISABLED)
                            if(lyr.visible){

                                // TEST IF THE SMARTOBJECT IS ACTUALLY LINKED
                                if(!isLinkedSO(lyr)) {

                                    // RUN THE UPDATE SUB-FUNCTION
                                    doTheUpdate(lyr, i);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    // PARSE ALL THE LAYERS
    for (var i = theParent.layers.length - 1 - prevVal; i >= 0; i--) {

        var theLayer = theParent.layers[i];

        // ONLY ArtLayers
        if (theLayer.typename == "ArtLayer") {

            // IF THE LAYER IS SMARTOBJECT
            if (theLayer.kind == LayerKind.SMARTOBJECT) {

                // IF THE LAYER IS SET TO "visible" (THAT IS: NOT DISABLED)
                if(theLayer.visible){

                    // TEST IF THE SMARTOBJECT IS ACTUALLY LINKED
                    if(!isLinkedSO(theLayer)){

                        // RUN THE UPDATE SUB-FUNCTION
                        doTheUpdate(theLayer, i);

                        // IF WE ARE AT THE LAST LAYER IN THE STACK AND IT IS NOT OUR MAIN DOCUMENT
                        if(i == 0 && app.activeDocument.name !== mainDocName) {

                            // SAVE CHANGES (UPDATE) AND CLOSE IT
                            app.activeDocument.close(SaveOptions.SAVECHANGES);
                        }
                    }
                }
            }

        // ONLY Groups
        } else if (theLayer.typename == "LayerSet") {

            // RUN SUB-FUNCTION FOR GROUP PARSING
            parseGroup(theLayer);

        // ANYTHING ELSE
        } else {

            autoupdateAllSmartObjects(theLayer, m);
        }
    }

    return;
};


Q:

Apache rewrite rule with parameters?

I have the following URL:
http://domain.com/index.php?m=feedback&cSubject=My Subject

I want to have a rewrite rule so that the following:
http://domain.com/feedback?Subject=My Subject

maps to the previous url. Heres my rule at the moment:
RewriteRule ^feedback?Subject=(.*)$ index.php?m=feedback&cSubject=$1

Doesn't seem to be working tho! Any ideas?

A:

Query Strings are not parsed by Apache Mod_Rewrite, but there is a workaround. Try this
RewriteRule ^feedback/?$ index.php?m=feedback&c%{QUERY_STRING} [NC,L]

A:

You can use RewriteCond statement to do exactly what you want:
RewriteEngine On

RewriteCond %{QUERY_STRING} Subject=(.*)
RewriteRule ^feedback$ index.php?m=feedback&cSubject=%1 [L]


Q:

How can I change the values in a particular column that are equal to a given value?

data_active is any dataset.
Ideally when the condition is satisfied, the values must be changed. But when I execute this code, it is changing the values in each of the specified columns to the values given in the if statement.
for (i in 1:nrow(data_active))
{
 if(data_active[i,1]==4866)
 {
  data_active$St="MH"
  data_active$Reg="South Central"
  data_active$REGION="South"
  data_active$Market="86"
 }
}

A:

You need to get used to a 'thinking with R' mentality. You don't need for loops or if statements. You can do this with just one line of code.
Try the following (replace id with your column name):
data_active[data_active$id == 4866,c("St","Reg","REGION","Market")] <- c("MH","South Central", "SOUTH", "86")

First, this statement is finding the rows where id matches 4866, and selecting from them the columns in the list created by c.
data_active[data_active$id == 4866,c("St","Reg","REGION","Market")]

Secondly, it is setting the values of these columnns to a new list, containing the values you desire.
<- c("MH","South Central", "SOUTH", "86")

A:

Inside your if statement, you have assigned a value to the entire column, not just to the row indicated by i. To assign to just a specific row, you need to assign to just that element of the vector.
for (i in 1:nrow(data_active))
{
 if(data_active[i,1]==4866)
 {
  data_active$St[i]="MH"
  data_active$Reg[i]="South Central"
  data_active$REGION[i]="South"
  data_active$Market[i]="86"
 }
}

That said, this is not the idiomatic way to do this in R. More natural would be to use logical indexing.
data_active$St[data_active[,1]==4866]="MH"
data_active$Reg[data_active[,1]==4866]="South Central"
data_active$REGION[data_active[,1]==4866]="South"
data_active$Market[data_active[,1]==4866]="86"


Q:

Permutations with limited repetition and various constraints

you have a string of 360 letters: 180 x 'A' and 180 x 'B'. I (hope I) understand that the number of ways this string can be permuted is $$\frac{360!}{180!180!} = \binom{360}{180}$$
What I have absolutely no clue about is how to calculate how this number changes if the following restrictions are both put into place.

The numbers of 'switches' ('AB' or 'BA') should be as close to equal as possible to the number of repetitions ('AA' or 'BB'). That would mean either 180 switches and 179 repetitions or vice versa.
The maximum number consecutive repetitions is 3 (thus AAAB would be valid, AAAAB not).

Thanks for any insights!

A:

Let's consider groups of one to three consecutive identical letters as building blocks and denote the numbers of such groups by $a_1$, $a_2$, $a_3$ for the As and by $b_1$, $b_2$, $b_3$ for the Bs, and let's first consider strings beginning with A and ending in B (and thus $179$ switches and $180$ repetitions). Then we have the following constraints:
\begin{align}
a_1+2a_2+3a_3&=180\;,\\
b_1+2b_2+3b_3&=180\;,\\
a_1+a_2+a_3&=90\;,\\
b_1+b_2+b_3&=90\;,\\
\end{align}
with solution
\begin{align}
a_2&=90-2a_1\;,\\
b_2&=90-2b_1\;,\\
a_3&=a_1\;,\\
b_3&=b_1\;.
\end{align}
Thus the number of admissible arrangements of this form is
$$
\left(\sum_{k=0}^{45}\binom{90}{k,k,90-2k}\right)^2=448581910545737950775083699792561795907509^2\;.
$$
The same number of arrangements begins with B and ends in A. You can carry out a similar analysis to find the number of admissible arrangements that begin and end with the same letter (and thus have $180$ switches and $179$ repetitions).


Q:

Hide sensitive post data in Laravel

Django has some nice helpers for ensuring sensitive data (passwords, credit card data) never gets reflected in logs or error output. This functionality is also available in some third-party tools like Raygun
Is there a built-in equivalent for Laravel?
For example, error pages and presumably debug emails include the complete raw POST data; I would like to strip this out.
One approach is to remove keys from $_POST after reading from it, but is this enough to prevent accidental password exposure?

A:

No, there is not.
If you're debugging something then it definitely makes sense for debug mode to show you what's going on and to not hide anything from you. With that said, no one would use debug mode in production so there really shouldn't be any fear of exposing sensitive data there. Unless you are explicitly logging this data or showing it to the user somewhere Laravel wouldn't do that in production mode.


Q:

Best UI interface/Language to query MarkLogic Data

We will be moving from Oracle and use MarkLogic 8 as our datastore and will be using MarkLogic's Java api to talk with data.
I am exploring for any UI tool (like SQL Developer is there for Oracle), which can be used for ML. I found that ML's Query Manager can used for accessing data. But I see multiple options wrt language:

SQL
SPARQL
XQuery
JavaScript

We need to perform CRUD operations and search for data, and our testing team is aware of SQL (for Oracle), so I am confused which route I should follow and on what basis I should decide which one/two will be better to explore. We are most likely to use JSON document type.
Any help/suggestions would be helpful.

A:

You already mention you will be using the MarkLogic Java Client API, that should provide most of the common needs you could have, including search, CRUD, facets, lexicon values, and also custom extension though REST extensions as the Client API will be leveraging the MarkLogic REST API. It saves you from having to code inside MarkLogic to a large extent.
Apart from that you can run ad hoc commands from the Query Console, using one of the above mentioned languages. SQL will require the presence of a so-called SQL view (see also your earlier question Using SQL in Query Manager in MarkLogic). SPARQL will require enabling the triple index, and ingestion of RDF data.
That leaves XQuery and JavaScript, that have pretty much identical expression power, and performance. If you are unfamiliar with XQuery and XML languages in general, JavaScript might be more appealing.
HTH!


Q:

Safe values of $\mu$ and $\sigma$ when randomly sampling from a Log-Normal Distribution?

I believe I'm obtaining overflow errors when randomly sampling from a log-normal distribution with the command:
RandomVariate[LogNormalDistribution[μ, σ], 1]

Specifically, I can obtain an accurate looking distribution with values of $\mu \approx 1$ and $\sigma \approx 1$, but I get significant outliers for values of $\mu > 10$ and $\sigma > 10$.  Why would this occur?  Isn't it true that the ratio $\dfrac{\mu}{\sigma}$ should govern the probability of obtaining values $\gg \mu$?
What values of $\mu$ and $\sigma$ will give accurate values properly reflecting a random sample from LogNormalDistribution?

A:

If $X\sim N\left(\mu ,\sigma ^2\right)$ and $Y=e^X$, then $Y\sim \text{Lognormal}(\mu ,\sigma )$. So, by selecting LogNormalDistribution[10, 10], you are effectively generating values from a $N(10, 100$) distribution (which is a very large variance), and then raising them to $e^X$ ... which will generate deliciously large variates.
To see this:
Here are 6 values generated from a Lognormal, with a given random seed:
SeedRandom[42];
RandomVariate[LogNormalDistribution[10, 10], 6]

{0.886492, 8.54449*10^7, 0.0194899, 1.42431*10^6, 1572.01,
   8.07229*10^8}

... and here are the same 6 values generated from the associated Normal, given the same random seed, and raised to $e^X$:
SeedRandom[42];
Exp[RandomVariate[NormalDistribution[10, 10], 6]]

{0.886492, 8.54449*10^7, 0.0194899, 1.42431*10^6, 1572.01,
   8.07229*10^8}

In summary: there is nothing wrong with the values being generated ... they are 'safe' /// you are just getting what you asked for.


Q:

WordPress AJAX call refuses to return data

I'm trying to return some meta data once a select field changes.  However, I've done several iterations of the code below, and it works fine if I simply echo it from a php script, but when I try to return it as a response, it fails. I know that it's definitely running the function because if I simply tell it to 'echo 'xxxx', it works. Below is the code I'm attempting to implement.  I'm completely stumped and hope I'm simply overlooking something...
add_action('admin_footer', 'get_criteria_javascript');

function get_criteria_javascript() {
?>
<script type="text/javascript">
jQuery(document).ready(function($) {
    if(jQuery('select#pages').length > 0) {
        jQuery('select#pages').live('change', function() {
            var selected = jQuery(this).val();
            var data = { action: 'get_criteria', post_id: selected };

            jQuery.ajax({
                type: 'post',
                dataType: 'html',
                url: 'admin-ajax.php',
                data: {action: 'get_criteria', post_id : selected },
                success: function(response) {
                    alert(response);
                }
            });
        });
    }
});
</script>
<?php
}

add_action('wp_ajax_get_criteria', 'get_criteria_callback');

// if I use echo get_criteria_callback(627); here, it returns the expected results...

function get_criteria_callback($post_id) {
    $meta = get_post_meta($post_id, 'criteria');
    $content = implode(', ', $meta[0]);
/* This is one version. Although I can echo it fine, if I return this as a response, it tells me my implode is using invalid arguments */

    echo $content;
    die();
 }

A:

In your ajax call the url parameter should not be hardcoded, use ajaxurl instead. an ajax call is a new http request. So the data you send is passed through POST method.
function get_get_criteria_callback(){
  $post_id = isset( $_POST['post_id'] ) ? $_POST['post_id'] : false;

  if( $post_id ){
    $meta = get_post_meta($post_id, 'criteria');
    $content = implode( ', ', $meta[0] );
  }

  echo $content;

  die();

}

Hope it helps!


Q:

Expose a web service (wsdl) as a webform

Just wanted to ask if anyone knows of a reliable & easy way to expose a webservice (wsdl) as a webform to end-users.
Our team develops a lot of software for external contacts, which often involve creating a web service and exposing it as both a wsdl and a website. We'd like to automate this last step as much as possible (especially for the mindless data-pumping projects) so we can concentrate on developing web services instead of websites.
I recently came across Enunciate, but have not found the time yet to play with it in detail. I was wondering if anyone has any experience with it  (or with any similar projects) what your findings are, and what direction you would advice us to take with this.
Best regards,
Tim

Update2:
Turns out what I need is perfectly described in this Enunciate module: http://jira.codehaus.org/browse/ENUNCIATE-23. The only problem is that it's not implemented... (yet?)
Anyone have any experience in creating your own modules, or knows of an existing solution that provides the same functionality?

A:

I'm not sure how much weight my response carries (since I'm the lead developer of Enunciate) but I'd like to encourage you to try it out. I know a lot of happy Enunciate users.
Even if you decide not to use it, I'd like to hear about your experience and why you decided against it.


Q:

Node.js plesk - Sending emails with nodemailer not working

I'm using node.js with nodemailer on a fresh ubuntu plesk root server.
When trying to send an email like this:
module.exports = {
    SMTP_HOST: 'host',
    SMTP_USER: 'username',
    SMTP_PASS: 'password',
};

let transporter = nodemailer.createTransport({
  host: SMTP_HOST,
  //port: 465,
  port: 587,
  secure: true,
  auth: {
      user: SMTP_USER,
      pass: SMTP_PASS
  },
  tls:{
    rejectUnauthorized:false  // if on local
  }
});

... I'm getting this error message:
{ Error: connect ECONNREFUSED ip-adress:587
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1106:14)
errno: 'ECONNREFUSED',
code: 'ECONNECTION',
syscall: 'connect',
address: 'ip-adress',
port: 587,
command: 'CONN' }

How can I send emails via a plesk root server?
... if I use port 465 I'm getting this error:
{ Error: Data command failed: 550 5.7.1 Command rejected
at SMTPConnection._formatError (/home/project/node_modules/nodemailer/lib/smtp-connection/index.js:605:19)
at SMTPConnection._actionDATA (/home/project/node_modules/nodemailer/lib/smtp-connection/index.js:1454:34)
at SMTPConnection._responseActions.push.str (/home/project/node_modules/nodemailer/lib/smtp-connection/index.js:1426:26)
at SMTPConnection._processResponse (/home/project/node_modules/nodemailer/lib/smtp-connection/index.js:764:20)
at SMTPConnection._onData (/home/project/node_modules/nodemailer/lib/smtp-connection/index.js:570:14)
at TLSSocket._socket.on.chunk (/home/project/node_modules/nodemailer/lib/smtp-connection/index.js:522:47)
at TLSSocket.emit (events.js:198:13)
at addChunk (_stream_readable.js:288:12)
at readableAddChunk (_stream_readable.js:269:11)
at TLSSocket.Readable.push (_stream_readable.js:224:10)
at TLSWrap.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)
code: 'EENVELOPE',
response: '550 5.7.1 Command rejected',
responseCode: 550,
command: 'DATA' }

A:

Adding sendmail: true (https://nodemailer.com/transports/sendmail/) solved the issue:
let transporter = nodemailer.createTransport({
  sendmail: true,
  newline: 'unix',
  path: '/usr/sbin/sendmail',
  host: SMTP_HOST,
  //port: 465,
  port: 587,
  secure: true,
  auth: {
      user: SMTP_USER,
      pass: SMTP_PASS
  },
  tls:{
    rejectUnauthorized:false  // if on local
  }
});


Q:

When to use worker and factory function in angularjs

i am learning angularjs from Pro angularjs by adam freeman.
This is an example he defined an directive in angularjs
myApp.directive("highlight", function () {
  return function (scope, element, attrs) {
    if (scope.day == attrs["highlight"]) {
      element.css("color", "red");
    }
  };
});

the first function the writer calls is factory function and it returns a worker function. I' m not able to understand why he returns another function.
When i write the code below, the code returns an error.
I don't know what i'm doing wrong.
myApp.directive("highlight", function (scope, element, attrs) {
  if (scope.day == attrs["highlight"]) {
    return element.css("color","red")
  }
});

A:

If you take a look at the Angular docs about directives, you'll see that there are two ways you can define a directive. One is to use the directive definition object and the other is to just return a postLink function.
The example in your book shows the latter form. The reason your function doesn't work is because Angular calls your function and expects it to return a directive definition object or a postLink function. Instead the function you defined returns nothing or the result of element.css("color", "red") depending on your if statement.


Q:

Why use a passphrase for RSA key?

Today I generated my first key pair, so my knowledge here is - so to speak  - very limited.
On client side I am using Windows and to log in I use PuTTY and I used PuTTYGen to create the keys.
Here (https://winscp.net/eng/docs/ui_puttygen) they say:

If you leave the passphrase fields blank, the key will be saved
  unencrypted. You should not do this without good reason; if you do,
  your private key file on disk will be all an attacker needs to gain
  access to any machine configured to accept that key. If you want to be
  able to passwordless log in without having to type a passphrase every
  time, you should consider using Pageant so that your decrypted key is
  only held in memory rather than on disk.

But here I am failing to see why I should even use RSA rather than regular password authentication when I need to use the passphrase. If I do a passphrase I still need to type in a password when logging in.
On a side I would ask a question about this part:

Pageant so that your decrypted key is only held in memory rather than on disk

Does it really protect anything? I don't know how to read things from memory but isn't it a fairly common thing to do for hackers? To read/replace bits in memory?

A:

You do not need a passphrase for your RSA key. But if your key gets compromised (for example, because you carry the key on a thumb drive and you lose it), an attacker could immediately access the assets the key is protecting.
Using a strong password will give you more time to change keys in case of a key compromise.
Related question on Superuser:

Do I need to have a passphrase for my SSH RSA key?


Q:

Using Flask: bootstrap works but custom stylesheet doesnt't

I have checked the other topics, they seem similar but won't solve my problem:
I am writing a web application using flask and bootstrap works fine but my custom stylesheet gets completely ignored and I can't figure out why.
  <head>
      <!-- Required meta tags -->
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
      <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
      <link href="/static/styles.css" rel="stylesheet">
      <title>C$50 Final_Project: {% block title %}{% endblock %}</title>
  </head>

A:

Browser cache needed to be cleared...
I am not sure why this question was downvoted so much, but I probably should have added, that the path for static.css is not the problem...


Q:

Dropdown menu transition on CSS

I am trying to add dropdown transition for the menu I am working on, but it seems that I have no idea what I am doing wrong. Where is my mistake or what i have to add for transition dropdown menu? Here is my CSS and HTML code.

.nav li a {
  transition-property: all;
  transition-duration: .2s;
  transition-timing-function: ease-in-out;
}

ul {
  float: left;
  padding: 0px;
  list-style: none;
}

ul li {
  float: left;
  width: 200px;
  height: 40px;
  background-color: #F05050;
  text-align: center;
  font-size: 20px;
  line-height: 40px;
  margin-right: 2px;
}

ul li a {
  text-decoration: none;
  color: white;
  display: block;
}

ul li a:hover {
  position: relative;
  z-index: 1;
  background-color: #C6AEF0;
}

ul li:hover ul {
  position: relative;
  z-index: 1;
}

ul li ul li {
  opacity: 0.9;
  display: none;
}

ul li:hover ul li {
  display: block;
}

Home

News

Czech Republic

Facts and figures

Area

Climate

Study

How to apply

Programmes

Scholarships

Tuition fees

Living

Arrival

Living costs

Work

Contact

A:

First you are applying the transition to only a element and then you cannot do transition with display property, You should animate another property instead.
Example using max-height:

.nav li a {
  transition-property: all;
  transition-duration: .2s;
  transition-timing-function: ease-in-out;
}

ul {
  float: left;
  padding: 0px;
  list-style: none;
}

ul li {
  float: left;
  width: 200px;
  height: 40px;
  background-color: #F05050;
  text-align: center;
  font-size: 20px;
  line-height: 40px;
  margin-right: 2px;
}

ul li a {
  text-decoration: none;
  color: white;
  display: block;
}

ul li a:hover {
  position: relative;
  z-index: 1;
  background-color: #C6AEF0;
}

ul li:hover ul {
  position: relative;
  z-index: 1;
}

ul li ul {
  max-height:0px;
  overflow:hidden;
  transition:0.5s;
}

ul li:hover ul {
  max-height:300px;
}

Home

News

Czech Republic

Facts and figures

Area

Climate

Study

How to apply

Programmes

Scholarships

Tuition fees

Living

Arrival

Living costs

Work

Contact

Some usefull links to get more ideas:
https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_animated_properties
https://www.w3.org/TR/css-transitions-1/#animatable-properties
Transitions on the display: property
How can I transition height: 0; to height: auto; using CSS?


Q:

Can`t make cascade select in z-song laravel-admin

Laravel Version: 5.8
Laravel-admin: 1.7.9
I can`t make cascade select
I have tables:
users: id, name
categories: id, name
categories_users: id, categories_id, user_id
models:
class User extends Authenticatable {

 public function category()
    {
        return $this->belongsToMany(Categories::class, 'categories_users', 'categories_id');
    }
}

class Categories extends Model {

public function users()
    {
        return $this->belongsToMany(User::class, 'categories_users');
    }
}

I need cascade select:
$form->select('user_id', 'User')->options($seller)->load('categories_id', '/admin/api/users')->required();

$form->select('categories_id', 'Categories of user')->required();

but it not work !!!
Controller:
public function getData(Request $request){

        $user_id = $request->get('q');

        return User::find($user_id)->category()->get(['id', DB::raw('name as text')]);
    }

A:

public function getData(Request $request){

    $user_id = $request->get('q');

    $q = DB::table('categories_users')->where('user_id', $user_id)->pluck('categories_id');

    $categories = Categories::whereIn('id', $q)->get(['id', DB::raw('name as text')]);

    return $categories;
}

It work!


Q:

Finding the most correlated item

I have a restaurant sales details as below.
+----------+------------+---------+----------+
| Location | Units Sold | Revenue | Footfall |
+----------+------------+---------+----------+
| Loc - 01 |        100 | 1,150   |       85 |
+----------+------------+---------+----------+

I want to find the most correlated restaurant to the above from the below tables restaurant data
+----------+------------+---------+----------+
| Location | Units Sold | Revenue | Footfall |
+----------+------------+---------+----------+
| Loc - 02 |        100 | 1,250   |       60 |
| Loc - 03 |         90 | 990     |       90 |
| Loc - 04 |        120 | 1,200   |       98 |
| Loc - 05 |        115 | 1,035   |       87 |
| Loc - 06 |         89 | 1,157   |       74 |
| Loc - 07 |        110 | 1,265   |       80 |
+----------+------------+---------+----------+

please guide me how this can be done with python or pandas..
Note : - correlation means most matching/similar restaurant in terms of Units Sold, Revenue & Footfall.

A:

If your correlation should be described like minimal euclidean distance, solution is:
#convert columns to numeric
df1['Revenue'] = df1['Revenue'].str.replace(',','').astype(int)
df2['Revenue'] = df2['Revenue'].str.replace(',','').astype(int)

#distance of all columns subtracted by first row of first DataFrame
dist = np.sqrt((df2['Units Sold']-df1.loc[0, 'Units Sold'])**2 +
               (df2['Revenue']- df1.loc[0, 'Revenue'])**2 +
               (df2['Footfall']- df1.loc[0, 'Footfall'])**2)

print (dist)
0    103.077641
1    160.390149
2     55.398556
3    115.991379
4     17.058722
5    115.542200
dtype: float64

#get index of minimal value and select row of second df
print (df2.loc[[dist.idxmin()]])
   Location  Units Sold  Revenue  Footfall
4  Loc - 06          89     1157        74


Q:

How to use *.pub/*.sec files to encrypt/decrypt another file?

I created a pair of *.pub and *.sec files using the instructions and code given here:
https://www.gnupg.org/documentation/manuals/gnupg/Unattended-GPG-key-generation.html
(I am using this documentation because the ultimate application I have in
mind is an automated encryption/decryption pipeline.)
Q1: How can I use gpg2 and the *.pub file to encrypt another file?
Q2: How can I use gpg2 and the companion *.sec to decrypt a file encrypted using the companion *.pub file?

Important: I am interested only in answers that are suitable for programmatic implementation of an unsupervised operation. Please do not post answers that can only be carried out interactively.  I am particularly interested in solutions that can be implemented in Python.

Please include precise pointers to the relevant documentation.

A:

Some information about what you said:

I created a pair of *.pub and *.sec files using the instructions

Perfect to share the public key(s) with people you are exchanging information, but technically, when you are working programmatically, you don't need to use these files directly.
To be noted:

when you encrypt data, you will specify the recipient corresponding to the key to use to encrypt
when you decrypt data, you will first import the owner's public key, and then you will be able to decrypt data without specifying recipient, because it is embedded in the encrypted data

Actually, I am somewhat confused on this question. I have read conflicting information [...]

I agree it's quite confusing. In this situation, I think it is better to use version 1 for which there is more experience, and for which you find third party library to use.
In this answer, I tried:

python-gnupg (for GnuPG v1) which is a well known Python library and match perfectly your needs
cryptorito (for GnuPG v2) for which I didn't find enough documentation

With the first library, you can simply install it in your system:
sudo pip install python-gnupg

And then write a Python script to perform all the operations you want.
I wrote a simple one to answer your question.
#!/bin/python

import gnupg

GPG_DIR='/home/bsquare/.gnupg'
FILE_TO_ENCRYPT='/tmp/myFileToEncrypt'
ENCRYPTED_FILE='/tmp/encryptedFile'
DECRYPTED_FILE='/tmp/decryptedFile'
SENDER_USER='Bsquare'
TARGET_USER='Kjo'

gpg = gnupg.GPG(gnupghome=GPG_DIR)

print("Listing keys ...")
print(gpg.list_keys())

# On SENDER_USER side ... encrypt the file for TARGET_USER, with his public key (would match the kjo.pub if the key was exported).
print("Encrypting file " + FILE_TO_ENCRYPT + " for " + TARGET_USER + " ...")
with open(FILE_TO_ENCRYPT, "rb") as sourceFile:
    encrypted_ascii_data = gpg.encrypt_file(sourceFile, TARGET_USER)
    # print(encrypted_ascii_data)
    with open(ENCRYPTED_FILE, "w+") as targetFile:
        print("encrypted_ascii_data", targetFile)

# On TARGET_USER side ... decrypt the file with his private key (would match the kjo.sec if the key was exported).
print("Decrypting file " + ENCRYPTED_FILE + " for " + TARGET_USER + " ...")
with open(ENCRYPTED_FILE, "rb") as sourceFile:
    decrypted_ascii_data = gpg.decrypt_file(sourceFile)
    # print(decrypted_ascii_data)
    with open(DECRYPTED_FILE, "w+") as targetFile:
        print(decrypted_ascii_data, targetFile)

To be noted my keyring contains pub/sec pair for my Bsquare user, and the pub key of Kjo user.


Q:

Windows Service or Asp.net web api RESTful service?

I'm developing a C# solution with .NET Framework 4.5.1.
I need to have a program (an object instance) running all the time waiting to receive commands. This program will have a state and depending on this state it will allow some commands or others.
For example, it will have an open and close command. If the state is not openned and the program receives the close command, it won't do anything.
I've thought to create a windows service or a ASP.NET MVC WebApi 2.2 app.
If I choose windows service, the program will be running always but I don't know how to communicate with it (maybe adding it a TCP/IP server).
If I use ASP.NET MVC WebApi 2.2 I can send the commands using POST or PUT messages, but I don't know if I can have an object instance running while the web service is up.
The program is a class that I have to instanced it. This instance will keep its state and a communication with a WCF service.
What do you recommend me?

A:

Options from which to choose are strange a little.
You can self-host Web API in windows service, and communicate with service using HTTP. Note, that Web API is about stateless, so, if you need to preserve the state, this should be a persistable data.
As to a way for communicate with windows service, using something other, than Web API - there are number of ways to do this. WCF with TCP/Named Pipes, pure Named Pipes (without WCF), sockets, memory mapped files. You just need to select most appropriate for your requirements.


Q:

How to get the max of a column in MySQL

I want to get the id of a row, based on max number that exists in number column on table x.
For example:
I have the following records inside x table.
 id      | number
---------+---------
 9       | 289
 10      | 100
 24      | 187
 54      | 345

I want a query to return the id 54 (SELECT x.id ...) by finding out that the max of the column number is 345.
How can I succeed that?

A:

Please try the following query:
Solution #1:
SELECT
x.*
FROM x
INNER JOIN
(
  SELECT
   MAX(number) AS max_number
  FROM x
) AS maxTable
ON x.number = maxTable.max_number

Explanation:
SELECT
  MAX(number) AS max_number
FROM x;

Result:
maxTable:
max_number
   345

Now make an inner join between your table x and the above table named  maxTable on maxTable.max_number and x.number.
x table:
    =====================
    | id      | number  |
    =====================
    | 9       | 289     |
    ---------------------
    | 10      | 100     |
    ---------------------
    | 24      | 187     |
    ---------------------
    | 54      | 345     |
    ---------------------

Thus in the final output you will get only the entries which have maxTable.max_number in their number column.
Solution #2:
You can use WHERE IN to accomplish this too.
SELECT
*
FROM x
WHERE x.number IN ( SELECT MAX(number) FROM x )


Q:

Select from PLSQL Associative array?

Is it possible to use SELECT FROM when using an associative array?  I'm passing an array to a stored procedure through a .NET application, and I wanna be able to use that array as a condition when selecting from another table.  Lets say I'm passing an array of IDs to the procedure, I wanna be able to do this:

select * from table1 where userID in (select column_value from array)

The type for the array is defined in the package:

type id_array is type of number index by pls_integer

A:

Yes, it is possible, by wrapping the array with a pipelined function. Here's a good primer on pipelined functions:
http://www.oracle-developer.net/display.php?id=429
UPDATE: Oracle 12c now supports querying associative arrays using the TABLE operator, as long as the type is declared in a package spec: https://galobalda.wordpress.com/2014/08/02/new-in-oracle-12c-querying-an-associative-array-in-plsql-programs/
e.g.
select * from table1
where userID in (select column_value from table(array));


Q:

JSF / Mojarra 2.0.2: ui:repeat is totally broken when updating via AJAX

Using ui:repeat for simple listing of elements produces very strange results - when you add an element, the first element is always replaced with the values from the last element before the submit. Same occurs when removing the elements - the first element shows actually the just removed element.
With h:dataTable the same works perfectly.
Running Mojarra 2.0.2.

A:

This is probably because bug in Mojarra 2.0.2. At least in this case, updating to Mojarra 2.0.3 resolves the issue. However, the bug refers to cases that won't work with even 2.0.3.
Just wanted to write this up into a separate question as I've been having all sorts of problems (and asking all sort of questions) relating to ui:repeat and this is a specific case again.
Other failings with ui:repeat:

Why doesn't h:dataTable inside ui:repeat get correct ID?
How to refer to dataTable parent within the dataTable?

My conclusion: the whole ui:repeat tag is totally broken at least in Mojarra 2.0.2. Updating to Mojarra 2.0.3 fixes some of the issues.


Q:

How to select some column in huge table which contain null data in some row and use distinict in column

I have huge table which contains some column null data but I don't want to change anything in table.
In one of my view I want to select just two column to display in the page, first is ID and second is Area but in Area, I should use distinct and prevent to display null value
there is my code but it not work and tell me how can I do it.
public class ClsArea
{
    public int id { get; set; }
    public string AreaName { get; set; }
}

public ActionResult Index()
        {

            return View(DB.school.ToList());
        }

----------

@model IEnumerable<school.Models.ClsArea>

            <select class="form-control">
                @foreach (var itemArea in Model.Select(c => new { c.IdSMP, c.Area }).ToList() as IEnumerable<ClsArea>)
                {

                        <option value=@itemArea.id>
                            @itemArea.areaname
                        </option>

                }
            </select>

Error Display
The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[<>f__AnonymousType1`2[System.Int32,System.String]]', but this dictionary requires a model item of type 'System.Collections.Generic.IList`1[PMIS_V01.Models.ClsArea]'.

A:

Distinct will not prevent NULL values. It was not designed to do so. It will pull one NULL value with others.
If you want to skip the NULL values then why don't you just ignore those? Something like:
DB.school.where(s => s.Area != null).ToList()

Update:
You are expecting list of school.Models.ClsArea in the view but you are sending list of DB.school type from action. DB.school is the entity model type right?


Q:

'stringByAppendingPathComponent' is unavailable

I'm getting the error
'stringByAppendingPathComponent' is unavailable: Use 'stringByAppendingPathComponent' on NSString instead.

when I try to do
let documentsFolder = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let databasePath = documentsFolder.stringByAppendingPathComponent("test.sqlite")

This apparently worked for people before, but it doesn't work for me now in Xcode 7 beta 5.
This thread on the Apple Developer Forums had the suggestion to use an extension or do a direct cast to NSString. But if I do convert it to an NSString
let databasePath = documentsFolder.stringByAppendingPathComponent("test.sqlite" as NSString)

then I get the error
'NSString' is not implicitly convertible to 'String'...

and it gives me the option to "fix-it" by inserting as String, which brings us back to the original error.
This also happens for stringByAppendingPathExtension.
What do I do?

A:

You can create a URL rather rather than a String path.
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
let fileURL = documentsURL?.appendingPathComponent("test.sqlite")

If you absolutely need the path, then you can get it like this:
guard let path = fileURL?.path else {
    return
}

print(path) // path will exist at this point

There was some discussion in the thread you mentioned that Apple may be purposely guiding people toward using URLs rather than String paths.
See also:

What's the difference between path and URL in iOS?
NSFileManager URL vs Path
Swift 2.0: Why Guard is Better than If

A:

You can use:
let dbPath = (documentsFolder as NSString).stringByAppendingPathComponent("db.sqlite")