text:
Q: Unity / How to set Limit for enemy spawn? I managed to spawn enemies but they keep spawning. How can I set a limit to avoid from spawning unceasingly?
I've tried to add spawnLimit and spawnCounter  but couldn't manage it to work.
var playerHealth = 100;     // Reference to the player's heatlh.
var enemy : GameObject;                // The enemy prefab to be spawned.
var spawnTime : float = 3f;            // How long between each spawn.
var spawnPoints : Transform[];         // An array of the spawn points this enemy can spawn from.

function Start ()
{
    // Call the Spawn function after a delay of the spawnTime and then continue to call after the same amount of time.
    InvokeRepeating ("Spawn", spawnTime, spawnTime);
}

function Spawn ()
{
    // If the player has no health left...
    if(playerHealth <= 0f)
    {
        // ... exit the function.
        return;
    }

    // Find a random index between zero and one less than the number of spawn points.
    var spawnPointIndex : int = Random.Range (0, spawnPoints.Length);

    // Create an instance of the enemy prefab at the randomly selected spawn point's position and rotation.
    Instantiate (enemy, spawnPoints[spawnPointIndex].position, spawnPoints[spawnPointIndex].rotation);
}

A: You can use this kind of counter:
int maxEnemies = 100;
int enemiyCounter = 0;

and in Spawn() add:
if(enemiyCounter < maxEnemies){
    Instantiate (enemy, spawnPoints[spawnPointIndex].position, spawnPoints[spawnPointIndex].rotation);
    enemyCounter++;
}

instead of
Instantiate (enemy, spawnPoints[spawnPointIndex].position, spawnPoints[spawnPointIndex].rotation);

A: The answer that @ukasz-motyczka gave is great for a one-time spawn, but if you want a continuous spawn (every time an enemy is killed it is replaced), then you will need to dynamically count how many enemies there are.
Duck gives a good answer on how to count enemies
If you combine his code with ukasz-motyczka's then you can drop the variable to keep track of how many enemies you've spawned since you are dynamically counting them.  You would get something like this:
int maxEnemies = 100;

and in Spawn()
// to count the number of objects:
var enemyCount : int = GameObject.FindGameObjectsWithTag("Enemy").Length;

if(enemyCount < maxEnemies){
Instantiate (enemy, spawnPoints[spawnPointIndex].position, spawnPoints[spawnPointIndex].rotation);

A: While using CancelInvoke("spawn"); when you want to stop spawn enemies.
You should know about CancelInvoke() if you are playing with invoke() and InvokeRepeating()


text:
Q: filtering in magento collection? the following code:
    $collection->addAttributeToFilter(array(
                   array('attribute'=> 'someattribute','like' => 'value'),
                   array('attribute'=> 'otherattribute','like' => 'value'),

            ));

creates a query something like:
         where  ( someattribute like 'value' OR otherattribute like 'value' )

but how could i add an AND condition to this OR conditions? I mean something like this:
        where ( (someattribute like 'value' AND someattribute  != 'another value')  OR otherattribute like 'value' )

I am using addAttributeToFilter multiple times in the construction of my collection, however, i tried to add the above mentioned condition with the following code:
 $collection->getSelect->where( "(someattribute like 'value' AND someattribute  != 'another value')  OR otherattribute like 'value' )"  )

but it's not working. Maybe it's not possible to use addAttributeToFilter AS well as where to the same collection?
many thanks in advance

A: ok, it's working...there was some error in the conditionals i added
so, you can use addAttributeToFilter and also "where" on the same magento collection. Anyway, maybe it will help someone else as well, this solution, but still wondering if you can replicate the above where condition using only addAttributeToFilter...

A: By definition :
->addAttributeToFilter(array(
               array('attribute'=> 'someattribute','like' => 'value'),
               array('attribute'=> 'otherattribute','like' => 'value'),

        )

This is a OR selection to have a AND use :
 ->addAttributeToFilter(array('attribute'=> 'someattribute','like' => 'value'))->addAttributeToFilter(array('attribute'=> 'otherattribute','like' => 'value'))

redpajama_set_name: RedPajamaStackExchange


text:
Q: Ajax script doesn't insert into database I'm trying to make friends system and friend adding with ajax. The problem is that when I click on the button nothing happen. Doesn't insert anything into database. So this is the button
 Add as friends

and this is the add_friend.php
include 'database.php';
$pdo = Database::connect();

if(!empty($_POST["id"])) {

    $friend_id = $_POST['id'];
    $id = $_SESSION['id'];

            $value = $pdo->prepare('SELECT * FROM user_friends WHERE friend_id= ? and id = ?'); // BDD query, page ID values
            $value->bindParam(1, $friend_id, PDO::PARAM_INT);
            $value->bindParam(2, $id, PDO::PARAM_INT);
            $value->execute();
            $result = $value->fetch();

if( $result > 0) {
        echo 'already added';
}
else
{
    $friend_id = $_POST['id'];
    $id = $_SESSION['id'];

    $query = $pdo -> prepare("INSERT INTO user_friends (friend_id, id)
                            VALUES (:friend_id, :id)");
    $query -> execute(array(
                      ":friend_id"         => $friend_id,
                      ":id"          => $id
    ));
}

and this

Table is simple user_friends - whit rows - friend_id (int 4) and id (int 4)
Any idea what can be the problem?

A: This line is wrong
$('.newFriend', $('.buttons')).click(function(){
               ^            ^// wrong method

change it to,
$('.newFriend, .buttons').click(function(){

A: First select a browser for testing your ajax call. Either Google Chrome or Firefox with Firebug plugin are good. My preferred choice is Firefox.
Here is how i debug with Firebug in Firefox press F12:
firebug opens then click on Net tab, then click on XHR,there you will see the data passed between your browser and the server.
You must identify if the problem is on you clientside script or on the server side script.
Every time you make a request, there is a new url displayed under XHR, click on the plus sign at the beginning of the url string, there you can see Header,Post,Response, JSON, Cache and cookie tab, these are the stuffs passed back and forth between the browser and the server.
The Post tab shows the datas sent by your browser, the Response  tab shows datas sent by the server afterwards.
If there is an error server side, generated by your php script, you'll see it there.


text:
Q: What does fget_light in Linux work? I'm studying about System Calls in Linux and I read the read() System Calls.
SYSCALL_DEFINE3(read, unsigned int, fd, char __user *, buf, size_t, count)
{
    struct file *file;
    ssize_t ret = -EBADF;
    int fput_needed;

    file = fget_light(fd, &fput_needed);
    if (file) {
        loff_t pos = file_pos_read(file);
        ret = vfs_read(file, buf, count, &pos);
        file_pos_write(file, pos);
        fput_light(file, fput_needed);
    }

    return ret;
}

This is the definition of fget_light()
struct file *fget_light(unsigned int fd, int *fput_needed)
 {
         struct file *file;
         struct files_struct *files = current->files;

         *fput_needed = 0;
         if (likely((atomic_read(&files->count) == 1))) {
                 file = fcheck_files(files, fd);
         } else {
                 rcu_read_lock();
                 file = fcheck_files(files, fd);
                 if (file) {
                         if (atomic_long_inc_not_zero(&file->f_count))
                                 *fput_needed = 1;
                         else
                                 /* Didn't get the reference, someone's freed */
                                 file = NULL;
                 }
                 rcu_read_unlock();
         }

         return file;
 }

Can you explain me, what does fget_light do?

A: Each task has a file descriptor table. This file descriptor table is indexed by file descriptor number, and contains information (file descriptions) about each open file.
As many other objects in the kernel, file descriptions are reference-counted. This means that when some part of the kernel wants to access a file description, it has to take a reference, do whatever it needs to do, and release the reference. When the reference count drops to zero, the object can be freed. For file descriptions, open() increments the reference count and close() decrements it, so file descriptions cannot be released while they are open and/or the kernel is using them (e.g: imagine a thread in your process close()ing a file while another thread is still read()ing the file: the file description will not actually be released until the read fput()s its reference).
To get a reference to a file description from a file descriptor, the kernel has the function fget(), and fput() releases that reference. Since several threads may be accessing the same file description at the same time on different CPUs, fget() and fput() must use appropriate locking. In modern times they use RCU; mere readers of the file descriptor table incur no/almost no cost.
But RCU is not enough optimization. Consider that it's very common to have processes which are not multi-threaded. In this case you don't have to worry about other threads from the same process accessing the same file description. The only task with access to our file descriptor table is us. So, as an optimization, fget_light()/fput_light() don't touch the reference count when the current file descriptor table is only used in a single task.
struct file *fget_light(unsigned int fd, int *fput_needed)
{
     struct file *file;
     /* The file descriptor table for our _current_ task */
     struct files_struct *files = current->files;

     /* Assume we won't need to touch the reference count,
      *  since the count won't reach zero (we are not close(),
      *  and hope we don't run concurrently to close()),
      *  fput_light() won't actually need to fput().
      */
     *fput_needed = 0;

     /* Check whether we are actually the only task with access to the fd table */
     if (likely((atomic_read(&files->count) == 1))) {
             /* Yep, get the reference to the file description */
             file = fcheck_files(files, fd);
     } else {
             /* Nope, we'll need some locking */
             rcu_read_lock();
             /* Get the reference to the file description */
             file = fcheck_files(files, fd);
             if (file) {
                     /* Increment the reference count */
                     if (atomic_long_inc_not_zero(&file->f_count))
                             /* fput_light() will actually need to fput() */
                             *fput_needed = 1;
                     else
                             /* Didn't get the reference, someone's freed */
                             /* Happens if the file was close()d and all the
                              *  other accessors ended its work and fput().
                              */
                             file = NULL;
             }
             rcu_read_unlock();
     }

     return file;
}

A: Basically, the function translates the fd passed by the user to the syscall to the kernel-internal file structure pointer by calling the fcheck_files function that looks into the file table of the process (that would be its files parameter). For more information, read this.


text:
Q: Dynamically adding a form to a Django formset with Javascript I want to automatically add new forms to a Django formset using Javascript, so that when the user clicks an "add" button it runs JavaScript that adds a new form to the page.

A: See the code i used,

You can use your form id and all in the script.
The example form would be like this

    {% trans 'Name' %}*:
    {{ members_form.empty_form.first_name }}{{ members_form.empty_form.name.errors.as_text }}

    {% trans 'Age' %}*:
    {{members_form.empty_form.age}}{{members_form.empty_form.age.errors.as_text}}

    {% trans 'Gender' %}*:
    {{members_form.empty_form.gender}}{{members_form.empty_form.gender.errors.as_text}}

Make use of it ;)


text:
Q: error in namenode starting When i try to start the hadoop on master node i am getting the following output.and the namenode is not starting.
[hduser@dellnode1 ~]$ start-dfs.sh
starting namenode, logging to /usr/local/hadoop/bin/../logs/hadoop-hduser-namenode-dellnode1.library.out
dellnode1.library: datanode running as process 5123. Stop it first.
dellnode3.library: datanode running as process 4072. Stop it first.
dellnode2.library: datanode running as process 4670. Stop it first.
dellnode1.library: secondarynamenode running as process 5234. Stop it first.
[hduser@dellnode1 ~]$ jps
5696 Jps
5123 DataNode
5234 SecondaryNameNode

A: According to running "stop-all.sh" on newer versions of hardoop, this is deprecated. You should instead use:
stop-dfs.sh
and
stop-yarn.sh

A: "Stop it first".

*

*First call stop-all.sh

*Type jps

*Call start-all.sh (or start-dfs.sh and start-mapred.sh)

*Type jps (if namenode don't appear type "hadoop namenode" and check error)

A: Today, while executing pig scripts I got the same error mentioned in the question:
starting namenode, logging to /usr/local/hadoop/libexec/../logs/hadoop-training-namenode-localhost.localdomain.out
localhost: /home/training/.bashrc: line 10: /jdk1.7.0_10/bin: No such file or directory
localhost: Warning: $HADOOP_HOME is deprecated.
localhost:
localhost: starting datanode, logging to /usr/local/hadoop/libexec/../logs/hadoop-training-datanode-localhost.localdomain.out
localhost: /home/training/.bashrc: line 10: /jdk1.7.0_10/bin: No such file or directory
localhost: Warning: $HADOOP_HOME is deprecated.
localhost:
localhost: starting secondarynamenode, logging to /usr/local/hadoop/libexec/../logs/hadoop-training-secondarynamenode-localhost.localdomain.out
starting jobtracker, logging to /usr/local/hadoop/libexec/../logs/hadoop-training-jobtracker-localhost.localdomain.out
localhost: /home/training/.bashrc: line 10: /jdk1.7.0_10/bin: No such file or directory
localhost: Warning: $HADOOP_HOME is deprecated.
localhost:
localhost: starting tasktracker, logging to /usr/local/hadoop/libexec/../logs/hadoop-training-tasktracker-localhost.localdomain.out

So, the answer is:
[training@localhost bin]$ stop-all.sh

and then type:
[training@localhost bin]$ start-all.sh

The issue will be resolved. Now you can run the pig script with mapreduce!

A: In Mac (If you install using homebrew) Where 3.0.0 is Hadoop version. In Linux change the installation path accordingly(only this part will change . /usr/local/Cellar/).
> /usr/local/Cellar/hadoop/3.0.0/sbin/stopyarn.sh
> /usr/local/Cellar/hadoop/3.0.0/sbin/stopdfs.sh
> /usr/local/Cellar/hadoop/3.0.0/sbin/stop-all.sh"

Better for pro users write this alias at the end of your ~/.bashrc or ~/.zshrc(If you are zsh user). And just type hstopfrom your command line everytime you want to stop Hadoop and all the related processes.
alias hstop="/usr/local/Cellar/hadoop/3.0.0/sbin/stop-yarn.sh;/usr/local/Cellar/hadoop/3.0.0/sbin/stop-dfs.sh;/usr/local/Cellar/hadoop/3.0.0/sbin/stop-all.sh"


text:
Q: Ionic CLI: [ERROR] Gulpfile (or dependent module) not found: .\gulpfile.js Senario
I recently upon running an Ionic 3 app, updated (well accidentally) the Ionic CLI version. Now upon running the build from command line, it produces the following error every time and halts the build:

In the error message it says to disable the gulp integration by running the command ionic config set gulp.enabled false which I did. But still getting the same error. I also tried to add the command to the start script of package.json to no avail (not needed though since it seems the config is set globally).
Any help would be appreciated.
Ionic CLI version: 3.9.2

A: Finally figured out what the problem was. Even if Gulp integration has been disabled with the command ionic config set gulp.enabled false, as long as Gulp is a Dev dependency (i.e. there is a reference to it in the package.json under devDependencies) the Ionic CLI would (well, logically) assume that the Ionic project has a dependency on Gulp, therefore would throw the error (see original post).
Solution
The solution for a case where you don't want Gulp integration, apart from disabling it by running the command ionic config set gulp.enabled false, is to also make sure Gulp is NOT under the devDependencies in the package.json file.
Hope this helps anyone else with a similar issue.

NOTE: Not sure from which version onwards Ionic requires integration with Cordova and Gulp in the shape of ionic.config.json file. Anyway, the above solution will be relevant for a similar case in any of those versions.


text:
Q: Dynamically replace data inside a div container What is the best way to load data dynamically inside a DIV container?
Let's say I have a number of pictures on a page. Clicking a picture opens a DIV container on the screen (no page refresh) which contains all comments for that image.
At the moment I am sending an AJAX request to load comments from the DB and echo them out in another page. I am then appending that data, with jQuery, inside the DIV container. Clicking on another image clears the container and new data is loaded vie new AJAX request.
It just seems to me that this might not be the most efficient way of doing it, because if the user is going back and forth clicking on images on the page, then data has to be reloaded every single time.
I see that facebook changes the URL every time when a new image is selected. So may be they use an ID from the URL to load the data without sending an AJAX request?
May be once data is loaded and another image is selected, it will be better to just hide the old image comments on the page rather than discard them ? So that if the image is clicked again, it will not be required to reload its data?

A: If you respecify the < img >-Tag inside some div so the pictures get loaded after you do that. If you specify the same picture twice or more times, the image is already in the cache of most browsers. Thatwhy you can just do something like
$('#divid').html(' < img src="..." > ');
If you want to preload your pictures, I would put some images into some very small div aside somewhere. If you put pictures into a hidden container some browsers wont preload them.
In case you stored your pictures into some database or memcache, use caching-headers. You might program some outputpicture.php?id=12345.
In that case something like
header('Content-Type: '.get_img_type($data));
header('Content-Length: '.strlen($data));
header("Pragma: public");
$expires = 60*60*24*14;
header("Cache-Control: maxage=".$expires);
header("Last-Modified: Mon, 26 Jul 1984 05:00:00 GMT");
header('Expires: ' . gmdate('D, d M Y H:i:s', time()+$expires) . ' GMT');

could help alot.

A: you can add your get address in javascript object , and map the content loaded to it, every time you make ajax request.
then when user clicks on the image, instead of sending an ajax request, first check if you have that request in the object to load it from there, if you haven't the address in the object then you can proceed and send an ajax request and save its result to the object I mentioned.

A: Here is an idea as to how you may avoid making frequent/duplicate ajax requests for the same image.
Say you've a function to draw comments in your div that acepts the reponse from the server, such as:
function displayComments(resp) {
    //Do stuff
}

And let's assume an ajax call on image click looks like the following.
//We're probably better of using the wrapper (class/ID) of images to
//delegate events since setting/unsetting data may cause problems
//if we'd used bind on images directly
$("imagesContainerSelector").on("click", "img", function() {

    var $this = $(this);

    //See if comments have already been fetched previously.
    //If yes, we'd have stored them as that image's data and
    //we'd now simply use that data to display the comments.
    if ( $this.data("comments") ) {

        displayComments($this.data("comments"));
    } else {
        //We've not fetched comments for this image yet, so, fetch it
        $.ajax({
            url: '...',
            data: '...'
            //more options
        }).done(function(data) {
            //When done, display comments
            displayComments(data);
            //Set the resp as data for later use
            $this.data("comments", data);
        });
    }
});


text:
Q: Syntax for POST request I am trying to make a POST request to the following url: http://xxx.xxx.xxx.xxx/api/signup
However I get this response:
http://xxx.xxx.xxx.xxx/api/signup?first_name=&last_name=&email_id=&password=&dob ...Please pass parameters...
So I tried making the request like this:
http://xxx.xxx.xxx.xxx/api/signup?first_name=Jay&last_name=Last&email_id=Jay@test.com&password=qqq&dob=1/1/15
But I get the same response.
I have no idea what the correct syntax is supposed to be...
Can someone please explain how I should rewrite the url?
Edit
After I make the request, if successful, I get a response saying "success new user" and a JSON with the key/vals

A: Does encoding your values make any difference?
for example:
http://xxx.xxx.xxx.xxx/api/signup?first_name=Jay&last_name=Last&email_id=Jay%40test.com&password=qqq&dob=1%2F1%2F15


text:
Q: adf refresh mysql auto_increment "ID" not shown until query is re-executed I have a problem very similar to this question :
Oracle ADF web browser refresh button gets old page
My application is also running on top of a MySQL database. I have a table named IncidentType which contains 2 columns :
IncidentTypeID (int, auto_increment)
Description (varchar 60)
In my web page, I can create new records and commit them to the database. However, the IncidentTypeID will not be shown until I reload the page (via a "refresh" or close then reopen the page). Essentially, not until the VO's query is executed again on the database.
If I look at the data in the database, the IncidentTypeID is correctly assigned.
I noticed the same behaviour on the ADF Business Component tester.
What would you advice to modify to force the query to be re-executed after each commit and ?
I tried the solutions in the link above, but it didn't changed the behaviour.
I'm using jDev 11.1.2.3.0

A: See the unsupported features and "Set Up Primary Key Generation " workaround here:
http://www.oracle.com/technetwork/developer-tools/jdev/multidatabaseapp-085183.html


text:
Q: SVG to PDF (with Perl Cairo?) In a perl script, I try to convert svg files to pdf. This works great by just refering to Inkscape:
system "inkscape -D -z --file=$in --export-pdf=$out";

But it is enormously slow even for little 100 KB files, I mean it can be minutes per file, causing the script to fail when running with a time-out constrain, eg. on a webserver.
To speed up, I have read about svg2pdf as a standalone, but never found a binary for Win7 or managed to compile it, even with the libcairo dlls present.
My last idea now is to use the CPAN module Cairo. It makes me hoping that it can convert an svg file to pdf, but in the documentation I only find drawings and surfaces, but no method to write/convert.
Has anyone experience with that?

A: Making my comment an answer: You could try rsvg-convert which is part of the librsvg library. It's probably faster than Inkscape but it's still an external command.


text:
Q: Overscroll header/footer for ScrollView? ListView has this nice feature where you can set an overscroll header or footer. ScrollView, unfortunately, has no such thing. Does anyone know of a way to put together something that works like a ScrollView with an overscroll header/footer?

A: My best guess is you might be able to accomplish this with a similar approach as pull-to-refresh for lists is implemented on Android devices: you basically stretch a view at the top of (probably actually above - same for a 'footer', but then below) the ScrollView to fake an overscroll effect.
For some ideas on this, have a look at this pull-to-refresh implementation. It dynamically adjusts the padding of a header view in the list to simulate it being overscrolled when 'pulling'.

A: Can't you put your ScrollView inside a RelativeLayout, which will also contain the header and footer? Something like this:
<RelativeLayout ...>
    <TextView
        android:id="@+id/header"
        android:alignParentTop="true"/>
    <ScrollView
        android:id="@+id/scroller"
        android:layout_below="@id/header"
        android:layout_height="fill_parent"/>
    <TextView
        android:id="@+id/footer"
        android:layout_below="@id/scroller"
        android:alignParentBottom="true"/>
</RelativeLayout>

In this question ( Can we use a ScrollView inside a LinearLayout? ), someone showed how to put a ScrollView inside a LinearLayout. It should be the same.


text:
Q: Can you share a single login / desktop session between multiple accounts? A little bit of background first.  We have many desktop applications that we have written to do various batch processes.  Currently they are all running under a single account.  When one of these batch processes needs to be updated, one of the systems team members logs into the machine, stops the application, uploads new code, and runs the process again.  Currently all the batch processes run under a shared account, and the systems team members all log in to this same shared account to manage the batch processes.
Is there a way to give each member of the systems team a separate account, while allowing them to log into a single desktop session where they can update the appropriate processes?  While this would be easy if the applications in question were services, we would rather not convert all the processes to services.
We are using Windows Server 2008, and remote desktop to log into the remote server and manage the batch processes.

A: No, that's not possible. A separate session is created per user. UserA can't logon to UserB's session as UserA.
UserA could shadow UserB's session, so why not configure remote control in the RDP-Tcp properties of the server to allow interactive remote control without requiring the user's permission. That way any member of the system team can "shadow" the session in which the batch processes run and then stop "shadowing" the session when they're done.

A: Have you come across Microsoft's SRVANY.EXE tool?  I don't believe MS have released a Win2k8 version, but the Win2k3 version runs fine on Win2k8.  Basically, it's a wrapper that you can configure run your script / program as a service.  It listens to messages from the Service Control Manager (SCM), and stops/starts your underlying code as an when requested.  We use it to run Perl / VBScript / Shell Script as services.

A: If you want to allow them remote access to the same session you could use an application like TeamViewer or TightVNC, since they always share the current view of the desktop. TeamViewer has more features but TightVNC is OpenSource, so can use it at work for free.
Wikipedia has a list with several more remote desktop applications:
Comparison of remote desktop software


text:
Q: making a javascript function/button click event call on another page I need to invoke a javascript function (contains a jquery.ajax() call) like showfilterresult(). This call is invoked on a page monitoring.gsp onclick of a button like "filter".
The call I am making is from a different page, What I need to do is load the montoring.gsp page and also have this showfilterresult() call be made on the loaded page. (so I want to make 2 calls, one to the page and another to a function on the page)
Right now I am doing this:
 <javascript>
jQuery.ajax({
     var myurl = /myapp/users/monitoring
        url: myurl,
        dataType: 'html',
        timeout: 10000,
        beforeSend: function() {
             jQuery('#mydiv').html(../showspinner.gif)
          },
        success: function(data) {
        window.location = myurl;
        }
      });

</javascript>

The showfilterresult() function is as follows:
function showFilterResult(){
    var frm=jQuery('#fromDate').val();
    var to=jQuery('#toDate').val();
    if($('#fromDate').val().length>0  && $('#toDate').val().length>0){
            jQuery.ajax({
                type:'POST',
                data:{
                    'timeWindow':$("#timeWindow").val(),
                    'p1':p1,
                    'p3':$('#p3 option:selected').text(),
                    'fromDate':$("#fromDate").val(),
                    'toDate':$("#toDate").val(),
                },
                url: '/myapp/users/filterResult',
                beforeSend: function() {
                    jQuery("#filteredResult").html('/showspinner.gif')
                },
                success:function(data,textStatus){
                    jQuery("#filteredResult").html(data)
                }
            });

I also need to know How would I pass the url parameters to the showfilterresult() call from my page, by default the function takes the values from the textfields on the monitoring.gsp page.
Update: This is analogous to: I have my personal webpage and I need to invoke another webpage like google.com and also need to pass some parameters and invoke the "search" call on google.com with the parameters, so once I click link/button my webpage it not only forwards to google.com but also invokes the search event with my passed params and I directly see the google search results page.
Regards,
Priyank

A: Do not use native jQuery.ajax function. In grails you have a jquery plugin.

*

*Install this plugin using grails install-plugin jquery.

*Import the jQuery files into your html using <g:javascript library="jquery" />

*Replace your first AJAX function with:
<g:remoteFunction
     controller="user"
     action="monitoring"
     before="$('#mydiv').html('../showspinner.gif')"
     onComplete="window.location = ${createLink(
         controller: 'user',
         action: 'monitoring')}" />

*Replace your second AJAX function with:
<g:remoteFunction
     controller="user"
     action="filterResult"
     params="$('#yourFormId').serialize()"
     before="$('#filteredResult').html('/showspinner.gif')"
     update="filteredResult" />

Maybe you have to check, whether your params are set correctly. In any case you can provide parameters in the first case by using params tag.


text:
Q: SVG alignment and scroll not working I need to display SVG text in the same font size and if the length of the text varies, it should be horizontally scrollable. There are many questions like this on the web but there's no one answer that works, at least that I can find. I have put together pieces from the various answers as can be seen in this jsfiddle. But it has problems in all of the browsers.
In FF, the left alignment is good but the scroll doesn't work at all.
In Chrome, the left alignment isn't even close and the scroll doesn't work.
In IE, it is almost the way I want it. The left alignment is a little off but the scrolling works.
Is it possible to have the text start at the same X position and the scrollbar to work for all browsers?

      <svg xmlns="http://www.w3.org/2000/svg"
           xmlns:xlink="http://www.w3.org/1999/xlink"
           width="100%" height="80"
           onload="init(evt)"
           align="center">
            <rect id="rect1" x="20" y="10" width="100%" height="100%" fill="white" stroke="red"/>
            <text id="text-to-resize"
              text-anchor="middle"
              x="170" y="50"
              font-family="Times New Roman" font-size="55">
              <tspan text-anchor="middle" dy="15">Some short text</tspan>
            </text>
      </svg>

      <svg xmlns="http://www.w3.org/2000/svg"
           xmlns:xlink="http://www.w3.org/1999/xlink"
           width="100%" height="80"
           onload="init(evt)"
           align="center">
            <rect id="rect1" x="20" y="10" width="100%" height="100%" fill="white" stroke="red"/>
            <text id="text-to-resize"
              text-anchor="middle"
              x="730" y="50"
              font-family="Times New Roman" font-size="55">
              <tspan text-anchor="middle" dy="15">Some Unknown Text that is too long to display without scrolling</tspan>
            </text>
      </svg>


text:
Q: How to enable list search with powershell Have a 2013 Farm and I am curious if there is a way to turn on Search This List for a List or Library from PowerShell

A: This is not a setting what you can change. This feature comes with the View of the List or Library.
This option gets displayed on the View when the view Style is set to "Default"
You can read this http://www.sbrickey.com/Tech/Blog/Post/SharePoint_Feature_Request_Deploying_View_Styles to find more about the Styles and how to set it via PowerShell.


text:
Q: SqlDataAdapter vs SqlDataReader What are the differences between using SqlDataAdapter vs SqlDataReader for getting data from a DB?
I am specifically looking into their Pros and Cons as well as their speed and memory performances.
Thanks

A: DataReader:

*

*Needs the connection held open until you are finished (don't forget to close it!).

*Can typically only be iterated over once

*Is not as useful for updating back to the database

On the other hand, it:

*

*Only has one record in memory at a time rather than an entire result set (this can be HUGE)

*Is about as fast as you can get for that one iteration

*Allows you start processing results sooner (once the first record is available). For some query types this can also be a very big deal.

DataAdapter/DataSet

*

*Lets you close the connection as soon it's done loading data, and may even close it for you automatically

*All of the results are available in memory

*You can iterate over it as many times as you need, or even look up a specific record by index

*Has some built-in faculties for updating back to the database

At the cost of:

*

*Much higher memory use

*You wait until all the data is loaded before using any of it

So really it depends on what you're doing, but I tend to prefer a DataReader until I need something that's only supported by a dataset.  SqlDataReader is perfect for the common data access case of binding to a read-only grid.
For more info, see the official Microsoft documentation.

A: The answer to that can be quite broad.
Essentially, the major difference for me that usually influences my decisions on which to use is that with a SQLDataReader, you are "streaming" data from the database. With a SQLDataAdapter, you are extracting the data from the database into an object that can itself be queried further, as well as performing CRUD operations on.
Obviously with a stream of data SQLDataReader is MUCH faster, but you can only process one record at a time. With a SQLDataAdapter, you have a complete collection of the matching rows to your query from the database to work with/pass through your code.
WARNING: If you are using a SQLDataReader, ALWAYS, ALWAYS, ALWAYS make sure that you write proper code to close the connection since you are keeping the connection open with the SQLDataReader. Failure to do this, or proper error handling to close the connection in case of an error in processing the results will CRIPPLE your application with connection leaks.
Pardon my VB, but this is the minimum amount of code you should have when using a SqlDataReader:
Using cn As New SqlConnection("..."), _
      cmd As New SqlCommand("...", cn)

    cn.Open()
    Using rdr As SqlDataReader = cmd.ExecuteReader()
        While rdr.Read()
            ''# ...
        End While
    End Using
End Using

equivalent C#:
using (var cn = new SqlConnection("..."))
using (var cmd = new SqlCommand("..."))
{
    cn.Open();
    using(var rdr = cmd.ExecuteReader())
    {
        while(rdr.Read())
        {
            //...
        }
    }
}

A: A SqlDataAdapter is typically used to fill a DataSet or DataTable and so you will have access to the data after your connection has been closed (disconnected access).
The SqlDataReader is a fast forward-only and connected cursor which tends to be generally quicker than filling a DataSet/DataTable.
Furthermore, with a SqlDataReader, you deal with your data one record at a time, and don't hold any data in memory. Obviously with a DataTable or DataSet, you do have a memory allocation overhead.
If you don't need to keep your data in memory, so for rendering stuff only, go for the SqlDataReader. If you want to deal with your data in a disconnected fashion choose the DataAdapter to fill either a DataSet or DataTable.

A: Use an SqlDataAdapter when wanting to populate an in-memory DataSet/DataTable from the database. You then have the flexibility to close/dispose off the connection, pass the datatable/set around in memory. You could then manipulate the data and persist it back into the DB using the data adapter, in conjunction with InsertCommand/UpdateCommand.
Use an SqlDataReader when wanting fast, low-memory footprint data access without the need for flexibility for e.g. passing the data around your business logic. This is more optimal for quick, low-memory usage retrieval of large data volumes as it doesn't load all the data into memory all in one go - with the SqlDataAdapter approach, the DataSet/DataTable would be filled with all the data so if there's a lot of rows & columns, that will require a lot of memory to hold.

A: The Fill function uses a DataReader internally. If your consideration is "Which one is more efficient?", then using a DataReader in a tight loop that populates a collection record-by-record, is likely to be the same load on the system as using DataAdapter.Fill.
(System.Data.dll, System.Data.Common.DbDataAdapter, FillInternal.)


text:
Q: Jquery sort is not working with children tag see the below code
source = $("<root><item desc='SQL'/><item desc='Microsoft'/><item desc='Action Script'><item desc='Java script'></root>")

//WAY 1: This way is not working...
source.children().sort(function(a, b)
    {
        var aText = $(a).attr("desc").toLowerCase();
        var bText = $(b).attr("desc").toLowerCase();

        if(aText == bText)
            return 0;

        return aText > bText ? 1 : -1;
    });

alert(source[0].outerHTML);

//WAY 2: This is working...
var temp = source.children();

temp.sort(function(a, b)
    {
        var aText = $(a).attr("desc").toLowerCase();
        var bText = $(b).attr("desc").toLowerCase();

        if(aText == bText)
            return 0;

        return aText > bText ? 1 : -1;
    });

source = $("<root/>");
source.append(temp);

alert(source[0].outerHTML);

way 1 is not working, way 2 is working good. why should i assign children to another variable and then sort, assign them back to original variable? Is this right and efficient way?
you can try this FIDDLE....

A: The order of the children in the jQuery collection has nothing to do with the order of the children as XML nodes. In the jQuery collection they're just pointers to the nodes. In your second example, you're adding them to a new root in their new order.
An analogy: Imagine you've got a bunch of baseball players, and their baseball cards. You line up the baseball players in batting order, and then you line up their cards in the same order as the players.
In your first example, you're just sorting the baseball cards. The players themselves don't move.
In your second example, you sort the cards, and then you tell the players to move to a new line in the same order that you've sorted the cards into.


text:
Q: rails-api is installing rails I am building an Rails API-only application.
When I run from the command line this:
rails-api new myapp -T -d postgresql

I see this in the Gemfile:
source 'https://rubygems.org'

gem 'rails', '4.2.0'
gem 'rails-api'
gem 'spring', :group => :development
gem 'pg'

Rails 4.2 in installed on the system, but is it possible to install rails-api without automatically installing rails?

A: Partially you a right, rails-api has dependency to railties (not rails, my mistake), but railties is a core of rails.
So, you really can remove line gem 'rails', '4.2.0' from Gemfile and run server (because it part of railties).
I think rails gem here because railties has generator of Rails applications and rails-api used it. But generated application by default has dependencies to such components of Rails as active_record, active_mailer, etc. So, rails-api just leave dependency to rails because otherwise it must remove all these dependencies from generated application.

A: Install Rails 5 in your system using below command:
gem install rails -v 5

then create new rails API project below command:
rails new project_name --api -d postgresql


text:
Q: C char pointer array in stucts, how to I have a problem understanding how to access specified places in the char arrays in structs.
typedef struct Memory
{
char * bitmap[8];
char * memblock[64];
int i;
//...
}Memblock

int somefunction(void)
Memblock mem;

Lets say I've allocated the stuct, and now want to do the bitwise operation on bitmap: bitmap[0] & 1;
Tried *mem->bitmap[0] & 1; with variations without any luck. Does someone have good explanation how to dereference it?
PS: I understand how to get bitmap, but not bitmap[i].

A: First of all fix char* bitmap[8] to char bitmap[8].
 typedef struct Memory
 {
 char bitmap[8];
 char * memblock[64];
 int i;
 //...
 }Memblock

 int somefunction(void)
 Memblock mem;

Then instead of using mem->bitmap[0] & 1 you need to use mem.bitmap[0] & 1 ,since mem is not a pointer to Memory.

A: Assuming mem is really meant to be an instance of struct Memory and bitmap is really meant to be an array of char *, the correct syntax to access what bitmap[i] points to is
*mem.bitmap[i]

If you're paranoid about precedence, you could add some parentheses:
*(mem.bitmap[i])

but both the component selection operator . and the subscript operator [] have higher precedence than unary *, so parentheses are not required in this case.
You would only use the -> operator if mem was a pointer to struct Memory.
Having said all that, are you sure that bitmap needs to be an array of pointers to char instead of an array of char?

A: You have declared an array of 8 pointers to characters and another array of 64 pointers to characters in your struct Memory. That's possibly not what you intended.
Additionally you dropped some necessary semicolons from the code you show.


text:
Q: A question about proving that there is no greatest cardinal I would like to know if it is possible to prove that there is no greatest cardinal without axiom of choice

A: This is just Hartogs theorem, stating that if $X$ is any set, then there is an ordinal which admits no injections into $X$.
If $\alpha$ is any ordinal, then $\alpha$ can be mapped into $\mathcal P(\alpha)$, which has a larger cardinality, so by Hartogs theorem there is an ordinal of cardinality larger than $\alpha$. Namely, if $\alpha$ was a cardinal, then there has to be a larger cardinal than $\alpha$.
It should also be noted that without the axiom of choice, the class of cardinals contains more than just ordinals. So appealing toe Cantor's theorem works just fine, as it ensures that there is no maximal cardinal.


text:
Q: How do I display results from a sql query via php onto a php page? could someone help me out?
I have these 2 files:

*

*keywords.php

*records.php

The keywords.php is like a search page where user submits a query like keywords.php?keywords=robert
Now what I want, is to send the value robert to records.php and display all records matching the name robert from the blog_posts table to the keywords.php page
my keywords.php
<?php
$keywords = $_GET['keywords'];
?>
<!DOCTYPE html>

        <meta charset="utf-8">
        <title>Test</title>

 Loading...please wait

and this is my records.php
<?php
require_once("config.php");

$limit = (intval($_GET['limit']) != 0 ) ? $_GET['limit'] : 10;
$offset = (intval($_GET['offset']) != 0 ) ? $_GET['offset'] : 0;

$keywords = $_GET['keywords'];

$sql = "SELECT * FROM blog_posts WHERE keyword LIKE '".$keywords."' ORDER BY postid ASC LIMIT $limit OFFSET $offset";
try {
  $stmt = $DB->prepare($sql);
  $stmt->execute();
  $results = $stmt->fetchAll();
} catch (Exception $ex) {
  echo $ex->getMessage();
}
if (count($results) > 0) {
  foreach ($results as $res) {
    echo '
' . $res['keyword'] . '
';
  }
}
?>

thanks alot for your help

A: There are several changes needed in keywords.php. Take a look at the changes below.
<?php
$keywords = $_GET['keywords'];
?>
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Test</title>

 Loading...please wait


text:
Q: Removing a field from jSon String I am storing jSon string as hexa-decimal or some characters string, its all working fine whan I retrieving as json string in my code, but there is one field I want to remove from the jSob object after I retrieved.
  var t = StoredProcedures.SP_GlobalSearch.Execute(new SP_GlobalSearch_Params
                    {
                        Search = request.search,
                        SourceKey = "",
                        Skip = start,
                        Take = length,
                        ShowDeleted = false
                    }).Select(x => new SP_GlobalSearch
                    {
                        JsonObject = x.Data != null ? new JavaScriptSerializer().DeserializeObject(x.Data.Replace("", "")) : null,
                        Date = x.Date,
                        JsonObjectId = x.JsonObjectId,
                        SourceKey = x.SourceKey,
                        SourceId = x.SourceId,
                        TotalCount = x.TotalCount
                    });

                    var response = t?.ToList();

                    var jsondata = new DataTableResponse<SP_GlobalSearch>
                    {
                        totalCount = (int)response.Where(x => x.TotalCount != null).FirstOrDefault().TotalCount,
                        data = response.Where(x => x.TotalCount == null)
                    };

                    var jsonResult = Json(jsondata);
                    jsonResult.MaxJsonLength = Int32.MaxValue;
                    return jsonResult;

I am reading the text as jSon with the below statement,
JavaScriptSerializer().DeserializeObject(x.Data.Replace("", ""))

I want to remove the violations field from it, any help please. Thanks in advance
Here is my json:
{
   "InspectionResultId":846,
   "InspectionResultNumber":"T00846",
   "InspectionRequestId":507,
   "InspectionRequestNumber":"R00507",
   "CaseId":689,
   "InspectionResultStatusId":605,
   "EnforcementSectionId":104,
   "ViolationTypeId":603,
   "DateOfInspection":"\/Date(1589439600000)\/",
   "InspectionComment":"send to office staff, open investigation",
   "InspectedCompanyDataId":964,
   "ContactTypeId":701,
   "EnteredById":"7f54fa3e-b5cd-4b2e-9490-92f64c022246",
   "InspectionResultTimestamp":"\/Date(1588280817470)\/",
   "DateCreated":"\/Date(1588280817487)\/",
   "DateUpdated":"\/Date(1588281867967)\/",
   "CreatedByUserId":"7f54fa3e-b5cd-4b2e-9490-92f64c022246",
   "UpdatedByUserId":"7f54fa3e-b5cd-4b2e-9490-92f64c022246",
   "Case":{
      "RelatedContactId":0,
      "CaseId":689,
      "CaseNumber":"I00689",
      "IsInvestigation":true,
      "CaseStatusId":801,
      "InspectionItemSourceId":211,
      "EnforcementSectionId":104,
      "ReminderDate":"\/Date(1590044400000)\/",
      "PreCaseSummary":"send to office staff, open investigation",
      "AssignedToInspectorId":"7f54fa3e-b5cd-4b2e-9490-92f64c022246",
      "CaseTimestamp":"\/Date(1588281867403)\/",
      "CaseCompanyId":964,
      "DateCreated":"\/Date(1588281867437)\/",
      "DateUpdated":"\/Date(1588281867840)\/",
      "CreatedByUserId":"7f54fa3e-b5cd-4b2e-9490-92f64c022246",
      "UpdatedByUserId":"7f54fa3e-b5cd-4b2e-9490-92f64c022246",
      "IsDeleted":false,
      "InterpreterNeeded":false,
      "VoluntaryDisclosure":false,
      "PenaltyAdjustment":0,
      "Company":{
         "ContactId":964,
         "ContactTypeId":1000,
         "FirstName":"04.30.2020 new co",
         "Notes":"new request",
         "Active":true,
         "Created":"\/Date(1588279909680)\/",
         "Updated":"\/Date(1588279909680)\/",
         "DateCreated":"\/Date(1588279909680)\/",
         "DateUpdated":"\/Date(1588279909680)\/",
         "IsEJArea":false,
         "CreatedByUserId":"7f54fa3e-b5cd-4b2e-9490-92f64c022246",
         "UpdatedByUserId":"7f54fa3e-b5cd-4b2e-9490-92f64c022246",
         "Classification":{

         },
         "Class":"Company",
         "IsSpecial":false,
         "Address":{
            "Street1":"5678 Street",
            "City":"Sacramento",
            "StateCode":"CA",
            "Zip":"95812",
            "Country":"0"
         }
      }
   },
   "InspectionResultStatus":{
      "InspectionResultStatusId":605,
      "InspectionResultStatusName":"Clean",
      "InspectionResultStatusSortOrder":5
   },
   "EnforcementSection":{
      "EnforcementSectionId":104,
      "EnforcementSectionName":"STBES",
      "EnforcementSectionSortOrder":0,
      "BranchId":2
   },
   "InspectedCompanyData":{
      "ContactId":964,
      "ContactTypeId":1000,
      "FirstName":"04.30.2020 new co",
      "Notes":"new request",
      "Active":true,
      "Created":"\/Date(1588279909680)\/",
      "Updated":"\/Date(1588279909680)\/",
      "DateCreated":"\/Date(1588279909680)\/",
      "DateUpdated":"\/Date(1588279909680)\/",
      "IsEJArea":false,
      "CreatedByUserId":"7f54fa3e-b5cd-4b2e-9490-92f64c022246",
      "UpdatedByUserId":"7f54fa3e-b5cd-4b2e-9490-92f64c022246",
      "Classification":{

      },
      "Class":"Company",
      "IsSpecial":false
   },
   "InspectionItems":[
      {
         "InspectionItemId":1054,
         "InspectionItemNumber":"T00000",
         "InspectionRequestId":507,
         "InspectionResultId":846,
         "CaseId":689,
         "InspectionItemSourceId":229,
         "IsCreatedInCase":false,
         "ShowYearMakeModel":"",
         "ShowYearMakeModelVIN":"",
         "GrossWeight":0.00,
         "RegHoldSet":false,
         "InspectionItemTimestamp":"\/Date(1588280802553)\/",
         "DateCreated":"\/Date(1588280802567)\/",
         "DateUpdated":"\/Date(1588281868153)\/",
         "CreatedByUserId":"7f54fa3e-b5cd-4b2e-9490-92f64c022246",
         "UpdatedByUserId":"7f54fa3e-b5cd-4b2e-9490-92f64c022246",
         "Violations":[

         ]
      }
   ],
   "CompletedBy":[
      {
         "IsActive":true,
         "FirstName":"Daphne",
         "LastName":"Greene",
         "ObjectGUID":"S-1-5-21-1538631513-416410304-3002070310-33442",
         "NameLoginFormat":"dgreene",
         "NameFirstLast":"Daphne Greene",
         "NameLastFirst":"Greene Daphne",
         "Email":"daphne.greene@arb.ca.gov",
         "EmailConfirmed":false,
         "SecurityStamp":"e061e77e-c93e-4b9e-8497-4852b5cb4ca2",
         "PhoneNumberConfirmed":false,
         "TwoFactorEnabled":false,
         "LockoutEnabled":false,
         "AccessFailedCount":0,
         "Id":"7f54fa3e-b5cd-4b2e-9490-92f64c022246",
         "UserName":"dgreene"
      }
   ],
   "EnteredBy":{
      "IsActive":true,
      "FirstName":"Daphne",
      "LastName":"Greene",
      "ObjectGUID":"S-1-5-21-1538631513-416410304-3002070310-33442",
      "NameLoginFormat":"dgreene",
      "NameFirstLast":"Daphne Greene",
      "NameLastFirst":"Greene Daphne",
      "Email":"daphne.greene@arb.ca.gov",
      "EmailConfirmed":false,
      "SecurityStamp":"e061e77e-c93e-4b9e-8497-4852b5cb4ca2",
      "PhoneNumberConfirmed":false,
      "TwoFactorEnabled":false,
      "LockoutEnabled":false,
      "AccessFailedCount":0,
      "Id":"7f54fa3e-b5cd-4b2e-9490-92f64c022246",
      "UserName":"dgreene"
   },
   "MyGridContacts":[

   ],
   "CreatedByUser":{
      "IsActive":true,
      "FirstName":"Daphne",
      "LastName":"Greene",
      "ObjectGUID":"S-1-5-21-1538631513-416410304-3002070310-33442",
      "NameLoginFormat":"dgreene",
      "NameFirstLast":"Daphne Greene",
      "NameLastFirst":"Greene Daphne",
      "Email":"daphne.greene@arb.ca.gov",
      "EmailConfirmed":false,
      "SecurityStamp":"e061e77e-c93e-4b9e-8497-4852b5cb4ca2",
      "PhoneNumberConfirmed":false,
      "TwoFactorEnabled":false,
      "LockoutEnabled":false,
      "AccessFailedCount":0,
      "Id":"7f54fa3e-b5cd-4b2e-9490-92f64c022246",
      "UserName":"dgreene"
   },
   "UpdatedByUser":{
      "IsActive":true,
      "FirstName":"Daphne",
      "LastName":"Greene",
      "ObjectGUID":"S-1-5-21-1538631513-416410304-3002070310-33442",
      "NameLoginFormat":"dgreene",
      "NameFirstLast":"Daphne Greene",
      "NameLastFirst":"Greene Daphne",
      "Email":"daphne.greene@arb.ca.gov",
      "EmailConfirmed":false,
      "SecurityStamp":"e061e77e-c93e-4b9e-8497-4852b5cb4ca2",
      "PhoneNumberConfirmed":false,
      "TwoFactorEnabled":false,
      "LockoutEnabled":false,
      "AccessFailedCount":0,
      "Id":"7f54fa3e-b5cd-4b2e-9490-92f64c022246",
      "UserName":"dgreene"
   }
}

This above object is a dynamic object returned as string I want to remove Violation related fields and its values from it.
I want to remove the Violations, ViolationTypeId etc fields related to Violation from the jSon object above, can you please help me in this regards thank you.

A: You can simply convert it to object, remove the field and back to string.
for example in javascript
assuming your json is in variable myjson
tmp = Object(myjson.Data)
delete tmp.Violations
myjson.Data = JSON.stringify(tmp)

in C#, assuming Data is your string json
JObject tmp = JObject.Parse(Data);
tmp.Property("Violations").Remove();
Data = JavaScriptSerializer().Serialize(jsonResult.Data);


text:
Q: Flattened 3D array interior values I have a flattened 3D array representing the vertex indices of a procedural mesh that I'm trying to optimize.  I create the array like so:
int* vertIndices = new int[WIDTH * HEIGHT * DEPTH];

and to add to the array
vertIndices[x + WIDTH * (y + HEIGHT * z)] = vertIndex;

The issue is that I only need to keep track of the vertices on the surface of the mesh.  Interior vertices do not get created.
Therefore, I'm creating a lot of wasted integers that never get used.
Here is a loop through the vertIndices array of a mesh with WIDTH: 7, HEIGHT: 7 and DEPTH: 7

All those -1163005939 values are vertices that would be located within the interior of the mesh but do not get created.
My question is how can I improve the formula
x + WIDTH * (y + HEIGHT * z)

to ignore interior values.
Thanks!

A: I think you won't get around of introducing some kind of condition to the formula. Something like this:
int getIndex(int x, int y, int z) {
    //First get the amount of points in all layers before this z layer.
    int beforeZ = (z) ? WIDTH*HEIGHT + (z - 1)*2*(WIDTH + HEIGHT - 2) : 0;

    //Then get the amount of points within this layer before this line.
    int beforeY = (y) ? WIDTH + 2*(y - 1) : 0;
    if(z == 0 || z == DEPTH - 1) beforeY = y*WIDTH;

    //And finally the amount of points within this line before this point.
    int beforeX = (x) ? 1 : 0;
    if(z == 0 || z == DEPTH - 1 || y == 0 || y == HEIGHT - 1) beforeX = x;

    //Return the amount of points before this one.
    return beforeZ + beforeY + beforeX;
}

I admit that this is a bit ugly, but I think it's quite close to the best you can get. At least if you don't want to create some kind of lookup table that matches coordinates to indices and vice versa. Such lookup tables would, of course, be the really big gun that can handle any case, with the drawback of quite significant memory usage and likely slower operation.


text:
Q: What does it mean? "Thou hast been smitten?"
https://www.google.nl/search?q=What+does+Thou+hast+been+smitten+mean%3F
Doesn't deliver real results.

A: In contemporary English (though your tag is incorrect, it's not Old English, it's Early Modern English), we would write it as:

You have been smitten.

Thou is a now rarely used, second person singular (and familiar) pronoun, for which we would normally use you today.
Hast is an even more rarely used second person singular form of have. It's the one word in this sentence that you might not find in some dictionaries (though you certainly would in some), and the reason I'm answering rather than just voting to close as general reference. (English used to end verbs with -est or -st in the second person singular).
Smitten is the participle of smite. It can mean the persona addressed was hit, stricken with illness, punished by a god, affected painfully by something, or has fallen in love (love being compared to illness in its irrationality and the ache that even requited love can bring).

A: This is an older form of English. In Modern English you would say: "You have been smitten". Here is the definition of the verb "smite": http://www.thefreedictionary.com/smite
Maybe the person has become sick or maybe the have fallen madly in love.


text:
Q: ?attr/xxx and inherits style seem not to be reconized in android I have an Android App and a linked Module
In my Module i have an attr.xml file that defines custom tags
<declare-styleable name="CoreAtttributes">
    <attr name="styleNoActionBar" format="reference"/>
...

and a style.xml file that define CoreTheme
<style name="CoreTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="styleNoActionBar">@style/CoreTheme.NoActionBar</item>

with
<style name="CoreTheme.NoActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>

and in the manifest
<application
    android:allowBackup="true"
    android:supportsRtl="true"
    android:theme="@style/CoreTheme">
....

In my App i have an attr.xml file that defines other custom tags and inherits from my CoreAttributes defined previously
<declare-styleable name="AppAttributes" parent="@declare-styleable/CoreAtttributes">
    <attr name="other....." format="reference"/>
 ....

and a style.xml file that defines AppTheme inherits from CoreTheme
<style name="AppTheme.NoActionBar" parent="CoreTheme">
    <item name="other.....">....</item>
....

and in the App Manifest
<application
    android:name="......"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_label"
    android:supportsRtl="true"
    android:theme="@style/AppTheme"
    tools:replace="android:theme">

    <activity
        android:name=".view.activity.HomeActivity"
        android:label="@string/home_activity_label"
        style="?attr/styleNoActionBar" <-- HERE ITS NOT RECONIZED !!!
        android:windowSoftInputMode="adjustPan">
    </activity>

And when HomeActivity is launched it raises an error : "This Activity already has an action bar supplied by the window decor" so it seems that the style used by the HomeActivity is not seen ???
Thanks for your help. I've searched a long time without beeing able to find a solution.


text:
Q: When I click on the save button it will check that data on the database before saving it in Django? When I click on the save button it will check that data on the database before saving it in Django. search data at database before insert in Django administration. I don't want to save the same data that already save in the database.
like this on:
Here Home save to double. But I want that if the home already saves then the second time I try to Save the same name it will not save.
How can I code it?
models.py
class Brand(models.Model):
    brand_id = models.id = models.AutoField(primary_key=True, auto_created=True)
    brand_name = models.CharField(max_length=50)
    brand_date = models.DateTimeField(auto_now_add=True, null=False)

A: You could add unique=True to avoid duplicates:
brand_name = models.CharField(max_length=50, unique=True)

A: Use unique=True if you want a unique field.
As you are new to python, the following tricks can come handy in future
Suppose you want a combination of fields to be unique you could add Constraints in Meta
class Brand(models.Model):
    brand_name = models.CharField(max_length=255, index=True)
    brand_location = models.CharField(max_length=255, index=True)
    brand_date = models.DateTimeField(auto_now_add=True, null=False)

    class Meta:
        constraints = [
            models.UniqueConstraint(fields=['brand_name', 'brand_location'], name='unique_brand')
        ]

Now you will have only a unique brand_name per location.
You can read more on constraints from here

A: I Miss to Add unique=True to brand_name.
brand_name = models.CharField(max_length=50, unique=True)


text:
Q: how do you create new lines in a textfield? I have a model with a TextField ("notes"), and I want to add strings to it using variables, but separate the variables with a new line (\n)
aaa = "variable 1"
bbb = "variable 2"
ccc = "variable 3"

model.objects.create(id=id, notes=aaa + '\n' + bbb + '\n' + ccc)

However, when I render the field in the template as {{object.notes}}, the variables aren't separated at all.

A: \n represents newline in plain text, but you are asking about auto-creation of actual p and br HTML tags in the template layer. See the docs for linebreaks and linebreaksbr.
Both of these will handle automatic insertion of linebreaks or paragraphs in your templates.

A: Try this:
Use < br />  instead of \n


text:
Q: bind variables dynamically in sql server I am running the below block in sql server 2014 , but it is getting failed with the error -

Must declare the table variable @tname.

Any ideas to fix this error?
DECLARE @IntVariable NVARCHAR(500);
DECLARE @SQLString NVARCHAR(500);
DECLARE @ParmDefinition NVARCHAR(500);

/* Build the SQL string one time.*/
SET @SQLString =
     N'SELECT * into #t from @tname';
SET @ParmDefinition = N'@tname NVARCHAR(500)';
/* Execute the string with the first parameter value. */
SET @IntVariable = 'tst_tbl';
EXECUTE sp_executesql @SQLString, @ParmDefinition,
                      @tname = @IntVariable;


text:
Q: Displaying of factor levels and labels in R I am having an issue with displaying the correct grouping of a factor variable after using MICE. I believe this is an R thing, but I included it with mice just to be sure.
So, I run my mice algorithm, here is a snipit of how I call I format it in the mice algorithm. Note, I want it to be 0 for no drug, and 1 for yes drug, so I coerce it to be a factor with levels 0 and 1 before I run it
mydat$drug=factor(mydat$drug,levels=c(0,1),labels=c(0,1))

I then run mice and it runs logistic regression (this is the default) on drug, along with my other variables to be imputed.
I can extract the results of one of the imputations when it is complete by
drug=complete(imp,1)$drug

We can view it
> head(drug)
[1] 0 0 1 0 1 1
attr(,"contrasts")
  2
0 0
1 1
Levels: 0 1

So the data is certainly 0,1.
However, when I do something with it, like cbind, it changes to 1's and 2's
> head(cbind(drug))
 drug
[1,]    1
[2,]    1
[3,]    2
[4,]    1
[5,]    2
[6,]    2

Even when I coerce it to a numeric
> head(as.numeric(drug))
[1] 1 1 2 1 2 2

I want to say it has something to do with the contrasts, but when I delete the contrast by doing
attr(drug,"contrasts")=NULL

It still shows up with 1's and 2's when called and printed by others.
I am able to get it to print correctly by using I()
> head(I(drug))
[1] 0 0 1 0 1 1
Levels: 0 1

So, I believe that this is an R issue, but I don't know how to remedy it. Is using I() the correct solution, or is it just a workaround that happens to work here? What is actually happening behind the scenes that is making the output display as 1's and 2's?
Thanks

A: The 0s and 1s are the names of your levels.  The underlying integer corresponding to the names is 1 and 2.  You can see with str,
str(drug)
# Factor w/ 2 levels "0","1": 2 2 2 2 2 2 1 1 2 2

When you coerce the factor to numeric, you drop the names and get the integer representation.

A: Factors start with the first level being represented internally by 1.
Your two options:
1) Adjust for 1-based index of levels:
as.numeric(drug) - 1

2) Take the labels of the factors and convert to numeric:
as.numeric(as.character(drug))

Some people will point you in the direction of the faster option that does the same thing:
as.numeric(levels(drug))[drug]

I'd also consider using logical values instead of factor in the first place.
mydat$drug = as.logical(mydat$drug)

A: This is how R encodes factors.  The underlying numeric representation of the factors always starts with 1.  As you can see with the following to examples:
as.numeric(factor(c(0,1)))
as.numeric(factor(c(A,B)))

Not sure about the specifics about how MICE works, but if it requires a factor instead of a simple 0/1 numeric variable to use logistic regression, you can always hack the results with something like the following:
as.numeric(as.character(factor(c(0,1))))

or in your specific case
drug <- as.numeric(as.character(drug))


text:
Q: Why is pyperclip "not found", even though it is clearly installed? I'm doing a basic coding project for class.  It's the password locker from "Automate the Boring Stuff".
I have everything coded properly, compiled without errors and I've made the bat file and it's in the right spot.
This is the code (minus the dashes in front of the hashtags)
#! python3

#pw.py This is an insecure Password Locker.

PASSWORDS = {'yahooEmail':'12345', 'googleEmail':'23456','facebook':'34567', 'luggage':'45678'}

import sys, pyperclip
if len(sys.argv) < 2:
    print('Usage: py pw.py [account] - copy account password')
sys.exit()

account = sys.argv[1]   # first command line arg is the account name

if account in PASSWORDS:
    pyperclip.copy(PASSWORDS[acount])
    print('Password for ' + account + ' copied to clipboard.')
else:
    print('There is no account named ' + account +'.')

So it should, of course, just allow me to type in the key to see the value, and copy/past new values as needed.
But when I run it I get this:
Traceback (most recent call last):

  File "C:\Users\shawn\Desktop\Python homework\pw.py", line 6, in <module>

    import sys, pyperclip

ModuleNotFoundError: No module named 'pyperclip'


text:
Q: Android change button background I want to reverse the colors (text & background) of my button when it is clicked.
I have the following XML files. When I test it, I can see the text color changes but the background color remains the same. I could not see what I'm missing.
layout.xml
...
<Button
    android:id="@+id/start_btn"
    android:layout_gravity="center_horizontal|center_vertical"
    android:layout_margin="0dp"
    android:text="start"
    android:background="@drawable/button_background"
    android:textColor="@drawable/button_text_color"
    android:fontFamily="@string/font_family"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    />
...

button_text_color.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true"
        android:color="@color/miops_dark_red" />
    <item android:color="@android:color/white" />
</selector>

button_background.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:state_focused="true">
        <shape xmlns:android="http://schemas.android.com/apk/res/android">
            <solid android:color="@android:color/white" />
            <stroke
                android:width="1dp"
                android:color="@color/miops_dark_red" />
            <padding
                android:bottom="1dp"
                android:left="1dp"
                android:right="1dp"
                android:top="1dp" />
        </shape>
    </item>
    <item>
        <shape xmlns:android="http://schemas.android.com/apk/res/android">
            <solid android:color="@color/miops_dark_red" />
            <stroke
                android:width="1dp"
                android:color="@android:color/white" />
            <padding
                android:bottom="1dp"
                android:left="1dp"
                android:right="1dp"
                android:top="1dp" />
        </shape>
    </item>
</selector>

A: finally I managed to solve the problem;
I have modified background.xml as followed;
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:drawable="@drawable/button_background_pressed"
        android:state_focused="true"
        />
    <item
        android:drawable="@drawable/button_background_pressed"
        android:state_pressed="true"
        />
    <item
        android:drawable="@drawable/button_background_released"
        />
</selector>

and added folowing two;
button_background_pressed.xml
<?xml version="1.0" encoding="utf-8"?>

<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@android:color/white" />
<stroke
    android:width="1dp"
    android:color="@color/miops_dark_red" />
<padding
    android:bottom="1dp"
    android:left="1dp"
    android:right="1dp"
    android:top="1dp" />
</shape>

button_background_released.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@color/miops_dark_red" />
    <stroke
        android:width="1dp"
        android:color="@android:color/white" />
    <padding
        android:bottom="1dp"
        android:left="1dp"
        android:right="1dp"
        android:top="1dp" />
</shape>

A: mLogin.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN) {
mLogin.setBackgroundColor(Color.rgb(AESConstants.RED_DOWN,AESConstants.GREEN_DOWN,AESConstants.BLUE_DOWN));
}
else if(event.getAction() == MotionEvent.ACTION_UP) {
mLogin.setBackgroundColor(Color.rgb(AESConstants.RED_UP,AESConstants.GREEN_UP,AESConstants.BLUE_UP));
}
return false;
}
});

This is one approach You can do something like this from code itself instead from the layout files

A: change your btn_bak.xml for the code below (or just add the gradient, which i think is the problem), you use only border (stroke). The below i use in my app, and if i understood your question correct you can easily modify it to your needs.
If gives the button a yellow background when pressed, and the black is just a frame around the button and if nothing, than white background.
Tell me if it works.
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >

<item android:state_pressed="true">
    <shape>
        <gradient
            android:startColor="@color/yellow1"
            android:endColor="@color/yellow"
            android:angle="270" />
        <stroke
            android:width="3dp"
            android:color="@color/black" />
        <corners
            android:radius="3dp" />
        <padding
            android:top="20dp"
            android:bottom="10dp" />
    </shape>
</item>

<item>
    <shape>
        <gradient
            android:endColor="@color/white"
            android:startColor="@color/white"
            android:angle="270" />
        <padding
            android:top="20dp"
            android:bottom="10dp" />
    </shape>
</item>
</selector>

A: Try this..
@SuppressLint("ResourceAsColor")
    private void setBackgroundColor(String color,Button btn) {
    GradientDrawable drawable = (GradientDrawable)btn.getBackground();
    drawable.setColor(Color.parseColor(color));
    drawable.setStroke(4,Color.parseColor(color));
    btn.setColorFilter(Color.parseColor("#ffffff"));
}


text:
Q: Best nested parallelization approach with Rust Futures Not sure if this is even a good question to ask but I hope that the answer could also cover if nested parallelization is bad or not in addition to my main questions. Thank you so much!
Suppose I have tasks a, b, c and d. These tasks each have their separate sub tasks, a1, a2 so on..
Sometimes, a1 might have a bunch of sub tasks to accomplish as well. The tasks are nested inside a, b, c and d because they are dependent on processing together as a whole, so there won't be a way to decouple them and create tasks e, f and g (so on..).
I am currently utilising Futures and Threadpool to process these tasks in a concurrent, parallel way (such that a, b.. run in parallel, and a1, a2 run in parallel).
However, I was greeted with
thread 'tokio-runtime-worker' panicked at 'called `Result::unwrap()` on an `Err` value: Os { code: 35, kind: WouldBlock, message: "Resource temporarily unavailable" }', src/my_folder/my_file.rs:123:123

The code above that failed is
let thread_pool = ThreadPool::new().unwrap();

So the questions are:

*

*Is nested parallelization correct in this case? (If not, what should I do? If yes, how should I do?)

*How do I ensure that Threadpools are created safely, such that it would not fail unwrapping when the resources are inadequate?

*If (2) is a wrong thing to do, how should I implement my code?

let tasks: Vec<_> = block_transactions.into_iter()
    .map(|encoded_tx| {
        let pool = core_pool.clone();
        let rpc_url = core_rpc_url.clone();
        let block = core_block.clone();

        tokio::spawn(async move {
            let sol_client = RpcClient::new(rpc_url.clone());

            let mut tx = crate::models::transactions::Transaction {
                hash: "".to_string(),
                block: block.number.clone(),
                is_confirmed: true,
                status: TransactionStatus::Success,
                fee: 0,
                timestamp: block.timestamp.clone()
            };

            if let Some(decoded_tx) = (&encoded_tx.transaction).decode() {
                // Each item in the signatures array is a digital signature
                // of the given message

                // Additional safety net
                if decoded_tx.signatures.len() >= 1 {
                    // Signatures should be Vec<Signature>.
                    // The first one, signatures[0], is the hash that is used to
                    // identify the transaction (eg. in the explorer), and you can
                    // get the base58-encoded string using the .to_string() method.
                    // Seed first signature
                    tx.hash = decoded_tx.signatures[0].to_string();

                    // Seed the transaction
                    let tx_res = crate::actions::transactions::create_or_ignore_transaction(
                        &*pool.get().unwrap(),
                        &tx,
                    );

                    // Seed everything that depends ONLY on the created transaction
                    if let Ok(created_tx) = tx_res {
                        // Spawn the futures threader first
                        let thread_pool = ThreadPool::new().unwrap();

                        // Seed subsequents
                        let tst_pool = pool.clone();
                        let tst_dtx = decoded_tx.clone();
                        let tst_tx = tx.clone();
                        let transaction_signatures_task = async move {
                            let transaction_signatures: Vec<_> = tst_dtx
                                .signatures
                                .as_slice()
                                .into_par_iter()
                                .filter(|signature| &signature.to_string() != &tst_tx.hash)
                                .map(|signature| {
                                    // Subsequent signature are lead to the same tx, just
                                    // signed from a different key pair.
                                    InsertableTransactionSignature {
                                        transaction_hash: tst_tx.hash.clone(),
                                        signature: signature.to_string().clone(),
                                        timestamp: tst_tx.timestamp.clone(),
                                    }
                                })
                                .collect();

                            let cts_result =
                                crate::actions::transaction_signatures::create_transaction_signatures(
                                    &*tst_pool.get().unwrap(),
                                    transaction_signatures.as_slice(),
                                );

                            if let Ok(created_ts) = cts_result {
                                if created_ts.len() != (tst_dtx.signatures.len() - 1) {
                                    eprintln!("[processors/transaction] WARN: Looks like there's a signature \
                        creation count mismatch for tx {}", tst_tx.hash.clone());
                                }
                            } else {
                                let cts_result_err = cts_result.err().unwrap();
                                eprintln!(
                                    "[processors/transaction] FATAL: signature seeding error for \
                    tx {} due to: {}",
                                    tst_tx.hash.clone(),
                                    cts_result_err.to_string()
                                );
                            }
                        };
                        let tst_handle = thread_pool
                            .spawn_with_handle(transaction_signatures_task)
                            .unwrap();

                        // A message contains a header,
                        // The message header contains three unsigned 8-bit values.
                        // The first value is the number of required signatures in the
                        // containing transaction. The second value is the number of those
                        // corresponding account addresses that are read-only.
                        // The third value in the message header is the number of read-only
                        // account addresses not requiring signatures.
                        // identify which are required addresses, addresses requesting write
                        // access, then address with readonly access
                        let req_sig_count =
                            (decoded_tx.message.header.num_required_signatures.clone()) as usize;
                        let rw_sig_count = (decoded_tx
                            .message
                            .header
                            .num_readonly_signed_accounts
                            .clone()) as usize;
                        let ro_sig_count = (decoded_tx
                            .message
                            .header
                            .num_readonly_unsigned_accounts
                            .clone()) as usize;

                        // tx.message.account_keys is a compact-array of account addresses,
                        // The addresses that require signatures appear at the beginning of the
                        // account address array, with addresses requesting write access first
                        // and read-only accounts following. The addresses that do not require
                        // signatures follow the addresses that do, again with read-write
                        // accounts first and read-only accounts following.
                        let at_pool = pool.clone();
                        let at_tx = tx.clone();
                        let at_dtx = decoded_tx.clone();
                        let at_block = block.clone();
                        let accounts_task = async move {
                            crate::processors::account::process_account_data(
                            &at_pool,
                            &sol_client,
                            &at_tx.hash,
                            &req_sig_count,
                            &rw_sig_count,
                            &ro_sig_count,
                            &at_dtx.message.account_keys,
                            &at_block.timestamp)
                                .await;
                        };
                        let at_handle = thread_pool
                            .spawn_with_handle(accounts_task)
                            .unwrap();

                        // Each instruction specifies a single program, a subset of
                        // the transaction's accounts that should be passed to the program,
                        // and a data byte array that is passed to the program. The program
                        // interprets the data array and operates on the accounts specified
                        // by the instructions. The program can return successfully, or
                        // with an error code. An error return causes the entire
                        // transaction to fail immediately.
                        let it_pool = pool.clone();
                        let it_ctx = created_tx.clone();
                        let it_dtx = decoded_tx.clone();
                        let instruction_task = async move {
                            crate::processors::instruction::
                            process_instructions(&it_pool, &it_dtx,
                                                 &it_ctx,
                                                 it_dtx.message.instructions.as_slice(),
                                                 it_dtx.message.account_keys.as_slice())
                                .await;
                        };
                        let it_handle = thread_pool
                            .spawn_with_handle(instruction_task)
                            .unwrap();

                        // Ensure we have the tx meta as well
                        let tmt_pool = pool.clone();
                        let tmt_block = block.clone();
                        let tmt_meta = encoded_tx.meta.clone();
                        let tx_meta_task = async move {
                            if let Some(tx_meta) = tmt_meta {
                                let tm_thread_pool = ThreadPool::new().unwrap();

                                // Process the transaction's meta and validate the various
                                // data structures. Seed the accounts, alternate tx hashes,
                                // logs, balance inputs first
                                // pub log_messages: Option<Vec<String>>,
                                let tlt_pool = tmt_pool.clone();
                                let tlt_txm = tx_meta.clone();
                                let tlt_tx = tx.clone();
                                let transaction_log_task = async move {
                                    if let Some(log_messages) = &tlt_txm.log_messages {
                                        let transaction_logs =
                                            log_messages.into_par_iter().enumerate()
                                                .map(|(idx, log_msg)| {
                                                    InsertableTransactionLog {
                                                        transaction_hash: tlt_tx.hash.clone(),
                                                        data: log_msg.clone(),
                                                        line: idx as i32,
                                                        timestamp: tlt_tx.timestamp.clone()
                                                    }
                                                })
                                                .collect::<Vec<InsertableTransactionLog>>();

                                        let tl_result = crate::actions::transaction_logs::batch_create(
                                            &*tlt_pool.get().unwrap(),
                                            transaction_logs.as_slice()
                                        );

                                        if let Err(err) = tl_result {
                                            eprintln!("[processors/transaction] WARN: Problem pushing \
                                    transaction logs for tx {} due to {}", tlt_tx.hash.clone(),
                                                      err.to_string());
                                        }
                                    }
                                };
                                let tlt_handle = tm_thread_pool
                                    .spawn_with_handle(transaction_log_task)
                                    .unwrap();

                                // Gather and seed all account inputs
                                let ait_pool = tmt_pool.clone();
                                let ait_txm = tx_meta.clone();
                                let ait_tx = tx.clone();
                                let ait_dtx = decoded_tx.clone();
                                let account_inputs_task = async move {
                                    let account_inputs: Vec<InsertableAccountInput> = (0..ait_dtx.message.account_keys.len())
                                        .into_par_iter()
                                        .map(|i| {
                                            let current_account_hash =
                                                ait_dtx.message.account_keys[i].clone().to_string();

                                            InsertableAccountInput {
                                                transaction_hash: ait_tx.hash.clone(),
                                                account: current_account_hash.to_string(),
                                                token_id: "".to_string(),
                                                pre_balance: (ait_txm.pre_balances[i] as i64),
                                                post_balance: Option::from(ait_txm.post_balances[i] as i64),
                                                timestamp: block.timestamp.clone()
                                            }
                                        }).collect();

                                    let result = crate::actions::account_inputs::batch_create(
                                        &*ait_pool.get().unwrap(),
                                        account_inputs);

                                    if let Err(error) = result {
                                        eprintln!("[processors/transaction] FATAL: Problem indexing \
                                    account inputs for tx {} due to {}", ait_tx.hash.clone(),
                                                  error.to_string());
                                    }
                                };
                                let ait_handle = tm_thread_pool
                                    .spawn_with_handle(account_inputs_task)
                                    .unwrap();

                                // If there are token balances for this transaction
                                // pub pre_token_balances: Option<Vec<UiTransactionTokenBalance>>,
                                // pub post_token_balances: Option<Vec<UiTransactionTokenBalance>>,
                                let tai_pool = tmt_pool.clone();
                                let tai_txm = tx_meta.clone();
                                let tai_tx = tx.clone();
                                let tai_block = tmt_block.clone();
                                let tai_dtx = decoded_tx.clone();
                                let token_account_inputs_task = async move {
                                    if let (Some(pre_token_balances),
                                        Some(post_token_balances)) =
                                    (tai_txm.pre_token_balances, tai_txm.post_token_balances)
                                    {
                                        super::account_input::process_token_account_inputs(
                                            &tai_pool,
                                            &tai_tx.hash,
                                            &pre_token_balances,
                                            &post_token_balances,
                                            &tai_dtx.message.account_keys,
                                            &tai_block.timestamp,
                                        ).await;
                                    }
                                };
                                let tai_handle = tm_thread_pool
                                    .spawn_with_handle(token_account_inputs_task)
                                    .unwrap();

                                let iit_pool = tmt_pool.clone();
                                let iit_dtx = decoded_tx.clone();
                                let iit_txm = tx_meta.clone();
                                let iit_tx = tx.clone();
                                let inner_instructions_task = async move {
                                    if let Some(inner_instructions) = iit_txm.inner_instructions {
                                        crate::processors::inner_instruction::process(&iit_pool,
                                                                                inner_instructions.as_slice(),
                                                                                &iit_dtx, &iit_tx,
                                                                                iit_dtx.message.account_keys.as_slice())
                                            .await;
                                    }
                                };
                                let iit_handle = tm_thread_pool
                                    .spawn_with_handle(inner_instructions_task)
                                    .unwrap();

                                let tasks_future = future::join_all(vec![tlt_handle, ait_handle, tai_handle, iit_handle]);
                                tasks_future.await;

                                // Update the tx's metadata and proceed with instructions processing
                                let update_result =
                                    crate::actions::transactions::update(&*tmt_pool.get().unwrap(), &tx);

                                if let Err(update_err) = update_result {
                                        eprintln!(
                                            "[blockchain_syncer] FATAL: Problem updating tx: {}",
                                            update_err
                                        );
                                    }
                            } else {
                                eprintln!(
                                    "[processors/transaction] WARN: tx {} has no metadata!",
                                    tx.hash
                                );
                            }
                        };
                        let tmt_handle = thread_pool
                            .spawn_with_handle(tx_meta_task)
                            .unwrap();

                        let future_batch =
                            future::join_all(vec![at_handle, it_handle, tst_handle, tmt_handle]);

                        future_batch.await;
                    } else {
                        let tx_err = tx_res.err();

                        if let Some(err) = tx_err {
                            eprintln!(
                                "[blockchain_syncer] WARN: Problem pushing tx {} to DB \
                            due to: {}",
                                tx.hash, err
                            )
                        } else {
                            eprintln!(
                                "[blockchain_syncer] FATAL: Problem pushing tx {} to DB \
                            due to an unknown error",
                                tx.hash
                            );
                        }
                    }
                } else {
                    eprintln!(
                        "[blockchain_syncer] FATAL: a transaction in block {} has no hashes!",
                        &block.number
                    );
                }
            } else {
                eprintln!(
                    "[blockchain_syncer] FATAL: Unable to obtain \
                                    account information vec from chain for tx {}",
                    &tx.hash
                );
            }
        })
    })
    .collect();

future::join_all(tasks).await;


text:
Q: Efficient (Space) Serialization for Network Transfer I am attempting to write some infrastructure to facilitate updating objects between a server and client(s). This will likely be used in a game, however, I feel that the question is not at all specific to the game (so I have asked it here).
For security and efficiency reasons I would like the server to selectively update object properties. For example, a specific property of an object may only be useful to the client which controls that object, as such the server will only update the 'owner' with this information. Alternatively, some properties may need to be sent to all clients. To implement this I have defined a custom attribute which specifies the manner in which the network should handle the property:
    [AttributeUsage(AttributeTargets.Property)]
    public class NetworkParameterAttribute : System.Attribute
    {
        public enum NetworkParameterType
        {
            ServerToOwner,
            ServerToAll,
            ServerToOwnerView,
            OwnerToServer
        }

        private NetworkParameterType type;
        public NetworkParameterType Type
        {
            get
            {
                return type;
            }
        }

        public NetworkParameterAttribute(NetworkParameterType Type)
        {
            this.type = Type;
        }
    }

Now in an object class I can define properties like so:
    public class TestObject
    {
        [NetworkParameter(NetworkParameterAttribute.NetworkParameterType.ServerToAll)]
        public int ID { get; set; }

        [NetworkParameter(NetworkParameterAttribute.NetworkParameterType.ServerToOwner)]
        public string Name { get; set; }
    }

I can then write a simple function which automatically grabs a certain set of properties from an object:
    public byte[] GetBytes(NetworkParameterAttribute.NetworkParameterType type)
    {
        MemoryStream stream = new MemoryStream();
        BinaryFormatter formatter = new BinaryFormatter();
        foreach (PropertyInfo info in this.GetType().GetProperties())
        {
            foreach (object attribute in info.GetCustomAttributes(true))
            {
                if (attribute is NetworkParameterAttribute &&
                    ((NetworkParameterAttribute)attribute).Type == type)
                {
                    formatter.Serialize(stream, info.GetValue(this, null));
                }
            }
        }
        byte[] buf = new byte[stream.Length];
        Array.Copy(stream.GetBuffer(), buf, stream.Length);
        return buf;
    }

A similar function can put the object back together on the receiving side. The issue that I am having is that the serialization is very inefficient in terms of space used. For example, grabbing the ServerToAll properties from a TestObject results in 54 bytes (whereas it could be as little as 4).
So the question: Is there a more efficient way of serializing objects to a byte stream that will work for my intended purpose? Note that I would prefer not to write a lot of serialization related code.
Thank you!

A: NetworkParameterAttribute should have additional field that denotes the corresponding property as "dirty". Every change to a property should effectively set this flag, and during serialization the flag should be reset. Only dirty properties should actually be serialized.
Additionally, now that the object is only partially serialized, during serialization now you need to provide the information about what properties are being serialized. Maintain one bitvector of dirty properties while you populate the stream, and put this bitvector in the beginning of returned byte array.
EDIT: Instead of having a flag inside an attribute we can have the actual value that was serialized last. The advantage is that we don't need additional code for each property to keep the flag synchronized with the property. During serialization we compare two values and serialize property if the values are not equal.


text:
Q: How do I import in a spring xml conditionally How Do I import in a Spring based on contexts.
What i am looking for is something like
<import context = "x" resource="x.xml"/>
<import context = "y" resource="y.xml"/>

which is basically importing x or y based on some conditions.
I am using Spring 2.5.6


text:
Q: R, Cumulative Sum in Reverse Let's say we have two tables:
A table of budgets:
Item    Budget
A       900
B       350
C       100
D       0

bDT = structure(list(Item = c("A", "B", "C", "D"), Budget = c(900L,
350L, 100L, 0L)), .Names = c("Item", "Budget"), row.names = c(NA,
-4L), class = "data.frame")

and a table of expected expenses by item per date.
 Item       Date Expense
    A 2017-08-24     850
    B 2017-08-18     300
    B 2017-08-11      50
    C 2017-08-18      50
    C 2017-08-11     100
    D 2017-08-01     500

expDF = structure(list(Item = c("A", "B", "B", "C", "C", "D"), Date = structure(c(17402,
17396, 17389, 17396, 17389, 17379), class = "Date"), Expense = c(850L,
300L, 50L, 50L, 100L, 500L)), .Names = c("Item", "Date", "Expense"
), row.names = c(NA, -6L), class = "data.frame")

I'm looking to summarize the amount we can spend per item per date like this:
Item    Date        Spend
A       8/24/2017   850
B       8/18/2017   300
B       8/11/2017   50
C       8/18/2017   50
C       8/11/2017   50
D       8/1/2017    0

A: This works:
library(data.table)
setDT(bDF); setDT(expDF)

expDF[bDF, on=.(Item), Spending :=
  pmin(
    Expense,
    pmax(
      0,
      Budget - cumsum(shift(Expense, fill=0))
    )
  )
, by=.EACHI]

   Item       Date Expense Spending
1:    A 2017-08-24     850      850
2:    B 2017-08-18     300      300
3:    B 2017-08-11      50       50
4:    C 2017-08-18      50       50
5:    C 2017-08-11     100       50
6:    D 2017-08-01     500        0

How it works

*

*cumsum(shift(Expense, fill = 0)) is prior spending**

*max(0, Budget - prior spending) is remaining budget

*min(Expense, remaining budget) is current spending

The data.table syntax x[i, on=, j, by=.EACHI] is a join. In this case j takes the form v := expr, which adds a new column to x. See ?data.table for details.

** Well, "prior" in ordering of the table. I'll ignore the OP's weird reversed dates.