text:
Q: How to force OS to claim back memory? (C++) In my C++ code, I allocate a huge amount of memory to create a tree, and then I use 'delete' in every node to free the memory.
After I delete everything, I check the amount of used memory by the OS, and I see that the memory wasn't freed. That's expected, because the process doesn't return the memory to the OS right away, because it still might use it again.
The problem is that I create another huge tree right after I delete the first one, and instead of using the already allocated memory, the process allocates more memory from the OS. Because of this, I ran out of RAM and my computer got really slow, to the point where I couldn't even switch tabs. I checked the memory usage at several moments to see if that's what really happened, and it is.
If only I could make the process use the same memory it used before, or maybe if I could force the process to give the memory back to the OS.
What can I do to solve this problem?
(I'm using Debian)
I'm creating a tree of dynamic objects. The Node class has a vector to store the child nodes, among the other class variables:
std::vector child;
The class destructor deletes all the dynamically allocated class variables, and then deletes the child nodes:
~Node() {
    //Deleting the other variables
                .
                .
                .

    //Deleting the child nodes
    for(int i = 0; i < child.size(); i++) {
        delete child[i];
    }
}

My class has a method that creates a tree of a given height, in which the current node is the root node:
void createTree(int height) {
    if(height == 0) {
        return;
    }
    for(int i = 0; i < numberOfChildNodes; i++) {
        child.push_back(new Node());
        child[i]->createTree(height - 1);
    }
}

This class has another method where I create a tree with height = 3, then I delete the entire tree and create another one with height = 4, then I delete the entire tree and create one with height = 5, and so on, until a memory limit is reached:
void highestTreePossible() {
    int i, height = 3;
    struct sysinfo memInfo;
    while(true) {
        createTree(height);
        sysinfo (&memInfo);
        if(memInfo.freeram > limit) {
            std::cout << "Highest tree possible: height = " << height;
            break;
        }
        for(i = 0; i < child.size(); i++) {
            delete child[i];
        }
        child.clear();
        height++;
    }
    for(i = 0; i < child.size(); i++) {
        delete child[i];
    }
    child.clear();
}

A:
How to force OS to claim back memory? (C++)

Terminate the process.
Other than that, there may be OS specific calls that can do it, but attempting to use those can interfere with the dynamic memory allocator implementation which may rely on being in control of the memory that it has.

... and instead of using the already allocated memory, the process allocates more memory from the OS.

If this is the case, then it seems like your program might have a memory leak, and that you actually don't delete everything. I recommend making sure that there are no leaks.

I posted the code in this other topic, back when I thought the problem was a memory leak. It's the same code.

The code is incomplete and it is not possible to conclusively tell that the complete program doesn't leak memory.
Back then you described the case differently, and based on that description there was no reason to assume that there is a memory leak.


text:
Q: Binary arithmetic with two's complement By intuition I can see that the 2's complement will be the negative of a number but I want a more rigorous proof to convince myself that no arithmetic will ever fail.
EDIT
More clarification:
Consider the domain [0,8)
decimal | 2's comp | integer
   0    |    8     |     0
   1    |    7     |     1
   2    |    6     |     2
   3    |    5     |     3
   4    |    4     |    -4
   5    |    3     |    -3
   6    |    2     |    -2
   7    |    1     |    -1

it seems that integer column picks its -ve numbers from the lower half of 2's complement column and the +ve numbers from the upper half of decimal column.
What magic is going on here?

A: First off, observe that the group $G=(\{-4, -3, ..., 0, 1, ..., 3\}, +)$ is isomorphic to $\mathbb{Z}_{8}$.
The bijection $f:G \to \mathbb{Z}_{8}$ is exactly the two's complement. Why? Because:

*

*$2c(0)=0$, and

*For all $a$, $a^{\prime}$, if $2c(a)=a^{\prime}$, then $2c(a+1)=a^{\prime}-1$.

And that's why two's complement addition works. A similar argument can be made for multiplication, and any number of bits. Hope I didn't make things more confusing, but this is how I would go about rigorously proving the correctness of two's complement arithmetic.

A: One way to think of n-bit 2's complement is that the lower $n-1$ bits represent a positive number and the highest bit represents $-2^{-n+1}$.  Then to prove that arithmetic comes out right assuming there is no overflow, you just consider the cases.  If you add positive numbers $m$ and $p$, you get $m+p$ as long as $m+p \lt 2^{-n+1}$.  If you add a positive $m$ to a negative $p$ that is smaller in absolute value, there will be a carry that wipes out the negative sign bit in $p$ and so on.

A: Note that the 2's complement of the most negative number in that number system is itself (e.g. the 2's complement of -128 is -128 itself) etc.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Process XMLFile out of request I created a REST API in GoLang (with gorillamux), and in one request from my API, I process an XMLFile. The problem is, this file is big, 5, 6, 10 MB. I can't process in postfile request, because the time for process. Each node of xml is an http request to another API (very time).
The question is.
In GoLang, its possible receive the request, return response (200), and process file out of request?

A:
In GoLang, its possible receive the request, return response (200), and process file out of request?

Of course. You can use a goroutine:
func myHandler(w http.ResponseWriter, r *http.Request) {
    go func() {
        // Process the stuff in a goroutine
    }()
    w.WriteHeader(200) // but send the response immediately
}

A: Yes. Go provides very convenient tools for it. One of classical approaches to this task is to make a channel which will serve as a task queue. Your API function will write to the channel new tasks and another worker goroutine will read and process them :
type Task struct {...} // some fields to describe you task - may be XML document
var TaskQueue chan Task

func worker() {
      for task := range TaskQueue {
             // process task
       }
}

func handler(w http.ResponseWriter, r*http.Request) {
    task := Task{...} // put here some values you need
    TaskQueue <- task
    w.WriteHeader(200)
}

func main() {
    TaskQueue = make(chan Task, 1)
     go worker()
     http.Handle("/", handler)
     http.ListenAndServe(":8080", nil)
}

This way gives you some flexibility:

*

*you may run several workers to process tasks in parallel and you can be sure there will be no more workers so can control load to your server

*if all workers are busy new tasks can be put in queue - second parameter of make sets queue length

*if queue gets overloaded you may check it in handler and return an error (not shown here)


text:
Q: symofony4 custom route loader does't register src/Resources/config/routing.yaml
services:
    _defaults:
        autowire: true
        autoconfigure: true
        public: true

    App\Routing\ResourceRouteLoader:
        arguments:
            - '@App\Metadata\Resource\Factory\ResourceMetadataFactory'
            - 'App\Action\PlaceholderAction'
            - '%simple_rest.resource_class_directories%'
        tags: [ 'routing.loader' ]

config/routes/app_rest.yaml
app_rest:
    resource: .
    type: app_rest
    prefix: /api

the ResourceRouteLoader service is in the service container, but has no 'routing.loader' tag

Conclusion
It seems the imports from config/services.yaml doen't work as expected , it works when I move all my services from directory src/Resources/config/ to config/services.yaml file


text:
Q: duplicate deletion problem I am working on a database where i have two tables.
BILL_MASTER (master_table)
Bill_Master_ID
Consumer_No
BILL_GENERATION (Detail table)
Bill_Master_ID
Somehow user has inserted two identical consumer #'s in bill master but bill_master_id is different..here is the example of bill_master table
Bill_Master_ID   Consumer_No
1                1234567890
2                1234567890

now user has made one transaction of bill_master_id "1" and record exists in Bill_Generation table.
What i want to do is when i pass consumer # in SQL statement as parameter it check if selected consumer# Bill_master_id exist in bill_generation or not. If yes then count return should be 1 else 0.

A: If I understand you correctly, this should do what you want.
IF (SELECT COUNT(consumer_no) FROM bill_master m
    inner join bill_generation g on m.bill_master_id=g.bill_master_id
    WHERE consumer_no=1234567890
   ) > 1
   SELECT 1
ELSE
   SELECT 0

A: The title is misleading, this has nothing to do with deletion unless that's additional to the question.
So what you mean is, based on consumer no, you need to find any record in bill_generation for any of the consumer's ids in bill_master?
select case when exists (
    select *
    from bill_master m
    inner join bill_generation g on g.bill_master_id = m.bill_master_id
    where m.consumer_no = 1234   -- or some number
    ) then 1 else 0 end

To actually delete records from bill_master except the lowest id, you can use this
;with tmp as (
    select *, rn = row_number() over (partition by consumer_no order by bill_master_id)
    from bill_master)
 delete tmp where rn > 1


text:
Q: How to Initialize the TextView to display dynamic content while building an Android application? Here is the problem that I am trying to solve, I ask the user to perform some computation in the current activity which I call as activity1 and I ask the user to press a button to perform the computation after the user presses the button I move him to another activity where I need to display the results of the computation performed by the user, but I am unable to set the TextView for the activity, I read several stackoverflow posts and then finally landed on one that I found somewhat relevant - NullPointer Exception when assigning value to TextView. I keep on getting these NullPointerExceptions and I don't know now what to do. Here is the code for activity2 file wherein I want to display the contents of the computation to the user.
package com.example.mathcalculator;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class CalculatorActivity3 extends ActionBarActivity {

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

        Bundle bundle = new Bundle();
        bundle.putString("key", getIntent().getStringExtra(CalculatorActivity2.EXTRA_MESSAGE));

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment()).commit();
        }

        setContentView(R.layout.activity_calculator_activity3);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.calculator_activity3, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_calculator_activity3, container, false);
            TextView textView = (TextView) rootView.findViewById(R.id.text_view);
            String strtext = getArguments().getString("key");
            textView.setText("The result of the computation is :" + strtext);
            return rootView;
        }
    }

}

This is the activity through which I am passing the content:
package com.example.mathcalculator;

import java.math.BigDecimal;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

public class CalculatorActivity2 extends ActionBarActivity {

    // this is the operation requested by the user and we store it in a global variable
    public static String operationRequested = "";

    // this is the message that is passed along with the result of the computation
    public static String EXTRA_MESSAGE = "com.example.mathcalculator.CalculatorActivity2.Message";

    // this function is used to perform the requisite operation as requested by the user on the previous screen of the application
    public void computeOperation(View view){

        // get the numbers from the 2 fields
        EditText et1 = (EditText)findViewById(R.id.number_1);
        EditText et2 = (EditText)findViewById(R.id.number_2);
        String et1String = et1.getText().toString();
        String et2String = et2.getText().toString();

        // these are the 2 decimal numbers input by the user in the 2 edit text fields
        BigDecimal num1 = new BigDecimal(et1String);
        BigDecimal num2 = new BigDecimal(et2String);

        // make an intent to pass the result to the next activity
        Intent intent = new Intent(this,CalculatorActivity3.class);

        if(operationRequested.equals("sum")){

            // this is the result of the operation
            BigDecimal result = num1.add(num2);
            Log.e("The operation requested was sum and the result of the operation is : " , result.toString());
            // put the key-value pair in the intent
            intent.putExtra(EXTRA_MESSAGE, result.toString());
        }
        else if(operationRequested.equals("difference")){

            // this is the result of the operation
            BigDecimal result = num1.subtract(num2);
            Log.e("The operation requested was difference and the result of the operation is : " , result.toString());
            // put the key-value pair in the intent
            intent.putExtra(EXTRA_MESSAGE, result.toString());
        }
        else if(operationRequested.equals("product")){

            // this is the result of the operation
            BigDecimal result = num1.multiply(num2);
            Log.e("The operation requested was product and the result of the operation is : " , result.toString());
            // put the key-value pair in the intent
            intent.putExtra(EXTRA_MESSAGE, result.toString());
        }
        else if(operationRequested.equals("division")){

            // this is the result of the operation
            BigDecimal result = num1.divide(num2);
            Log.e("The operation requested was division and the result of the operation is : " , result.toString());
            // put the key-value pair in the intent
            intent.putExtra(EXTRA_MESSAGE, result.toString());
        }
        else;

        // start the new activity
        startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_calculator_activity2);

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction().add(R.id.container, new PlaceholderFragment()).commit();
        }

        // this is the intent received from the previous activity
        Intent intent = getIntent();
        operationRequested = intent.getStringExtra(CalculatorActivity1.EXTRA_MESSAGE);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.calculator_activity2, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(
                    R.layout.fragment_calculator_activity2, container, false);
            return rootView;
        }
    }

}

and the fragment file for the same activity above
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@drawable/calculato_activity_1">

    <TextView android:id="@+id/text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

A: The problem is that you are trying to add a fragment to the transaction before you set the layout for you acitivity.
problem:
if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderF()).commit();ragment
    }

    setContentView(R.layout.activity_calculator_activity3);

As you can see you set the layout after to do a transaction thus it will catch a exception to the .add(R.id.container, new PlaceholderF()).commit();
 R.id.container is not yet added so it will return null.
solution:
add the fragment after you set the layout for your activity
     setContentView(R.layout.activity_calculator_activity3);

 if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderF()).commit();ragment
        }


text:
Q: InfoBox Code - Missing Object error Using Google Maps V3 (PHP/MYSQL with custome infobox), I've put together the code (below) to try and implement the InfoBox code into one of my maps.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Map My Finds - All Locations</title>
        <link rel="stylesheet" href="css/alllocationsstyle.css" type="text/css" media="all" />

When I try and run this I get the following error: 'object expected line 29 char 5'.
Where am I going wrong?
I also would be grateful if someone could possibly give me some advice on whether there may be any debugging tools that could help me identify these types of error in the furture.
UPDATED CODE
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>All Locations</title>
        <link rel="stylesheet" href="css/alllocationsstyle.css" type="text/css" media="all" />

NEW WORKING CODE
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>All Locations</title>
        <link rel="stylesheet" href="css/alllocationsstyle.css" type="text/css" media="all" />

A: You are calling a function downloadUrl() that you have not defined.  You need to define that function.  One way to do that would be to include this code from the original question:
function downloadUrl(url, callback) {
  var request = window.ActiveXObject ?
      new ActiveXObject('Microsoft.XMLHTTP') :
      new XMLHttpRequest;

  request.onreadystatechange = function() {
    if (request.readyState == 4) {
      request.onreadystatechange = doNothing;
      callback(request, request.status);
    }
  };

  request.open('GET', url, true);
  request.send(null);
}


text:
Q: Cannot setup WebpackDevMiddleware on windows I've been banging my head against this issue all day now and still can't figure it out. This is the error I am getting
project\node_modules\webpack-dev-middleware\lib\context.js:95
  context.compiler.hooks.invalid.tap('WebpackDevMiddleware', invalid);
                         ^

TypeError: Cannot read property 'invalid' of undefined

So something to do with my webpack dev middleware.
I've checked that the webpack on it's own is fine which or the sake of space I'll leave a gist to.
However when I try and launch it within the following Node / Express file I get the above error.
const env = require("node-env-file");
const envLocation = __dirname + "/../.env";
env(envLocation);

const path = require('path');
const express = require('express');
const webpack = require('webpack');
const webpackMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware');
const config = require('./../webpack.config.js')({env : "dev"});

const app = express();

if (process.env.ENV === "DEV") {
    const compiler = webpack(config);
    const middleware = webpackMiddleware(compiler, {
        publicPath: config.output.publicPath,
        contentBase: 'src',
        stats: {
            colors: true,
            hash: false,
            timings: true,
            chunks: false,
            chunkModules: false,
            modules: false
        }
    });

    app.use(middleware);
} else {
    app.use(express.static(__dirname + '/dist'));

    app.get('*', function response(req, res) {
        res.sendFile(path.join(__dirname, 'dist/index.html'));
    });
}

// Set Port, hosting services will look for process.env.PORT
app.set('port', (process.env.PORT || 3000));

// start the server
app.listen(app.get('port'), () => {
    console.log(`Server is running on port ${app.get('port')}`);
});

Can anyone see if I'm missing something obvious? I'm running this on a windows 10 machine.
package.json
"extract-text-webpack-plugin": "3.0.2",
"file-loader": "1.1.6",
"html-loader": "0.5.5",
"html-webpack-plugin": "2.30.1",
"node-sass": "4.7.2",
"rimraf": "2.6.2",
"sass-loader": "6.0.6",
"source-list-map": "2.0.0",
"style-loader": "0.20.1",
"uglify-js": "3.3.9",
"url-loader": "0.6.2",
"webpack": "3.10.0",
"webpack-dev-middleware": "^3.0.1",
"webpack-hot-middleware": "^2.21.2",
"webpack-dev-server": "2.11.1"

A: Try upgrading to webpack 4. worked for me.


text:
Q: Tkinter formatting rows I am using Tkinter and have a grid that is successfully outputting the first 2 rows as intended. Now, every time I run the program I want to display a variable number of rows (always after those first 2 rows) starting at row = 2, column = 0. So if there are 4 items to display, all would be shown on the left side one under the other.
Currently, the program only works if there is only 1 item to display. Then it will output properly. If there are more products, then only the last in the list will display.
I tried to do something like .grid(row=2+product), but then I get an error - TypeError: unsupported operand type(s) for +: 'int' and 'dict'.
How can I handle using a variable number of products to create a variable number of labels and display all of them properly?
from tkinter import *
window=Tk()
for product in productList:
    productLabel = Label(
        window,
        bg='#DC143C'
    ).grid(row=2, column=0)
window.mainloop()

A: You can use enumerate() function to get a index and add it to the row option:
for i, product in enumerate(productList):
    productLabel = Label(
        window,
        text=product,
        bg='#DC143C'
    ).grid(row=2+i, column=0)


text:
Q: NHibernate - accessing an object's parent via id or object reference I have the following classes:
public class Parent
{
    public virtual int ParentId { get; set; }
    public virtual string Name { get; set; }
    public virtual ICollection<Child> Children { get; set; }
}

public class Child
{
    public virtual int ChildId { get; set; }
    public virtual string Name { get; set; }
    //public virtual int ParentId { get; set; }
    public virtual Parent Parent { get; set; }
}

These classes map to corresponding tables in the database in a one-to-many relationship. In my mapping classes, I do the following:
using FluentNHibernate.Mapping;
public partial class ParentMap : ClassMap<Parent>
{
    public ParentMap()
    {
        Id(p => p.ParentId).Column.("PARENT_ID").GeneratedBy.Native();
        Map(p => p.Name).Column("PARENT_NAME").Not.Nullable();
        HasMany<Child>(p => p.Children).Cascade.All().LazyLoad().Inverse().AsSet();
    }
}

public partial class ChildMap : ClassMap<Child>
{
    public ChildMap()
    {
        Id(c => c.ChildId).Column("CHILD_ID").GeneratedBy.Native();
        Map(c => c.Name).Column("CHILD_NAME").Not.Nullable();
        References<Parent>(c => x.Parent).Column("PARENT_ID").Not.LazyLoad().Not.Nullable();
    }
}

What I need to be able to do is expose (uncomment the line in the class definition above) the ParentId property in the Child class so that I can do the following:
var child = new Child();
child.ParentId = 1;

That is, I want to be able to attach the Parent to the Child via the child.ParentId property while still being able to access the Parent via the child.Parent property. E.g.,
// i currently have to do the following in order to link the child with
// the parent when I update an existing Child instance (ParentService() and
// ChildService() are service classes that sit between my applications and
// NHibernate).
var parentService = new ParentService();
var parent = parentService.GetById(1);
var child = new Child() { ChildId = 2, Parent = parent, Name = "New Name" };
var childService = new ChildService();
childService.Save(child);

// in a different project, i access the Parent object via the child's
// Parent property
var childService = new ChildService();
var child = childService.GetById(2);
Console.WriteLine(child.Parent.Name);

// i want to do this instead
var child = new Child() { Id = 2, ParentId = 1, Name = "New Name" };
var childService = new ChildService();
childService.Save(child);
Console.WriteLine(child.Id); // 11

// [ ... ]

var childService = new ChildService();
var child = childService.GetById(2);
Console.WriteLine(child.Parent.Name);

How would I change the mappings to make that happen? TIA,
Ralf Thompson

A: That's not a correct usage of NHibernate.
To get the Id of the parent use:
var parentId = child.Parent.Id; //this does not cause loading

To set the parent by Id, use
child.Parent = session.Load<Parent>(parentId); //this never goes to the DB either


text:
Q: QuickCheck: How to use exhaustiveness checker to prevent forgotten constructors of a sum type I have a Haskell data type like
data Mytype
  = C1
  | C2 Char
  | C3 Int String

If I case on a Mytype and forget to handle one of the cases, GHC gives me a warning (exhaustiveness check).
I now want to write a QuickCheck Arbitrary instance to generate MyTypes like:
instance Arbitrary Mytype where
  arbitrary = do
    n <- choose (1, 3 :: Int)
    case n of
      1 -> C1
      2 -> C2 <$> arbitrary
      3 -> C3 <$> arbitrary <*> someCustomGen

The problem with this is that I can add a new alternative to Mytype and forget to update the Arbitrary instance, thus having my tests not test that alternative.
I would like to find a way of using GHC's exhaustiveness checker to remind me of forgotten cases in my Arbitrary instance.
The best I've come up with is
arbitrary = do
  x <- elements [C1, C2 undefined, C3 undefined undefined]
  case x of
    C1     -> C1
    C2 _   -> C2 <$> arbitrary
    C3 _ _ -> C3 <$> arbitrary <*> someCustomGen

But it doesn't really feel elegant.
I intuitively feel that there's no 100% clean solution to this, but would appreciate anything that reduces the chance of forgetting such cases - especially in a big project where code and tests are separated.

A: I implemented a solution with TemplateHaskell, you can find a prototype at https://gist.github.com/nh2/d982e2ca4280a03364a8. With this you can write:
instance Arbitrary Mytype where
  arbitrary = oneof $(exhaustivenessCheck ''Mytype [|
      [ pure C1
      , C2 <$> arbitrary
      , C3 <$> arbitrary <*> arbitrary
      ]
    |])

It works like this: You give it a type name (like ''Mytype) and an expression (in my case a list of arbitrary style Gens). It gets the list of all constructors for that type name and checks whether the expression contains all of these constructors at least once. If you just added a constructor but forgot to add it to the Arbitrary instance, this function will warn you at compile time.
This is how it's implemented with TH:
exhaustivenessCheck :: Name -> Q Exp -> Q Exp
exhaustivenessCheck tyName qList = do
  tyInfo <- reify tyName
  let conNames = case tyInfo of
        TyConI (DataD _cxt _name _tyVarBndrs cons _derives) -> map conNameOf cons
        _ -> fail "exhaustivenessCheck: Can only handle simple data declarations"

  list <- qList
  case list of
    input@(ListE l) -> do
      -- We could be more specific by searching for `ConE`s in `l`
      let cons = toListOf tinplate l :: [Name]
      case filter (`notElem` cons) conNames of
        [] -> return input
        missings -> fail $ "exhaustivenessCheck: missing case: " ++ show missings
    _ -> fail "exhaustivenessCheck: argument must be a list"

I'm using GHC.Generics to easily traverse the syntax tree of the Exp: With toListOf tinplate exp :: [Name] (from lens) I can easily find all Names in the whole exp.
I was surprised that the types from Language.Haskell.TH do not have Generic instances, and neither (with current GHC 7.8) do Integer or Word8 - Generic instances for these are required because they appear in Exp. So I added them as orphan instances (for most things, StandaloneDeriving does it but for primitive types like Integer I had to copy-paste instances as Int has them).
The solution is not perfect because it doesn't use the exhaustiveness checker like case does, but as we agree, that's not possible while staying DRY, and this TH solution is DRY.
One possible improvement/alternative would be to write a TH function that does this check for all Arbitrary instances in a whole module at once instead of calling exhaustivenessCheck inside each Arbitrary instance.

A: You want to ensure that your code behaves in a particular way; the simplest way to check the behaviour of code is to test it.
In this case, the desired behaviour is that each constructor gets reasonable coverage in tests. We can check that with a simple test:
allCons xs = length xs > 100 ==> length constructors == 3
             where constructors = nubBy eqCons xs
                   eqCons  C1       C1      = True
                   eqCons  C1       _       = False
                   eqCons (C2 _)   (C2 _)   = True
                   eqCons (C2 _)    _       = False
                   eqCons (C3 _ _) (C3 _ _) = True
                   eqCons (C3 _ _)  _       = False

This is pretty naive, but it's a good first shot. Its advantages:

*

*eqCons will trigger an exhaustiveness warning if new constructors are added, which is what you want

*It checks that your instance is handling all constructors, which is what you want

*It also checks that all constructors are actually generated with some useful probability (in this case at least 1%)

*It also checks that your instance is usable, eg. doesn't hang

Its disadvantages:

*

*Requires a large amount of test data, in order to filter out those with length > 100

*eqCons is quite verbose, since a catch-all eqCons _ _ = False would bypass the exhaustiveness check

*Uses magic numbers 100 and 3

*Not very generic

There are ways to improve this, eg. we can compute the constructors using the Data.Data module:
allCons xs = sufficient ==> length constructors == consCount
             where sufficient   = length xs > 100 * consCount
                   constructors = length . nub . map toConstr $ xs
                   consCount    = dataTypeConstrs (head xs)

This loses the compile-time exhaustiveness check, but it's redundant as long as we test regularly and our code has become more generic.
If we really want the exhaustiveness check, there are a few places where we could shoe-horn it back in:
allCons xs = sufficient ==> length constructors == consCount
             where sufficient   = length xs > 100 * consCount
                   constructors = length . nub . map toConstr $ xs
                   consCount    = length . dataTypeConstrs $ case head xs of
                                                                  x@(C1)     -> x
                                                                  x@(C2 _)   -> x
                                                                  x@(C3 _ _) -> x

Notice that we use consCount to eliminate the magic 3 completely. The magic 100 (which determined the minimum required frequency of a constructor) now scales with consCount, but that just requires even more test data!
We can solve that quite easily using a newtype:
consCount = length (dataTypeConstrs C1)

newtype MyTypeList = MTL [MyType] deriving (Eq,Show)

instance Arbitrary MyTypeList where
  arbitrary = MTL <$> vectorOf (100 * consCount) arbitrary
  shrink (MTL xs) = MTL (shrink <$> xs)

allCons (MTL xs) = length constructors == consCount
                   where constructors = length . nub . map toConstr $ xs

We can put a simple exhaustiveness check in there somewhere if we like, eg.
instance Arbitrary MyTypeList where
  arbitrary = do x <- arbitrary
                 MTL <$> vectorOf (100 * consCount) getT
              where getT = do x <- arbitrary
                              return $ case x of
                                            C1     -> x
                                            C2 _   -> x
                                            C3 _ _ -> x
  shrink (MTL xs) = MTL (shrink <$> xs)

A: Here I exploit an unused variable _x. This is not really more elegant than your solution, though.
instance Arbitrary Mytype where
  arbitrary = do
    let _x = case _x of C1 -> _x ; C2 _ -> _x ; C3 _ _ -> _x
    n <- choose (1, 3 :: Int)
    case n of
      1 -> C1
      2 -> C2 <$> arbitrary
      3 -> C3 <$> arbitrary <*> someCustomGen

Of course, one has to keep the last case coherent with the dummy definition of _x, so it is not completely DRY.
Alternatively, one might exploit Template Haskell to build a compile-time assert checking that the constructors in Data.Data.dataTypeOf are the expected ones. This assert has to be kept coherent with the Arbitrary instance, so this is not completely DRY either.
If you do not need custom generators, I believe Data.Data can be exploited to generate Arbitrary instances via Template Haskell (I think I saw some code doing exactly that, but I can't remember where). In this way, there's no chance the instance can miss a constructor.

A: Here is a solution using the generic-random library:
{-# language DeriveGeneric #-}
{-# language TypeOperators #-}

import Generic.Random
import GHC.Generics
import Test.QuickCheck

data Mytype
  = C1
  | C2 Char
  | C3 Int String
  deriving Generic

instance Arbitrary Mytype where
  arbitrary = genericArbitraryG customGens uniform
    where
      customGens :: Gen String :+ ()
      customGens = someCustomGen :+ ()

someCustomGen :: Gen String
someCustomGen = undefined

genericArbitraryG takes care of generating each constructor of MyType. In this case we use uniform to get a uniform distribution of constructors. With customGens we define that each String field in Mytype is generated with someCustomGen.
See Generic.Random.Tutorial for more examples.


text:
Q: Clang - changing linker I am trying to compile/link a program using Clang but its defaulting to using MSVC's link.exe. I am trying to override this and change the linker being used to LD.
I am adding this into my compilation command: "link-fuse=ld" (I have tried replacing ld with a path to the actual executable) and receive this error:
LINK: fatal error: LNK1181: cannot open input file "ink-fuse=ld.lib"
Notice that the "l" from link is being peeled off. How can I change the linker Clang is using?

A: The correct flag is -fuse-ld=ld. See how they illustrate the use of lld in a similar way: https://lld.llvm.org/#using-lld


text:
Q: difference between * and /* in gitignore I find /* and * has different means when I compare with the setting:
*

!/init.el
!/README.md
!.gitignore
!/lib/

VS
/*

!/init.el
!/README.md
!.gitignore
!/lib/

The former not track /lib/ but the latter track it.
How to undertand * and /*?
UPDATE
I think this question is not exactly same as another one. Because he is focus on dir/** and dir/* but this one is focus on /* and *.

A: The first version ignores all files except those listed explicitly. lib is ignored because it contains no trackable files. Git does not track folders, so directories that appear empty seem to get ignored.
The second version ignores all root level files and directories except those listed explicitly. It does not ignore anything that is trackable and not in the root directory. lib is listed explicitly, so it is not ignored. Any files it contains are not at the root level, so they aren't ignored either.

A: The answer is a little complicated because Git's scanning algorithm is tricky, but it boils down to the fact that * matches lib/custom-file.el but /* does not.
As a general rule, in glob patterns, * does not "cross" path name separator /-es.  Hence A*B matches ANameThatEndsInB but not ADirectory/WithAFileB.
Putting a / in a glob pattern requires that the thing before the / name a directory and the thing after the / occur within the directory: A*/*B does match ADirectory/WithAFileB.  The name components, ADirectory and WithAFileB, are matched individually against the glob components, A* and *B.
A glob pattern ending in /, as in */, matches only directories.  One starting with / has another special meaning in Git (but note that, e.g., the .gitignore entry /foo/bar/ consists of two components: /foo/ and then bar/; the bar/ part does not start with a slash).  In particular, if the pattern starts with /, it applies only to files in the top level of that Git directory.  If that's the top level .gitignore then this means the root of the work-tree itself.
Now, as in Mad Physicist's answer, it's true that if Git has no existing tracked files within a directory, Git does not have to read that directory sometimes.  An ignore pattern that matches a directory name will make Git skip the scanning of the directory, if Git does not already have to scan that directory for some other reason.  So in general, if you have a .gitignore that has * in it anywhere, any directory tends to get skipped entirely—well, as long as Git doesn't already have to look inside it for some other reason.  So * in a .gitignore tends to ignore all directories.  However, Git's ignore rules say that whenever Git has hold of a file or directory name and is checking .gitignore files, it should read through the entire file and find all matches, including the ones with ! in front of them.  This means that, for instance:
*
!*/

will tell Git to ignore everything (including directories), but override that by saying don't ignore the */ directories.  But the * will continue to ignore all files.
If you make it read:
/*
!/*/

you'll ignore all files in this directory (the one containing the .gitignore) but have Git scan all its subdirectories.  Everything within any sub-directory such as foo/name will fail to match either of these glob patterns, since the foo/name part has a slash and the * cannot cross it.


text:
Q: Grails Unit test controller I'm trying to do a Unit test on this controller. I'm new to this sort of testing so I dont know from where do I start and how to test things that are needed to be tested, like user, render view.)
class ShoppingCartController {

    def shoppingCartWebshopService
    def shoppingCartService
    def springSecurityService
    def checkoutOperaService
    def databaseService
    def dodAdresaService

    def payingOrder(SetShop1Command cmd) {

        def user = springSecurityService.isLoggedIn() ? springSecurityService.currentUser.sifpartnera : null
        def tempAdrese = databaseService.getAdrese(user)
        def adrese = []
        tempAdrese.each{
            adrese.add(it.adresa)
        }

        if (cmd.hasErrors()) {
            render(view: 'OrderChoseAddress', model: [cmd : cmd, params : params, adrese: adrese ])
        }

        def inputUnAdrese = params.inputUnAdrese

        [inputUnAdrese: inputUnAdrese, adrese: adrese]
    }

This is my test
@Mock([SpringSecurityService,DatabaseService])
@TestFor(ShoppingCartController)
class ShoppingCartControllerTests {

void testPayingOrder(){

    when:
    // params.user = 19
    // user.equals(id)
    // println user
    // controller.OrderChoseAddress()
        controller.params.user = "admin"
        controller.databaseService = new DatabaseService()

    then:
        assert model.adrese != null
}


text:
Q: In what Atlantis episode was a wraith stunner pistol shot and destroyed? In an episode of Stargate Atlantis, I recall a battle where a wraith stunner pistol was shot and destroyed/disabled. I seem to recall it was Sheppard who was using it at the time, but I could be mistaken.
Does anyone recall in which episode this occurred? I think this may have been the only time a stunner pistol was damaged like this.
Here is a photo of the damaged stunner:

A: I ended up watching the series again and found the damaged stunner in Season 4, Episode 5, "Travelers"
Larrin picks up the stunner from the dead wraith that Sheppard killed and discovers that it was damaged.

Additionally, stunner pistols weren't introduced until the first episode of Season 2.


text:
Q: How to moves the divs by clicking on each one I want to when I click on every div
 It's the first to be in front of  everyone and the others div are moved.for example div4 is in front of everyone.when I click on div1 I want to put div1 in place of div4 and Then again, on each one that I click on, it's the front but My code does not work properly after several times and does not display one of the shapes.

$(".haml-category").click(function() {
  var top = $(this).data("top");
  var zindex = $(this).data("zindex");
  var temp = $(".haml-category-container").find(".selected");
  $(".haml-category-container").find(".selected").removeClass("selected").data("zindex", zindex).data("top", top).css({
    "z-index": zindex,
    "top": top
  });
  $(this).data("zindex", temp.data("zindex")).data("top", temp.data("top")).addClass("selected");

});
.haml-category-container {
  position: relative;
background-color:#ccc;
}

.haml-category {
  position: absolute;
  width: 100%;
  height: 500px;
  top: 0;
  right: 0;
  border: 1px solid black;
  transition: top 1s;
}

.sec-saheb-bar {
  z-index: 0;
}

.sec-ranande {
  z-index: 1;
  top: 40px;
}

.sec-barbar {
  z-index: 2;
  top: 85px;
}

.sec-bazaryab {
  z-index: 3;
  top: 130px;
}

.selected {
  z-index: 3;
  top: 130px;
}

div1

 content div1

div2

 content div2

div3

 content div3

div4

 content div4

A: I did this FRANKENSTEIN's monster in 2010 for testing purpose.how you can see i put everywhere z-index:9  watch the demo try to drag every element over other element.with some modifications you can convert it in jquery

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<TITLE></TITLE>

<meta charset="UTF-8">

<FORM METHOD=POST ACTION="#" NAME="f1">

xpic<INPUT TYPE="text" NAME="xpic">

ypic<INPUT TYPE="text" NAME="ypic">

ypic<INPUT TYPE="submit" NAME="submit" value="submit">

</FORM>

Yes!

yep yep !

 11
 12
 13

 21
 22
 23

 31
 32
 33

  <FORM METHOD=POST ACTION="#" NAME="f3">
 <TEXTAREA style="position:absolute;left:50;top:175;z-index:9;" onmouseover="overb(this);doit(this)" onmouseout="outb(this);" id="txt" NAME="aa" ROWS="20" COLS="20"></TEXTAREA>
  </FORM>

A: The variable temp may has be changed,modified as below.

$(".haml-category").click(function() {
  var top = $(this).data("top");
  var zindex = $(this).data("zindex");
  var temp = $(".haml-category-container").find(".selected");
  var top2 = temp.data("top");
  var zindex2 = temp.data("zindex");
  $(this).data("zindex", zindex2).data("top", top2).css({
    "z-index": zindex2,
    "top": top2
  }).addClass("selected");
  temp.removeClass("selected").data("zindex", zindex).data("top", top);
  temp.css({
    "z-index": zindex,
    "top": top
  });

});
.haml-category-container {
  position: relative;
}

.haml-category {
  position: absolute;
  width: 100%;
  height: 500px;
  top: 0;
  right: 0;
  border: 1px solid black;
  transition: top 1s;
}

.sec-saheb-bar {
  z-index: 0;
}

.sec-ranande {
  z-index: 1;
  top: 40px;
}

.sec-barbar {
  z-index: 2;
  top: 85px;
}

.sec-bazaryab {
  z-index: 3;
  top: 130px;
}

.selected {
  z-index: 3;
  top: 130px;
}
#sec-saheb-bar{
  background-color:#0077CC;
}
#sec-ranande{
  background-color:#1F1D1C;
}
#sec-barbar{
  background-color:#FECD45;
}
#sec-bazaryab{
  background-color:#1AA160;
}

div1

div2

div3

div4


text:
Q: How to convert '__NSIArrayI' to JSON Array in Swift? I am new to Swift 4 and working on an iOS app. I have the following JSON data retrieved from the server which will be extracted to data table.
[
  {
    "fund_nav_validity":"24 August to 31 August 2016\n",
    "fund_nav_cost":10,
    "fund_nav_sell":9.85,
    "nav_id":118,
    "fund_nav_buy":10,
    "fund_id":1,
    "nav_as_on_date":"24-Aug-16",
    "fund_nav_market":9.95
  },
  {
    "fund_nav_validity":"04 September to 07 September 2016\n",
    "fund_nav_cost":10,
    "fund_nav_sell":9.85,
    "nav_id":117,
    "fund_nav_buy":10,
    "fund_id":1,
    "nav_as_on_date":"01-Sep-16",
    "fund_nav_market":9.95
 }
]

I have done following task in the navdata function to retrieve the '__NSIArrayI' to JSON:
func getNAVData(){
        Alamofire.request(url, method: .post).responseJSON{
            response in
            if response.result.isSuccess{
                print("Success")
                //let navDataJSON : JSON = JSON(response.result.value!
                let navDataJSON : JSON = JSON(response.result.value!)

                print(navDataJSON)
            }else{
                print("Failed")
            }
        }

    }

I need to convert it to JSON Array which is done in java. How to do the similar task in Swift 4?

A: you are in the right way, in here you need to convert your  JSON response to array the reason your json started with this type[{}] and check your JSON response contains the value or not in intially. try the below code
 if response.result.isSuccess{
            print("Success")
            // convert your JSON to swiftyJSON array type if your JSON response as array as well as check its contains data or not
             guard let resJson = JSON(responseObject.result.value!).array ,  !resJson.isEmpty else { return
            }
            // create the Swifty JSON array for global access like wise
            var navDataJSON  =  [JSON]() //[JSON]() --> Swifty-JSON array memory allocation.
            navDataJSON =  resJson

        }

A: If you want to use SwiftyJSON return responseData rather than responseJSON. This avoids a double conversion, and handle always a potential error
func getNAVData(){
    Alamofire.request(url, method: .post).responseData { response in

        switch response.result {
            case .success(let data):
                 let navDataJSON = JSON(data).arrayValue
                 print(navDataJSON)

             case .failure(let error): print(error)
        }
    }
}

The result navDataJSON is a JSON array.

However in Swift 4+ it's highly recommended to use the more efficient and built-in Codable protocol
struct Fund : Decodable {
    let fundNavValidity, navAsOnDate : String
    let fundNavCost, navId, fundNavBuy, fundId : Int
    let fundNavSell, fundNavMarket : Double
}

func getNAVData(){
    Alamofire.request(url, method: .post).responseData { response in

        switch response.result {
            case .success(let data):
                 do {
                     let decoder = JSONDecoder()
                     decoder.keyDecodingStrategy = .convertFromSnakeCase
                     let navDataJSON = decoder.decode([Fund].self, from : data)
                     print(navDataJSON)
                 } catch { print(error) }

             case .failure(let error): print(error)
        }
    }
}

The result is an array of Fund structs.

A: You're getting the JSON array and if you want to convert to model Array then you can use create Model Struct and confirm to Decodable Protocol, without using SwiftyJSON using inbuilt solution to parse JSON.
import Foundation

// MARK: - Element
struct Model: Decodable {
    let fundNavValidity: String
    let fundNavCost: Int
    let fundNavSell: Double
    let navId: Int
    let fundNavBuy: Int
    let fundId: Int
    let navAsOnDate: String
    let fundNavMarket: Double

    enum CodingKeys: String, CodingKey {
        case fundNavValidity = "fund_nav_validity"
        case fundNavCost = "fund_nav_cost"
        case fundNavSell = "fund_nav_sell"
        case navId = "nav_id"
        case fundNavBuy = "fund_nav_buy"
        case fundId = "fund_id"
        case navAsOnDate = "nav_as_on_date"
        case fundNavMarket = "fund_nav_market"
    }
}

then in getNAVData method you can use JSONDecoder to covert to Model struct array like below
func getNAVData() {
        Alamofire.request(url, method: .post).responseJSON {
            response in
            switch response.result {
            case .success(let data):
                do {
                    let modelArray = try JSONDecoder().decode([Model].self, from: data)
                    print(modelArray)
                } catch {
                    print("Error: \(error)")
                }
            case .failure(let error):
                print(error.localizedDescription)
            }
        }
    }


text:
Q: Как связать Yii2 и React Возник такой вопрос, который покажется вам глупым.
Я создал API на Yii2 (basic), которое позволяет получать нужные данные из базы в json формате. Yii2 запускается на локальном сервере. Теперь я хочу создать, собственно, интерфейс на React и с помощью Ajax запросов обращаться к этим данным.Что для этого нужно сделать?
Создать create-react-app в корневой папке проекта, и как-то сообщить yii об этом проекте? Или как-то по-другому это делается? Ответьте, пожалуйста, совсем новичок в этом.

И ещё, обязательно ли приложение будет SPA, или может быть и MPA?

A: SPA или MPA решать исключительно вам. Зависит от самого проекта. А по поводу подключения к yii2 вам нужно сбилдить свой проект в чистый js. Для этого в scripts в package.json нужно иметь   "build": "react-scripts build", после запустить в терминале npm run build. Если же вы создавали React проект в WebStorm, то этот скрипт уже туда внесен. После того, как вы сбилдите js, в папке build будет index.html где будут подключен js. Далее нужно будет перенести index.html и директории с ресурсами js и css в ваш проект на yii. То есть в корневой роут внести эту эту верстку с этими ресурсами, как бы вы сделали имев обычную верстку.

A: Для связки Yii2 как API и React как фронта, есть библиотека ReactYii2Essentials: https://github.com/BlackBes/react-yii2-essentials
Она сейчас в разработке, но уже позволяет в React воссоздать привычную для Yii2 иерархию, добавляет знакомые компоненты.
Так же у этой библиотеки, есть библиотека для самого yii2, онв добавляет gii генератор React CRUD, для быстрого старта, а так же базовые контроллеры и модели, чтобы API работал без костылей.
Рекомендую, попробуйте.


text:
Q: Display one by one record using next / previous button I am showing 10 records using Hash Map like this:
 for (int i = 0; i < jArray.length(); i++) {
                JSONObject c = jArray.getJSONObject(i);

            //  Item objItem = new Item();

                u_Id = jArray.getJSONObject(i).getString(TAG_ID);
                u_name = jArray.getJSONObject(i).getString(TAG_NAME);
                u_refer = jArray.getJSONObject(i).getString(TAG_Image);
                u_image = jArray.getJSONObject(i).getString(TAG_refere);
                u_des = jArray.getJSONObject(i).getString(TAG_des);

                HashMap<String, String> map = new HashMap<String, String>();

                map.put(TAG_ID, u_Id);
                map.put(TAG_NAME, u_name);
                map.put(TAG_refere, u_refer);
                List.add(map);

                Log.v(TAG_ID, u_Id);
                Log.v(TAG_NAME,u_name);
                Log.v(TAG_refere, u_refer);
                Log.v(TAG_Image,u_image);
                Log.v(TAG_des, u_des);

             ListAdapter adapter = new SimpleAdapter(this, List,
             R.layout.row,new String[] { TAG_ID, TAG_NAME }, new int[] {R.id.textView1, R.id.textView2 });
             listView.setAdapter(adapter);
           //  View header = (View)getLayoutInflater().inflate(R.layout.todo_row, null);
           //  listView.addHeaderView(header);

            }

now I want to show record one by one on next and previous button , on previous button should displayed previous record and on next button should displayed next record . please any help will be appreciated.

A: i achieved my goal by doing this :
 int position =0 ;

@Override
        public void onClick(View button) {
            if (button == nxt) {
                if(position < List.size() - 1){
                    position++;
                    List.get(position);
                    String name = List.get(position).get(TAG_NAME);
                    String Des = List.get(position).get(TAG_des);
                    String aa = String.valueOf(position);
                 //  Log.v("tag",name);
                 //   Log.v("tag", Des);
                   System.out.println( name+Des);
                }
                else
                  Log.d("TAG","Last Record");
            } else if (button == pre) {
                if(position > 0){
                   position--;
                  List.get(position);
                  String aa = String.valueOf(position);
                 Log.i("tag", aa);
               // System.out.print(position);
              //  (position);
              }
              else
                Log.d("TAG","First Record");

A:
Send your String array and position values to next activity

list.setOnItemClickListener(new OnItemClickListener() {
          public void onItemClick(AdapterView<?> parent, View view,
              int position, long id) {
              Intent i = new Intent(listview.this, Single_SMS.class);
              // sending data to new activity
              i.putExtra("position", position);
              i.putExtra("strings", web);
              startActivity(i);

          }
        });

Retrieve both string array and position in the next activity.

public class NextActivity extends Activity {
int position;
String[] web;
int size;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
     setContentView(R.layout.single_sms);

    Bundle bd = getIntent().getExtras();

    if (bd != null) {
        position = bd.getInt("position", 0);
        web = bd.getStringArray("strings");
        size = web.length;
        Button txtProduct = (Button) findViewById(R.id.button1);
        txtProduct.setText(" " + web[position]);
    }

    btn_next.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            position = position + 1;
            if (position > size) {
                Button txtProduct = (Button) findViewById(R.id.button1);
                txtProduct.setText(" " + web[position]);
            }

        }
    });

}}


text:
Q: I have a button in homepage theme in 2 language how I can send the user when he click in button learn more when he is in the English home page to about us in English and when he is in the Arabic home page and click go to about us in Arabic language

A: Install the WPML plugin and use another language and add the item to your navigation menu.


text:
Q: How to send additional parameters in keycloak login? I am working on keycloak login and I have to send additional parameters in keycloak login such as role to login as admin and a normal user. I would like to know is it possible. I have added a checkbox for admin in login template. I attach the template of login theme below. If someone knows how about it then please let me know. Thank you.
login.ftl
<#import "template.ftl" as layout>
<@layout.registrationLayout displayMessage=!messagesPerField.existsError('username','password') displayInfo=realm.password && realm.registrationAllowed && !registrationDisabled??; section>
    <#if section = "header">
        ${msg("loginAccountTitle")}
    <#elseif section = "form">

        <#if realm.password>
            <form id="kc-form-login" onsubmit="login.disabled = true; return true;" action="${url.loginAction}" method="post">
                <#if !usernameHidden??>

                        <#if !realm.loginWithEmailAllowed>${msg("username")}<#elseif !realm.registrationEmailAsUsername>${msg("usernameOrEmail")}<#else>${msg("email")}</#if>

                        <input tabindex="1" id="username" class="${properties.kcInputClass!}" name="username" value="${(login.username!'')}"  type="text" autofocus autocomplete="off"
                               aria-invalid="<#if messagesPerField.existsError('username','password')>true</#if>"
                        />

                        <#if messagesPerField.existsError('username','password')>

                                    ${kcSanitize(messagesPerField.getFirstError('username','password'))?no_esc}

                        </#if>

                </#if>

                    ${msg("password")}

                    <input tabindex="2" id="password" class="${properties.kcInputClass!}" name="password" type="password" autocomplete="off"
                           aria-invalid="<#if messagesPerField.existsError('username','password')>true</#if>"
                    />

                    <#if usernameHidden?? && messagesPerField.existsError('username','password')>

                                ${kcSanitize(messagesPerField.getFirstError('username','password'))?no_esc}

                    </#if>

                        <input type="checkbox" id="admin" name="admin" value="on"> Admin mode

                        <#if realm.rememberMe && !usernameHidden??>

                                    <#if login.rememberMe??>
                                        <input tabindex="3" id="rememberMe" name="rememberMe" type="checkbox" checked> ${msg("rememberMe")}
                                    <#else>
                                        <input tabindex="3" id="rememberMe" name="rememberMe" type="checkbox"> ${msg("rememberMe")}
                                    </#if>

                        </#if>

                            <#if realm.resetPasswordAllowed>
                                ${msg("doForgotPassword")}
                            </#if>

                      <input type="hidden" id="id-hidden-input" name="credentialId" <#if auth.selectedCredential?has_content>value="${auth.selectedCredential}"</#if>/>
                      <input tabindex="4" class="${properties.kcButtonClass!} ${properties.kcButtonPrimaryClass!} ${properties.kcButtonBlockClass!} ${properties.kcButtonLargeClass!}" name="login" id="kc-login" type="submit" value="${msg("doLogIn")}"/>

            </form>
        </#if>

    <#elseif section = "info" >
        <#if realm.password && realm.registrationAllowed && !registrationDisabled??>

                    ${msg("noAccount")} ${msg("doRegister")}

        </#if>
    <#elseif section = "socialProviders" >
        <#if realm.password && social.providers??>

${msg("identity-provider-login-label")}

                <ul class="${properties.kcFormSocialAccountListClass!} <#if social.providers?size gt 3>${properties.kcFormSocialAccountListGridClass!}</#if>">
                    <#list social.providers as p>
                        <a id="social-${p.alias}" class="${properties.kcFormSocialAccountListButtonClass!} <#if social.providers?size gt 3>${properties.kcFormSocialAccountGridItem!}</#if>"
                                type="button" href="${p.loginUrl}">
                            <#if p.iconClasses?has_content>

                                ${p.displayName!}
                            <#else>
                                ${p.displayName!}
                            </#if>

                    </#list>

        </#if>
    </#if>

</@layout.registrationLayout>

A: Actually login takes place on the premises that users 's roles are already known by keycloak. Keycloak stores roles of every user.


text:
Q: How to handle double layer protective route wrapper in React I have created a protective Route wrapper component to restrict access to other components if the user is not logged in.
import React from 'react'
import { Route, Redirect } from 'react-router-dom'
import { useAuthContext} from '../AuthContext'

export default function PrivateRoute({ component: Component, ...rest }) {

    const { currentUser } = useAuthContext()

    return (
        <Route {...rest} render={props => {
            if (!currentUser) {
                return <Redirect to="/login" />
            } else {
                return <Component { ...props } />
            }
        }} />
    )
}

This works fine, but then I wanted to add another layer for when the user has logged in for the first time and it has to finish its registration, so if there is no firstNameDb (which is required) in the database the access to other pages than /profile should be restricted:
import React from 'react'
import { Route, Redirect } from 'react-router-dom'
import { useAuthContext} from '../AuthContext'

export default function PrivateRoute({ component: Component, ...rest }) {

    const { currentUser, userData: { firstNameDb } } = useAuthContext()

    return (
        <Route {...rest} render={props => {
            if (!currentUser) {
                return <Redirect to="/login" />
            } else if (!firstNameDb) {
                return <Redirect to="/profile" />
            } else {
                return <Component { ...props } />
            }
        }} />
    )
}

This also works fine, but only when the user is for the first time in the app and finishes registration. For the rest of the cases, when the user already finished the registration and logged in, this doesn't, because firstNameDb always starts empty "" and takes a bit of time to setState and get populated from the API call, and wherever you will find yourself in the app and refresh the page, you will always end up in /profile.
AuthContext.js
...
const [userData, setUserData] = useState({
   firstNameDb: "",
   ...
})

What would be a way to avoid this or the best way to solve this kind of permission?


text:
Q: Is it possible to call functions in a remote shell script? I'm trying to remotely call a function defined in a shell script on a different server, and have that function run on the remote server.
Hopefully the following example should make this clear.
On host2 I have two scripts.
utils.sh:
f ()
{
  hostname
}

test.sh:
. utils.sh
f

On host2 I can then do the following:
host2:/tmp# ./test.sh
 host2

From host1, I want to be able to call the function f and have it run on host2 (so in this example, it would print "host2" since f just calls hostname). However, in fact I get the following error:
host1:~# ssh root@host2 /tmp/test.sh
 /tmp/test.sh: line 1: utils.sh: No such file or directory
 /tmp/test.sh: line 2: f: command not found

So, it's clear that test.sh is actually running on host1 - which is why it can't find /tmp/utils.sh (since that's only on host2) and correspondingly why if can't run function f.
Is it possible to call a function in a remote shell script, and have it run on the remote machine? Or is there anything else I can do to achieve a similar aim?
Thanks :-)

A: Ah, there was a bug in my script.
test.sh should have been
. /tmp/utils.sh
f

I was missing the full path to the utils.sh script.
-Edited to add:-
Worth noting that it's not necessary to wrap the dotting in & function call in a new script - it is also possible to call directly like so:
host1:~# ssh root@host2 ". /tmp/utils.sh; f"
 host2


text:
Q: Unmarshalled XML to abstract class, how to know the xsi:type in order to instanciate one class or another I have to unmarshall a XML(XML version 1) to get the values and put these ones in a new version of that XML(XML version 2). The problem is there are a lot of tags with xsi, and this fact is reflected in the unmarshalled class as abstract classes that can be extended by a various classes, and my question is, what is the way to know the class which extends of an abstract class given by the XML xsi:type? I put here my code and the resources, thanks.
XML schema that content the data that I want: http://www.datex2.eu/content
/xml-schema
XML source with data: http://infocar.dgt.es/datex2/dgt/SituationPublication/all/content.xml
XML schema of actual version: http://www.datex2.eu/content/datex-ii-xml-schema-23 My finall achieve is to convert the first XML in one of this.
My actually code(Testing):
public class Main {

    public static void main(String[] args) throws IOException, SAXException, TransformerException, JAXBException, XMLStreamException, ParserConfigurationException {

        URL url = null;

        try {

            url = new URL("http://infocar.dgt.es/datex2/dgt/SituationPublication/all/content.xml");

        } catch (MalformedURLException e) {

            e.printStackTrace();
        }
        System.out.println("Abriendo URL..");
        URLConnection conn = url.openConnection();
        System.out.println("URL cargada");
        System.out.println("Cargando los datos necesarios...");

        JAXBContext jaxbContext = JAXBContext.newInstance(eu.datex.schema._1_0._1_0.D2LogicalModel.class);
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        JAXBElement<eu.datex.schema._1_0._1_0.D2LogicalModel> DatexModelElement = (JAXBElement<eu.datex.schema._1_0._1_0.D2LogicalModel>) unmarshaller.unmarshal(url);
        eu.datex.schema._1_0._1_0.D2LogicalModel datex1 = DatexModelElement.getValue();
        eu.datex2.schema._2_0._2_3.D2LogicalModel datex2 = new eu.datex2.schema._2_0._2_3.D2LogicalModel();

        SituationPublication situation = (SituationPublication)datex1.getPayloadPublication();

        List<Situation> situationList = situation.getSituation();
        for (int i = 0; i < situationList.size(); ++i)
        {
            List<SituationRecord>situationRecordList = situationList.get(i).getSituationRecord();
            for(int y = 0; y < situationRecordList.size(); ++y)
            {
               //the question is here, how to know which class extends as SituationRecord in other to have one get method or another?

            }

        }
      }
}

SituationRecord.class example:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2010.11.14 at 03:28:36 PM PST
//

package eu.datex.schema._1_0._1_0;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlID;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

/**
 * An identifiable instance of a single record/element within a situation.
 *
 *
Java class for SituationRecord complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="SituationRecord">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="situationRecordCreationReference" type="{http://datex2.eu/schema/1_0/1_0}String" minOccurs="0"/>
 *         <element name="situationRecordCreationTime" type="{http://datex2.eu/schema/1_0/1_0}DateTime"/>
 *         <element name="situationRecordObservationTime" type="{http://datex2.eu/schema/1_0/1_0}DateTime" minOccurs="0"/>
 *         <element name="situationRecordVersion" type="{http://datex2.eu/schema/1_0/1_0}NonNegativeInteger"/>
 *         <element name="situationRecordVersionTime" type="{http://datex2.eu/schema/1_0/1_0}DateTime"/>
 *         <element name="situationRecordFirstSupplierVersionTime" type="{http://datex2.eu/schema/1_0/1_0}DateTime"/>
 *         <element name="informationUsageOverride" type="{http://datex2.eu/schema/1_0/1_0}InformationUsageEnum" minOccurs="0"/>
 *         <element name="probabilityOfOccurrence" type="{http://datex2.eu/schema/1_0/1_0}ProbabilityOfOccurrenceEnum"/>
 *         <element name="sourceInformation" type="{http://datex2.eu/schema/1_0/1_0}SourceInformation" minOccurs="0"/>
 *         <element name="validity" type="{http://datex2.eu/schema/1_0/1_0}Validity"/>
 *         <element name="impact" type="{http://datex2.eu/schema/1_0/1_0}Impact" minOccurs="0"/>
 *         <element name="cause" type="{http://datex2.eu/schema/1_0/1_0}Cause" minOccurs="0"/>
 *         <element name="advice" type="{http://datex2.eu/schema/1_0/1_0}Advice" maxOccurs="unbounded" minOccurs="0"/>
 *         <element name="generalPublicComment" type="{http://datex2.eu/schema/1_0/1_0}Comment" maxOccurs="unbounded" minOccurs="0"/>
 *         <element name="nonGeneralPublicComment" type="{http://datex2.eu/schema/1_0/1_0}Comment" maxOccurs="unbounded" minOccurs="0"/>
 *         <element name="groupOfLocations" type="{http://datex2.eu/schema/1_0/1_0}GroupOfLocations"/>
 *         <element name="management" type="{http://datex2.eu/schema/1_0/1_0}Management" minOccurs="0"/>
 *         <element name="situationRecordExtension" type="{http://datex2.eu/schema/1_0/1_0}ExtensionType" minOccurs="0"/>
 *       </sequence>
 *       <attribute name="id" use="required" type="{http://www.w3.org/2001/XMLSchema}ID" />
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "SituationRecord", propOrder = {
    "situationRecordCreationReference",
    "situationRecordCreationTime",
    "situationRecordObservationTime",
    "situationRecordVersion",
    "situationRecordVersionTime",
    "situationRecordFirstSupplierVersionTime",
    "informationUsageOverride",
    "probabilityOfOccurrence",
    "sourceInformation",
    "validity",
    "impact",
    "cause",
    "advice",
    "generalPublicComment",
    "nonGeneralPublicComment",
    "groupOfLocations",
    "management",
    "situationRecordExtension"
})
@XmlSeeAlso({
    NonRoadEventInformation.class,
    OperatorAction.class,
    TrafficElement.class
})
public abstract class SituationRecord {

    protected String situationRecordCreationReference;
    @XmlElement(required = true)
    protected DateTime situationRecordCreationTime;
    protected DateTime situationRecordObservationTime;
    @XmlElement(required = true)
    protected BigInteger situationRecordVersion;
    @XmlElement(required = true)
    protected DateTime situationRecordVersionTime;
    @XmlElement(required = true)
    protected DateTime situationRecordFirstSupplierVersionTime;
    protected InformationUsageEnum informationUsageOverride;
    @XmlElement(required = true)
    protected ProbabilityOfOccurrenceEnum probabilityOfOccurrence;
    protected SourceInformation sourceInformation;
    @XmlElement(required = true)
    protected Validity validity;
    protected Impact impact;
    protected Cause cause;
    protected List<Advice> advice;
    protected List<CommentStructure> generalPublicComment;
    protected List<CommentStructure> nonGeneralPublicComment;
    @XmlElement(required = true)
    protected GroupOfLocations groupOfLocations;
    protected Management management;
    protected ExtensionType situationRecordExtension;
    @XmlAttribute(required = true)
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    @XmlID
    @XmlSchemaType(name = "ID")
    protected String id;

    /**
     * Gets the value of the situationRecordCreationReference property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getSituationRecordCreationReference() {
        return situationRecordCreationReference;
    }

    /**
     * Sets the value of the situationRecordCreationReference property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setSituationRecordCreationReference(String value) {
        this.situationRecordCreationReference = value;
    }

    /**
     * Gets the value of the situationRecordCreationTime property.
     *
     * @return
     *     possible object is
     *     {@link DateTime }
     *
     */
    public DateTime getSituationRecordCreationTime() {
        return situationRecordCreationTime;
    }

    /**
     * Sets the value of the situationRecordCreationTime property.
     *
     * @param value
     *     allowed object is
     *     {@link DateTime }
     *
     */
    public void setSituationRecordCreationTime(DateTime value) {
        this.situationRecordCreationTime = value;
    }

    /**
     * Gets the value of the situationRecordObservationTime property.
     *
     * @return
     *     possible object is
     *     {@link DateTime }
     *
     */
    public DateTime getSituationRecordObservationTime() {
        return situationRecordObservationTime;
    }

    /**
     * Sets the value of the situationRecordObservationTime property.
     *
     * @param value
     *     allowed object is
     *     {@link DateTime }
     *
     */
    public void setSituationRecordObservationTime(DateTime value) {
        this.situationRecordObservationTime = value;
    }

    /**
     * Gets the value of the situationRecordVersion property.
     *
     * @return
     *     possible object is
     *     {@link BigInteger }
     *
     */
    public BigInteger getSituationRecordVersion() {
        return situationRecordVersion;
    }

    /**
     * Sets the value of the situationRecordVersion property.
     *
     * @param value
     *     allowed object is
     *     {@link BigInteger }
     *
     */
    public void setSituationRecordVersion(BigInteger value) {
        this.situationRecordVersion = value;
    }

    /**
     * Gets the value of the situationRecordVersionTime property.
     *
     * @return
     *     possible object is
     *     {@link DateTime }
     *
     */
    public DateTime getSituationRecordVersionTime() {
        return situationRecordVersionTime;
    }

    /**
     * Sets the value of the situationRecordVersionTime property.
     *
     * @param value
     *     allowed object is
     *     {@link DateTime }
     *
     */
    public void setSituationRecordVersionTime(DateTime value) {
        this.situationRecordVersionTime = value;
    }

    /**
     * Gets the value of the situationRecordFirstSupplierVersionTime property.
     *
     * @return
     *     possible object is
     *     {@link DateTime }
     *
     */
    public DateTime getSituationRecordFirstSupplierVersionTime() {
        return situationRecordFirstSupplierVersionTime;
    }

    /**
     * Sets the value of the situationRecordFirstSupplierVersionTime property.
     *
     * @param value
     *     allowed object is
     *     {@link DateTime }
     *
     */
    public void setSituationRecordFirstSupplierVersionTime(DateTime value) {
        this.situationRecordFirstSupplierVersionTime = value;
    }

    /**
     * Gets the value of the informationUsageOverride property.
     *
     * @return
     *     possible object is
     *     {@link InformationUsageEnum }
     *
     */
    public InformationUsageEnum getInformationUsageOverride() {
        return informationUsageOverride;
    }

    /**
     * Sets the value of the informationUsageOverride property.
     *
     * @param value
     *     allowed object is
     *     {@link InformationUsageEnum }
     *
     */
    public void setInformationUsageOverride(InformationUsageEnum value) {
        this.informationUsageOverride = value;
    }

    /**
     * Gets the value of the probabilityOfOccurrence property.
     *
     * @return
     *     possible object is
     *     {@link ProbabilityOfOccurrenceEnum }
     *
     */
    public ProbabilityOfOccurrenceEnum getProbabilityOfOccurrence() {
        return probabilityOfOccurrence;
    }

    /**
     * Sets the value of the probabilityOfOccurrence property.
     *
     * @param value
     *     allowed object is
     *     {@link ProbabilityOfOccurrenceEnum }
     *
     */
    public void setProbabilityOfOccurrence(ProbabilityOfOccurrenceEnum value) {
        this.probabilityOfOccurrence = value;
    }

    /**
     * Gets the value of the sourceInformation property.
     *
     * @return
     *     possible object is
     *     {@link SourceInformation }
     *
     */
    public SourceInformation getSourceInformation() {
        return sourceInformation;
    }

    /**
     * Sets the value of the sourceInformation property.
     *
     * @param value
     *     allowed object is
     *     {@link SourceInformation }
     *
     */
    public void setSourceInformation(SourceInformation value) {
        this.sourceInformation = value;
    }

    /**
     * Gets the value of the validity property.
     *
     * @return
     *     possible object is
     *     {@link Validity }
     *
     */
    public Validity getValidity() {
        return validity;
    }

    /**
     * Sets the value of the validity property.
     *
     * @param value
     *     allowed object is
     *     {@link Validity }
     *
     */
    public void setValidity(Validity value) {
        this.validity = value;
    }

    /**
     * Gets the value of the impact property.
     *
     * @return
     *     possible object is
     *     {@link Impact }
     *
     */
    public Impact getImpact() {
        return impact;
    }

    /**
     * Sets the value of the impact property.
     *
     * @param value
     *     allowed object is
     *     {@link Impact }
     *
     */
    public void setImpact(Impact value) {
        this.impact = value;
    }

    /**
     * Gets the value of the cause property.
     *
     * @return
     *     possible object is
     *     {@link Cause }
     *
     */
    public Cause getCause() {
        return cause;
    }

    /**
     * Sets the value of the cause property.
     *
     * @param value
     *     allowed object is
     *     {@link Cause }
     *
     */
    public void setCause(Cause value) {
        this.cause = value;
    }

    /**
     * Gets the value of the advice property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the advice property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getAdvice().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link Advice }
     *
     *
     */
    public List<Advice> getAdvice() {
        if (advice == null) {
            advice = new ArrayList<Advice>();
        }
        return this.advice;
    }

    /**
     * Gets the value of the generalPublicComment property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the generalPublicComment property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getGeneralPublicComment().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link CommentStructure.Comment }
     *
     *
     */
    public List<CommentStructure> getGeneralPublicComment() {
        if (generalPublicComment == null) {
            generalPublicComment = new ArrayList<CommentStructure>();
        }
        return this.generalPublicComment;
    }

    /**
     * Gets the value of the nonGeneralPublicComment property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the nonGeneralPublicComment property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getNonGeneralPublicComment().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link CommentStructure.Comment }
     *
     *
     */
    public List<CommentStructure> getNonGeneralPublicComment() {
        if (nonGeneralPublicComment == null) {
            nonGeneralPublicComment = new ArrayList<CommentStructure>();
        }
        return this.nonGeneralPublicComment;
    }

    /**
     * Gets the value of the groupOfLocations property.
     *
     * @return
     *     possible object is
     *     {@link GroupOfLocations }
     *
     */
    public GroupOfLocations getGroupOfLocations() {
        return groupOfLocations;
    }

    /**
     * Sets the value of the groupOfLocations property.
     *
     * @param value
     *     allowed object is
     *     {@link GroupOfLocations }
     *
     */
    public void setGroupOfLocations(GroupOfLocations value) {
        this.groupOfLocations = value;
    }

    /**
     * Gets the value of the management property.
     *
     * @return
     *     possible object is
     *     {@link Management }
     *
     */
    public Management getManagement() {
        return management;
    }

    /**
     * Sets the value of the management property.
     *
     * @param value
     *     allowed object is
     *     {@link Management }
     *
     */
    public void setManagement(Management value) {
        this.management = value;
    }

    /**
     * Gets the value of the situationRecordExtension property.
     *
     * @return
     *     possible object is
     *     {@link ExtensionType }
     *
     */
    public ExtensionType getSituationRecordExtension() {
        return situationRecordExtension;
    }

    /**
     * Sets the value of the situationRecordExtension property.
     *
     * @param value
     *     allowed object is
     *     {@link ExtensionType }
     *
     */
    public void setSituationRecordExtension(ExtensionType value) {
        this.situationRecordExtension = value;
    }

    /**
     * Gets the value of the id property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getId() {
        return id;
    }

    /**
     * Sets the value of the id property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setId(String value) {
        this.id = value;
    }

}

A: JAXB is able to implement the class given by the XML xsi automatically.
situationRecord.getClass().toString()
The above line gives me the name of the class which extends of situationRecord.class


text:
Q: sorting dates in key of tuples in dictionary I have a dictionary with entries that are of the format
a = dict({(2,2013):[], (2,2011):[], (7,2013):[] , (4,2013):[]})
i want my output to be like this:
{(2,2011):[], (2,2013):[], (4,2013):[] , (7,2013):[]}
By the way its supposed to be (month,year), how can i achieve that?

A: import operator
myDict = {1: 1, 2: 2, 4:4, 2:1}
sorted_myDict = sorted(myDict.iteritems(), key=operator.itemgetter(1))

sorted_myDict  will be a list of tuples sorted by the second element in each tuple.
@Decency answer is also very good option.

A: If you need to retain order for some reason, you can use an OrderedDict object.

Ordered dictionaries are just like regular dictionaries but they remember the order that items were inserted. When iterating over an ordered dictionary, the items are returned in the order their keys were first added.

Docs: http://docs.python.org/2/library/collections.html#collections.OrderedDict
class collections.OrderedDict([items])

A: after a lot of trying i changed my approach and instead of tuples, i used datetime objects and then applied the:

months_sorted = sorted(months.iteritems(), key=operator.itemgetter(0))


text:
Q: Why in C++ Local Object doesn't free after the function terminated? class MyClass
{
private:
    int color;
    string name;
public:
    MyClass(int co, string n) :
            name(n), color(co)
    {
        cout << "MyClass created" << endl;
    }
    ~MyClass()
    {
        cout << "MyClass is deleted" << endl;
    }
    string getName()
    {
        return this->name;
    }
};

MyClass func()
{
    MyClass c(0, "test");
    return c;
}

int main()
{
    MyClass cls = func();
   cout << cls.getName() << endl;
}

And the output:
MyClass created
test
MyClass is deleted

Hello, I know that in C it's impossible to get an address of local variable from function calls ( i.e  - it's impossible to  initaialize on the stack an array of int by calling another function and returns it) .
I noticed that in C++ something is different;
I created an instance of some object without use the operator new, outside the main function, then returns it to the main function and it's like I initizalized in the main. May someone can explain why the address of object's instance didn't free after the function which created it terminated?
(I expected that MyClass instance deleted when func terminated - No "test" on the output)
thanking you in advance


text:
Q: Updating Anaconda's root Python to newer minor version on Windows does nothing I have an Anaconda (not miniconda) Python 2.7 install on Windows. I would like to update the version of Python installed to the latest minor version (2.7.9), which I see is available in the channels that conda is configured to use. However, typing conda update python basically says:
# All requested packages already installed.
# packages in environment at C:\Anaconda:
#
python                    2.7.5                         2

How does one update to another minor version of Python on Windows? I guess that since conda is written in Python and Windows does not let you overwrite or delete open files, that might be slightly difficult to do on Windows... But is it possible?

A: You are right that Windows won't let conda update Python in the root environment. The only option is to create a new environment with conda create. Otherwise, for now, you will have to reinstall Anaconda to update the root environment Python. We are working on a way to update Python in the root environment, but it isn't finished yet.


text:
Q: tracking scrolling offset of a fixed div from top of window So i have a long scrolling 1page website with a fixed navigation bar.
With this navigation bar I would like to track its .offset().top so I may add or remove classes based on the offset from the top of the window.
Live code link
Example (this is my logic but i cannot make the jQuery alert even work.
$(window).scroll(function () {
  var elem = $('.navigation');
  var topValue = offset.top;
  if (topValue > 400) {
    alert(topValue);
  }
});

A: Try jQuery Waypoints. Instead of specifying an offset, you use the elements on your page to trigger a callback whenever they come into view:
$(function () {
  $("#map").waypoint(function () {
    alert("Scrolled to #map");
  });
});

Edit:
But to properly answer your question, your navigation will always be in the same position because position: fixed positions your element relative to the viewport, not the page. If you want to do this without Waypoints, just check the body tag's scrollTop:
$(function () {
  $(window).scroll(function () {
    var offset = $("body").scrollTop();
    if (offset > 400)
      alert("Scrolled to 400");
  });
});

A: The issue with your code is that you are using offset.top, but you have no offset variable declared, meaning that the .top is not returning anything.
It seems that You've looked at the jQuery documentation for the offset(), but haven't understood/read the example properly.
At the documentation, they are initializing a variable:
var offset = $(this).offset();

And then extracting the .top and .left values:
alert(" coordinates: ( " + offset.left + ", " + offset.top + " ) ");

Looking at the web-page from your link, you don't need a very extensive script to check how much did the user scroll. This small function gives you what you need:
See this working Fiddle Example!
// getPageScroll() by quirksmode.com
function getPageScroll() {
    var xScroll, yScroll;
    if (self.pageYOffset) {
      yScroll = self.pageYOffset;
      xScroll = self.pageXOffset;
    } else if (document.documentElement && document.documentElement.scrollTop) {
      yScroll = document.documentElement.scrollTop;
      xScroll = document.documentElement.scrollLeft;
    } else if (document.body) {// all other Explorers
      yScroll = document.body.scrollTop;
      xScroll = document.body.scrollLeft;
    }
    return new Array(xScroll,yScroll)
}

More reading about this can be found at this stackoverflow answer.


text:
Q: Can we use boost format for out of sequence ordering Lets go to the code directly
#include <boost/format.hpp>
#include <iostream>
#include <vector>

using namespace std;

string strtemplate="First:%1%, Second:%2%";
int main()
{
    vector<string> v;
    v.push_back("first");
    v.push_back("second");
#if 0
    cout<<str(boost::format(strtemplate) % v[1] % v[0])<<endl;
#else
    boost::format fmter(strtemplate);
    for(int i=0;i<2;++i)
    {
            fmter % v[i];
    }
    cout<<str(fmter)<<endl;
#endif
    return 0;
}

Expected output is the one inside if. The need is that, I might get the values in out of order but want them to be place in my pre-formatted string.
Note : I have used a vector here just for illustration so traversing the vector is reverse order is not an option for me.

A: In case your vector is in reverse order for example, why not have a format template as follows?
"First: %3%, Second %2%, Third: %1%.";

You will need to know the order of the input vector in relation to the order of the slots in your string beforehand though, if that is what you are asking. Otherwise, you would need to do some analysis on the input vector, and build the format string during runtime, which sort of defeats the purpose.
I highly recommend you to look into the fmt library for string formatting, it is much more lightweight than Boost format, and also much faster. There is work underway to get it into the standard.


text:
Q: Creating multidimensional array containing database output Im creating a website, where I make a foreach, that echos out some groups, containing checkboxes, with values and names. At the moment that data comes from a multidimensional array, but writing that array when adding new items, is slow, and not very user-friendly.
At the moment, my foreach looks like this:
echo '<form method="post" action="'.$_SERVER['PHP_SELF'].'">';

/* NEXT WE CREATE OUR FOREACH LOOPS TO ECHO THE HTML FOR LOOKS AND CHECKBOXES */
$totalID=0;  // this is a counter we use to build our check box names
foreach ($items as $list){
        $totalID++; // add one to the checkbox name counter
        echo "
{$list['title']}
\n";  // and echo out our section header

        foreach ($list['items'] as $cbox){  // now for each item in the list, call it $cbox
                                   // $cbox now holds the item name, and point value
                echo "<input type='checkbox' name='totals[$totalID][]' value='{$cbox[1]}'> {$cbox[0]}\n";
        }
}

echo "</form>";

And my array I write is something like this:
$items['computers']['title']='Computer Brand';
$items['computers']['items'][]=array('Apple iMac',1);
$items['computers']['items'][]=array('Apple Macbook',.5);
$items['phones']['title']='Phone Brand';
$items['phones']['items'][]=array('iPhone',1);
$items['phones']['items'][]=array('HTC',1);

As said, I can write this, but takes time.
I want to get it into a database, that data above, but I'm having problems about echo'ing it out, I really can't see how I should do.
My current database looks like this:
http://i.stack.imgur.com/Rj0wQ.png
Anyone that have some tips how to do this easy, and also do it user friendly?
Thank you!

A: $sql = "SELECT category, title, brand, point FROM yourtable ORDER BY category, title";
$result = mysql_query($sql);
$data = array();
while(list($category, $title, $brand, $point) = mysql_fetch_array($result)) {
   if (!isset($data[$category])) {
       $data[$category] = array();
   }
   if (!isset($data[$category]['title'] && (!empty($title)) {
       $data[$category]['title'] = $title;
   }
   if (!isset($data[$category]['items'])) {
       $data[$category]['items'] = array();
   }
   $data[$category]['itemps'][] = array($brand, $point);
}

Your table is just screaming for some normalization, however. It's a horrendous construct.

A: Well if you dont' want to parse your result into a multi-dimensionnal array like you did before which would be the easiest task but you have to double de CPU work, there is one way i use often in this case:
No1: Make sure your result is sorted by "Category" and then sorted by whatever criteria you want to order your answers as.
No2: Initialize the "$current_category" to NULL
No3: Loop and detect new $categories and output the header as you go. Your script will look like this:
$currentcategory = NULL;

$result = mysql_query($query);

while($row = mysql_fetch_assoc($result)){

    //Check for a category change
    if($currentcategory != $row['category']){
        echo '
'.$row['title'].'
'.PHP_EOL;
        $currentcategory = $row['category'];
    }

    //Output the label
    echo '<input type="checkbox" name="totals'.$row['id'].' value="'.$row['point']'."> '.$row['brand'].''.PHP_EOL;

}


text:
Q: Azure Function - Suspend queue trigger I have azure function with queue trigger and I wanna perform deploy of new version, but before that I need to be sure that function will finish ongoing executions. Does disabling specific functions (or stopping whole function) will interrupt current executions? If yes, is there any other way to suspend new executions and allow finish current one? And is there any metric which will show me ongoing execution count?

A: If you mean stop running a few minutes, and then keep running from the point stopped. The answer is No.
Actually, you can't suspend the queue trigger functions, because the queue message already consumed and deleted after triggering, whether the whole function execute or not.
Even use staging slot swapping, the function would not be interrupted, but would be running still, which is not suspend the queue trigger, either.


text:
Q: "Seekable" file descriptor to use with MediaRecorder Android 6.0 (API 23) So I am trying to use my Android as a webcam. My code is working perfectly for API <= 22. I am using ParcelFileDescriptor's createPipe() method to create pipe for reading and writing.
In short, my writing to the pipe looks like following:
ParcelFileDescriptor[] parcelFileDescriptors = ParcelFileDescriptor.createPipe();

ParcelFileDescriptor mParcelWrite =new ParcelFileDescriptor(mParcelFileDescriptors[1]);

MediaRecorder mMediaRecorder = new MediaRecorder();
mMediaRecorder.setOutputFile(mParcelWrite.getFileDescriptor());
..
..// Other settings.
mMediaRecorder.start();

When I run this, I get the following exception,
E/MediaRecorder: start failed: -2147483648
W/System.err: java.lang.RuntimeException: start failed. W/System.err: at android.media.MediaRecorder.start(Native Method)
W/System.err: at com.ksy.recordlib.service.recoder.RecoderVideoSource.prepare(RecoderVideoSource.java:105)
W/System.err: at com.ksy.recordlib.service.recoder.RecoderVideoSource.run(RecoderVideoSource.java:173)
W/System.err: at java.lang.Thread.run(Thread.java:818)

I got to know, that in API 23, they made a change which prevented MediaRecorder to work with File descriptors that are not seekable.
ParcelFileDescriptor when used with createPipe() doesn't seem to be seekable.
My question is, How can I make it seekable? Is there any alternative to it?
Thanks.

A: I have been investigating this for a week. There is a hidden format in the output formats you can set which is
mMediaRecorder.setOutputFormat(8);
From the documentation
**@hide H.264/AAC data encapsulated in MPEG2/TS

public static final int OUTPUT_FORMAT_MPEG2TS = 8;**
However it does not still work on Marshmallow or Nougat. I made it work for kit kat. Let me know if this helps.