text:
Q: How to disable field when type value equal Here i am having two form fields

*

*Property Type

*Bedroom

My requirement is Property Type Plot/Site/Land is checked means  Bedroom i want to make unchecked and disable suppose  Plot/Site/Land means again i want to do enable the bedroom field how can do this

$(function() {
  $("input[name=propertyType]").change(function() {
    var propertyType = $(this).val();
    if(propertyType == 7){
      $("input[name=unitType]").prop("disabled", true);
    }else{
      $("input[name=unitType]").prop("disabled", false);
    }
  });
});

Property Type :
<fieldset>
    <input type="checkbox" name="propertyType" value="4"> Apartment
    <input type="checkbox" name="propertyType" value="7"> Plot/Site/Land
</fieldset>

Bedroom:

<fieldset>
    <input value="1 Room/Hall" name="unitType" type="checkbox">1 Room/Hall
    <input value="1 RK" name="unitType" type="checkbox">1 RK
</fieldset>

A: Since you are only interested in the change event of value = "7", you need to change the selector to
var $value7 = $("input[name='propertyType'][value='7']");
$value7.change(function() {
  $("input[name='unitType']").prop( "disabled",  !$(this ).prop( "checked" ) );
});

$("input[name='unitType']").prop( "disabled",  !$value7.prop( "checked" ) );

And remove myFunction call from everywhere else.
Demo

var $value7 = $("input[name='propertyType'][value='7']");
$value7.change(function() {
  $("input[name='unitType']").prop( "disabled",  !$(this ).prop( "checked" ) );
});

$("input[name='unitType']").prop( "disabled",  !$value7.prop( "checked" ) );

Property Type :

<fieldset class="checkboxes">
  <input type="checkbox" name="propertyType" value="4"> Apartment
  <input type="checkbox" name="propertyType" value="5"> Independent House/ Villa
  <input type="checkbox" name="propertyType" value="6"> Individual House/ Standalone Building
  <input type="checkbox" name="propertyType" value="7"> Plot/Site/Land
</fieldset>

Bedroom:

<input value="1 Room/Hall" name="unitType" type="checkbox">1 Room/Hall

<input value="1 RK" name="unitType" type="checkbox">1 RK

<input value="1 BHK" name="unitType" type="checkbox">1 BHK

<input value="2 BHK" name="unitType" type="checkbox">2 BHK

<input value="3 BHK" name="unitType" type="checkbox">3 BHK

<input value="4 BHK" name="unitType" type="checkbox">4 BHK

<input value="4+ BHK" name="unitType" type="checkbox">4+ BHK

A: You need to use change listener and target your Plot/Site/Land input. This should give you a nice start.

$(function() {

  $("input[value='7']").change(function() {
    $("input[name=unitType]").prop("checked", false);
  });

});

  <input type="checkbox" name="propertyType" value="5" onclick="myFunction()"> Independent House/ Villa

  <input type="checkbox" name="propertyType" value="6" onclick="myFunction()"> Individual House/ Standalone Building

  <input type="checkbox" name="propertyType" value="7" onclick="myFunction()"> Plot/Site/Land
</fieldset>

Bedroom:

<input value="1 Room/Hall" name="unitType" type="checkbox" onclick="myFunction()">1 Room/Hall

<input value="1 RK" name="unitType" type="checkbox" onclick="myFunction()">1 RK

<input value="1 BHK" name="unitType" type="checkbox" onclick="myFunction()">1 BHK

<input value="2 BHK" name="unitType" type="checkbox" onclick="myFunction()">2 BHK

<input value="3 BHK" name="unitType" type="checkbox" onclick="myFunction()">3 BHK

<input value="4 BHK" name="unitType" type="checkbox" onclick="myFunction()">4 BHK

<input value="4+ BHK" name="unitType" type="checkbox" onclick="myFunction()">4+ BHK

A: Use a radiobutton instead
This is what a radiobutton is designed for. When given the same name, you can only select one:
<fieldset>
    <input type="radio" name="propertyType" value="4"> Apartment
    <input type="radio" name="propertyType" value="7"> Plot/Site/Land
</fieldset>

This required no Javascript and users are familiar with radiobuttons so expected behaviour (you can choose one, a checkbox suggests multiple).

A:

$(function() {
  $("input[name=propertyType]").change(function() {
    var propertyType = $(this).val();
    if(propertyType == 7 && $(this). prop("checked")){
      $("input[name='propertyType'][value!='7']").prop("checked",false);
      $("input[name='unitType']").prop("checked",false);
      $("input[name=unitType]").prop("disabled", true);
    }else{
      $("input[name='propertyType'][value='7']").prop("checked",false);
      $("input[name=unitType]").prop("disabled", false);
    }
  });
});

Property Type :
<fieldset>
    <input type="checkbox" name="propertyType" value="4"> Apartment
    <input type="checkbox" name="propertyType" value="7"> Plot/Site/Land
</fieldset>

Bedroom:

<fieldset>
    <input value="1 Room/Hall" name="unitType" type="checkbox">1 Room/Hall
    <input value="1 RK" name="unitType" type="checkbox">1 RK
</fieldset>


text:
Q: Display results if null or not. SQL I have two tables, ingredient and ingredient_language.
I need to display (from SQL) all translations of each ingredient, and in case that I did not have any translations for some language, in the rows have to appear like this, for example:
Language | Ingredient
ENG        Salt
GER        NULL

How can I display it?
The structure of the tables are
Ingredient{id_ingredient}
Ingredient_Language{id_ingredient, id_language, traduction}

Thanks.
EDIT:
SELECT i.id_ingredient, l.id_language, l.trad
FROM Ingredient i
  LEFT OUTER JOIN Ingredient_language l ON l.id_ingredient = i.id_ingredient

Okey, the structure are:
·Table 1 (Ingredient) > Columns: Id_ingredient (PK), standard_name
·Table 2 (Language) > Columns: ID_Language (PK), name_language
·Table 3 (Ingredient_Language) > Columns: ID_Ingredient_Language (PK),ID_ingredient (FK), ID_LANGUAGE(FK), description

Example of data (Can not do any screen at this moment):
 ·Table 1: 01, Orange
 ·Table 2: SP, SPANISH
           ENG, ENGLISH
 ·Table 3: 01, 01, SP, Naranja

What I need to get? The following example:
Header: id_language, id_ingredient, description
Row1:      SP            01            NARANJA
Row2:      ENG           01              NULL

Thanks for the help.

A: SELECT l.traduction,l.id_language,i.id_ingredient
FROM Ingredient_Language AS l
  LEFT OUTER JOIN Ingredient AS i ON l.id_ingredient = i.id_ingredient

Just change the SELECT part to your needs.
Just a guess, you might actually wanna begin the join from your language table like
SELECT l.id_language,i.id_ingredient
FROM Language l
  LEFT OUTER JOIN Ingredient_Language il ON l.id_language = il.id_language
  LEFT OUTER JOIN Ingredient i ON li.id_ingredient = i.id_ingredient

A: You want to start with a cross join, which combines every ingredient with every language:
SELECT i.id_ingredient, l.id_language, il.trad
FROM Ingredient i
CROSS JOIN Language l

and add all existing translations to that with
LEFT JOIN Ingredient_language il
   ON  il.id_ingredient = i.id_ingredient
   AND il.id_language = l.id_language

if you have a database which does not support CROSS JOIN you can try
SELECT i.id_ingredient, l.id_language, il.trad
FROM Ingredient i
JOIN Language l ON 1=1
LEFT JOIN Ingredient_language il
   ON  il.id_ingredient = i.id_ingredient
   AND il.id_language = l.id_language

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to clean node_modules folder when prepping for deployment How would I go about cleaning the node_modules folder when prepping my code for deployment.
I am making an app using node-webkit and would prefer to include the least amount of files possible when bundling the final version of the app as the unzip process takes some time.
I've looked at npm dedupe and use npm install --production to get rid of duplicates and fetch only production files, however I am still left with Readme files, benchmarks, tests and build files which I don't need.
What I would like to end up with for each module in the node_modules folder is a LICENSE file if it exists, the package.json and anything else that I need for the module to run, but nothing more.
The question: How to automatically clean a node_modules directory for a SCM commit was heading somewhat in the same direction, but it is talking about committing so not really what I am looking for.
The question: NPM clean modules again was somewhat along the same lines as mine, but not quite fully there.
This answer helps as it is more efficient version for dedupe for bundling the final app.
Update
I tried the custom module linked from here but it didn't seem to work correctly, even after some fiddling about.
With all that said, I haven't quite found the right answer yet.

Here's an example of what I am looking for.
In my project I currently have two dependencies: socket.io and socket.io-client.
Together they make up 15 MB with 550 files in 110 folders.
Manually cleaning readme, makefile, VC++ build files such as .pdb and .obj and other unnecessary files I was able to shrink it down to 2.74 MB with 265 files in 73 folders.
This is with just two modules.
I would like to find out if there is a way to do this automatically, preferably with npm.

A: This module attempts to intelligently cleanup the node_modules folder:
modclean
Install:
npm install modclean -g

or
npm install modclean --save-dev

Usage:
modclean

It uses a set of default patterns to remove unnecessary bloat from modules throughout the dependency tree.

A: Well cleaning the node_modules for the deployment for a webkit application, its kind of difficult, because of the modules inside node_modules directory are installed with or without test files other misc files and so, if the owner of the module, has declared an .npmignore file with dir/files such as tests or examples those will be excluded from packaging process when the owner publishes his module, but it will exist in the repository (git) as normal.

Exclude test code in npm package?
the above is left in module owners hands, if he/she "forgets" to make one, then package will contain pretty much everything.

Note that since you don't use the development package of socket.io or socket.io-client it doesn't mean you have to npm install socket.io --save-dev, a simple npm install socket.io -V would install the production package as it was uploaded by its owner.

A possible workaround would be to make a grunt task, to clean your entire node_modules as you would like it to be.

a couple of rules would be

*

*test or tests directory or *test*.js files

*build directories (not sure about it might contain some binaries sometimes that are necessary)

*history.md
GruntJS

Hope i helped somehow, also take a look at Tilemill and how they deploy their application.

A: Maybe you are interested in this little find command, which I've assembled over time. Please be aware, that this is not a "one-size-fits-all" solution! You need to check it very carefully against your requirements. It is intended for node.js environments and will definitely destroy browser environments. I run in a bash script as a postinstall script in npm.
DO NOT BLINDLY COPY 'N PASTE. You have been warned!
find node_modules \( \( -name "dist" -or -name "ts" -or -name "logos" -or -name "min" -or -name "test*" -or -name "doc*" -or -name "tst" -or -name "example*" -or -name "build" -or -name "man" -or -name "benchmark*" \) -and -type d \) -or \
   \( \( -iname "readme*" -or -iname "changelog*" -or -iname "notice*" -or -iname "test*.js" -or -iname "*.min.js" \) -and -type f \) -or \
   \( -path "*moment-timezone/data/unpacked*" -and -type d \)

To be sure, I've not added the final line | xargs rm -rf. You can safely execute the above command without deleting anything and later add the pipe to xargs with rm to make it really happen.
What does the find command do? I'll explain it pattern by pattern.

*

*\( \( -name "dist" -or -name "ts" -or -name "logos" -or -name "min" -or -name "test*" -or -name "doc*" -or -name "tst" -or -name "example*" -or -name "build" -or -name "man" -or -name "benchmark*" \) -and -type d \) => search for directories that match on the text in the quotes. The * is a wildcard.

*\( \( -iname "readme*" -or -iname "changelog*" -or -iname "notice*" -or -iname "test*.js" -or -iname "*.min.js" \) -and -type f \) => search for files in any folder where the text in the quotes matches regardless of the case. Especially the pattern "*.min.js" could be dangerous for some people.

*\( -path "*moment-timezone/data/unpacked*" -and -type d \) => remove the unpacked data from moment. This also saves plenty of space.
Feel free to improve this!

A: Modules installed with NPM should never contain development files (i.e. benchmarks, tests etc.). If they are included you should contact the module maintainer and ask to have them added to .npmignore.
Note: Development files in this case means the files that are needed for development of the actual module and not your application.
It's been suggested before, but having a deploy task in grunt is probably a good idea. Just make sure to test the application after the cleanup. grunt-contrib-clean is great for cleaning.
See .npmignore from connect for some ideas on which files/directories that shouldn't be in a production package.

A: I was looking into this for deploying to AWS's elasticbeanstalk. When I run the eb deploy command it was magically finding what files to upload and it wasn't getting any of the bower_components or node_modules. I wondered how.
It turns out that eb deploy invokes git archive under the hood. git archive checks out the branch you specify and makes a zip of all the files.
Presumably you don't commit things like your node_modules or bower_components directories to git, so git archive might be a solution to your problem. If you want to avoid things like test cases and README files and so on, you might still need to do some tagging in git. But you're starting at a substantially smaller list and you're obviously excluding the bulk of the stuff you want to exclude.

A: I think you're looking for npm prune

npm prune [<name> [<name ...]]
This command removes "extraneous" packages. If a package name is
  provided, then only packages matching one of the supplied names are
  removed.
Extraneous packages are packages that are not listed on the parent
  package's dependencies list.

Documentation https://docs.npmjs.com/cli/prune


text:
Q: substrn in Crystal report and Oracle SQl I am working on crystal report and Oracle SQL developer.
I have a field, Birthdate like 01-JAN-92 and I want to extract the year in numerical form.
92 in the case above.
I used substr("p.Birthdate",8,2) function to extract 92 and it works fine in oracle sql,
but when I copy the query from Oracle to Crystal Report, no data is coming in Crystal Report.
I tried MID function too, and Oracle SQL developer, Crystal Report just don't recognise the mid function.

A: You could use a simple TO_CHAR("p.Birthdate",'YYYY')
if you want the year with just two digits, that would be better TO_CHAR("p.Birthdate",'RR')


text:
Q: Cannot access variable in innerclass : Android Studio The goal from my projects is to assign which number that represents checkbox that checked into the empty array.
int [] mChecked = new int []{};

I tried to make a loop which checkbox number is clicked to and assign mCheked array to new value the number corresponds to the checkbox number, when I tried it failed to access variable in inner class. In android studio you must create new variable final int FinalI = i; to track the code, but if its final you cannot reassign the value.
This is the part of code that error.
 for(int i=0 ; i < arrayCheck.length ; i++)
    {

        arrayCheck[i].setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

               mChecked[i] = i+1;

            }
        });
    }

especially on this line
mChecked[i] = i+1;

image of error part
This is the full code
  package com.okssaami.myapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;

public class MainActivity extends AppCompatActivity {

    CheckBox G1, G2, G3, G4, G5, G6, G7, G8, G9, G10, G11, G12, G13, G14, G15,
            G16, G17, G18, G19, G20, G21, G22, G23, G24, G25, G26, G27, G28, G29, G30,
            G31, G32, G33, G34;
    Button Submit;

    int [] mChecked = new int []{};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        int [] ids = new int [] {
                R.id.G1,
                R.id.G2,
                R.id.G3,
                R.id.G4,
                R.id.G5,
                R.id.G6,
                R.id.G7,
                R.id.G8,
                R.id.G9,
                R.id.G10,
                R.id.G11,
                R.id.G12,
                R.id.G13,
                R.id.G14,
                R.id.G15,
                R.id.G16,
                R.id.G17,
                R.id.G18,
                R.id.G19,
                R.id.G20,
                R.id.G21,
                R.id.G22,
                R.id.G23,
                R.id.G24,
                R.id.G25,
                R.id.G26,
                R.id.G27,
                R.id.G28,
                R.id.G29,
                R.id.G30,
                R.id.G31,
                R.id.G32,
                R.id.G33,
                R.id.G34
        };

        final CheckBox [] arrayCheck = new CheckBox[ids.length];

        for(int i=0 ; i < arrayCheck.length ; i++)
        {
            arrayCheck[i] = (CheckBox) findViewById(ids[i]);
        }

        for(int i=0 ; i < arrayCheck.length ; i++)
        {

            arrayCheck[i].setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                   mChecked[i] = i+1;

                }
            });
        }

    }

}

A: This is the result of your variable i being declared on the stack and then you try to use it after the stack is gone in an inner class (the compiler identifies that and tells you to use a final variable so it can use it inside the inner class). To understand exactly what you are doing wrong, you can have a look at this article.
Try this:
for(int i=0 ; i < arrayCheck.length ; i++)
{
    final int value = i;
    arrayCheck[i].setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

           mChecked[value] = value+1;

        }
    });
}

A: You are getting this error because you can't access a variable of a class, from its inner class if it is not final

Local classes can most definitely reference instance variables. The reason they cannot reference non final local variables is because the local class instance can remain in memory after the method returns. When the method returns the local variables go out of scope, so a copy of them is needed. If the variables weren't final then the copy of the variable in the method could change, while the copy in the local class didn't, so they'd be out of synch.

See this article for detailed explanation why is that.

A: This can be done like this:
 for(int i=0 ; i < arrayCheck.length ; i++)
    {
        arrayCheck[i].setTag(i);
        arrayCheck[i].setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
              int position= Integer.parseInt(buttonView.getTag().toString());
              mChecked[position] = position+1;

            }
        });
    }

but it will add value to mChecked on checked and unchecked of checkbox.


text:
Q: How use ng-view inside ng-view? I have main ng-view, and controller with left\right side. The right side is fixed, but left side I want change by other templates and controllers.
http://plnkr.co/edit/MTxmmZWRY7O0nH88qK3F

  Choose:
  Moby |
  Moby: Ch1 |
  Gatsby |
  Gatsby: Ch4 |
  Scarlet Letter

$location.path() = {{main.$location.path()}}

$route.current.templateUrl = {{main.$route.current.templateUrl}}

$route.current.params = {{main.$route.current.params}}

$routeParams = {{main.$routeParams}}

A: I used a solution derived from here: http://www.bennadel.com/blog/2420-Mapping-AngularJS-Routes-Onto-URL-Parameters-And-Client-Side-Events.htm
Allowing me to effectively nest views (and skipping the limited ng-view altogether)
After doing so, this other (simpler, better, I believe) solution appeared:
http://angular-ui.github.com/ (scroll down to "Route Checking")

A: You can not. Just use https://github.com/angular-ui/ui-router for that. It allows using nested views.


text:
Q: ColdFusion memory usage for Components I am creating a site using VMC and using beans to transfer the data from the Model to the Controller/Views.
I plan to implement some basic and very simple caching that will store the beans in a simple struct if they have not changed (as usage grows, we will implement a better caching system around ver 1.3).
So the question goes to what goes in our bean.
One type of bean would only hold the basic data and would rely on some outside service to do the rest of the work (contacting the DAO to get the query, parsing the query to load the bean values). This is the "anemic bean" model as I have been told repeatedly by a co-worker :-).
Another type of bean would be more self-contained. It would know where the DAO is so would call the DAO directly to get the data query. It would contain necessary functions to parse out the query and set the properties. It would basically combine much of the "service" layer with the bean, leaving the direct database in the DAO layer.
Of course, to the controller/views, both beans would look and act the same.
But the question is memory and how ColdFusion/Java deals with it.
With the anemic model, the bean would just have enough memory to hold the property variables with just a touch more to let it point to the Service when it needs to.
With the heavier functions in the second type bean, would it take up more memory in the cache??? Would each copy of the bean have a full copy of the methods?
I tend to think that the second model would not have much more memory since they would "share" the methods and would only need memory for the property variables.
IMHO the second method would simplify the codebase, since the code the bean needs would be closer to the bean rather than scattered between the DAO and Services. And it would reduce simple functions in the Service that merely pass along calls to the DAO of the bean could go directly to the DAO when it needed it...
Does the question make sense?? Or at least how I am asking it?

A: All the memory management is handed at Java level, so it follows the same rules. In Java the only "new" memory that's allocated when an object instance is created is for its member variables; there is not memory foot print for the methods of the component/class itself: that stuff is only stored in memory once, with a reference back to it.
One possible consideration is that each method of a CFC is compiled as its own discrete class (why? I don't know), so each method is its own class. This will perhaps mean a slightly larger memory footprint for CFC usage compared to Java class usage, but this will still not be something that scales with object-instantiation: each instance of an object will still just consume memory for its member variables, not the methods of the CFC that defines the object.

A: all cfm pages are compiled to memory by default, a CFC needs to implicitly be stored in memory (application scope for example) in order to avoid instantiating it each time, however you do it requires the same memory for the same component, any additional usage will depend on any data you are storing within your component or bean.
Have you had a look at ColdSpring ?


text:
Q: Can I use backgroundWorker after calling hide method in VB.NET I have a simple question about Background worker. I have never used it so I have no Idea about how it works.
I am using VB.NET express 2010.
All I want to do a database monitoring in a form's backgroundWorker.
Here are few things I am trying to achieve.

*

*Monitoring SQLite DB file with select statement.

*Extracting Data from DB and put them into variables.

*Compare values with certain conditions and if something matches, pass values to another form and call it.

*Keep on monitoring.

*I want background worker to do this when form's form.hide() method is called.

Please give your valuable response and if i't not the correct way, please suggest another one so.

A: Hiding the form will not stop the background worker - in fact closing the form will not stop it - the form will wait for the background worker isBusy property to report false before continuing.

Update in Response to new comment
You'd probably be best using a timer and offloading the other work to a new thread, see example below. If the operation hasn't completed then the If _worker is nothing will stop the operation from being restarted. Be sure to set _worker = nothing at the end of your process for this to work though.
Also I've just typed this up quickly, it may not work out of the box but should give you a starting point.
Imports System.Threading

Public Class Form1

    Dim _worker As Thread

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        Timer1.Interval = 10000
        'interval in milliseconds so 1000ms = 1 second / above 10000 = 10 seconds

        Timer1.Enabled = True
        Timer1.Start()

    End Sub

    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        StartWorkerThread()
    End Sub

    Private Sub StartWorkerThread()

        If _worker Is Nothing Then
            _worker = New Thread(AddressOf myWorker)
            _worker.Start()

        End If

    End Sub

    Private Sub myWorker()
        'do your work here...use an event or a delate to fire another sub/function on the main thread if required

            'when finished
            _worker = nothing
            'Important! This will allow the operation to be started again on the timer tick
        End Sub

    End Class


text:
Q: Ajax auto search in codeigniter code did not works Controller code:
public function auto_search() {

    $search_data = $this->input->post('search_data');
    //print_r($search_data);  die();
    $query = $this->search_model->autocomplete($search_data);
    print_r($query);  die();

    foreach ($query->result() as $row):
        echo $row->uid  ;
        echo  $row->name ;
    endforeach;
}

The javascript:
<script type="text/javascript" src="js/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
    function ajaxSearch() {

        var input_data = $('#search_data').val();

        $.ajax({
              type: "POST",
              url: "/search/auto_search",
              data: {search_data:input_data},
              success: function(data1) {
              alert(data1);

                if (data1.length > 0) {
                   $('#suggestions').show();
                   $('#autoSuggestionsList').addClass('auto_list');
                   $('#autoSuggestionsList').html(data1);
                }
              }
          });
    }
</script>

In controller when i print the search_data that is print_r($search_data); die(); i did not get any result.
I think ajax call is not get  in to the controller   Please provide solution for this
Moreover, when I echo out the query in controller that is print_r($query) ; I did not get any result. Also autosearch is not working. Please provide solution for this.

A: I think it is ajaxSearch function not runing.
your try
public function auto_search()
{

    $search_data = $this->input->post('search_data');
    $query = $this->search_model->autocomplete($search_data);

    if (!empty($query)) {
        foreach ($query->result() as $row) {
            echo $row->uid;
            echo $row->name;
        }
    } else {
        echo '';
    }
}

<script type="text/javascript" src="js/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
    $(function () {
        function ajaxSearch() {

            var input_data = $('#search_data').val();

            $.ajax({
                type: "POST",
                url: "/search/auto_search",
                data: {search_data: input_data},
                success: function (data1) {
                    alert(data1);

                    if (data1.length > 0) {
                        $('#suggestions').show();
                        $('#autoSuggestionsList').addClass('auto_list');
                        $('#autoSuggestionsList').html(data1);
                    }
                }
            });
        }

        // start ajaxSearch
        ajaxSearch();
    });

</script>

Thank you

A: You need to pass all ur data into array and then convert it into json_encode for more referrence about encoding -> http://php.net/manual/en/function.json-encode.php..
here is sample code for you.
public function auto_search() {

    $search_data = $this->input->post('search_data');
    //print_r($search_data);  die();
    $query = $this->search_model->autocomplete($search_data);
    //print_r($query);  die(); <- you should replace the die.

    $myArray = [];
    foreach ($query->result() as $key => $row):
        $myArray['keyname'] = $row->uid;
        $myArray['keyname1'] = $row->name;
    endforeach;

  //data retrieves by jquery
  echo json_encode($myArray);

}

In you jquery.
$.ajax({
          type: "POST",
          url: "/search/auto_search",
          data: {search_data:input_data},
          success: function(data1) {
          console.log(data1);
          console.log(data1.keyname);
          console.log(data1.keyname1);

            if (data1.length > 0) {
               $('#suggestions').show();
               $('#autoSuggestionsList').addClass('auto_list');
               $('#autoSuggestionsList').html(data1);
            }
          }
      });

try to look at you're browser console panel. and see the retrieved data in your function and also try to check if your ajax url is correct.


text:
Q: Get in Excel current value in focused cell I'm developing an Excel add-in.
I need to get the value from A1 cell, so I use this code
value = workbook.Worksheets[1].Range["A1:A1"].Value2;

This works great but if :
- Previous Cell value is "1"
- User types "2" but does not press Enter or Tab
- User activates ribbon pressing it's button
Value2 got from this code sample is "1" (previous value) not "2" (current value shown in cell but not validated). This is wrong in my situation, I need "2".
How can I fix this?

I tried forcing selection of another cell
 Application.ActiveCell.Offset[1, 0].Select();

or
 Application.ActiveSheet.Range["A2"].Select();

but no way.. "2" value is lost.

I also tried getting value from text area in toolbar ("2" is shown there) but don't know hoe to do!

A: When Excel in in Edit Mode (Similar to pressing F2 in an Excel's cell), most of the buttons on the ribbon and the VBA Editor become inaccessible.
Having said that, Can VBA code run in Edit mode? Yes, it can as shown in THIS link
To answer your question, You will have to use API's to trap the key and then find out what the current value of the cell is. Trust me, it is not worth the pain.
Simple Alternative:
Use ExcelApp.Interactive to check for Excel's Edit mode. And if the Excel is in Edit mode then inform user to exit the cell and try again. Did a quick check on the web and found a similar example HERE See the section The correct solution for all Excel versions, 2000 – 2010
This code is in vb.net but can be easily converted to C#
Function IsEditing() As Boolean
    If ExcelApp.Interactive = False Then Return False
    Try
        ExcelApp.Interactive = False
        ExcelApp.Interactive = True
    Catch
        Return True
    End Try
    Return False
End Function

C# Code from Chat
bool IsEditing()
{
    if (Globals.ThisAddIn.Application.Interactive == false)
        return false;
        try
        {
            Globals.ThisAddIn.Application.Interactive = false;
            Globals.ThisAddIn.Application.Interactive = true;
            }
                catch (Exception e)
            {
            return true;
        }
    return false;
}


text:
Q: describe() from psych package not providing full descriptives I need the full descriptives including all the moments, but when I use describe() from psych package, it doesn't give me the options I specify, for example skew and kurtosis, but it gives me all the deciles which I haven't specified for.
Can't figure out what the issue is.  Anyone else had this issue and know how to solve?  I know I can get skew and kurtosis using skew()and kurtosis() but I want all the describes in one call, not item by item.
Here's my code:

s3desc <- describe(shrimp3s, skew = TRUE, ranges = TRUE, type = 1, quant = NULL, fast = NULL, IQR = TRUE)
s3desc

What I get is:
**>  13  Variables      95  Observations

-------------------------------------------------------------------------------------------------------------------------------------- pond.sqm
         n  missing distinct     Info     Mean      Gmd      .05      .10      .25      .50      .75      .90      .95
        95        0       42    0.986     3227     1559     1000     1000     2047     3500     4300     4560     5157
lowest :  800 1000 1100 1200 1450, highest: 5290 5400 5500 5700 5840
  --------------------------------------------------------------------------------------------------------------------------------------**

A: You have fallen into the multiple packages problem.  You are actually running the describe function from Hmisc.
Try loading the psych package and then describe(shrimp)
Or, if you need to have the Hmisc package active, specify which describe you want.
psych::describe(shrimp)


text:
Q: Remove inner nested string with RegEx I have a string that is formed from tag-substitution, which also results in parts of the string being marked for deletion, for example:
Keep1
{/*DELETE}
Delete1a
    {/*DELETE}
    Delete2
    {DELETE*/}
Delete1b
{DELETE*/}
Keep2
{/*DELETE}
Delete3
{DELETE*/}
Keep3

Am I correct that a RegEx cannot be used to select only the inner DELETE2 and DELETE3, remove those, and then repeat to get the DELETE1a/b until no further matches are found?
The RegEx I am passing to my replace function is
\{\/\*DELETE\}([\s\S]*?)\{DELETE\*\/\}

This matches
{/*DELETE}
Delete1a
    {/*DELETE}
    Delete2
    {DELETE*/}

If this is the only RegEx match that I can make I could [suppress the leading {/*DELETE} and] call the replace function recursively which, I think, would enable me to remove the nested {TAGS}
Is a better way?
I am using the RegEx in VBScript
EDIT: In case it helps I can change the {/*DELETE} and {DELETE*/} tags, even to a single character
EDIT2: I could use a single-character as the Start/End delete marker - if, for example, that would be faster for a RegEx expression to resolve e.g. by being less complex
e.g. if the Start-Delete is [ and then end delete is ]
Keep1
[
Delete1a
    [
    Delete2
    ]
Delete1b
]
Keep2
[
Delete3
]
Keep3

These characters chosen for appearance in this example, in practice they would occur within my real-world data, but I expect I could chose two ASCII values which do not appear in my data at all.
Clarification: The {DELETE} tags will not always appear on a line by themselves, so this style of string formation will also exist
Keep1{/*DELETE}Delete1a
    {/*DELETE}Delete2{DELETE*/}
Delete1b{DELETE*/}Keep2a
Keep2b{/*DELETE}Delete3{DELETE*/}Keep3

or with single-character delete-tags:
Keep1[Delete1a
    [Delete2]
Delete1b]Keep2a
Keep2b[Delete3]Keep3

A: Multicharacter delimiters
If your delimiters are multicharacter tags, you may use a tempered greedy token:
\{\/\*DELETE}((?:(?!\{\/\*DELETE})[\s\S])*?)\{DELETE\*\/}
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

that will match any char, 0+ times, that is not a starting point for a {/*DELETE} char sequence.  Run this regex replace recursively, see Iteration 1 and Iteration 2 demos.
NOTE that if you have these delimiters inside comments or string literals, this won't work correctly.
To make it safe, you may define that the delimiting tags only appear as single entities on a line:
^\s*\{\/\*DELETE}(\s*(?:\r?\n(?!\s*\{(?:\/\*DELETE|DELETE\*\/)}).*)*)\r?\n\s*\{DELETE\*\/}\s*$

See Iteration 1 and Iteration 2 demos (here, you will need to enable regExp.Multiline = True)
Single char delimiters
This is by far the easiest scenario - you may the starting delimiter char, then match any 0+ chars other than the starting and ending delimiter char using a negated character class - and then the ending delimiter char.
If the starting delimiter char is [ and the ending delimiter char is ], the regex is a well-known
\[[^\][]*\]

See the regex demo: Iteration 1 and Iteration 2.
Note that [ and ] usually are part of data you need, so perhaps, you will want to use some more fancy paired stuff, like ⦅ (2985  LEFT WHITE PARENTHESIS) and ⦆ (2986  RIGHT WHITE PARENTHESIS):
\u2985[^\u2985\u2986]*\u2986

See another regex demo.


text:
Q: object is not iterable - Django Modelform I'm using Model forms to add a row to a table in Django,
here are my views and forms file
views.py
def add_ad_mod(request):
    current_user = request.user
    current_ip = get_client_ip(request)
    selected  = Temp.objects.filter(created_by_ip=current_ip).order_by('-created_at')[0]
    selected_category = selected.cat
    selected_town = selected.town
    if request.method == 'POST':
        add_ad_mod_form = AddAdModForm(request.POST, request.FILES, cat=selected_category, loc=selected_town)
        if add_ad_mod_form.is_valid():
            model_instance = add_ad_mod_form.save(commit=False)
            model_instance.created_by = current_user.email
            model_instance.category = selected_category
            model_instance.town=selected_town
            if request.user.is_superuser:
                model_instance.is_active = True
            else:
                model_instance.is_active = False
            add_ad_mod_form.save()
            return redirect('dashboard')
    else:
        add_ad_mod_form = AddAdModForm(cat=selected_category, loc=selected_town)

    context = {
        'add_ad_mod_form': add_ad_mod_form,
        'selected_category': selected_category,
        'selected_town': selected_town,
    }
    return render(request, 'add_ad_mod.html', context)

I am using views.py to send a variable as you see to the form itself
forms.py
class AddAdModForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        current_categ = kwargs.pop('cat')
        current_loc = kwargs.pop('loc')
        super(AddAdModForm, self).__init__(*args, **kwargs)
        self.fields['sub_category'] = forms.ModelChoiceField(label="Sniffer", queryset=SubCate.objects.filter(main_category=current_categ))
        self.fields['sub_location'] = forms.ModelMultipleChoiceField (widget=forms.CheckboxSelectMultiple,label="Sniffer", queryset=SubLoc.objects.filter(main_town=current_loc))

    title = forms.CharField(
        widget=forms.TextInput(
            attrs={
                'placeholder': 'Ad Title here',
                'style': 'width: 100%; max-width: 800px;'
            }
        )
    )

    description = forms.CharField(
        widget=forms.Textarea(
            attrs={
                'placeholder': 'Ad description is here',
                'style': 'width: 100%; max-width: 800px;'
            }
        )
    )

    image = forms.ImageField(required=True)
    image2 = forms.ImageField(required=False)
    image3 = forms.ImageField(required=False)
    image4 = forms.ImageField(required=False)
    image5 = forms.ImageField(required=False)

    address = forms.CharField(max_length=100,
        widget=forms.Textarea(
            attrs={
                'placeholder': 'Detailed Address is here ',
                'style': 'width: 100%; max-width: 800px;'
            }
        )
    )

    class Meta:
        model = Item
        fields = ['title', 'sub_category', 'price', 'description', 'sub_location', 'address', 'image', 'image2', 'image3', 'image4',
                  'image5', 'phone']

And here is my models.py file:
class Category(models.Model):
    category_name = models.CharField(max_length=60)

    def __str__(self):
        return self.category_name

class Town(models.Model):
    town_name = models.CharField(max_length=300)

    def __str__(self):
        return self.town_name

class SubCate(models.Model):
    sub_category_name = models.CharField(max_length=100)
    main_category = models.ForeignKey(Category, on_delete=CASCADE)

    def __str__(self):
        return self.sub_category_name

class SubLoc(models.Model):
    sub_location_name = models.CharField(max_length=100)
    main_town = models.ForeignKey(Town, on_delete=CASCADE)

    def __str__(self):
        return self.sub_location_name

class Item(models.Model):
    category = models.ForeignKey(Category, on_delete=CASCADE)
    sub_category = models.ManyToManyField(SubCate)
    title = models.CharField(max_length=250)
    description = models.TextField(max_length=1200)
    price = models.IntegerField(default=0)
    town = models.ForeignKey(Town, on_delete=CASCADE)
    sub_location = models.ManyToManyField(SubLoc)
    address = models.TextField(max_length=100)
    image = models.ImageField(upload_to='media/', null=False, blank=False)
    image2 = models.ImageField(upload_to='media/', null=True,  blank=True)
    image3 = models.ImageField(upload_to='media/', null=True, blank=True)
    image4 = models.ImageField(upload_to='media/', null=True, blank=True)
    image5 = models.ImageField(upload_to='media/', null=True, blank=True)
    created_by = models.CharField(max_length=600)
    created_at = models.DateField(auto_now=True)
    phone = models.IntegerField(default=0)
    is_active = models.BooleanField(default=False)
    is_deleted = models.BooleanField(default=False)

    def __str__(self):
        return self.title

Despite the items is added to the database and if I reloaded my website I can see the item posted - it gives me the error instead of redirecting normally (The error is not in the page user redirected to after submitting, as I can browse into it normally )
Traceback:

File "C:\Users\lito\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py" in inner
  35.             response = get_response(request)

File "C:\Users\lito\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response
  128.                 response = self.process_exception_by_middleware(e, request)

File "C:\Users\lito\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response
  126.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\lito\Desktop\DJ\JEHLUM - Copy - Copy\web_site\views.py" in add_ad_mod
  219.             add_ad_mod_form.save()

File "C:\Users\lito\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\forms\models.py" in save
  457.             self._save_m2m()

File "C:\Users\lito\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\forms\models.py" in _save_m2m
  439.                 f.save_form_data(self.instance, cleaned_data[f.name])

File "C:\Users\lito\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\fields\related.py" in save_form_data
  1619.         getattr(instance, self.attname).set(data)

File "C:\Users\lito\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\fields\related_descriptors.py" in set
  947.             objs = tuple(objs)

Exception Type: TypeError at /add_ad/mod/
Exception Value: 'SubCate' object is not iterable

A: As I mentioned in the comments, it looks like both of these fields should be multiple choice, since they are both representing ManyToManyFields in the model.
self.fields['sub_category'] = forms.ModelMultipleChoiceField(label="Sniffer", queryset=SubCate.objects.filter(main_category=current_categ))
self.fields['sub_location'] = forms.ModelMultipleChoiceField (widget=forms.CheckboxSelectMultiple,label="Sniffer", queryset=SubLoc.objects.filter(main_town=current_loc))

Also as mentioned, you need to call save on the model instance, and save_m2m on the form:
if add_ad_mod_form.is_valid():
    model_instance = add_ad_mod_form.save(commit=False)
    ...
    model_instance.save()
    add_ad_mod_form.save_m2m()
    return redirect('dashboard')


text:
Q: I know what is the buoyancy force acting on a solid body but what is the buoyant force when the body is hollow? A empty cylindrical bucket when forced with its open end first into the water until its lower end is below the surface then what will be the buoyant force acting on it?

A: The buoyant force will be almost the same as if it was a solid body (a little lower because the air inside is compressed a bit), because of Archimedes' principle.


text:
Q: Is there a built in function to select a candle based on time? For example, I want to change the barcolor of the 12:00 pm candle.
Something like this:

barcolor(time_of_candle == 12:00pm? color.blue: na)

A: Hour and minute in exchange timezone.
barcolor(hour == 12 and minute == 00 ? color.blue: na)


text:
Q: How to create project in cocos2dx 3.0 beta? I'm trying to create project in cocos2dx 3.0 beta but command line shows error as

H:\cocos2dx\package\cocos2d-x-3.0beta\tools\project-creator>./create_project.py
  -n TestCPP -k com.san.testcpp -l cpp '.' is not recognized as an internal or external command, operable program or batch file.

Can anybody show me steps to create project in cocos2dx 3.0 .
Any help would be appreciated.
Thanx

A: From the path that you provided it seems that you are on a Windows machine, and you are trying yo start the creator "the unix way".
Do you have python installed? If so, do you have it in your PATH? Here are the general steps to get it running:

*

*Install python (I'm not sure how it is with cocos2d-x 3.0, but with previous versions you had to use python 2.x, you can try a newer version). Let's say you install it in C:\python

*[Optional] Add C:\python to your PATH system variable and restart the cmd tool.

*If you added to PATH : navigate to where you have the create_project.py and simply run python.exe create_project.py [parameters]

*If you didn't add to PATH, the above command becomes a little longer : C:\python\python.exe create_project.py [parameters]
That's it.


text:
Q: Z order column in databricks table I am working on creating a notebook which end users could run by providing the table name as input and get an efficient sample query(by utilising the partition key and Z order column). I could get the partition column with describe table or spark.catalog, but not able to find a way to get the Z order column from table metadata?
The code for getting the partition column is given below.
columns = spark.catalog.listColumns(tableName=tablename,dbName=dbname)
  partition_columns_details = list(filter(lambda c: c.isPartition , columns))
  partition_columns=[ (c.name) for c in partition_columns_details ]

A: Maybe first an important thing to know about the difference between partitioning and Z ordering. Once you partition a table on a column, this partition remains after each transaction. If you do an insert, update, optimize, ... the table will still be partitioned on that column.
This is not the case for Z ordering. If you do Z ordering on a table during an optimize, and after that you do an insert, update, ... it is possible that the data is not well structured anymore.
That being said, here is an example to find which column(s) the last Z ordering was done on:
df = spark.sql(f'DESCRIBE HISTORY {table_name}')
(df.filter(F.col('operation')=='OPTIMIZE')
   .orderBy(F.desc('timestamp'))
   .select('operationParameters.zOrderBy')
   .collect()[0].zOrderBy)

You can probably expand the code above with some extra information. E.g. where there many other transactions done after the z ordering, ...? Note that not all transactions 'destroy' the Z ordering result. VACUUM for example will be registered within the history, but does not impact Z ordering. After a small INSERT you also will probably still benefit from the Z ordering that was done before.


text:
Q: std::mutex and std::condition_variable construction overhead vs heap allocation I have a task class that I need to be movable. I have around 10-15 tasks that are contained in a task_storage parent class. Inside task::execute() I need to wait for an atomic variable to reach zero:
void task::execute()
{
    for_subtasks([this]
        {
            thread_pool.post([this]
                {
                    this->do_work();

                    // Atomic counter.
                    --(this->_remaining_subtasks);
                });
        });

    // wait for `_remaining_subtasks == 0`
}

I have thought of three alternatives to wait for _remaining_subtasks == 0 while keeping task movable:

*

*Use a while(...){ sleep(1); } busy waiting loop.

*Construct and use an std::mutex and an std::condition_variable inside the function.
void task::execute()
{
    std::mutex m;
    std::condition_variable cv;

    for_subtasks(/* ... */);

    std::unique_lock<std::mutex> l(m);
    cv.wait(l, [this]{ return this->_remaining_subtasks == 0; });
}

*Store   an std::unique_ptr<std::mutex> and an std::unique_ptr<std::condition_variable> inside task as fields. This would allow task to be movable, but also introduce indirection to access the synchronization primitives.
void task::execute()
{
    for_subtasks(/* ... */);

    std::unique_lock<std::mutex> l(*this->_m);
    this->_cv.wait(l, [this]{ return this->_remaining_subtasks == 0; });
}

I don't intend on using busy waiting. I tried profiling the fastest solution between 2 and 3 but could not get any meaningful result.
Is the construction overhead for std::mutex and std::condition_variable significant? Or would the heap allocations/accesses be slower?

A:
Is the construction overhead for std::mutex and std::condition_variable significant? Or would the heap allocations/accesses be slower?

In both cases constructors must be invoked. The difference is where the memory is allocated: static storage, stack or heap. Heap allocation is the slowest.
On Linux and POSIX compatible systems, std::mutex and std::condition_variable are thin wrappers over POSIX pthread_mutex_t and pthread_cond_t structures. Initializing these structures involves setting member variables of fundamental types and no calls. In other words, the construction is cheap.


text:
Q: How to fetch components from firebase database child? I'm trying to fetch images from firebase database storage using picasso.
The images are stored into a child labeled profileimage, when trying to fetch the images instead giving me the download url it sends back this instead com.google.android.gms.tasks.zzu@342b889
I think the error may be coming from this line of code :
String image = dataSnapshot.child("profileimage").getValue(String.class);
database structure:
"user": {
    "Exw3XA8p1lPODAi6M3muxRk6qVy1": {
      "profileimage": "com.google.android.gms.tasks.zzu@342b889",
    },

Here's the code :
userRef.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

//error occurs at the line below
 String image = dataSnapshot.child("profileimage").getValue().toString();
                       Toast.makeText(SetupActivity.this,"ImageValue! "+image,Toast.LENGTH_LONG).show();

                        Picasso.get()
                            .load("https://firebasestorage.googleapis.com/v0/b/bfitbeta-a4458.appspot.com/o/profile%20image%2FExw3XA8p1lPODAi6M3muxRk6qVy1jpg?alt=media&token=a4c2b8b4-848e-425c-b553-b334a258e2fa")
                            .fit()
                            .centerCrop()
                            .placeholder(R.drawable.profile)
                            .into(profileimage, new Callback() {
                                @Override
                                public void onSuccess() {

                                }

                                @Override
                                public void onError(Exception e) {
                                    System.out.println(e);
                                    Log.d("BFIT1", String.valueOf(e));
                                    e.printStackTrace();

                                    Toast.makeText(SetupActivity.this,"Error!",Toast.LENGTH_SHORT).show();

                                }
                            }
                            );
                }
//
                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {

                }
            });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode ==GALLARY_PICK && resultCode== RESULT_OK && data!=null)
        {
            Uri imageuri = data.getData();

            CropImage.activity(imageuri)
                    .setGuidelines(CropImageView.Guidelines.ON)
                    .setAspectRatio(1, 1)
                    .start(this);

        }

        if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
            CropImage.ActivityResult result = CropImage.getActivityResult(data);
            if (resultCode == RESULT_OK) {

                loadingbar.setTitle("saving image");
                loadingbar.setMessage("please wait ....");
                loadingbar.show();
                loadingbar.setCanceledOnTouchOutside(true);
                Uri resultUri = result.getUri();
                final StorageReference filePath = Userprofileimageref.child(currentuserid + "jpg");

                filePath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onComplete(final Task<UploadTask.TaskSnapshot> task) {

                        if (task.isSuccessful())
                        {
                            Toast.makeText(SetupActivity.this,"Profile image stored successfully",Toast.LENGTH_SHORT).show();
                            final String downloadUrl = filePath.getDownloadUrl().toString();
                            userRef.child("profileimage").setValue(downloadUrl)
                                    .addOnSuccessListener(new OnSuccessListener<Void>() {
                                        @Override
                                        public void onSuccess(Void aVoid) {
                                            if (task.isSuccessful())
                                            {
                                                Intent selfintent = new Intent(SetupActivity.this,SetupActivity.class);
                                                startActivity(selfintent);
                                                Toast.makeText(SetupActivity.this,"image saved successfully",Toast.LENGTH_SHORT).show();
                                                loadingbar.dismiss();

                                            }
                                            else
                                            {
                                                String message = task.getException().getMessage();
                                                Toast.makeText(SetupActivity.this,"Error occurred: "+ message,Toast.LENGTH_SHORT).show();
                                                loadingbar.dismiss();

                                            }

                                        }
                                    });
                        }

                    }
                });
            }else
            {
                Toast.makeText(SetupActivity.this,"image cannot be cropped",Toast.LENGTH_SHORT).show();
                loadingbar.dismiss();
            }

        }

    }

Please help!!


text:
Q: Java LinkedList problems Error :
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 3, Size: 2
    at java.util.LinkedList.checkElementIndex(LinkedList.java:553)
    at java.util.LinkedList.get(LinkedList.java:474)
    at InterfacePackage.Main.main(Main.java:116)
Java Result: 1

Code (shortened) :
if(input.length() > 0)
{
    if(command.size() == 1)
    {
        switch(command.get(0).toLowerCase())
        {
            case "exit":
            case  "qqq":
                active = false;
                break;
            default:
                System.out.println("invalid input, for complete list of commands enter 'help'...");
                break;
        }
    }
    else if(command.size() > 1)
    {
        if(command.get(0).equalsIgnoreCase("shutdown") && command.size()==3)
        {
            Shutdown shutdown = new Shutdown();
            shutdown.Start(command);
        }
        else if(((command.get(0).equalsIgnoreCase("scan")
            && command.get(1).equalsIgnoreCase("ips"))
            || command.get(3).equalsIgnoreCase("/e"))
            && (command.size()>=2 || command.size()<4))
        {
            SystemsIPs sips = new SystemsIPs();
            sips.Start(command);
        }
        else
        {
            System.out.println("invalid input, for complete list of commands enter 'help'...");
        }
    }
}

The error occurs when the users enters two string within a line that doesn't exist in the else if(command.size() > 1) loop.
For example, if the user would enter : hello world the program produces this error.
So this is a program that does various things based on user input to a console. I've been getting this error and and wanting to know what is causing it. I know I can just catch it, but I really want to know what causing this error.

A: Your error seems to be caused by
command.get(3).equalsIgnoreCase("/e"))

There is no index 3.  Check if that index exists first, before you do that.

A: You're getting an IndexOutOfBoundsException as it says, and it occurs when you're trying to access a position in a collection/array and that position is empty, you're trying to access to an index that doesnt exist. If you don't want that to happen then force the program to use an Collection with a size more than 3 element.

A: The problem is in this line:
else if(((command.get(0).equalsIgnoreCase("scan") &&
command.get(1).equalsIgnoreCase("ips")) ||
command.get(3).equalsIgnoreCase("/e")) &&
(command.size()>=2 || command.size()<4))

You are using command.get(3) to retrieve the 3rd element of the LinkedList, but it's not guaranteed that there are at least 3 elements in the list.
So you'd better add a condition command.size() >= 3 before command.get(3).

A: Ok so here is how I solved the problem :
else if((command.get(0).equalsIgnoreCase("scan") && command.get(1).equalsIgnoreCase("ips")) && (command.size()>=2 || command.size()<4))

So I removed the
|| command.get(3).equalsIgnoreCase("/e"))

... from the code entirely, and improved the case in the separate class that this if statement directs to.
Here is what I did in the separate class...
if(command.size()==3 && command.get(2).equalsIgnoreCase("/e")) { }
else if(command.size()==2) { }

And it works (:


text:
Q: Firebase Google Authentication Error - Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'constructor') While making the Google Authentication feature with Firebase, I got an error like this. The problem is sometimes it logs in but sometimes it doesn't work.
I guess it's an async error or something...
Is there anything I did wrong?
(I'm very new to using Firebase, and I was writing code following some Firebase lectures. which was quite old, so I also needed to check recent documentation from time to time.)
const onSocialClick = async (e) => {
        const {
            target: { name },
        } = e;
        let provider;
        if (name === 'google') {
            // Creates the provider object.
            provider = new GoogleAuthProvider();
            provider.addScope('profile');
            provider.addScope('email');
        } else if (name === 'github') {
            provider = new GithubAuthProvider();
            provider.addScope('repo');
        }
        const user = await signInWithRedirect(auth, provider);
    };


text:
Q: Почему jquery element.attr() не срабатывают стили? Есть модалка:

Reconcile

            <button class="close-btn">

            </button>

Date

Description

Currency

Amount

Reconciled

07-09-2017

Deposit G4S - 0123456789

EURO

14.055,00

Drag transactions here

        <button class="modal-btn-save col-sm-3">Save & Close</button>

Discrepancy: 3.650

Есть код jQuery:
$('.close-btn').on('click', function() {
    $('.reconciliation-modal').attr('display','none;');
})

Атрибут в html появляется, но не воздействует на модалку(она не пропадает). Вопрос: почему?
P.S.
Стили для модалки:
.reconciliation-modal {
    position: absolute;
    z-index: 999;
    left: 15%;
    top:30%;
    right:0;
    bottom:0;
    max-height: 500px;
    background: #fff;
    -webkit-border-radius: 5px;
    border-radius: 5px;
    -webkit-box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
    box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
}
.reconciliation-modal .close-btn {
float: right;
text-align: right;
}
.reconciliation-modal .modal-droppable-area {
padding-top: 25%;
padding-bottom: 25%;
text-align: center;
background: #cacaca;
}

A: Потому что это не атрибут
$('.reconciliation-modal').css('display','none');

или
$('.reconciliation-modal').hide();


text:
Q: Reducer in the store is showing an error (react, redux toolkit, typescript) I am using redux in typescript, i want to make a reducer that will update the state of the store,
and my types are:
interface IArticle {
  id: number,
  title: string,
  body: string,
}

type ArticleState = {
  articles: IArticle[]
}

type ArticleAction = {
  type: string,
  article: IArticle
}

type DispatchType = (args: ArticleAction) => ArticleAction

my actionCreators.ts is like this:
import * as actionTypes from "./actionTypes"

// A function to add an article
export function addArticle(article:IArticle)
{
  const action: ArticleAction={
    type: actionTypes.ADD_ARTICLE,
    article,
  }
  return simulateHttpRequest(action)
}

// A function to remove an article
export function removeArticle(article:IArticle){
  const action: ArticleAction={
    type: actionTypes.REMOVE_ARTICLE,
    article,
  }
  return simulateHttpRequest(action)
}

export function simulateHttpRequest(action: ArticleAction) {
  return (dispatch: DispatchType) => {
    setTimeout(() => {
      dispatch(action)
    }, 500)
  }
}

while my reducer is as follows:
import * as actionTypes from "./actionTypes"

const initialState: ArticleState = {
  articles:[]
}
let lastID =0
const reducer = (state:ArticleState=initialState,action:ArticleAction)=>{
  switch(action.type){
    case actionTypes.ADD_ARTICLE:
      const newArticle:IArticle = {
        id: ++lastID,
        title: action.article.title,
        body: action.article.body
      }
      return { ...state,newArticle}

    case actionTypes.REMOVE_ARTICLE:
      return state.articles.filter((article)=> article.id !== action.article.id)
    default: return state
  }
}

export default reducer

so far everything is okay.
Finally,my reducer is showing an error when i am trying to make a store as follows:
export const store = configureStore({
  reducer: {
    reducer: reducer,
  }
});

the error:
Type '(state: ArticleState | undefined, action: ArticleAction) => ArticleState | IArticle[] | { newArticle: IArticle; articles: IArticle[]; }' is not assignable to type 'Reducer<ArticleState | IArticle[] | { newArticle: IArticle; articles: IArticle[]; }, AnyAction>'.
  Types of parameters 'state' and 'state' are incompatible.
    Type 'ArticleState | IArticle[] | { newArticle: IArticle; articles: IArticle[]; } | undefined' is not assignable to type 'ArticleState | undefined'.
      Property 'articles' is missing in type 'IArticle[]' but required in type 'ArticleState'.ts(2322)
type.d.ts(10, 3): 'articles' is declared here.

Any help will be appreciated

A: I think it's complaining about this line
return { ...state, newArticle}

You're overwriting the array of articles with a single article. You should add the new item to the existing array and merge that into the state. Here's one way you could do it:
case actionTypes.ADD_ARTICLE:
  const newArticle:IArticle = {
    id: ++lastID,
    title: action.article.title,
    body: action.article.body
  }
  const newItems = [...state.articles, newArticle];
  return { articles: newItems };

A: Finally, I found a solution to my problem.
in the reducer function, action have to be type AnyAction
const ArticleReducer = (
  state: ArticleState = initialState ,
  action: ArticleAction | AnyAction
)


text:
Q: How to access a specific user's model data as admin? I'm creating a simple model form that is only available to staff. It has a user selection dropdown list populated by models.py user = models.ForeignKey(User, on_delete=models.CASCADE).
On submit I need my view to look up the selected user from the form and return the data in the models for that user (from the built-in Django database). How would I go about doing this?
I have searched here and the recommended articles, but they all appear to be for accessing a model as the logged-in user. Here is a screenshot of the form and my code:

models.py
class GetData(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)

forms.py
class DataRequestForm(forms.ModelForm):
    class Meta:
        model = GetData
        fields = ['user']

Views.py
@login_required
def data_form(request):
    if request.user.is_staff == True:
        if request.method == 'POST':
            form = DataRequestForm(request.POST)
            if form.is_valid():
                user = request.POST["user"]
                print("Form is Valid")
                print(user)
                # How to access that user's model data here?

A: You should first get user by id then get model details using that retrieved user.
views.py
@login_required
def data_form(request):
    if request.user.is_staff == True:
        if request.method == 'POST':
            form = DataRequestForm(request.POST)
            if form.is_valid():
                user = request.POST["user"]
                print("Form is Valid")
                print(user)

                # getting user data by id.
                get_user = get_object_or_404(User, id=user)

                get_another_model_data = SecondModel.objects.filter(user=get_user)

                # perform or save the data here


text:
Q: Django Blog - Comment System I am new to Django, and I am wondering how I can intelligently link the system of comments and posts using class-based views. Here's my 'models.py' file in the 'blog' app:
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse

class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    date_posted = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('post-detail', kwargs={'pk': self.pk})

class Comment(models.Model):
    post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE)
    title = models.CharField(max_length=100)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    content = models.TextField()
    date_posted = models.DateTimeField(default=timezone.now)

    class Meta:
        ordering = ['date_posted']

    def __str__(self):
        return '{} - {}'.format(self.author, self.date_posted)

There's my 'post_detail.html' template that shows the specific post and here I just want to show all comments under the post:
{% extends 'blog/base.html' %}

{% block content %}

                    {{ object.author }}

                {{ object.date_posted  | date:"F d, Y" }}
                {% if object.author == user %}

                        Update
                        Delete

                {% endif %}

                {{ object.title }}

{{ object.content }}

Comments Section

{% endblock content %}

'views.py' file looks like this:
from blog.forms import CommentForm
from django.db import models
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.mixins import UserPassesTestMixin
from django.contrib.auth.models import User
from django.shortcuts import redirect, render
from django.shortcuts import get_object_or_404
from django.views.generic import ListView
from django.views.generic import DetailView
from django.views.generic import CreateView
from django.views.generic import UpdateView
from django.views.generic import DeleteView
from .models import Post
from .models import Comment

def home(request):
    context = {
        'title': 'Home',
        'posts': Post.objects.all()
    }
    return render(request, 'blog/home.html', context)

class PostListView(ListView):
    model = Post
    template_name = 'blog/home.html'
    context_object_name='posts'
    ordering = ['-date_posted']
    paginate_by = 7

class UserPostListView(ListView):
    model = Post
    template_name = 'blog/user_posts.html'
    context_object_name='posts'
    paginate_by = 7

    def get_queryset(self):
        user = get_object_or_404(User, username=self.kwargs.get('username'))
        return Post.objects.filter(author=user).order_by('-date_posted')

class PostDetailView(DetailView):
    model = Post

def comment(request, pk):
    post = get_object_or_404(Post, pk=pk)
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.post = post
            comment.save()
            return redirect('post-detail', pk=post.pk)
        else:
            form = CommentForm()
    return render(request, 'blog/post_detail.html', {'form': form})

class PostCreateView(LoginRequiredMixin, CreateView):
    model = Post
    fields = ['title', 'content']

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)

class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
    model = Post
    fields = ['title', 'content']

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)

    def test_func(self):
        post = self.get_object()
        if self.request.user == post.author:
            return True
        return False

class PostDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
    model = Post
    success_url = '/'

    def test_func(self):
        post = self.get_object()
        if self.request.user == post.author:
            return True
        return False

def about(request):
    return render(request, 'blog/about.html', {'title': 'About'})

I understand that everything should be done in the PostDetailView class but I have no clue how to start. I will appreciate any ideas or suggestions

A: You have a foreign key from Comment to Post, so if you have a Post object, you can get all related comments with post.comments.all().
You can do that directly in the template, you just have to omit the parenthesis. Here is a template snippet for illustration:

Comments Section

    {% for comment in object.comments.all %}

{{ comment }} {{ comment.context }}

    {% endfor %}

This kind of hides the database query to fetch the comments in the template. If you'd rather perform the queries in the view, you can overwrite PostDetailView.get_context_data():
class PostDetailView(DetailView):
model = Post
def get_context_data(self, **kwargs):
    ctx = super().get_context_datat(**kwargs)
    ctx["comments"] = ctx["object"].comments.all()
    return ctx

In this case, the for-loop in the template would look like this:
{% for comment in object.comments.all %}


text:
Q: SQLite Group By giving duplicates I am trying to write a query using SQLite but keeping running into the issue where my GROUP BY has duplicates. I am using SQLite and am struggling to get clean results.
I received a file that has a business unit but is displayed as AMER - xyz. I only want the AMER so I used the SUBSTR function. I believe this is where I am encountering my issue.
Below is my query along with sample results:
SELECT DISTINCT(UPPER(SUBSTR(business_unit,1,INSTR(business_unit,' -')))) as business_unit,
    COUNT(*)

FROM leads_market_region_marketo

GROUP BY business_unit

--------------------------------

bu      count
AMER    271107
AMER    130172
AMER    3218
AMER    13072
AMER    1088247
AMER    369576
ANZ     29913

What I want:
bu      count
AMER    x
ANZ     y
EMEA    z

A: You should GROUP BY the same criteria you want to get your groups.
SELECT UPPER(SUBSTR(business_unit,1,INSTR(business_unit,' -'))) as business_unit, COUNT(*)
FROM leads_market_region_marketo
GROUP BY UPPER(SUBSTR(business_unit,1,INSTR(business_unit,' -'))))

Hope it helps!


text:
Q: Why is a cycloid path the fastest way to roll a ball downward?
Possible Duplicate:
Path to obtain the shortest traveling time

I've been told that if one would want to make a ramp to get a ball from point A to a lower point B (at a certain horizontal distance from A), the best shape to make this ramp in - by which I mean the ramp that makes the ball reach point B the fastest - would be a cycloid path. Why is this?

A: To simply explain the curve consider what it does. It allows the ball to drop first to pick up speed and then transitions to more horizontal motion to span the distance from A to B.
If the ball were to transverse across first and then drop it would do so slowly. It is simply a matter of optimization to get the correct curve.
As @dmckee noted in the comments, this area of math is called "calculus of variations" because the variation of the ball path is considered.


text:
Q: jQuery Loupe and Click Events I'm currently using the loupe plugin to zoom in on a large organizational picture that is set up as an image map. Normally when a user clicks a portion of this image map they are redirected, unfortunately I can't find a method that will allow loupe to respond to a user clicking a link on an image map. Any advice would be greatly appreciated!
Thanks!

A: I'm not familiar with that particular plugin, but can't you simply attach your own click event handler?
Given this markup (based on the demo at the plugin's GitHub repo):

You can attach a click handler like this:
$(function(){
    $('a.demo').on('click', function(e){
        // prevent the link from going anywhere (if that's what you want)
        e.preventDefault();

        // do something else...
        alert('The Loupe link was clicked!');
    });
});

Edited to add that if you're working with an image map, you can simply attach a click event handler to the <area> elements, something like this:
$('area').on('click', function(e){
    // stuff here
});

A: This is old question but answer is quite simple:-
Just attach an event listener to the class .loupe
$('.loupe').on('click', function (e) {
  e.preventDefault();
  alert('The Loupe link was clicked!');
});

A: If you want loupe to go to the anchor tag parent to the original img tag, then try this, if that doesn't work, add a class to all the original images, and add to the selector before img.
$('.loupe').click(function(){
      $("img[src='"+$(this).find('img').attr('src')+"']").parent()[0].click();
});


text:
Q: Тестирование при использовании паттерна Repository Необходимо протестировать метод GetReportListForSchool:
Repository.cs
public class ReportRepository : IReportRepository
{
    private monit95Context db;
    public ReportRepository(monit95Context db)
    {
        this.db = db;
    }
    public List<Report> GetReportListForSchool(school _school)
    {
        List<Report> result = new List<Report>();
        foreach (var report in db.Reports)
        {
            string catalog = String.Format(@"{0}\{1} - {2}", report.path, _school.AreaID, _school.area.AreaName);
            string[] rarFiles = Directory.GetFiles(catalog, "*.rar")
                                         .Select(path => Path.GetFileName(path))
                                         .ToArray(); //получить список rar-файлов, т.е. коды школ
            if (Array.IndexOf(rarFiles, _school.SchoolID) != -1)
            {
                result.Add(report);
            }

        }

        return result.ToList();
    }
}

И здесь сразу первый вопрос:
1. Если у меня репозиторий работает с базой отчетов, правильно ли я поместил метод по поиску всех отчетов по школе именно в класс ReportRepository?
Вот часть кода из юнит-теста:
UnitTest.cs
    public void TestGetReportListForSchool()
    {
        //Организация
        IReportRepository reportRepository = new ReportRepository(new monit95Context());
        school _school = new school() //создаю школу
        {
            SchoolID = "0286",
            AreaID = 205
        };

        //Действие
        var reportList = reportRepository.GetReportListForSchool(_school);
        Assert.AreEqual(2, reportList.Count);
    }

Хотел проверить на количество возвращаемых отчетов. Но это не сработало т.к. при компиляция вышло сообщение о том, что нет строки подключения (context). Поиск в сети на вел на мысль, что необходимо использовать Mock-объект и здесь вопрос номер
2. Как в моем случаи, используя библиотеку Moq провести тестирование метода GetReportListForSchool?

A: Если monit95Context -- это EF-контекст, который наследуется от DbContext, то убедитесь, что свойство Reports -- виртуальное. В таком случае вы сможете замокать с помощью Moq сам контекст и содержимое Reports. Подробнее можно почитать на MSDN.
public void TestGetReportListForSchool()
{
    // вместо Report подставьте свой тип отчета
    var reports = new List<Report>()
    {
        new Report() { ... },
        new Report() { ... }
    }.AsQueryable();

    var reportsMock = new Mock<DbSet<Report>>();
    reportsMock.As<IQueryable<Report>>().Setup(m => m.Provider).Returns(reports.Provider);
    reportsMock.As<IQueryable<Report>>().Setup(m => m.Expression).Returns(reports.Expression);
    reportsMock.As<IQueryable<Report>>().Setup(m => m.ElementType).Returns(reports.ElementType);
    reportsMock.As<IQueryable<Report>>().Setup(m => m.GetEnumerator()).Returns(0 => reports.GetEnumerator());

    var contextMock = new Mock<monit95Context>();
    contextMock.Setup(c => c.Reports).Returns(reportsMock.Object);

    //Организация
    IReportRepository reportRepository = new ReportRepository(contextMock.Object);
    school _school = new school() //создаю школу
    {
        SchoolID = "0286",
        AreaID = 205
    };

    //Действие
    var reportList = reportRepository.GetReportListForSchool(_school);
    Assert.AreEqual(2, reportList.Count);
}

Однако мока контекста и списка отчетов недостаточно. Ваш метод также работает с файловой системой. Поэтому вам надо либо в начале теста создавать нужные файлы на диске, либо выносить функциональность работы с файловой системой в отдельную зависимость и мокать эту зависимость. Второй способ предпочтительнее.


text:
Q: Return negative value in main in C Hello StackOverflow community.
I am actually working on a project trying to emulate a very basic shell. I have an exit builtin that take a parameter and based on this I need to return the correct value (value % 256)
For example :
exit 42 will return 42
exit 300 will return 44
But I can't find exactly how this is exactly working is someone was trying to do exit -30 for example. I did some test and found out it was 226 beside the fact that it's 256 - 30 where it comes from ?

A: C standard leaves most things about the return values of main to be defined by the implementation. Basically returning 0, EXIT_SUCCESS, or EXIT_FAILURE is somehow standard and reliable, everything else depends on the platform. In this case it seems like the operating system gives you the value modulo 256 (as an uint8_t).

A: Your program is returning an unsigned int. Since the number has to be positive, the calculated value from the modulus ends up looking like the numbers 'wrapped around'.
Here is some quick test code to demonstrate:
int main(){
    unsigned int x = -30;
    signed int y = -30;
    printf("%d\n", x % 256);
    printf("%d\n", y % 256);
}

Output:
226
-30

A: Return values of a program to the linux kernel are of uint8_t type.

A: Modulo is always a positive number in the programming languages and besides here is a something on returing negative numbers from main to OS C++: How can I return a negative value in main.cpp


text:
Q: Heuristics behind Dirac delta function in Master equation for probability? I'm reading this paper [Phys. Rev. Lett. 106, 160601 (2011)] and it studies simple diffusion where a particle stochastically resets to its initial position $x_0$ at a constant rate $r$. As you can see, equation (1) is the master equation for $p(x,t|x_0)$, the probability that the particle is at $x$ at time $t$, having begun from $x_0$:
\begin{equation}
\frac{\partial p(x,t|x_0)}{\partial t}=D\frac{\partial^2p(x,t|x_0)}{\partial x^2}-rp(x,t|x_0)+r\delta(x-x_0),
\end{equation}
I understand the origin of the LHS and of the first term of the RHS, they come from the simple diffusion process. But what about the second and third terms of the RHS? I think the second one has to do with a negative flux out each $x$ (due to stochastic resetting, as the paper says), and the third one has to do with the positive flux into $x_0$, but is there a (heuristic) way to understand a little further the use of a Dirac delta function for this last term? For example, what if the resetting occurs to a set of points? How this modify the master equation?

A: Here's how I would come to some intuition for it. I would think about the rate of "probability flow" into a region by integrating the equation over a region in space. For now, let's suppose that no diffusion occurs at all, since that is more complicated (although directly doable and understandable). Then
$$\int_a^b dx\frac{\partial p(x,t|x_0)}{\partial t}=\int_a^bdx\left(-rp(x,t|x_0)+r\delta(x-x_0)\right),$$
which we can write as
$$\frac{\partial}{\partial t}\int_a^b dx~p(x,t|x_0) = -r\int_a^bdx~p(x,t|x_0)+r\int_a^bdx~\delta(x-x_0),$$
which we can further write as
$$\frac{\partial}{\partial t}P(a\leq x\leq b,t|x_0) = -rP(a\leq x\leq b,t|x_0)+r\int_a^bdx~\delta(x-x_0),$$
where $P(a\leq x\leq b,t|x_0)$ is the probability of there being a particle between $a$ and $b$ at time $t$ given that it started at $x_0$.
Now, if $x_0$ is not contained in the interval $[a,b]$, then this becomes
$$\frac{\partial}{\partial t}P(a\leq x\leq b,t|x_0) = -rP(a\leq x\leq b,t|x_0),$$
which just says that the probability of the particle being in the interval decays with time exponentially, which is exactly their resetting process, represented by the exponential decay of being at a particular spot other than $x_0$.
On the other hand, if $x_0$ is contained in the interval, then the equation becomes
$$\frac{\partial}{\partial t}P(a\leq x\leq b,t|x_0) = r(1-P(a\leq x\leq b,t|x_0)).$$ There are two components to the probability flow: there's the one we had before, that says that we are "losing probability" because there is an exponential process to jump away from $x$, but we are gaining probability because particles are jumping to $x_0$.
If we consider a centered interval about $x_0$, then
$$\frac{\partial}{\partial t}P(x_0-\epsilon\leq x\leq x_0+\epsilon,t|x_0) = r(1-P(x_0-\epsilon\leq x\leq x_0+\epsilon,t|x_0)),$$
and if we narrow in on $x_0$ by taking $\epsilon$ to be small, then this is approximately given by
$$\frac{\partial}{\partial t}P(x_0-\epsilon\leq x\leq x_0+\epsilon,t|x_0) \approx r,$$
which just states that the rate at which particles are resetting is exactly $r$.


text:
Q: Should "it" be used in "There is a table that has a book on (it)"? Is this sentence grammatically correct?:

There is a table that has a book on it.

Can I say (or why can't I say if not?):

There is a table that has a book on.

A:

*

*There is a table [that has a book on it].

This is a grammatical sentence. The restrictive relative clause

*

*[that has a book on it]

modifies its antecedent noun phrase a table, and contains two noun phrases (that, the subject relative pronoun, and it, the object of the preposition on) which both refer to a table.
This is grammatical because the clause is grammatical as a simple sentence

*

*The table  has a book on it.

The second sentence

*

**There is a table [that has a book on].

is ungrammatical (that's what the asterisk means) because the supposed relative clause

*

*[that has a book on]

is not grammatical as a simple sentence

*

**The table has a book on.
and therefore can't be grammatical as a relative clause.
It's tempting to strand prepositions in relative clauses, like

*

*The man put the book on a table; what color is the table that he put it on?
but you can only do that when the relative pronoun that (or which, or who, depending) is the object of the preposition. In

*

*a table that has a book on it
the relative pronoun that is already the subject and can't be moved or deleted, so the it that's the object of on is not a relative pronoun and can't be deleted or moved either.


text:
Q: When checking internet access in android, why does it always return "true"? How to check for Internet access in Android?
Why does it always return true?
I am sure I am not connected to Internet. Why does it return true?
public static boolean isOnline(Context context) {
    ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
    // test for connection
    if (cm.getActiveNetworkInfo() != null &&
        cm.getActiveNetworkInfo().isAvailable() &&
        cm.getActiveNetworkInfo().isConnected()) {

        return true;
    } else {
        Log.v("TAG", "Internet Connection Not Present");
        return false;
    }
}

A: You could try testing to figure out which connection is seen as active:
public boolean isOnline() {
  ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
  NetworkInfo netInfoMob = cm.getNetworkInfo(cm.TYPE_MOBILE);
  NetworkInfo netInfoWifi = cm.getNetworkInfo(cm.TYPE_WIFI);
  if (netInfoMobile != null && netInfoMobile.isConnectedOrConnecting()) {
    Log.v("TAG", "Mobile Internet connected");
    return true;
  }
  if (netInfoWifi != null && netInfoWifi.isConnectedOrConnecting()) {
    Log.v("TAG", "Wifi Internet connected");
    return true;
  }
  return false;
}

Edit: On the emulator, it will always show mobile connected regardless of your computer's Internet connection. Use F8 to switch it off, as per this answer:
https://stackoverflow.com/a/2937915/560092

A: public boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager
              = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        boolean isAvailable = activeNetworkInfo != null && activeNetworkInfo.isConnected();
        if(!isAvailable) {
            Toast.makeText(this,"Unable to connect", Toast.LENGTH_SHORT).show();
        }
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }

A: The method you are using doesn't always work correctly. Some times it will return true even if you are connected to a wifi network (but that network isn't actually connected to internet), etc. The other alternative is
public boolean isOnline() {
  ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
  NetworkInfo netInfoMob = cm.getNetworkInfo(cm.TYPE_MOBILE);
  NetworkInfo netInfoWifi = cm.getNetworkInfo(cm.TYPE_WIFI);
  if ((netInfoMobile != null && netInfoMobile.isConnectedOrConnecting()) || (netInfoWifi != null && netInfoWifi.isConnectedOrConnecting())) {
    return true;
}
  return false;
}


text:
Q: RBAC feature in flask I'm trying to create a Role Based Access Control system in my application dashboard. I have done it in PHP using Yii2 framework GitHub but I'm confused how to get it done in flask using python. I'm new to python.
I can't provide more details as I'm not clear with this.
Any suggestions welcome.

A: There is such an extension for flask already: Flask-RBAC. If you want to code one yourself you should inspect the code of the existing one. Or you can use it in your applications.

A: You can use Casbin. Casbin supports both PHP (PHP-Casbin) and Python (PyCasbin). It also has the Yii middleware and Flask middleware. Here's the FLask middleware: https://github.com/pycasbin/flask-authz


text:
Q: Android gradlew assembleRelease --sourcemap output fail because bundle doesn't exist yet When bundling react-native code via gradlew assembleRelease and having the generate source maps tag added to the app build.gradle, bundling error occurs.
"error ENOENT: no such file or directory,
app\build\intermediates\assets\release\index.android.js.map"
In './android/app/build.gradle', I have the extraPackagerArgs property to generate source maps.
project.ext.react = [
    entryFile: "index.js",
    extraPackagerArgs: ["--sourcemap-output", "$buildDir/intermediates/assets/release/index.android.js.map"]
]

Doesn't work
When calling cd android && gradlew assembleRelease in the root of the project folder.
This however fails because it seems as though its trying to generate the source map before the bundle file index.android.bundle is even created.
example:

*

*first I clean my project via android studio.

*\android\app\build\intermediates\assets\release will be empty.

*next, run cd android && gradlew assembleRelease.
The error is displayed stating that there is no bundle file as its trying to make a sourcemap.
Works
example:

*

*clean the project via android studio

*run cd android && gradlew assembleRelease without having extraPackagerArgs in the build.gradle file.
The bundle is created in ..\intermediates\assets\release.

*Next, add back the extraPackagerArgs for generate the sourcemap.

*Run again cd android && gradlew assembleRelease, and the sourcemap is created.
This tells me that whatever arguments are added to extraPackagerArgs seem to be running before the bundle is actually created.
Does anyone know a way to ensure that the sourcemaps only get generated after the bundle file is made?


text:
Q: Pass function member pointer as parameter to function I'm working on a Qt project and I have decided to implement a function which takes a pointer to a QLabel member function and its parameters, and applies it to some labels.
template <class R, class ...Args>
void ClockSim::applyToLabels (R (QLabel::*f)(Args...), Args&& ...args)
{
    ui->labelSingleTime->*f (std::forward<Args>(args)...);
    //Repeat it for many other labels

}

I tried to call it with:
applyToLabels (&QLabel::setStyleSheet, "color:red;");

It says:
error: no matching member function for call to 'applyToLabels'
candidate template ignored: could not match 'QLabel' against 'QWidget'
Any solution? Thanks

A: Since setStylesSheet is an inherited member of QWidget, the type of &QLabel::setStylesSheet is actually void (QWidget::*)(const QString&), and that doesn't match your template function parameter.
You'll need to use another template parameter for the actual class of the member function:
template <class R, class C, class ...Params, class ...Args>
typename std::enable_if<std::is_base_of<C,QLabel>::value &&
                        sizeof...(Params)==sizeof...(Args)>::type
ClockSim::applyToLabels (R (C::*f)(Params...), Args&& ...args)
{
    (ui->labelSingleTime->*f)(std::forward<Args>(args)...);
}

I've also made the function pointer parameters different from your passed args, since you try to pass a const char(&)[11] which is not a QString but converts to one.


text:
Q: How memory is allocated in threads My question is that the object text initialized with "t1" and then a t1 thread started and then text becomes "t2" and later one more thread t2 started.
I was expecting:
t1
t2

Real output:
t2
t2

Why ?
class Program
{
        static void Main()
        {
            string text = "t1";
            Thread t1 = new Thread(() => Console.WriteLine(text));
            t1.Start();
            text = "t2";
            Thread t2 = new Thread(() => Console.WriteLine(text));
            t2.Start();
        }
}

A: You don't need Threads (to get this result).
static void Main()
{
    string text = "t1";
    var action1 = () => Console.WriteLine(text);
    text = "t2";
    var action2 = () => Console.WriteLine(text);

    action1();  // "t2"
    action2();  // "t2"
}

The culprit here is the lambda operator, not the Threads. The variable text is 'closed over' or 'captured', both actions will use the same variable and the value at the time of execution, not the value of when they were created.
When you run the actions on separate Threads you have a race condition, run your program many times and you might see a "t1" sometimes.

A: Constructing a Thread (allocating a thread ) consumes time. Therefore while your thread is going up and running, the background thread will do its work, and apparently, it's done before t1 print out text object.
Defining local variables inside of the thread's scope is safer than defining them on global scopes. Shared data must be used with caution.


text:
Q: Best way to handle universal app state of view What is the best approach to catch state-of-view changes and modify app behaviour in each state? I am looking for good tutorial or advice whole morning and I just found nice tutorial for usage of VisualStateManager. It was really helpfull for me, but VisualStudio says, that this approach is obsolete. This way does not work with some features too, so how to efficiently and validly modify UI for each of four states (Landscape, Fill, Snapped, Portrait) in Windows 8.1 universal app?

A: There is no ApplicationViewState enum in windows 8.1.
However the approach is the same: Use visual states and VisualStateManager in SizeChanged event handler.
Read this blogpost: http://marcominerva.wordpress.com/2013/10/16/handling-visualstate-in-windows-8-1-store-apps/
It describes how to determine current Visual state in windows 8.1

A: In Windows 8 a page have 4 predefined view states, Snapped , Filled, FullScreenLandscape and FullScreenPortrait. To know the view state you have to use ApplicationView.Value that returned one of 4 states and then you have to invoke VisualStateManager.GotoState () passing as parameter the name of the state.
Now in windows 8.1 there are no predefined view states and value property of the ApplicationView has been deprecated. Now the window size is more fluid and the user can resize the width of the space occupied by the application in multi app mode , therefore the decisions of the window design must take according to the size of the window that holds the application.
When the event SizeChanged is triggered should call for current window information using ApplicationView.GetForCurrentView, This function returns a ApplicacionView and we can use properties like Orientation, IsFullScreen, AdjacentToLeftDisplayEdge, AdjacentToRightDisplayEdge to make decisions, also is neccesary determine the size of the window.
To find the width of the screen there are two ways.
We can access the parameter of type WindowSizeChangedEventArgs of the WindowSize event and then invoke e.Size.Width.
We may also use Window.Current.Bounds to find out the size of the window.
We also have to update the design of the window in the OnNavigatedTo method page because when you push the button back not trigger the SizeChanged event and if the current resolution is not the same as he had the previous page when it was loaded, then would not have the VisualState suitable.
I leave an example of possible solution
public class MainPage:Page
{
    public MainPage()
    {
        this.Loaded += page_Loaded;
        this.Unloaded += page_Unloaded;
    }

    private void page_Loaded(object sender, RoutedEventArgs e)
    {
        Window.Current.SizeChanged += Window_SizeChanged;
    }

    private void page_Unloaded(object sender, RoutedEventArgs e)
    {
        Window.Current.SizeChanged -= Window_SizeChanged;
    }

    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        UpdateVisualState();
    }

    private void Window_SizeChanged(object sender, WindowSizeChangedEventArgs e)
    {
        UpdateVisualState();

    }

    private void UpdateVisualState()
    {
        var visualState = string.Empty;
        var applicationView = ApplicationView.GetForCurrentView();

        if (applicationView.IsFullScreen)
        {
            if (applicationView.Orientation == ApplicationViewOrientation.Landscape)
                visualState = "FullScreenLandscape";
            else
                visualState = "FullScreenPortrait";
        }
        else
        {
            var size = Window.Current.Bounds;

            if (size.Width == 320)
                visualState = "Snapped";
            else if (size.Width <= 500)
                visualState = "Narrow";
            else
                visualState = "Filled";
        }

        VisualStateManager.GoToState(this, visualState, true);
    }
}


text:
Q: Showing that $o(\phi(g))|o(g)$ if $\phi:G_1\mapsto G_2$ is a homomorphism and $g\in G_1$ $o(g)$ denotes the order of $g$.
This is how I think I proved it:
Let $m:=o(g)$
Let $d=o(\phi(g))$. $~d\le m$ because $\langle\phi (g)\rangle=\{\phi(g),\phi(g)^2=\phi(g^2),...,\phi(g^m)=e_{G_2}\}$
If $o(\phi(g))=d$ by euclidean division there exist $q\in\Bbb N$ and $0\le r<d$ such that $$m=dq+r~\text{ and }~\phi(g)^d=e=\phi(g^d)\\ e=g^m=g^{dq+r}=g^{dq}g^r \implies g^r=g^{-dq}\\ \phi(g)^r=\phi(g^r)=\phi(g^{-dq})=(\phi(g)^d)^{-q}=e$$
 but $d>r$ is the order of $\phi(g)$ so $r$ must be zero.
I'm not sure if this is all correct

A: You can get this more quickly using the First Isomorphism Theorem. Recall that $o(g) = |\langle g \rangle|$. Now $o(\phi(g)) = |\phi( \langle g \rangle)|$. Taking $G = \langle g \rangle$, the First Isomorphism theorem tells us that $|G| = |Im(\phi)| \cdot |\ker(\phi)|$. Note that $|Im(\phi)| = o(\phi(g))$.

A: I would just write $\phi (g)^r=e$, with $r\lt d$.  So $r=0$.  (It's pretty clear, since $e=\phi(g)^m=\phi(g)^d$).
But it seems to be correct.
Actually,  once $\phi (g)^m=e$ you're done (by the little argument you essentially gave).  That is,  $g^a=e\implies o(g)\mid a$, generally.